Make sure your tests are properly marked with the Test attribute. If all of the tests are marked with only the Explicit attribute, the TestAdapter doesn't recognize the fixture.
While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:
tail -f /var/log/postgresql/*
Ubuntu 18.04, django 2+, python3+
You can you use GentleRequest, which is lightweight library for making http requests(DISCLAIMER: I am the author):
Connections connections = new HttpConnections();
Binary binary = new PacketsBinary(new
BufferedInputStream(new FileInputStream(file)),
file.length());
//Content-Type is set to multipart/form-data; boundary=
//{generated by multipart object}
MultipartForm multipart = new HttpMultipartForm(
new HttpFormPart("user", "aplication/json",
new JSONObject().toString().getBytes()),
new HttpFormPart("java", "java.png", "image/png",
binary.content()));
Response response = connections.response(new
PostRequest(url, multipart));
if (response.hasSuccessCode()) {
byte[] raw = response.body().value();
String string = response.body().stringValue();
JSONOBject json = response.body().jsonValue();
} else {
}
Feel free to check it out: https://github.com/Iprogrammerr/Gentle-Request
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client
SELECT * FROM (
SELECT * FROM table_name ORDER BY sortable_column DESC
) WHERE ROWNUM = 1;
I think, it is a very convenient way to use regular expressions
to find a range for applying attributes. This is how I did it:
NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:articleText];
NSRange range = [articleText rangeOfString:@"\\[.+?\\]" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia" size:16] range:range];
[goodText addAttribute:NSForegroundColorAttributeName value:[UIColor brownColor] range:range];
}
NSString *regEx = [NSString stringWithFormat:@"%@.+?\\s", [self.article.titleText substringToIndex:0]];
range = [articleText rangeOfString:regEx options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[goodText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Georgia-Bold" size:20] range:range];
[goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
}
[self.textView setAttributedText:goodText];
I was searching for a list of available attributes and didn't find them here and in a class reference's first page. So I decided to post here information on that.
Attributed strings support the following standard attributes for text. If the key is not in the dictionary, then use the default values described below.
NSString *NSFontAttributeName;
NSString *NSParagraphStyleAttributeName;
NSString *NSForegroundColorAttributeName;
NSString *NSUnderlineStyleAttributeName;
NSString *NSSuperscriptAttributeName;
NSString *NSBackgroundColorAttributeName;
NSString *NSAttachmentAttributeName;
NSString *NSLigatureAttributeName;
NSString *NSBaselineOffsetAttributeName;
NSString *NSKernAttributeName;
NSString *NSLinkAttributeName;
NSString *NSStrokeWidthAttributeName;
NSString *NSStrokeColorAttributeName;
NSString *NSUnderlineColorAttributeName;
NSString *NSStrikethroughStyleAttributeName;
NSString *NSStrikethroughColorAttributeName;
NSString *NSShadowAttributeName;
NSString *NSObliquenessAttributeName;
NSString *NSExpansionAttributeName;
NSString *NSCursorAttributeName;
NSString *NSToolTipAttributeName;
NSString *NSMarkedClauseSegmentAttributeName;
NSString *NSWritingDirectionAttributeName;
NSString *NSVerticalGlyphFormAttributeName;
NSString *NSTextAlternativesAttributeName;
NSAttributedString programming guide
A full class reference is here.
Syntax:
$data = Model::whereIn('field_name', [1, 2, 3])->get();
Use for Users Model
$usersList = Users::whereIn('id', [1, 2, 3])->get();
It help to reduce lot of codes. It is occasionally used in RGB values which consist of 8bits.
where 0xff means 24(0's ) and 8(1's) like 00000000 00000000 00000000 11111111
It effectively masks the variable so it leaves only the value in the last 8 bits, and ignores all the rest of the bits
It’s seen most in cases like when trying to transform color values from a special format to standard RGB values (which is 8 bits long).
Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.
function changeCss(className, classValue) {
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length == 0) {
var cssMainContainer = $('<style id="css-modifier-container"></style>');
cssMainContainer.appendTo($('head'));
}
cssMainContainer.append(className + " {" + classValue + "}\n");
}
Not really an answer to your question but validating url's is really a serious p.i.t.a You're probably just better off validating the domainname and leave query part of the url be. That is my experience. You could also resort to pinging the url and seeing if it results in a valid response but that might be too much for such a simple task.
Regular expressions to detect url's are abundant, google it :)
Simply convert int
to NSString
use :
int x=10;
NSString *strX=[NSString stringWithFormat:@"%d",x];
Common practice for handling currency is to use decimal type. Here is a simple example from "Agile Web Development with Rails"
add_column :products, :price, :decimal, :precision => 8, :scale => 2
This will allow you to handle prices from -999,999.99 to 999,999.99
You may also want to include a validation in your items like
def validate
errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01
end
to sanity-check your values.
I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in jQuery Validation Plugin
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://YOURJQUERYPATH/js/jquery.js" type="text/javascript"></script>
<script src="http://YOURJQUERYPATH/js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$.validator.addMethod("EMAIL", function(value, element) {
return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Email Address is invalid: Please enter a valid email address.");
$.validator.addMethod("PASSWORD",function(value,element){
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
},"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
$.validator.addMethod("SUBMIT",function(value,element){
return this.optional(element) || /[^ ]/i.test(value);
},"You did not click the submit button.");
// Validate signup form on keyup and submit
$("#LOGIN").validate({
rules: {
EMAIL: "required EMAIL",
PASSWORD: "required PASSWORD",
SUBMIT: "required SUBMIT",
},
});
});
</script>
</head>
<body>
<div id="LOGIN_FORM" class="form">
<form id="LOGIN" name="LOGIN" method="post" action="/index/secure/authentication?action=login">
<h1>Log In</h1>
<div id="LOGIN_EMAIL">
<label for="EMAIL">Email Address</label>
<input id="EMAIL" name="EMAIL" type="text" value="" tabindex="1" />
</div>
<div id="LOGIN_PASSWORD">
<label for="PASSWORD">Password</label>
<input id="PASSWORD" name="PASSWORD" type="password" value="" tabindex="2" />
</div>
<div id="LOGIN_SUBMIT">
<input id="SUBMIT" name="SUBMIT" type="submit" value="Submit" tabindex="3" />
</div>
</form>
</div>
</body>
</html>
SWIFT 5.1 of selected answer for newbies
class TestClass {
deinit {
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
NotificationCenter.default.removeObserver(self)
}
init() {
super.init()
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
}
@objc func receiveTest(_ notification: Notification?) {
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if notification?.name.isEqual(toString: "TestNotification") != nil {
print("Successfully received the test notification!")
}
}
}
... somewhere else in another class ...
func someMethod(){
// All instances of TestClass will be notified
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
}
If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
// Create a new X509TrustManager
sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
.sslContext(sslContext).build();
return client;
private TrustManager[] getTrustManager() {
return new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
}
char ch='"';
System.out.println(ch + "String" + ch);
Or
System.out.println('"' + "ASHISH" + '"');
If you have access to server's JMX interface, the start & end offsets are present at:
kafka.log:type=Log,name=LogStartOffset,topic=TOPICNAME,partition=PARTITIONNUMBER
kafka.log:type=Log,name=LogEndOffset,topic=TOPICNAME,partition=PARTITIONNUMBER
(you need to replace TOPICNAME
& PARTITIONNUMBER
).
Bear in mind you need to check for each of the replicas of given partition, or you need to find out which one of the brokers is the leader for a given partition (and this can change over time).
Alternatively, you can use Kafka Consumer methods beginningOffsets
and endOffsets
.
Seems to work here:
>>> a=[[1,1],[2,1],[3,1]]
>>> a
[[1, 1], [2, 1], [3, 1]]
>>> a[1]
[2, 1]
>>> a[1][0]
2
>>> a[1][1]
1
which means that cacerts keystore isn't password protected
That's a false assumption. If you read more carefully, you'll find that the listing was provided without verifying the integrity of the keystore because you didn't provide the password. The listing doesn't require a password, but your keystore definitely has a password, as indicated by:
In order to verify its integrity, you must provide your keystore password.
Java's default cacerts password is "changeit", unless you're on a Mac, where it's "changeme" up to a certain point. Apparently as of Mountain Lion (based on comments and another answer here), the password for Mac is now also "changeit", probably because Oracle is now handling distribution for the Mac JVM as well.
If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:
next(obj for obj in objs if obj.val == 5)
This is however faster than a complete list comprehension. Compare these two:
[i for i in xrange(100000) if i == 1000][0]
next(i for i in xrange(100000) if i == 1000)
The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).
A very elegant solution can be seen on the official redis image and in general in all official images.
Described in step-by-step process:
As seen on Dockerfile comments:
add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added
gosu is an alternative of su
/ sudo
for easy step-down from root user. (Redis is always run with redis
user)
/data
volume and set it as workdirBy configuring the /data volume with the VOLUME /data
command we now have a separate volume that can either be docker volume or bind-mounted to a host dir.
Configuring it as the workdir (WORKDIR /data
) makes it be the default directory where commands are executed from.
This means that all container executions will run through the docker-entrypoint script, and by default the command to be run is redis-server.
docker-entrypoint
is a script that does a simple function: Change ownership of current directory (/data) and step-down from root
to redis
user to run redis-server
. (If the executed command is not redis-server, it will run the command directly.)
This has the following effect
If the /data directory is bind-mounted to the host, the docker-entrypoint will prepare the user permissions before running redis-server under redis
user.
This gives you the ease-of-mind that there is zero-setup in order to run the container under any volume configuration.
Of course if you need to share the volume between different images you need to make sure they use the same userid/groupid otherwise the latest container will hijack the user permissions from the previous one.
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval
... which you don't).
var myBool = myString == "true";
Nope, that is not possible. Due to downwards compatibility issues, Java's generics are based on type erasure, i.a. at runtime, all you have is a non-generic List
object. There is some information about type parameters at runtime, but it resides in class definitions (i.e. you can ask "what generic type does this field's definition use?"), not in object instances.
#read file lines and edit specific item
file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])
a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])
file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)
Install Java 7u21 from: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
Set these variables:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
Run your app and have fun :)
LPCWSTR
stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char
. Common for any C/C++ code that has to deal with non-ASCII only strings.=
To get a normal C literal string to assign to a LPCWSTR
, you need to prefix it with L
LPCWSTR a = L"TestWindow";
There are basically 4 types of main constraints in SQL:
Domain Constraint: if one of the attribute values provided for a new tuple is not of the specified attribute domain
Key Constraint: if the value of a key attribute in a new tuple already exists in another tuple in the relation
Referential Integrity: if a foreign key value in a new tuple references a primary key value that does not exist in the referenced relation
Entity Integrity: if the primary key value is null in a new tuple
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
You need to check the return value against EOF
, not against 1
.
Note that in your example, you also used two different variable names, words
and word
, only declared words
, and didn't declare its length, which should be 16 to fit the 15 characters read in plus a NUL
character.
I had the situatuion when tomcat manager did not start. I had this exception in my logs/manager.DDD-MM-YY.log:
org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter CSRF
java.lang.ClassNotFoundException: org.apache.catalina.filters.CsrfPreventionFilter
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
...
This exception was raised because I used a version of tomcat that hadn't CSRF prevention filter. Tomcat 6.0.24 doesn't have the CSRF prevention filter in it. The first version that has it is the 6.0.30 version (at least. according to the changelog). As a result, Tomcat Manager was uncompatible with version of Tomcat that I used. I've digged description of this issue here: http://blog.techstacks.com/.m/2009/05/tomcat-management-setting-up-tomcat/comments/
Steps to fix it:
Now you should be able to access tomcat manager.
try (FileOutputStream out = new FileOutputStream(filename)) {
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
e.printStackTrace();
}
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
use Handler
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Code here will run in UI thread
}
});
You may also want to try two backslashes (\\")
to escape the escape character.
Try NotFoundMVC on nuget. It works , no setup.
I prefer this solution:
col = df.pop("Mid")
df.insert(0, col.name, col)
It's simpler to read and faster than other suggested answers.
def move_column_inplace(df, col, pos):
col = df.pop(col)
df.insert(pos, col.name, col)
Performance assessment:
For this test, the currently last column is moved to the front in each repetition. In-place methods generally perform better. While citynorman's solution can be made in-place, Ed Chum's method based on .loc
and sachinnm's method based on reindex
cannot.
While other methods are generic, citynorman's solution is limited to pos=0
. I didn't observe any performance difference between df.loc[cols]
and df[cols]
, which is why I didn't include some other suggestions.
I tested with python 3.6.8 and pandas 0.24.2 on a MacBook Pro (Mid 2015).
import numpy as np
import pandas as pd
n_cols = 11
df = pd.DataFrame(np.random.randn(200000, n_cols),
columns=range(n_cols))
def move_column_inplace(df, col, pos):
col = df.pop(col)
df.insert(pos, col.name, col)
def move_to_front_normanius_inplace(df, col):
move_column_inplace(df, col, 0)
return df
def move_to_front_chum(df, col):
cols = list(df)
cols.insert(0, cols.pop(cols.index(col)))
return df.loc[:, cols]
def move_to_front_chum_inplace(df, col):
col = df[col]
df.drop(col.name, axis=1, inplace=True)
df.insert(0, col.name, col)
return df
def move_to_front_elpastor(df, col):
cols = [col] + [ c for c in df.columns if c!=col ]
return df[cols] # or df.loc[cols]
def move_to_front_sachinmm(df, col):
cols = df.columns.tolist()
cols.insert(0, cols.pop(cols.index(col)))
df = df.reindex(columns=cols, copy=False)
return df
def move_to_front_citynorman_inplace(df, col):
# This approach exploits that reset_index() moves the index
# at the first position of the data frame.
df.set_index(col, inplace=True)
df.reset_index(inplace=True)
return df
def test(method, df):
col = np.random.randint(0, n_cols)
method(df, col)
col = np.random.randint(0, n_cols)
ret_mine = move_to_front_normanius_inplace(df.copy(), col)
ret_chum1 = move_to_front_chum(df.copy(), col)
ret_chum2 = move_to_front_chum_inplace(df.copy(), col)
ret_elpas = move_to_front_elpastor(df.copy(), col)
ret_sach = move_to_front_sachinmm(df.copy(), col)
ret_city = move_to_front_citynorman_inplace(df.copy(), col)
# Assert equivalence of solutions.
assert(ret_mine.equals(ret_chum1))
assert(ret_mine.equals(ret_chum2))
assert(ret_mine.equals(ret_elpas))
assert(ret_mine.equals(ret_sach))
assert(ret_mine.equals(ret_city))
Results:
# For n_cols = 11:
%timeit test(move_to_front_normanius_inplace, df)
# 1.05 ms ± 42.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 1.68 ms ± 46.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit test(move_to_front_sachinmm, df)
# 3.24 ms ± 96.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum, df)
# 3.84 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_elpastor, df)
# 3.85 ms ± 58.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 9.67 ms ± 101 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# For n_cols = 31:
%timeit test(move_to_front_normanius_inplace, df)
# 1.26 ms ± 31.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 1.95 ms ± 260 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_sachinmm, df)
# 10.7 ms ± 348 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum, df)
# 11.5 ms ± 869 µs per loop (mean ± std. dev. of 7 runs, 100 loops each
%timeit test(move_to_front_elpastor, df)
# 11.4 ms ± 598 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 31.4 ms ± 1.89 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
An alternative to ArgumentMatcher
is ArgumentCaptor
.
Official example:
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
A captor can also be defined using the @Captor annotation:
@Captor ArgumentCaptor<Person> captor;
//... MockitoAnnotations.initMocks(this);
@Test public void test() {
//...
verify(mock).doSomething(captor.capture());
assertEquals("John", captor.getValue().getName());
}
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
This worked for me:
It starts showing compilation errors in the code.
If you are using docker service and you have switched to other network. You need to restart docker service.
service docker restart
This solved my problem in docker.
preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);
The correct answer is:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
I believe the CSS-only solution text-overflow: ellipsis
applies to one line only, so you won't be able to go this route:
.yourdiv {
line-height: 1.5em; /* Sets line height to 1.5 times text size */
height: 3em; /* Sets the div height to 2x line-height (3 times text size) */
width: 100%; /* Use whatever width you want */
white-space: normal; /* Wrap lines of text */
overflow: hidden; /* Hide text that goes beyond the boundaries of the div */
text-overflow: ellipsis; /* Ellipses (cross-browser) */
-o-text-overflow: ellipsis; /* Ellipses (cross-browser) */
}
Have you tried http://tpgblog.com/threedots/ for jQuery?
As others have said, std::max_element()
and std::min_element()
return iterators, which need to be dereferenced to obtain the value.
The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.
For example (using C++11 for brevity):
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
auto biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest
<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest
<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
}
This yields:
Max element is 5 at position 4
min element is 1 at position 0
Using std::minmax_element()
as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9
since...
If several elements are equivalent to the largest element, the iterator to the last such element is returned.
There is a special trick I discovered by accident.
Try this, its simple : **speakout.xml : **
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_width="match_parent"
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_height="0dp"/>
<Button
android:id="@+id/btnspeakout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>
And Your SpeakOut.java :
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener {
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speakout);
btnspeakout = (Button) findViewById(R.id.btnspeakout);
edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
repeatTTS = new TextToSpeech(this, this);
btnspeakout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
repeatTTS.speak(edtTexttoSpeak.getText().toString(),
TextToSpeech.QUEUE_FLUSH, null);
}
});
}
@Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
}
}
SOURCE Parallelcodes.com's Post
To choose a different location or file type (e.g. PNG or SVG) for the favicon:
One reason can be that you want to have the icon in a specific location, perhaps in the images folder or something alike. For example:
<link rel="icon" href="_/img/favicon.png">
This diferent location may even be a CDN, just like SO seems to do with <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico">
.
To learn more about using other file types like PNG check out this question.
For cache busting purposes:
Add a query string to the path for cache-busting purposes:
<link rel="icon" href="/favicon.ico?v=1.1">
Favicons are very heavily cached and this a great way to ensure a refresh.
Footnote about default location:
As far as the first bit of the question: all modern browsers would detect a favicon at the default location, so that's not a reason to use a link
for it.
Footnote about rel="icon"
:
As indicated by @Semanino's answer, using rel="shortcut icon"
is an old technique which was required by older versions of Internet Explorer, but in most cases can be replaced by the more correct rel="icon"
instruction. The article @Semanino based this on properly links to the appropriate spec which shows a rel
value of shortcut
isn't a valid option.
$(document).ready(function () {_x000D_
$(document).mousemove(function () {_x000D_
$('#myList').css('display', 'block');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$("#hidebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
var fileArray1 = document.getElementsByClassName('file-input');_x000D_
for (var i = 0; i < fileArray1.length; i++) {_x000D_
var files = fileArray1[i].files;_x000D_
for (var j = 0; j < files.length; j++) {_x000D_
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");_x000D_
}_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) != '') {_x000D_
$('#unselect').css('display', 'block');_x000D_
$('#divforfile').css('color', 'green');_x000D_
$('#attach').css('color', 'green');_x000D_
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');_x000D_
_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) == '') {_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
$('#displayFileNames').append('Nessun File Selezionato');_x000D_
};_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
function choosefiles(obj) {_x000D_
$(obj).hide();_x000D_
$('#myList').css('display', 'none');_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#unselect').css('display', 'none');_x000D_
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");_x000D_
$('#displayFileNames').html('');_x000D_
}_x000D_
_x000D_
$(document).ready(function () {_x000D_
$('#unselect').click(function () {_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
$('#myFileInput').val('');_x000D_
document.getElementById('upload-form').reset(); _x000D_
$('#unselect').css('display', 'none');_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
_x000D_
});_x000D_
});
_x000D_
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
<style>_x000D_
.divs {_x000D_
position: absolute;_x000D_
display: inline-block;_x000D_
background-color: #fff;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
height: 2%;_x000D_
width: 15%;_x000D_
opacity: 0;_x000D_
background: #00f;_x000D_
z-index: 100;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
</style>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>_x000D_
_x000D_
<div class="divs" id="divforfile" style="color:black">_x000D_
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />_x000D_
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>_x000D_
</div>_x000D_
</form>_x000D_
<br />_x000D_
</div>_x000D_
<br /> _x000D_
<div>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>_x000D_
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">_x000D_
<span style="color:red">×</span>_x000D_
</button>_x000D_
<div id="displayFileNames">_x000D_
</div>_x000D_
<ul id="myList"></ul>_x000D_
</div>
_x000D_
This is my fully functional customerized file upload/Attachment using jquery & javascript (Visual studio). This will be useful !
Code will be available at the comment section !
Link : https://youtu.be/It38OzMAeig
Enjoy :)
$(document).ready(function () {_x000D_
$(document).mousemove(function () {_x000D_
$('#myList').css('display', 'block');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$("#hidebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
var fileArray1 = document.getElementsByClassName('file-input');_x000D_
for (var i = 0; i < fileArray1.length; i++) {_x000D_
var files = fileArray1[i].files;_x000D_
for (var j = 0; j < files.length; j++) {_x000D_
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");_x000D_
}_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) != '') {_x000D_
$('#unselect').css('display', 'block');_x000D_
$('#divforfile').css('color', 'green');_x000D_
$('#attach').css('color', 'green');_x000D_
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');_x000D_
_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) == '') {_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
$('#displayFileNames').append('Nessun File Selezionato');_x000D_
};_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
function choosefiles(obj) {_x000D_
$(obj).hide();_x000D_
$('#myList').css('display', 'none');_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#unselect').css('display', 'none');_x000D_
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");_x000D_
$('#displayFileNames').html('');_x000D_
}_x000D_
_x000D_
$(document).ready(function () {_x000D_
$('#unselect').click(function () {_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
$('#myFileInput').val('');_x000D_
document.getElementById('upload-form').reset(); _x000D_
$('#unselect').css('display', 'none');_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
_x000D_
});_x000D_
});
_x000D_
<style>_x000D_
.divs {_x000D_
position: absolute;_x000D_
display: inline-block;_x000D_
background-color: #fff;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
height: 2%;_x000D_
width: 15%;_x000D_
opacity: 0;_x000D_
background: #00f;_x000D_
z-index: 100;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
</style>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
_x000D_
<div>_x000D_
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>_x000D_
_x000D_
<div class="divs" id="divforfile" style="color:black">_x000D_
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />_x000D_
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>_x000D_
</div>_x000D_
</form>_x000D_
<br />_x000D_
</div>_x000D_
<br /> _x000D_
<div>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>_x000D_
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">_x000D_
<span style="color:red">×</span>_x000D_
</button>_x000D_
<div id="displayFileNames">_x000D_
</div>_x000D_
<ul id="myList"></ul>_x000D_
</div>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
$(document).mousemove(function () {_x000D_
$('#myList').css('display', 'block');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$("#hidebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
var fileArray1 = document.getElementsByClassName('file-input');_x000D_
for (var i = 0; i < fileArray1.length; i++) {_x000D_
var files = fileArray1[i].files;_x000D_
for (var j = 0; j < files.length; j++) {_x000D_
$("#myList").append("<li style='color:black'>" + files[j].name + "</li>");_x000D_
}_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) != '') {_x000D_
$('#unselect').css('display', 'block');_x000D_
$('#divforfile').css('color', 'green');_x000D_
$('#attach').css('color', 'green');_x000D_
$('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');_x000D_
_x000D_
};_x000D_
_x000D_
if (($("#myList").html()) == '') {_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
$('#displayFileNames').append('Nessun File Selezionato');_x000D_
};_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
function choosefiles(obj) {_x000D_
$(obj).hide();_x000D_
$('#myList').css('display', 'none');_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#unselect').css('display', 'none');_x000D_
$("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");_x000D_
$('#displayFileNames').html('');_x000D_
}_x000D_
_x000D_
$(document).ready(function () {_x000D_
$('#unselect').click(function () {_x000D_
$('#hidebtn').css('display', 'none');_x000D_
$("#seebtn").css('display', 'none');_x000D_
$('#displayFileNames').html('');_x000D_
$("#myList").html('');_x000D_
$('#myFileInput').val('');_x000D_
document.getElementById('upload-form').reset(); _x000D_
$('#unselect').css('display', 'none');_x000D_
$('#divforfile').css('color', 'black');_x000D_
$('#attach').css('color', 'black');_x000D_
_x000D_
});_x000D_
});
_x000D_
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
<style>_x000D_
.divs {_x000D_
position: absolute;_x000D_
display: inline-block;_x000D_
background-color: #fff;_x000D_
}_x000D_
_x000D_
.inputs {_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
height: 2%;_x000D_
width: 15%;_x000D_
opacity: 0;_x000D_
background: #00f;_x000D_
z-index: 100;_x000D_
}_x000D_
_x000D_
.icons {_x000D_
position: absolute;_x000D_
}_x000D_
_x000D_
</style>
_x000D_
<div>_x000D_
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>_x000D_
_x000D_
<div class="divs" id="divforfile" style="color:black">_x000D_
<input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />_x000D_
<i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>_x000D_
</div>_x000D_
</form>_x000D_
<br />_x000D_
</div>_x000D_
<br /> _x000D_
<div>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files ▼</p></button>_x000D_
<button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files ▲</p></button>_x000D_
<button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">_x000D_
<span style="color:red">×</span>_x000D_
</button>_x000D_
<div id="displayFileNames">_x000D_
</div>_x000D_
<ul id="myList"></ul>_x000D_
</div>
_x000D_
If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't much you can do; maybe something like:
diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
print k, ':', dict1[k], '->', dict2[k]
pretty much equivalent to what you have, but you might get nicer presentation for example by sorting diffkeys before you loop on it.
Java and C:
You may find more information in Android developers site.
You can use this
"String.Format("{0:F2}", String Value);"
Gives you only the two digits after Dot, exactly two digits.
Make sure the target window that you (or Facebook) is posting a message to, has completed loading. Most of the times I've gotten this error were when an iframe I was sending messages to had failed to load.
I faced similar issue, with RelativeLayout as the root element for each row in the recyclerview.
To solve the issue, find the xml file that holds each row and make sure that the root element's height is wrap_content
NOT match_parent
.
I like to use this clean code to pass one value only:
startActivity(new Intent(context, YourActivity.class).putExtra("key","value"));
This make more simple to write and understandable code.
Standard xargs
has no good way to do it; you're better off using find -exec
as someone else suggested, or wrap the sed
in a script which does nothing if there are no arguments. GNU xargs
has the --no-run-if-empty
option, and BSD / OS X xargs
has the -L
option which looks like it should do something similar.
using extern <variable type> <variable name>
in a header or another C file.
This is a tricky but super simple solution which works in many situations:
import os
os.system('sample_cmd > tmp')
print open('tmp', 'r').read()
A temporary file(here is tmp) is created with the output of the command and you can read from it your desired output.
Extra note from the comments: You can remove the tmp file in the case of one-time job. If you need to do this several times, there is no need to delete the tmp.
os.remove('tmp')
enumerate()
when working on list actually gives the index and the value of the items inside the list.
For example:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i, j in enumerate(list):
print(i, j)
gives
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
where the first column denotes the index of the item and 2nd column denotes the items itself.
In a dictionary
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
print(i, j)
it gives the output
0 0
1 1
2 2
3 4
4 5
5 6
6 7
where the first column gives the index of the key:value
pairs and the second column denotes the keys
of the dictionary enumm
.
So if you want the first column to be the keys
and second columns as values
, better try out dict.iteritems()
(Python 2) or dict.items()
(Python 3)
for i, j in enumm.items():
print(i, j)
output
0 1
1 2
2 3
4 4
5 5
6 6
7 7
Voila
Select s.stock_code,s.stock_desc,s.stock_desc_ar,
mc.category_name,s.sel_price,
case when s.allow_discount=0 then 'Non Promotional Item' else 'Prmotional
item' end 'Promotion'
From tbl_stock s inner join tbl_stock_category c on s.stock_id=c.stock_id
inner join tbl_category mc on c.category_id=mc.category_id
where mc.category_id=2 and s.isSerialBased=0
In case you have key value pairs in your input array, I used:
.filter(
this.multi_items[0] != null && store.state.isSearchBox === false
? item =>
_.map(this.multi_items, "value").includes(item["wijknaam"])
: item => item["wijknaam"].includes("")
);
where the input array is multi_items as: [{"text": "bla1", "value": "green"}, {"text": etc. etc.}]
_.map is a lodash function.
This is described here: https://yarnpkg.com/en/docs/cli/add#toc-adding-dependencies
For example:
yarn add https://github.com/novnc/noVNC.git#0613d18
I believe this is controlled by the css color
property applied to the element.
generate .class file separate and paste it into relevant package into the workspace. Refresh Project.
A fundamental mistake is here:
result = methodInfo.Invoke(methodInfo, parametersArray);
You are invoking the method on an instance of MethodInfo
. You need to pass in an instance of the type of object that you want to invoke on.
result = methodInfo.Invoke(classInstance, parametersArray);
I had a similar challenge when writing a Powershell script to interact with AWS CLI using the AWS Powershell Tools
I ran the command:
Get-S3Bucket // List AWS S3 buckets
And then I got the error:
Get-S3Bucket : A positional parameter cannot be found that accepts argument list
Here's how I fixed it:
Get-S3Bucket
does not accept // List AWS S3 buckets
as an attribute.
I had put it there as a comment, but it's not acceptable by the AWS CLI as a comment. AWS CLI rather sees it as a parameter.
I had to do it this way:
#List AWS S3 buckets
Get-S3Bucket
That's all.
I hope this helps
Try something like this:
HTML:
<img src='/folder/image1.jpg' id='imageid'/>
jQuery: ?
$('#imageid').hover(function() {
$(this).attr('src', '/folder/image2.jpg');
}, function() {
$(this).attr('src', '/folder/image1.jpg');
});
EDIT: (After OP HTML posted)
HTML:
<a href="#" id="name">
<img title="Hello" src="/ico/view.png"/>
</a>
jQuery:
$('#name img').hover(function() {
$(this).attr('src', '/ico/view1.png');
}, function() {
$(this).attr('src', '/ico/view.png');
});
A solution without require or fs:
var json = []
fetch('./content.json').then(response => json = response.json())
The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.
Examples:
auto a = 0.0f; // a is float
auto b = std::vector<int>(); // b is std::vector<int>()
MyType foo() { return MyType(); }
auto c = foo(); // c is MyType
Set an id to the option then use get element by id and disable it when x value has been selected..
example
<body>
<select class="pull-right text-muted small"
name="driveCapacity" id=driveCapacity onchange="checkRPM()">
<option value="4000.0" id="4000">4TB</option>
<option value="900.0" id="900">900GB</option>
<option value="300.0" id ="300">300GB</option>
</select>
</body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){
document.getElementById("driveCapacity").value = "4000.0";
document.getElementById("4000").disabled = false;
}else{
document.getElementById("4000").disabled = true;
}
</script>
I'd the same problem while I was developing a simple Java application that listens on a specific TCP. Usually, I had no problem, but when I run some stress test I noticed that some connection broke with error socket write exception
.
After Investigation I found a solution that solves my problem. I know this question is quite old, but I prefer to share my solution, someone can find it useful.
The problem was on ServerSocket creation. I read from Javadoc there is a default limit of 50 pending sockets. If you try opening another connection, these will be refused. The solution consist simply in change this default configuration at server side. In the following case, I create a Socket server that listen at TCP port 10_000
and accept max 200
pending sockets.
new Thread(() -> {
try (ServerSocket serverSocket = new ServerSocket(10_000, 200)) {
logger.info("Server starts listening on TCP port {}", port);
while (true) {
try {
ClientHandler clientHandler = clientHandlerProvider.getObject(serverSocket.accept(), this);
executor.execute(clientHandler::start);
} catch (Exception e) {
logger.error(e.getMessage());
}
}
} catch (IOException | SecurityException | IllegalArgumentException e) {
logger.error("Could not open server on TCP port {}. Reason: {}", port, e.getMessage());
}
}).start();
From Javadoc of ServerSocket:
The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter. If a connection indication arrives when the queue is full, the connection is refused.
While JonSkeet's answer explains the difference in a typically excellent way there is another difference: exception handling.
Task.WaitAll
throws an AggregateException
when any of the tasks throws and you can examine all thrown exceptions. The await
in await Task.WhenAll
unwraps the AggregateException
and 'returns' only the first exception.
When the program below executes with await Task.WhenAll(taskArray)
the output is as follows.
19/11/2016 12:18:37 AM: Task 1 started
19/11/2016 12:18:37 AM: Task 3 started
19/11/2016 12:18:37 AM: Task 2 started
Caught Exception in Main at 19/11/2016 12:18:40 AM: Task 1 throwing at 19/11/2016 12:18:38 AM
Done.
When the program below is executed with Task.WaitAll(taskArray)
the output is as follows.
19/11/2016 12:19:29 AM: Task 1 started
19/11/2016 12:19:29 AM: Task 2 started
19/11/2016 12:19:29 AM: Task 3 started
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 1 throwing at 19/11/2016 12:19:30 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 2 throwing at 19/11/2016 12:19:31 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 3 throwing at 19/11/2016 12:19:32 AM
Done.
The program:
class MyAmazingProgram
{
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{ }
}
static void WaitAndThrow(int id, int waitInMs)
{
Console.WriteLine($"{DateTime.UtcNow}: Task {id} started");
Thread.Sleep(waitInMs);
throw new CustomException($"Task {id} throwing at {DateTime.UtcNow}");
}
static void Main(string[] args)
{
Task.Run(async () =>
{
await MyAmazingMethodAsync();
}).Wait();
}
static async Task MyAmazingMethodAsync()
{
try
{
Task[] taskArray = { Task.Factory.StartNew(() => WaitAndThrow(1, 1000)),
Task.Factory.StartNew(() => WaitAndThrow(2, 2000)),
Task.Factory.StartNew(() => WaitAndThrow(3, 3000)) };
Task.WaitAll(taskArray);
//await Task.WhenAll(taskArray);
Console.WriteLine("This isn't going to happen");
}
catch (AggregateException ex)
{
foreach (var inner in ex.InnerExceptions)
{
Console.WriteLine($"Caught AggregateException in Main at {DateTime.UtcNow}: " + inner.Message);
}
}
catch (Exception ex)
{
Console.WriteLine($"Caught Exception in Main at {DateTime.UtcNow}: " + ex.Message);
}
Console.WriteLine("Done.");
Console.ReadLine();
}
}
CSS3: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm
.style1 {
...
background-size: 100%;
}
You can specify just width or height with:
background-size: 100% 50%;
Which will stretch it 100% of the width and 50% of the height.
Browser support: http://caniuse.com/#feat=background-img-opts
The question has changed, so to has the answer:
Strings can't be tested using math.isnan
as this expects a float argument. In your countries
list, you have floats and strings.
In your case the following should suffice:
cleanedList = [x for x in countries if str(x) != 'nan']
In your countries
list, the literal 'nan'
is a string not the Python float nan
which is equivalent to:
float('NaN')
In your case the following should suffice:
cleanedList = [x for x in countries if x != 'nan']
===Update October, 30, 2019===
Since we have new components such as ViewModel and LiveData, we can have a different/easier way to update Activity Title from Fragment by using ViewModel and Live Data
Activity
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow()
}
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.title.observe(this, Observer {
supportActionBar?.title = it
})
} }
MainFragment
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity?.run {
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
} ?: throw Throwable("invalid activity")
viewModel.updateActionBarTitle("Custom Title From Fragment")
} }
And MainModelView:
class MainViewModel : ViewModel() {
private val _title = MutableLiveData<String>()
val title: LiveData<String>
get() = _title
fun updateActionBarTitle(title: String) = _title.postValue(title) }
And then you can update the Activity title from Fragment using viewModel.updateActionBarTitle("Custom Title From Fragment")
===Update April, 10, 2015===
You should use listener to update your action bar title
Fragment:
public class UpdateActionBarTitleFragment extends Fragment {
private OnFragmentInteractionListener mListener;
public UpdateActionBarTitleFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (mListener != null) {
mListener.onFragmentInteraction("Custom Title");
}
return inflater.inflate(R.layout.fragment_update_action_bar_title2, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(String title);
}
}
And Activity:
public class UpdateActionBarTitleActivity extends ActionBarActivity implements UpdateActionBarTitleFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_action_bar_title);
}
@Override
public void onFragmentInteraction(String title) {
getSupportActionBar().setTitle(title);
}
}
Read more here: https://developer.android.com/training/basics/fragments/communicating.html
Darrel is of course right on with his response. One thing to add is that the reason why attempting to bind to a body containing a single token like "hello".
is that it isn’t quite URL form encoded data. By adding “=” in front like this:
=hello
it becomes a URL form encoding of a single key value pair with an empty name and value of “hello”.
However, a better solution is to use application/json when uploading a string:
POST /api/sample HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: host:8080
Content-Length: 7
"Hello"
Using HttpClient you can do it as follows:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(_baseAddress + "api/json", "Hello");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
Henrik
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();
In general, android:gravity="right"
is different from android:layout_gravity="right"
.
The first one affects the position of the text itself within the View, so if you want it to be right-aligned, then layout_width=
should be either "fill_parent"
or "match_parent"
.
The second one affects the View's position inside its parent, in other words - aligning the object itself (edit box or text view) inside the parent view.
with open(fpath, 'rb') as myfile:
fstr = myfile.read()
I encounter this error because the file is empty. This answer may not a correct answer for this question but should give developers a hint like me.
I'm not sure if this is available on OS X, but on linux I would make use of the module
command. See here.
Set up the modulefile correctly, then add something like this to your rc file (e.g. ~/.bashrc):
module load python3.3
This will make it so that your paths get switched around as required when you log in without impacting any system defaults.
All carousel
<script type="text/javascript">
$(document).ready(function () {
$('.carousel').carousel({
interval: 15000
})
});
</script>
I would suggest adding stdout
and stderr
file in systemd service
file itself.
Referring : https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=
As you have configured it should not like:
StandardOutput=/home/user/log1.log
StandardError=/home/user/log2.log
It should be:
StandardOutput=file:/home/user/log1.log
StandardError=file:/home/user/log2.log
This works when you don't want to restart the service again and again.
This will create a new file and does not append to the existing file.
Use Instead:
StandardOutput=append:/home/user/log1.log
StandardError=append:/home/user/log2.log
NOTE: Make sure you create the directory already. I guess it does not support to create a directory.
A really simple way to do this...
// create the option
var opt = $("<option>").val("myvalue").text("my text");
//append option to the select element
$(#my-select).append(opt);
This could be done in lots of ways, even in a single line if really you want to.
I think your problem may lie in how your datepicker is setup. Why don't you disconnect the input... do not use altField. Instead explicitly set the values when the onSelect fires. This will give you control of each interaction; the user text field, and the datepicker.
Note: Sometimes you have to call the routine on .change() and not .onSelect() because onSelect can be called on different interactions that you are not expecting.
Pseudo Code:
$('#date').datepicker({
//altField: , //do not use
onSelect: function(date){
$('#date').val(date); //Set my textbox value
//Do your search routine
},
}).change(function(){
//Or do it here...
});
$('#date').change(function(){
var thisDate = $(this).val();
if(isValidDate(thisDate)){
$('#date').datepicker('setDate', thisDate); //Set my datepicker value
//Do your search routine
});
});
This is what worked for me, it required moment-tz as well as moment though.
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
_x000D_
You can also use Json.NET.
return JsonConvert.SerializeObject(jsonResult.Data);
You can't delete objects, they are removed when there are no more references to them. You can delete references with delete
.
However, if you have created circular references in your objects you may have to de-couple some things.
One line working answer:
$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));
Output: drink
The approved answer will work ... if you know your proxy host and port =) . But in case you are looking for the proxy host and port the steps below should help
if auto configured proxy is given: then
1> open IE(or any browser)
2> get the url address from your browser through IE->Tools->internet option->connections->LAN Settings-> get address and give in url eg: as http://autocache.abc.com/ and enter, a file will be downloaded with .pac format, save to desktop
3> open .pac file in textpad, identify PROXY:
In your editor, it will come something like:
return "PROXY web-proxy.ind.abc.com:8080; PROXY proxy.sgp.abc.com:8080";
kudos to bekur from maven in 5 min not working
Once you have the host and port just pop in into this and your good to go
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("web-proxy.ind.abc.com", 8080));
URLConnection connection = new URL(url).openConnection(proxy);
See the docs: https://getbootstrap.com/docs/4.0/utilities/display/
In order to hide the content on mobile and display on the bigger devices you have to use the following classes:
d-none d-sm-block
The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.
I suggest to read about that before migration:
https://getbootstrap.com/docs/4.0/migration/#responsive-utilities
It should be:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
instead of
[mysqld]
sql_mode="NO_ENGINE_SUBSTITUTION"
then restart mysqld service.
Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.
This answer is more explicit
a = [1,1,1,1,2,2,2,2,3,3,3,4,4]
d = {}
for item in a:
if item in d:
d[item] = d.get(item)+1
else:
d[item] = 1
for k,v in d.items():
print(str(k)+':'+str(v))
# output
#1:4
#2:4
#3:3
#4:2
#remove dups
d = set(a)
print(d)
#{1, 2, 3, 4}
This will show image of base 64 data:
<style>
.logo {
width: 290px;
height: 63px;
background: url(data:image/png;base64,copy-paste-base64-data-here) no-repeat;
}
</style>
<div class="logo"></div>
As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:
$('#your-parent .collapse').on('show.bs.collapse', function (e) {
var actives = $('#your-parent').find('.in, .collapsing');
actives.each( function (index, element) {
$(element).collapse('hide');
})
})
I think "The actual validation errors" may contain sensitive information, and this could be the reason why Microsoft chose to put them in another place (properties). The solution marked here is practical, but it should be taken with caution.
I would prefer to create an extension method. More reasons to this:
If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.
You need to generate a font first. You must use the MakeFont
utility included within the FPDF package. I used on Linux this a bit extended script from the demo:
<?php
// Generation of font definition file for tutorial 7
require('../makefont/makefont.php');
$dir = opendir('/usr/share/fonts/truetype/ttf-dejavu/');
while (($relativeName = readdir($dir)) !== false) {
if ($relativeName == '..' || $relativeName == '.')
continue;
MakeFont("/usr/share/fonts/truetype/ttf-dejavu/$relativeName",'ISO-8859-2');
}
?>
Then I copied generated files to the font
directory of my web and used this:
$pdf->Cell(80,70, iconv('UTF-8', 'ISO-8859-2', 'Bunka jedna'),1);
(I was working on a table.) That worked for my language (Bunka jedna is czech for Cell one). Czech language belongs to central european languages, also ISO-8859-2. Regrettably the user of FPDF is forced to lost advantages of UTF-8 encoding. You cannot get this in your PDF:
Mestecko Fruens Bøge
Danish letter ø
becomes r
in ISO-8859-2.
Suggestion of solution: You need to get a Greek font, generate the font using proper encoding (ISO-8859-7) and use iconv
with the same target encoding as the one the font has been generated with.
For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.
$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
$dateInfo['is_dst']
);
Versions prior, this should work.
$date = '05/Feb/2010:14:00:01';
$format = '@^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$@';
preg_match($format, $date, $dateInfo);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
date('I')
);
You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.
$day = $date[0].$date[1];
$month = date('n', strtotime($date[3].$date[4].$date[5]));
$year = $date[7].$date[8].$date[9].$date[10];
$hour = $date[12].$date[13];
$minute = $date[15].$date[16];
$second = $date[18].$date[19];
Or substr, or explode, whatever you wish to parse that string.
I'm using GIMP 2.8.1. I hope this will work for you:
Open the "Windows" menu and select "Single-Window Mode".
Simple ;)
A better solution without if-else:
$(document).ready(function() {
$("#chkdwn2").click(function() {
$("#dropdown").prop("disabled", this.checked);
});
});
As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.
secondly, i think a correct constructor of the BufferedReader class will help you do your task.
String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();
this should help you.
[Update: as of Go 1.8, GOPATH
defaults to $HOME/go
, but you may still find this useful if you want to understand the GOPATH
layout, customize it, etc.]
The official Go site discusses GOPATH and how to lay out a workspace directory.
export GOPATH="$HOME/your-workspace-dir/"
-- run it in your shell, then add it to ~/.bashrc
or equivalent so it will be set for you in the future. Go will install packages under src/
, bin/
, and pkg/
, subdirectories there. You'll want to put your own packages somewhere under $GOPATH/src
, like $GOPATH/src/github.com/myusername/
if you want to publish to GitHub. You'll also probably want export PATH=$PATH:$GOPATH/bin
in your .bashrc
so you can run compiled programs under $GOPATH
.
Optionally, via Rob Pike, you can also set CDPATH
so it's faster to cd
to package dirs in bash: export CDPATH=.:$GOPATH/src/github.com:$GOPATH/src/golang.org/x
means you can just type cd net/html
instead of cd $GOPATH/src/golang.org/x/net/html
.
Keith Rarick notes you can set GOPATH=$HOME
to put Go's src/
, pkg/
and bin/
directories right under your homedir. That can be nice (for instance, you might already have $HOME/bin
in your path) but of course some folks use multiple workspaces, etc.
Process Bar:
Dependency:
implementation 'com.github.castorflex.smoothprogressbar:library:1.0.0'
XML:
<fr.castorflex.android.smoothprogressbar.SmoothProgressBar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/myProcessbar"
android:layout_width="match_parent"
android:layout_height="10dp"
android:indeterminate="true" />
In Res->color
<color name="pocket_color_1">#ff1635</color>
<integer-array name="pocket_background_colors">
<item>@color/pocket_color_1</item>
</integer-array>
<color name="pocket_color_stop">#00ff00</color>
<integer-array name="pocket_background_stop">
<item>@color/pocket_color_stop</item>
</integer-array>
In Main:
public class MainActivity extends AppCompatActivity{
SmoothProgressBar smoothProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smoothProgressBar=findViewById(R.id.myProcessbar);
showProcessBar();
stopAnimation(); // call when required to stop process
}
public void showProcessBar(){
smoothProgressBar.setVisibility(View.VISIBLE);
smoothProgressBar.setIndeterminateDrawable(new SmoothProgressDrawable.Builder(getApplicationContext())
.interpolator(new AccelerateInterpolator())
.progressiveStart(true)
.progressiveStopSpeed(1000)
.build());
smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
SmoothProgressBarUtils.generateDrawableWithColors(
getResources().getIntArray(R.array.pocket_background_colors),
((SmoothProgressDrawable) smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
}
public void stopAnimation(){
smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
SmoothProgressBarUtils.generateDrawableWithColors(
getResources().getIntArray(R.array.pocket_background_stop),
((SmoothProgressDrawable) smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
smoothProgressBar.progressiveStop();
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
smoothProgressBar.animate().alpha(0.0f).setDuration(6000).translationY(1000);
smoothProgressBar.setVisibility(View.GONE);
}
},1000);
}
}
The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.
You should have started the mongod instance with access control, i.e., the --auth command line option, such as:
$ mongod --auth
Let's start the mongo shell, and create an administrator in the admin database:
$ mongo
> use admin
> db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Now if you run command "db.stats()", or "show users", you will get error "not authorized on admin to execute command..."
> db.stats()
{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { dbstats: 1.0, scale: undefined }",
"code" : 13,
"codeName" : "Unauthorized"
}
The reason is that you still have not granted role "read" or "readWrite" to user myUserAdmin. You can do it as below:
> db.auth("myUserAdmin", "abc123")
> db.grantRolesToUser("myUserAdmin", [ { role: "read", db: "admin" } ])
Now You can verify it (Command "show users" now works):
> show users
{
"_id" : "admin.myUserAdmin",
"user" : "myUserAdmin",
"db" : "admin",
"roles" : [
{
"role" : "read",
"db" : "admin"
},
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
Now if you run "db.stats()", you'll also be OK:
> db.stats()
{
"db" : "admin",
"collections" : 2,
"views" : 0,
"objects" : 3,
"avgObjSize" : 151,
"dataSize" : 453,
"storageSize" : 65536,
"numExtents" : 0,
"indexes" : 3,
"indexSize" : 81920,
"ok" : 1
}
This user and role mechanism can be applied to any other databases in MongoDB as well, in addition to the admin database.
(MongoDB version 3.4.3)
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)
Just another method....
In addition to @tadman's answer I removed the wrappers in /usr/local/bin
as well as the file /etc/profile.d/rvm
.
The wrappers include:
erb
gem
irb
rake
rdoc
ri
ruby
testrb
Is this what you are looking for:
myListBox.DataSource = MyList;
Retrieve only the size in bytes, from ls.
ls -ltr | head -n1 | cut -d' ' -f2
First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
urlString.append("&key=YOUR_API_KEY");
return urlString.toString();
}
This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
This parser will return us string. We will call it like that.
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
Now we will send this string to our drawpath function. The drawpath function is
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
}
catch (JSONException e) {
}
}
Above code will draw the path on mMap. The code of decodePoly is
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
drawPath(result);
}
}
}
I hope it will help.
I know the question talking about eclipse but i got the similar issue many times with Intellij as well and the solution for it was easy .. Just run the 64 bit exe not the 32 one which is always the default one.
Just to add another option to the mix, there are several useful constants within the string
module. While more useful in other cases, they can be used here.
>>> from string import digits
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
There are several constants in the module, including:
ascii_letters
(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)hexdigits
(0123456789abcdefABCDEF)If you are using these constants heavily, it can be worthwhile to covert them to a frozenset
. That enables O(1) lookups, rather than O(n), where n is the length of the constant for the original strings.
>>> digits = frozenset(digits)
>>> ''.join(c for c in "abc123def456" if c in digits)
'123456'
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
A good way to implement containsAny for sets is using the Guava Sets.intersection().
containsAny
would return a boolean
, so the call looks like:
Sets.intersection(set1, set2).isEmpty()
This returns true iff the sets are disjoint, otherwise false. The time complexity of this is likely slightly better than retainAll because you dont have to do any cloning to avoid modifying your original set.
For Ubuntu 14.04
Check core dump enabled:
ulimit -a
One of the lines should be :
core file size (blocks, -c) unlimited
If not :
gedit ~/.bashrc
and add ulimit -c unlimited
to end of file and save, re-run terminal.
Build your application with debug information :
In Makefile -O0 -g
Run application that create core dump (core dump file with name ‘core’ should be created near application_name file):
./application_name
Run under gdb:
gdb application_name core
One advantage that the aforementioned copy-webpack-plugin brings that hasn't been explained before is that all the other methods mentioned here still bundle the resources into your bundle files (and require you to "require" or "import" them somewhere). If I just want to move some images around or some template partials, I don't want to clutter up my javascript bundle file with useless references to them, I just want the files emitted in the right place. I haven't found any other way to do this in webpack. Admittedly it's not what webpack originally was designed for, but it's definitely a current use case. (@BreakDS I hope this answers your question - it's only a benefit if you want it)
I think it is too early to give a "best practices" answer for this as there hasn't been enough time to use it in practice. If this was asked about throw specifiers right after they came out then the answers would be very different to now.
Having to think about whether or not I need to append
noexcept
after every function declaration would greatly reduce programmer productivity (and frankly, would be a pain).
Well, then use it when it's obvious that the function will never throw.
When can I realistically expect to observe a performance improvement after using
noexcept
? [...] Personally, I care aboutnoexcept
because of the increased freedom provided to the compiler to safely apply certain kinds of optimizations.
It seems like the biggest optimization gains are from user optimizations, not compiler ones due to the possibility of checking noexcept
and overloading on it. Most compilers follow a no-penalty-if-you-don't-throw exception handling method, so I doubt it would change much (or anything) on the machine code level of your code, although perhaps reduce the binary size by removing the handling code.
Using noexcept
in the big four (constructors, assignment, not destructors as they're already noexcept
) will likely cause the best improvements as noexcept
checks are 'common' in template code such as in std
containers. For instance, std::vector
won't use your class's move unless it's marked noexcept
(or the compiler can deduce it otherwise).
There seem to be several problems that can cause this symptom. To tell them apart, one needs to look in the setup log files in %PROGRAMFILES%\Microsoft SQL Server\[versionnumber]\Setup Bootstrap\Log
, probably Detail.txt
.
According to this article, when running the installer as a local administrator and trying to use a domain account for the service, it may claim that the credentials are invalid because the local administrator does not have sufficient permissions in the domain to look up the service account's SID. This was the main problem I was encountering, and it might be what was affecting the original poster a year and a half ago.
Checkout the tutorial from Ourcodeworld Ourcodeworld - encode and decode html entities with javascript
Most importantly, the he library example
he.encode('foo © bar ? baz ???? qux');
// ? 'foo © bar ≠ baz 𝌆 qux'
// Passing an `options` object to `encode`, to explicitly encode all symbols:
he.encode('foo © bar ? baz ???? qux', {
'encodeEverything': true
});
he.decode('foo © bar ≠ baz 𝌆 qux');
// ? 'foo © bar ? baz ???? qux'
This library would probably make your coding easier and better managed. It is popular, regularly updated and follows the HTML spec. It itself has no dependencies, as can be seen in the package.json
Look into System.Threading.Timer
class. I think this is what you're looking for.
The code example on MSDN seems to show this class doing very similar to what you're trying to do (check status after certain time).
The mentioned code example from the MSDN link:
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(10);
// Create a timer that invokes CheckStatus after one second,
// and every 1/4 second thereafter.
Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n",
DateTime.Now);
var stateTimer = new Timer(statusChecker.CheckStatus,
autoEvent, 1000, 250);
// When autoEvent signals, change the period to every half second.
autoEvent.WaitOne();
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period to .5 seconds.\n");
// When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne();
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
// The example displays output like the following:
// 11:59:54.202 Creating timer.
//
// 11:59:55.217 Checking status 1.
// 11:59:55.466 Checking status 2.
// 11:59:55.716 Checking status 3.
// 11:59:55.968 Checking status 4.
// 11:59:56.218 Checking status 5.
// 11:59:56.470 Checking status 6.
// 11:59:56.722 Checking status 7.
// 11:59:56.972 Checking status 8.
// 11:59:57.223 Checking status 9.
// 11:59:57.473 Checking status 10.
//
// Changing period to .5 seconds.
//
// 11:59:57.474 Checking status 1.
// 11:59:57.976 Checking status 2.
// 11:59:58.476 Checking status 3.
// 11:59:58.977 Checking status 4.
// 11:59:59.477 Checking status 5.
// 11:59:59.977 Checking status 6.
// 12:00:00.478 Checking status 7.
// 12:00:00.980 Checking status 8.
// 12:00:01.481 Checking status 9.
// 12:00:01.981 Checking status 10.
//
// Destroying timer.
JavaScript Code
function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}
$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
}
When trying to generate a random password you are trying to :
First generate a cryptographically secure set of random bytes
Second is turning those random bytes into a printable string
Now, there are multiple way to generate random bytes in php like :
$length = 32;
//PHP 7+
$bytes= random_bytes($length);
//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);
Then you want to turn these random bytes into a printable string :
You can use bin2hex :
$string = bin2hex($bytes);
or base64_encode :
$string = base64_encode($bytes);
However, note that you do not control the length of the string if you use base64. You can use bin2hex to do that, using 32 bytes will turn into a 64 char string. But it will only work like so in an EVEN string.
So basically you can just do :
$length = 32;
if(PHP_VERSION>=7){
$bytes= random_bytes($length);
}else{
$bytes= openssl_random_pseudo_bytes($length);
}
$string = bin2hex($bytes);
Simplistically, in UNIX, you have the concept of processes and programs. A process is an environment in which a program executes.
The simple idea behind the UNIX "execution model" is that there are two operations you can do.
The first is to fork()
, which creates a brand new process containing a duplicate (mostly) of the current program, including its state. There are a few differences between the two processes which allow them to figure out which is the parent and which is the child.
The second is to exec()
, which replaces the program in the current process with a brand new program.
From those two simple operations, the entire UNIX execution model can be constructed.
To add some more detail to the above:
The use of fork()
and exec()
exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.
The fork()
call makes a near duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations, but the idea is to create as close a copy as possible). Only one process calls fork()
but two processes return from that call - sounds bizarre but it's really quite elegant
The new process (called the child) gets a different process ID (PID) and has the PID of the old process (the parent) as its parent PID (PPID).
Because the two processes are now running exactly the same code, they need to be able to tell which is which - the return code of fork()
provides this information - the child gets 0, the parent gets the PID of the child (if the fork()
fails, no child is created and the parent gets an error code).
That way, the parent knows the PID of the child and can communicate with it, kill it, wait for it and so on (the child can always find its parent process with a call to getppid()
).
The exec()
call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.
So, fork()
and exec()
are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find
- the shell forks, then the child loads the find
program into memory, setting up all command line arguments, standard I/O and so forth.
But they're not required to be used together. It's perfectly acceptable for a program to call fork()
without a following exec()
if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions).
This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening. For this situation, the program contains both the parent and the child code.
Similarly, programs that know they're finished and just want to run another program don't need to fork()
, exec()
and then wait()/waitpid()
for the child. They can just load the child directly into their current process space with exec()
.
Some UNIX implementations have an optimized fork()
which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork()
until the program attempts to change something in that space. This is useful for those programs using only fork()
and not exec()
in that they don't have to copy an entire process space. Under Linux, fork()
only makes a copy of the page tables and a new task structure, exec()
will do the grunt work of "separating" the memory of the two processes.
If the exec
is called following fork
(and this is what happens mostly), that causes a write to the process space and it is then copied for the child process, before modifications are allowed.
Linux also has a vfork()
, even more optimised, which shares just about everything between the two processes. Because of that, there are certain restrictions in what the child can do, and the parent halts until the child calls exec()
or _exit()
.
The parent has to be stopped (and the child is not permitted to return from the current function) since the two processes even share the same stack. This is slightly more efficient for the classic use case of fork()
followed immediately by exec()
.
Note that there is a whole family of exec
calls (execl
, execle
, execve
and so on) but exec
in context here means any of them.
The following diagram illustrates the typical fork/exec
operation where the bash
shell is used to list a directory with the ls
command:
+--------+
| pid=7 |
| ppid=4 |
| bash |
+--------+
|
| calls fork
V
+--------+ +--------+
| pid=7 | forks | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash | | bash |
+--------+ +--------+
| |
| waits for pid 22 | calls exec to run ls
| V
| +--------+
| | pid=22 |
| | ppid=7 |
| | ls |
V +--------+
+--------+ |
| pid=7 | | exits
| ppid=4 | <---------------+
| bash |
+--------+
|
| continues
V
As said before, @Column(unique = true)
is a shortcut to UniqueConstraint
when it is only a single field.
From the example you gave, there is a huge difference between both.
@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;
@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;
This code implies that both mask
and group
have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.
On the other hand,
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)
Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.
If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(columnNames = "mask"),
@UniqueConstraint(columnNames = "group")
}
)
This has the same effect as the first code block.
I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).
From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.
Alternatives:
Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.
Create a custom Jenkins slave build that allows an option to specify the local port to use.
Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.
I am using like this in my code and it's working fine
below is a piece of code which you need to write
using System.Web.Script.Serialization;
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);
Try this ,
background: url(../IMAGES/background.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
For more information , follow this Perfect Full Page Background Image !!
There is a solution to solve page_onload problem (can't get size until page load complete) : Create a userControl :
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ClientSizeDetector.ascx.vb" Inherits="Project_UserControls_ClientSizeDetector" %>
<%If (IsFirstTime) Then%>
<script type="text/javascript">
var pageURL = window.location.href.search(/\?/) > 0 ? "&" : "?";
window.location.href = window.location.href + pageURL + "clientHeight=" + window.innerHeight + "&clientWidth=" + window.innerWidth;
</script>
<%End If%>
Code behind :
Private _isFirstTime As Boolean = False
Private _clientWidth As Integer = 0
Private _clientHeight As Integer = 0
Public Property ClientWidth() As Integer
Get
Return _clientWidth
End Get
Set(value As Integer)
_clientWidth = value
End Set
End Property
Public Property ClientHeight() As Integer
Get
Return _clientHeight
End Get
Set(value As Integer)
_clientHeight = value
End Set
End Property
public Property IsFirstTime() As Boolean
Get
Return _isFirstTime
End Get
Set(value As Boolean)
_isFirstTime = value
End Set
End Property
Protected Overrides Sub OnInit(e As EventArgs)
If (String.IsNullOrEmpty(Request.QueryString("clientHeight")) Or String.IsNullOrEmpty(Request.QueryString("clientWidth"))) Then
Me._isFirstTime = True
Else
Integer.TryParse(Request.QueryString("clientHeight").ToString(), ClientHeight)
Integer.TryParse(Request.QueryString("clientWidth").ToString(), ClientWidth)
Me._isFirstTime = False
End If
End Sub
So after, you can call your control properties
Try adding this in your vhost config:
RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
I found my way here while trying to get filenames, last modified stamps, file sizes etc and wanted to add my code. It only took a few minutes to write a loop to parse the ftp.dir(dir_list.append)
making use of python std lib stuff like strip()
(to clean up the line of text) and split()
to create an array.
ftp = FTP('sick.domain.bro')
ftp.login()
ftp.cwd('path/to/data')
dir_list = []
ftp.dir(dir_list.append)
# main thing is identifing which char marks start of good stuff
# '-rw-r--r-- 1 ppsrt ppsrt 545498 Jul 23 12:07 FILENAME.FOO
# ^ (that is line[29])
for line in dir_list:
print line[29:].strip().split(' ') # got yerself an array there bud!
# EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']
If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:
public class MyClass
{
Stream _s;
public MyClass(Stream s) { _s = s; }
}
But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:
public MyClass(Stream stream)
{
_ms = new MemoryStream();
CopyStream(stream, _ms);
}
// Merged From linked CopyStream below and Jon Skeet's ReadFully example
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[16*1024];
int read;
while((read = input.Read (buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}
The formula provided by Blake doesn't seem to work for me. For past dates it returns due in xx days and for future dates, it returns overdue. Also, it will only return 15 days overdue, when it could actually be 30, 60 90+.
I created this, which seems to work and provides 'Due in xx days', 'Overdue xx days' and 'Due Today'.
=IF(ISBLANK(O10),"",IF(DAYS(TODAY(),O10)<0,CONCATENATE("Due in ",-DAYS(TODAY(),O10)," Days"),IF(DAYS(TODAY(),O10)>0,CONCATENATE("Overdue ",DAYS(TODAY(),O10)," Days"),"Due Today")))
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.
LocalDateTime.parse(
"2012-07-10 14:58:00.000000".replace( " " , "T" )
)
You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.
Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).
You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date
) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.
Use an appropriate data type instead. Specifically, java.time.LocalDateTime
.
Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM
and mm
have different effects.
The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.
Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T
to comply fully.
The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
and I need the resultant date object to be of the same format.
No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.
Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime
objects which lacks those concepts.
String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
To generate a String representing the value of your LocalDateTime
:
toString
to get a String in standard ISO 8601 format.DateTimeFormatter
for producing strings in either custom formats or automatically-localized formats. Search Stack Overflow for more info as these topics have been covered many many times already.
ZonedDateTime
A LocalDateTime
does not represent an exact point on the timeline.
To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for 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.
Why complicate the situation? this is simple write some function like this:
function findBySpecField(data, reqField, value, resField) {
var container = data;
for (var i = 0; i < container.length; i++) {
if (container[i][reqField] == value) {
return(container[i][resField]);
}
}
return '';
}
Use Case:
var data=[{
"id": 502100,
"name": "B?rd? filiali"
},
{
"id": 502122
"name": "10 sayli filiali"
},
{
"id": 503176
"name": "5 sayli filiali"
}]
console.log('Result is '+findBySpecField(data,'id','502100','name'));
output:
Result is B?rd? filiali
Download whatever configuration script that your browser is using.
the script would have various host:port configuration. based on the domain you want to connect , one of the host:port is selected by the borwser.
in the eclipse network setting you can try to put on of the host ports and see if that works.
worked for me.
the config script looks like,
if (isPlainHostName(host))
return "DIRECT";
else if (dnsDomainIs(host, "<***sample host name *******>"))
return "PROXY ***some ip*****; DIRECT";
else if (dnsDomainIs(host, "address.com")
|| dnsDomainIs(host, "adress2..com")
|| dnsDomainIs(host, "address3.com")
|| dnsDomainIs(host, "address4.com")
return "PROXY <***some proxyhost****>:8080";
you would need to look for the host port in the return statement.
One reason: the literal 0
has a bad tendency to acquire the type int
, e.g. in perfect argument forwarding or more in general as argument with templated type.
Another reason: readability and clarity of code.
Using Reflections
Get everything on the classpath:
Reflections reflections = new Reflections(null, new ResourcesScanner());
Set<String> resourceList = reflections.getResources(x -> true);
Another example - get all files with extension .csv from some.package:
Reflections reflections = new Reflections("some.package", new ResourcesScanner());
Set<String> fileNames = reflections.getResources(Pattern.compile(".*\\.csv"));
Suspose we wish to access various views with dynamic component loading.The following code gives a working example of how to accomplish this by using a string parsed from the search string of a url.
Lets assume we want to access a page 'snozberrys' with two unique views using these url paths:
'http://localhost:3000/snozberrys?aComponent'
and
'http://localhost:3000/snozberrys?bComponent'
we define our view's controller like this:
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
import AComponent from './AComponent.js';
import CoBComponent sole from './BComponent.js';
const views = {
aComponent: <AComponent />,
console: <BComponent />
}
const View = (props) => {
let name = props.location.search.substr(1);
let view = views[name];
if(view == null) throw "View '" + name + "' is undefined";
return view;
}
class ViewManager extends Component {
render() {
return (
<Router>
<div>
<Route path='/' component={View}/>
</div>
</Router>
);
}
}
export default ViewManager
ReactDOM.render(<ViewManager />, document.getElementById('root'));
Try this one:
$("div.subtab_left li.notebook a").click(function(e) {
e.preventDefault();
return false;
});
To change transparency on an svg code the simplest way is to open it on any text editor and look for the style attributes. It depends on the svg creator the way the styles are displayed. As i am an Inkscape user the usual way it set the style values is through a style tag just as if it were html but using svg native attributes like fill
, stroke
, stroke-width
, opacity
and so on. opacity
affects the whole svg object, or path or group in which its stated and fill-opacity
, stroke-opacity
will affect just the fill and the stroke transparency. That said, I have also used and tasted to just use fill
and instead of using#fff
use instead the rgba standard like this rgba(255, 255, 255, 1)
just as in css. This works fine for must modern browsers.
Keep in mind that if you intend to further reedit your svg the best practice, in my experience, is to always keep an untouched version at hand. Inkscape is more flexible with hand changed svgs but Illustrator and CorelDraw may have issues importing and edited svg.
Example
<path style="fill:#ff0000;fill-opacity:1;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>
Example 2
<path style="fill:#ff0000;fill-opacity:.5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>
Example 3
<path style="fill:rgba(255, 0, 0, .5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>
Notice that in the last example the fill-opacity
has been removed as rgba standard covers both color and alpha channel.
If I understand things correctly, you want to install over your existing Vim, for better or worse :-) This is a bad idea and it is not the "clean" way to do it. Why? Well, OS X expects that nothing will ever change in /usr/bin unbeknownst to it, so any time you overwrite stuff in there you risk breaking some intricate interdependency. And, Let's say you do break something -- there's no way to "undo" that damage. You will be sad and alone. You may have to reinstall OS X.
The "clean" way is to install in a separate place, and make the new binary higher priority in the $PATH. Here is how I recommend doing that:
$ # Create the directories you need
$ sudo mkdir -p /opt/local/bin
$ # Download, compile, and install the latest Vim
$ cd ~
$ hg clone https://bitbucket.org/vim-mirror/vim or git clone https://github.com/vim/vim.git
$
$ cd vim
$ ./configure --prefix=/opt/local
$ make
$ sudo make install
$ # Add the binary to your path, ahead of /usr/bin
$ echo 'PATH=/opt/local/bin:$PATH' >> ~/.bash_profile
$ # Reload bash_profile so the changes take effect in this window
$ source ~/.bash_profile
Voila! Now when we use vim we will be using the new one. But, to get back to our old configuration in the event of huge f*ckups, we can just delete the /opt directory.
$ which vim
/opt/local/bin/vim
$ vim --version | head -n 2
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 27 2011 20:55:46)
MacOS X (unix) version
See how clean this is.
I recommend not to install in /usr/local/bin when you want to override binaries in /usr/bin, because by default OS X puts /usr/bin higher priority in $PATH than /usr/local/bin, and screwing with that opens its own can of worms.... So, that's what you SHOULD do.
Assuming you're set on doing that, you are definitely on track. To install on top of your current installation, you need to set the "prefix" directory. That's done like this:
hg clone https://bitbucket.org/vim-mirror/vim or git clone https://github.com/vim/vim.git
cd vim
./configure --prefix=/usr
make
sudo make install
You can pass "configure" a few other options too, if you want. Do "./configure --help" to see them. I hope you've got a backup before you do it, though, in case something goes wrong....
As you already state in your question, the main difference between union
and struct
is that union
members overlay the memory of each other so that the sizeof of a union is the one , while struct
members are laid out one after each other (with optional padding in between). Also an union is large enough to contain all its members, and have an alignment that fits all its members. So let's say int
can only be stored at 2 byte addresses and is 2 bytes wide, and long can only be stored at 4 byte addresses and is 4 bytes long. The following union
union test {
int a;
long b;
};
could have a sizeof
of 4, and an alignment requirement of 4. Both an union and a struct can have padding at the end, but not at their beginning. Writing to a struct changes only the value of the member written to. Writing to a member of an union will render the value of all other members invalid. You cannot access them if you haven't written to them before, otherwise the behavior is undefined. GCC provides as an extension that you can actually read from members of an union, even though you haven't written to them most recently. For an Operation System, it doesn't have to matter whether a user program writes to an union or to a structure. This actually is only an issue of the compiler.
Another important property of union and struct is, they allow that a pointer to them can point to types of any of its members. So the following is valid:
struct test {
int a;
double b;
} * some_test_pointer;
some_test_pointer can point to int*
or double*
. If you cast an address of type test
to int*
, it will point to its first member, a
, actually. The same is true for an union too. Thus, because an union will always have the right alignment, you can use an union to make pointing to some type valid:
union a {
int a;
double b;
};
That union will actually be able to point to an int, and a double:
union a * v = (union a*)some_int_pointer;
*some_int_pointer = 5;
v->a = 10;
return *some_int_pointer;
is actually valid, as stated by the C99 standard:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
- a type compatible with the effective type of the object
- ...
- an aggregate or union type that includes one of the aforementioned types among its members
The compiler won't optimize out the v->a = 10;
as it could affect the value of *some_int_pointer
(and the function will return 10
instead of 5
).
Just put this line :
builder.setAutoCancel(true);
And the full code is :
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
builder.setContentTitle("Notifications Title");
builder.setContentText("Your notification content here.");
builder.setSubText("Tap to view the website.");
Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder.setAutoCancel(true);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
In order to center text in md files you can use the center tag like html tag:
<center>Centered text</center>
I would use Pandas with col number
f = pd.read_csv("test.csv", usecols=[0,1,3,4])
f.to_csv("test.csv", index=False)
Go to Tools > Options > Advanced "Tab"(?) > Encryption Tab
Click the "Validation" button, and uncheck the checkbox for checking validity
Be advised though that this is pretty unsecure as it leaves you wide open to accept any invalid certificate. I'd only do this if using the browser on an Intranet where the validity of the cert isn't a concern to you, or you aren't concerned in general.
Hope this helps :-)
if(isset($_POST['submit'])){
ini_set("post_max_size", "30M");
ini_set("upload_max_filesize", "30M");
ini_set("memory_limit", "20000M");
$fileName='product_demo.png';
if($_FILES['imgproduct']['size'] > 0 &&
(($_FILES["imgproduct"]["type"] == "image/gif") ||
($_FILES["imgproduct"]["type"] == "image/jpeg")||
($_FILES["imgproduct"]["type"] == "image/pjpeg") ||
($_FILES["imgproduct"]["type"] == "image/png") &&
($_FILES["imgproduct"]["size"] < 2097152))){
if ($_FILES["imgproduct"]["error"] > 0){
echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
} else {
$rnd=rand(100,999);
$rnd=$rnd."_";
$fileName = $rnd.trim($_FILES['imgproduct']['name']);
$tmpName = $_FILES['imgproduct']['tmp_name'];
$fileSize = $_FILES['imgproduct']['size'];
$fileType = $_FILES['imgproduct']['type'];
$target = "upload/";
echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ;
move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
}
} else {
echo "Sorry, there was a problem uploading your file.";
}
}
In a function, use as
render: function (args) {
if (args.value != 0)
return (parseFloat(args.value).toFixed(2));
},
Label myLabel = new Label ();
myLabel.Content = "Hello World!";
I've heard that Geocoder is on the buggy side. I recently put together an example application that uses Google's http geocoding service to lookup location from lat/long. Feel free to check it out here
I was Working with Elastic SQL plugin. Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
It normally happens when you are download projects from the github. normally dark sdk contains inside flutter.
you can solve this issue following these few steps
C:\flutter\bin\cache\dart-sdk
Yes, you can use SQL IN
operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE
you will need to use OR
instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND
(as you tried) requires ALL conditions to be true, using OR
requires at least one to be true.
Despite the imprecise nature of the question, here's my interpretive answer.
var html = [
'<div> A line</div>',
'<div> Add more lines</div>',
'<div> To the array as you need.</div>'
].join('');
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = html;
document.getElementById('posts').appendChild(div);
You may have to restart android studio if above solutions aren't working, i restarted it and then it works.
You can also do this in the Visual Studio debugger without modifying the code.
Of course, this doesn't help if you're running the code on a different machine, but it can be quite handy to be able to spit out a stack trace automatically without affecting release code or without even needing to restart the program.
DataTable.Clone()
should do the trick.
DataTable newTable = originalTable.Clone();
I know that this is old but yesterday I faced the same issue when calling this URL using C# and the HttpClient class with the Bearer authentication token:
http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
It turns out that the solution for me was to use HTTPS instead of HTTP. So my URL would look like this:
https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
So here is a snippet of my code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.twitter.com/1.1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer **** YOUR BEARER TOKEN GOES HERE ****");
var response = client.GetAsync("statuses/user_timeline.json?count=10&screen_name=username").Result;
if (!response.IsSuccessStatusCode)
{
return result;
}
var items = response.Content.ReadAsAsync<IEnumerable<dynamic>>().Result;
foreach (dynamic item in items)
{
//Do the needful
}
}
Use List<Integer> list = new ArrayList<Integer>();
This works for me:
First you need to create method, which will be returns your headers you want to add to request:
private Map<String, String> getCustomHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("YOURHEADER", "VALUE");
return headers;
}
Second you need to create WebViewClient:
private WebViewClient getWebViewClient()
{
return new WebViewClient()
{
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
view.loadUrl(request.getUrl().toString(), getCustomHeaders());
return true;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url, getCustomHeaders());
return true;
}
};
}
Add WebViewClient to your WebView:
webView.setWebViewClient(getWebViewClient());
Hope this helps.
Following a solution for Kotlin programmers (from API 22)
val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }
express-fileupload
looks like the only middleware that still works these days.
With the same example, multer
and connect-multiparty
gives an undefined value of req.file or req.files, but express-fileupload
works.
And there are a lot of questions and issues raised about the empty value of req.file/req.files.
What is also useful, if you use it for Machine_learning and want to seperate always the same data, you could use:
df.sample(n=len(df), random_state=42)
this makes sure, that you keep your random choice always replicatable
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
I think you just need to give it a parent container... even if that container's height is defined in percentage. This seams to work just fine: JSFiddle
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.wrapper {
width: 100%;
height: 100%;
}
.container {
width: 100%;
height: 50%;
}
I run into same problem.
What I found from documentation, we should use namedspace.
in your case {% url login:login_view %}
Two things which can be done more efficiently:
StringBuilder
instead of StringBuffer
since it's the faster and younger brother.BufferedReader#readLine()
to read it line by line instead of reading it char by char.HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
If the JSON is actually a single line, then you can also remove the loop and builder.
HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
The CloseReason
enumeration you found on MSDN is just for the purpose of checking whether the user closed the app, or it was due to a shutdown, or closed by the task manager, etc...
You can do different actions, according to the reason, like:
void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.UserClosing)
// Prompt user to save his data
if(e.CloseReason == CloseReason.WindowsShutDown)
// Autosave and clear up ressources
}
But like you guessed, there is no difference between clicking the x button, or rightclicking the taskbar and clicking 'close', or pressing Alt F4, etc. It all ends up in a CloseReason.UserClosing
reason.
You should be able to do something like this:
byte[] bitmap = GetYourImage();
using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
image.Save("output.jpg", ImageFormat.Jpeg); // Or Png
}
Look here for more info.
Hopefully this helps.
Note that setTimeout
and setInterval
are very different functions:
setTimeout
will execute the code once, after the timeout.setInterval
will execute the code forever, in intervals of the provided timeout.Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid)
or clearInterval(tid)
respectively.
So, depending on what you want to do, you have two valid choices:
// set timeout
var tid = setTimeout(mycode, 2000);
function mycode() {
// do some stuff...
tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
clearTimeout(tid);
}
or
// set interval
var tid = setInterval(mycode, 2000);
function mycode() {
// do some stuff...
// no need to recall the function (it's an interval, it'll loop forever)
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
Both are very common ways of achieving the same.
Try this it works
<ul class="sub-menu" type="none">
<li class="sub-menu-list" ng-repeat="menu in list.components">
<a class="sub-menu-link">
{{ menu.component }}
</a>
</li>
</ul>
It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.
<input id="myFileInput" type="file" accept="image/*;capture=camera">
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
}
myInput.addEventListener('change', sendPic, false);
if typescript + webpack 2 + at-loader is being used, there is an additional step (@mleko's solution was only partially working for me):
// tsconfig.json
{
"compilerOptions": {
...
"rootDir": ".",
"paths": {
"lib/*": [
"src/org/global/lib/*"
]
}
}
}
// webpack.config.js
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');
resolve: {
plugins: [
new TsConfigPathsPlugin(/* { tsconfig, compiler } */)
]
}
If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.
In this usage, I have this array with each element needing an appended comma and newline.
$some_array = [];
data in $some_array
0: "Some string in an array"
1: "Another string in an array"
Per php.net
If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.
array_walk_recursive($some_array, function (&$value, $key) {
$value .= ",\n";
});
Result:
"Some string in an array,\n"
"Another string in an array,\n"
Here's the same concept using array_walk to prepend the database table name to the field.
$fields = [];
data in $fields:
0: "FirstName"
1: "LastName"
$tbl = "Employees"
array_walk($fields, 'prefixOnArray', $tbl.".");
function prefixOnArray(&$value, $key, $prefix) {
$value = $prefix.$value;
}
Result:
"Employees.FirstName"
"Employees.LastName"
I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.
With this you will get size in GB
hdfs dfs -du PATHTODIRECTORY | awk '/^[0-9]+/ { print int($1/(1024**3)) " [GB]\t" $2 }'
Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.
Historically, you would send an AJAX request in the beforeunload
function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.
Later came navigator.sendBeacon()
. By using the sendBeacon()
method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page.
Unless you are targeting only desktop users, sendBeacon()
should not be used with unload
or beforeunload
since these do not reliably fire on mobile devices. Instead you can listen to the visibilitychange
event. This event will fire every time your page is visible and the user switches tabs, switches apps, goes to the home screen, answers a phone call, navigates away from the page, closes the tab, refreshes, etc.
Here is an example of its usage:
document.addEventListener('visibilitychange', function() {
if (document.visibilityState == 'hidden') {
navigator.sendBeacon("/log.php", analyticsData);
}
});
When the user returns to the page, document.visibilityState
will change to 'visible'
, so you can also handle that event as well.
sendBeacon()
is supported in:
It is NOT currently supported in:
Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.
Update:
It might be worth mentioning that sendBeacon()
only sends POST
requests. If you need to send a request using any other method, an alternative would be to use the fetch API
with the keepalive
flag set to true
, which causes it to behave the same way as sendBeacon()
. Browser support for the fetch API is about the same.
fetch(url, {
method: ...,
body: ...,
headers: ...,
credentials: 'include',
mode: 'no-cors',
keepalive: true,
})
You need to be able to read code written by people who have different style and best practices opinions than you.
If you're only using cout
, nobody gets confused. But when you have lots of namespaces flying around and you see this class and you aren't exactly sure what it does, having the namespace explicit acts as a comment of sorts. You can see at first glance, "oh, this is a filesystem operation" or "that's doing network stuff".
Python 2, using lambda
>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
Both @Autowired
(or @Inject
) and @Resource
work equally well. But there is a conceptual difference or a difference in the meaning
@Resource
means get me a known resource by name. The name is extracted from the name of the annotated setter or field, or it is taken from the name-Parameter.@Inject
or @Autowired
try to wire in a suitable other component by type.So, basically these are two quite distinct concepts. Unfortunately the Spring-Implementation of @Resource
has a built-in fallback, which kicks in when resolution by-name fails. In this case, it falls back to the @Autowired
-kind resolution by-type. While this fallback is convenient, IMHO it causes a lot of confusion, because people are unaware of the conceptual difference and tend to use @Resource
for type-based autowiring.
Another solution (poor one do) is exiting VM Box with saving desktop (top option), restart would bring back the screen as it was before the rescale.
This one did works for me:
function hasVerticalScroll(node){
if(node == undefined){
if(window.innerHeight){
return document.body.offsetHeight> window.innerHeight;
}
else {
return document.documentElement.scrollHeight >
document.documentElement.offsetHeight ||
document.body.scrollHeight>document.body.offsetHeight;
}
}
else {
return node.scrollHeight> node.offsetHeight;
}
}
For the body, just use hasVerticalScroll()
.
@BD at Rivenhill: Since this old question has gotten renewed attention last year, let us go on a bit, just for the sake of discussion.
The body of your doIt
method does not do anything T
-specific at all. Here it is:
public class Clazz<T> {
static <T> void doIt(T object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
// ...
}
So you can entirely drop all type variables and just code
public class Clazz {
static void doIt(Object object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
// ...
}
Ok. But let's get back closer to the original problem. The first type variable on the class declaration is redundant. Only the second one on the method is needed. Here we go again, but it is not the final answer, yet:
public class Clazz {
static <T extends Saying> void doIt(T object) {
System.out.println("shake that booty "+ object.say());
}
public static void main(String args[]) {
Clazz.doIt(new KC());
Clazz.doIt(new SunshineBand());
}
}
// Output:
// KC
// Sunshine
interface Saying {
public String say();
}
class KC implements Saying {
public String say() {
return "KC";
}
}
class SunshineBand implements Saying {
public String say() {
return "Sunshine";
}
}
However, it's all too much fuss about nothing, since the following version works just the same way. All it needs is the interface type on the method parameter. No type variables in sight anywhere. Was that really the original problem?
public class Clazz {
static void doIt(Saying object) {
System.out.println("shake that booty "+ object.say());
}
public static void main(String args[]) {
Clazz.doIt(new KC());
Clazz.doIt(new SunshineBand());
}
}
interface Saying {
public String say();
}
class KC implements Saying {
public String say() {
return "KC";
}
}
class SunshineBand implements Saying {
public String say() {
return "Sunshine";
}
}
String to yyyy-MM-dd date format: Example:
TxtCalStDate.Text = Convert.ToDateTime(objItem["StartDate"]).ToString("yyyy/MM/dd");
I know this question is quite old, but I have found a nice solution. Basically, you pass a container layout to this function, and it will apply the font to all supported views, and recursively cicle in child layouts:
public static void setFont(ViewGroup layout)
{
final int childcount = layout.getChildCount();
for (int i = 0; i < childcount; i++)
{
// Get the view
View v = layout.getChildAt(i);
// Apply the font to a possible TextView
try {
((TextView) v).setTypeface(MY_CUSTOM_FONT);
continue;
}
catch (Exception e) { }
// Apply the font to a possible EditText
try {
((TextView) v).setTypeface(MY_CUSTOM_FONT);
continue;
}
catch (Exception e) { }
// Recursively cicle into a possible child layout
try {
ViewGroup vg = (ViewGroup) v;
Utility.setFont(vg);
continue;
}
catch (Exception e) { }
}
}
This would work very well -- You can use HTML5 to allow only image files to be uploaded. This is the code for uploader.htm --
<html>
<head>
<script>
function validateForm(){
var image = document.getElementById("image").value;
var name = document.getElementById("name").value;
if (image =='')
{
return false;
}
if(name =='')
{
return false;
}
else
{
return true;
}
return false;
}
</script>
</head>
<body>
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" name="ext" size="30"/>
<input type="text" name="name" id="name" size="30"/>
<input type="file" accept="image/*" name="image" id="image" />
<input type="submit" value='Save' onclick="return validateForm()"/>
</form>
</body>
</html>
Now the code for upload.php --
<?php
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
$saveto = "$name.$ext";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 100;
$tw = $w;
$th = $h;
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array( // Sharpen image
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1)
), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}
}
?>
Here's another solution using df.transform
and df.set_index
:
>>> (df['teams']
.transform([lambda x:x[0], lambda x:x[1]])
.set_axis(['team1','team2'],
axis=1,
inplace=False)
)
team1 team2
0 SF NYG
1 SF NYG
2 SF NYG
3 SF NYG
4 SF NYG
5 SF NYG
6 SF NYG
I think COALESCE
function partially similar to the isnull
, but try it.
Why don't you go for null handling functions through application programs, it is better alternative.
Just truncate the digits:
function truncDigits(inputNumber, digits) {
const fact = 10 ** digits;
return Math.floor(inputNumber * fact) / fact;
}
Post::where('id',3)->update(['title'=>'Updated title']);
Another quick test for a string to have something in it but space.
if [[ -n "${str// /}" ]]; then
echo "It is not empty!"
fi
"-n" means non-zero length string.
Then the first two slashes mean match all of the following, in our case space(s). Then the third slash is followed with the replacement (empty) string and closed with "}". Note the difference from the usual regular expression syntax.
You can read more about string manipulation in bash shell scripting here.
Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:
why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.
Solution:
check write permissions on registers
a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it
b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log
c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"
d. run the following command netsh int ipv6 reset reset.log
and repeat step c)
unistall all not-working miniports
a. go to device managers (windows+x -> device manager)
b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)
c. unistall these not working devices
d. reboot your computer
e. Repeat steps a) - d) until you will not see any yellow mark on miniports
delete your vpn connection and create a new one.
that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)
references:
First, please note that all the above queries may miss out or erroneously incorporate the INCLUDE columns of the indices. Also missing in some is the proper ordering and/or ASC/DESC option of the columns.
Modified the above query by jona. As an aside, in many of the database I use, I install my own CLR CONCATENATE aggregate function, so the code below depends on something like this being present. The above SQL statements reduce to a much more maintainable:
SELECT
s.[name] AS [schema_name]
, t.[name] AS [table_name]
, i.[name] AS [index_name]
, dbo.Concatenate(CASE WHEN ic.[key_ordinal] > 0 AND ic.[is_descending_key] = 1 THEN c.[name] + ' DESC' WHEN key_ordinal > 0 THEN c.[name] ELSE NULL END,',',1) AS [columns]
, dbo.Concatenate(CASE WHEN ic.[is_included_column] = 1 THEN c.[name] ELSE NULL END,',',1) AS [includes]
FROM
sys.tables t
INNER JOIN
sys.schemas s ON t.[schema_id] = s.[schema_id]
INNER JOIN
sys.indexes i ON i.[object_id] = t.[object_id]
INNER JOIN
sys.index_columns ic ON ic.[object_id] = t.[object_id] AND ic.index_id = i.index_id
INNER JOIN
sys.columns c ON c.[object_id] = t.[object_id] AND ic.column_id = c.column_id
GROUP BY
s.[name]
, t.[name]
, i.[name]
ORDER BY
s.[name]
, t.[name]
, i.[name]
There are lots of concatenation aggregates out there if your environment allows CLR-based functions added to it.
I removed an obsolete dependency on mybatis in the pom.xml to get mine running.
The other way around using numpy.where() :
import numpy as np
import pandas as pd
In [800]: df = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2'])
In [801]: df
Out[801]:
c1 c2
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [802]: np.where(df["c1"]==6)
Out[802]: (array([3]),)
In [803]: indices = list(np.where(df["c1"]==6)[0])
In [804]: df.iloc[indices]
Out[804]:
c1 c2
3 6 7
In [805]: df.iloc[indices].index
Out[805]: Int64Index([3], dtype='int64')
In [806]: df.iloc[indices].index.tolist()
Out[806]: [3]
You Can use this header
header('Content-type: text/html; charset=UTF-8');
and after decoding the string
$page = utf8_decode(curl_exec($ch));
It worked for me