Actually, you can do this, but with additional code.
There is Guava equivalent of ParameterizedTypeReference and it's called TypeToken.
Guava's class is much more powerful then Spring's equivalent. You can compose the TypeTokens as you wish. For example:
static <K, V> TypeToken<Map<K, V>> mapToken(TypeToken<K> keyToken, TypeToken<V> valueToken) {
return new TypeToken<Map<K, V>>() {}
.where(new TypeParameter<K>() {}, keyToken)
.where(new TypeParameter<V>() {}, valueToken);
}
If you call mapToken(TypeToken.of(String.class), TypeToken.of(BigInteger.class));
you will create TypeToken<Map<String, BigInteger>>
!
The only disadvantage here is that many Spring APIs require ParameterizedTypeReference
and not TypeToken
. But we can create ParameterizedTypeReference
implementation which is adapter to TypeToken
itself.
import com.google.common.reflect.TypeToken;
import org.springframework.core.ParameterizedTypeReference;
import java.lang.reflect.Type;
public class ParameterizedTypeReferenceBuilder {
public static <T> ParameterizedTypeReference<T> fromTypeToken(TypeToken<T> typeToken) {
return new TypeTokenParameterizedTypeReference<>(typeToken);
}
private static class TypeTokenParameterizedTypeReference<T> extends ParameterizedTypeReference<T> {
private final Type type;
private TypeTokenParameterizedTypeReference(TypeToken<T> typeToken) {
this.type = typeToken.getType();
}
@Override
public Type getType() {
return type;
}
@Override
public boolean equals(Object obj) {
return (this == obj || (obj instanceof ParameterizedTypeReference &&
this.type.equals(((ParameterizedTypeReference<?>) obj).getType())));
}
@Override
public int hashCode() {
return this.type.hashCode();
}
@Override
public String toString() {
return "ParameterizedTypeReference<" + this.type + ">";
}
}
}
Then you can use it like this:
public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
ParameterizedTypeReference<ResponseWrapper<T>> responseTypeRef =
ParameterizedTypeReferenceBuilder.fromTypeToken(
new TypeToken<ResponseWrapper<T>>() {}
.where(new TypeParameter<T>() {}, clazz));
ResponseEntity<ResponseWrapper<T>> response = template.exchange(
uri,
HttpMethod.POST,
null,
responseTypeRef);
return response;
}
And call it like:
ResponseWrapper<MyClass> result = makeRequest(uri, MyClass.class);
And the response body will be correctly deserialized as ResponseWrapper<MyClass>
!
You can even use more complex types if you rewrite your generic request method (or overload it) like this:
public <T> ResponseWrapper<T> makeRequest(URI uri, TypeToken<T> resultTypeToken) {
ParameterizedTypeReference<ResponseWrapper<T>> responseTypeRef =
ParameterizedTypeReferenceBuilder.fromTypeToken(
new TypeToken<ResponseWrapper<T>>() {}
.where(new TypeParameter<T>() {}, resultTypeToken));
ResponseEntity<ResponseWrapper<T>> response = template.exchange(
uri,
HttpMethod.POST,
null,
responseTypeRef);
return response;
}
This way T
can be complex type, like List<MyClass>
.
And call it like:
ResponseWrapper<List<MyClass>> result = makeRequest(uri, new TypeToken<List<MyClass>>() {});
Try this.
public static void main(String[] args) {
EchoServer0 myServer;
myServer = new EchoServer0();
myServer.listen();
}
What you were trying to do was declaring a variable of type Object
, not creating anything for that variable to reference, then trying to call a method that didn't exist (in the class Object
) on an object that hadn't been created. It was never going to work.
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
Another way of doing it is in custom JsonObjectRequest by:
@Override
public RetryPolicy getRetryPolicy() {
// here you can write a custom retry policy and return it
return super.getRetryPolicy();
}
Source: Android Volley Example
Bruno's answer was the correct one in the end. This is most easily controlled by the https.protocols
system property. This is how you are able to control what the factory method returns. Set to "TLSv1" for example.
A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.
If this is happening intermittently, then the most likely explanations are (IMO):
Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.
It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.
1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.
It looks like you are trying to connect using TLSv1.2, which isn't widely implemented on servers. Does your destination support tls1.2?
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
My solution without using moment
is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()
var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
The answer above is correct, but in terms of the workaround, I had problems with the BouncyCastle implementation when I set it as preferred provider:
java.lang.ArrayIndexOutOfBoundsException: 64
at com.sun.crypto.provider.TlsPrfGenerator.expand(DashoA13*..)
This is also discussed in one forum thread I found, which doesn't mention a solution. http://www.javakb.com/Uwe/Forum.aspx/java-programmer/47512/TLS-problems
I found an alternative solution which works for my case, although I'm not at all happy with it. The solution is to set it so that the Diffie-Hellman algorithm is not available at all. Then, supposing the server supports an alternative algorithm, it will be selecting during normal negotiation. Obviously the downside of this is that if somebody somehow manages to find a server that only supports Diffie-Hellman at 1024 bits or less then this actually means it will not work where it used to work before.
Here is code which works given an SSLSocket (before you connect it):
List<String> limited = new LinkedList<String>();
for(String suite : ((SSLSocket)s).getEnabledCipherSuites())
{
if(!suite.contains("_DHE_"))
{
limited.add(suite);
}
}
((SSLSocket)s).setEnabledCipherSuites(limited.toArray(
new String[limited.size()]));
Nasty.
public class GetUsers extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect()
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost htopost = new HttpPost("URL");
htopost.setHeader(new BasicHeader("Authorization","Basic Og=="));
try {
JSONObject param = new JSONObject();
param.put("PageSize",100);
param.put("Userid",userId);
param.put("CurrentPage",1);
htopost.setEntity(new StringEntity(param.toString()));
// Execute the request
HttpResponse response;
response = httpclient.execute(htopost);
// Examine the response status
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
json = new JSONArray(result);
// Closing the input stream will trigger connection release
instream.close();
return ""+response.getStatusLine().getStatusCode();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected String doInBackground(String... urls) {
return connect();
}
@Override
protected void onPostExecute(String status){
try {
if(status.equals("200"))
{
Global.defaultMoemntLsit.clear();
for (int i = 0; i < json.length(); i++) {
JSONObject ojb = json.getJSONObject(i);
UserMomentModel u = new UserMomentModel();
u.setId(ojb.getString("Name"));
u.setUserId(ojb.getString("ID"));
Global.defaultMoemntLsit.add(u);
}
userAdapter = new UserAdapter(getActivity(), Global.defaultMoemntLsit);
recycleView.setAdapter(userMomentAdapter);
recycleView.setLayoutManager(mLayoutManager);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
In my experience, I often encounter the following situations;
If you work in a corporate company, contact the network and security team. Because in requests made to external services, it may be necessary to give permission for the relevant endpoint.
Another issue is that the SSL certificate may have expired on the server where your application is running.
Another option if you're using vue cli 3 is to use a config file. Make a vue.config.js
at the same level as your package.json
and put a config like so:
module.exports = {
devServer: {
port: 3000
}
}
Configuring it with the script:
npm run serve --port 3000
works great but if you have more config options I like doing it in a config file. You can find more info in the docs.
Go to File->Import Settings... and select the jar settings file
Update as of IntelliJ 2020:
Go to File -> Manage IDE Settings -> Import Settings...
Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.
Use ARel
t = Person.arel_table
results = Person.where(
t[:name].eq("John").
or(t[:lastname].eq("Smith"))
)
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');
})
})
You are looking for serialize(). Here is an example:
$array = array('foo', 'bar');
//Array to String
$string = serialize($array);
//String to array
$array = unserialize($string);
You can use
insert into table_name
(date_field)
values
(TO_DATE('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss'));
Hope it helps.
It seems like they added a new Class named android.widget.Toolbar
that extends ViewGroup
. Also they added a new method setActionBar(Toolbar)
in Activity
. I haven't tested it yet, but it looks like you can wrap all kinds of TabWidgets
, Spinners
or custom views into a Toolbar
and use it as your Actionbar.
This might be a bit overkill, but I always use the the np.take
function for any wrap-around indexing:
>>> a = np.array([1, 2, 3])
>>> np.take(a, range(0, len(a)+1), mode='wrap')
array([1, 2, 3, 1])
>>> np.take(a, range(-1, len(a)+1), mode='wrap')
array([3, 1, 2, 3, 1])
I know I'm late to the party, but try this...
SELECT
`Train`,
`Dest`,
SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;
Src: Group Concat Documentation
Edit: fixed sql syntax
The function strip
will remove whitespace from the beginning and end of a string.
my_str = " text "
my_str = my_str.strip()
will set my_str
to "text"
.
Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:
List<string> filenamesList = ...;
foreach(string filename in filenamesList)
gvFilesOnServer.Rows.Add(new object[]{filename});
In any case, thanks user927524 for clearing this weird behavior!!
Here is what I have found:
Use RenderAction when you do not have a model to send to the view and have a lot of html to bring back that doesn't need to be stored in a variable.
Use Action when you do not have a model to send to the view and have a little bit of text to bring back that needs to be stored in a variable.
Use RenderPartial when you have a model to send to the view and there will be a lot of html that doesn't need to be stored in a variable.
Use Partial when you have a model to send to the view and there will be a little bit of text that needs to be stored in a variable.
RenderAction and RenderPartial are faster.
The length of the string in a Base64
format is greater then original: 133%
on average. So it makes sense to first compress it with GZIP
, and then encode to Base64
. It gives a reduction of up to 77%
for strings greater than 200 characters and more. Example:
public static void main(String[] args) throws IOException {
byte[] original = randomString(100).getBytes(StandardCharsets.UTF_8);
byte[] base64 = encodeToBase64(original);
byte[] gzipToBase64 = encodeToBase64(encodeToGZIP(original));
byte[] fromBase64 = decodeFromBase64(base64);
byte[] fromBase64Gzip = decodeFromGZIP(decodeFromBase64(gzipToBase64));
// test
System.out.println("Original: " + original.length + " bytes, 100%");
System.out.println("Base64: " + base64.length + " bytes, "
+ (base64.length * 100 / original.length) + "%");
System.out.println("GZIP+Base64: " + gzipToBase64.length + " bytes, "
+ (gzipToBase64.length * 100 / original.length) + "%");
//Original: 3700 bytes, 100%
//Base64: 4936 bytes, 133%
//GZIP+Base64: 2868 bytes, 77%
System.out.println(Arrays.equals(original, fromBase64)); // true
System.out.println(Arrays.equals(original, fromBase64Gzip)); // true
}
public static byte[] decodeFromBase64(byte[] arr) {
return Base64.getDecoder().decode(arr);
}
public static byte[] encodeToBase64(byte[] arr) {
return Base64.getEncoder().encode(arr);
}
public static byte[] decodeFromGZIP(byte[] arr) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(arr);
GZIPInputStream gzip = new GZIPInputStream(bais);
return gzip.readAllBytes();
}
public static byte[] encodeToGZIP(byte[] arr) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(baos);
gzip.write(arr);
gzip.finish();
return baos.toByteArray();
}
public static String randomString(int count) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < count; i++) {
str.append(" ").append(UUID.randomUUID().toString());
}
return str.toString();
}
I recommend using Prettier as it's very extensible but still works perfectly out of the box:
1. CMD + Shift + P -> Format Document
or
1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Selection
using Microsoft.Office.Interop.Excel;
string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;
//Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();
wb.Close();
This example used the 'Microsoft Excel 15.0 Object Library' but may be compatible with earlier versions of Interop and other libraries.
Lots of good answers here - just chipping in my own.
I had a requirement to parse a very specific JSON string, representing the results of making a web-API call. The JSON described a list of objects, and looked something like this:
[
{
"property1": "foo",
"property2": "bar",
"timeOfDay": "2019-09-30T00:00:00",
"numberOfHits": 98,
"isSpecial": false,
"comment": "just to be awkward, this contains a comma"
},
{
"property1": "fool",
"property2": "barrel",
"timeOfDay": "2019-10-31T00:00:00",
"numberOfHits": 11,
"isSpecial": false,
"comment": null
},
...
]
There are a few things to note about this:
null
).The ParseListOfObjects
function in the code below takes the JSON string as input, and returns a Collection
representing the items in the list. Each item is represented as a Dictionary
, where the keys of the dictionary correspond to the names of the object's properties. The values are automatically converted to the appropriate type (String
, Date
, Double
, Boolean
- or Empty
if the value is null
).
Your VBA project will need a reference to the Microsoft Scripting Runtime
library to use the Dictionary
object - though it would not be difficult to remove this dependency if you use a different way of encoding the results.
Here's my JSON.bas
:
Option Explicit
' NOTE: a fully-featured JSON parser in VBA would be a beast.
' This simple parser only supports VERY simple JSON (which is all we need).
' Specifically, it supports JSON comprising a list of objects, each of which has only simple properties.
Private Const strSTART_OF_LIST As String = "["
Private Const strEND_OF_LIST As String = "]"
Private Const strLIST_DELIMITER As String = ","
Private Const strSTART_OF_OBJECT As String = "{"
Private Const strEND_OF_OBJECT As String = "}"
Private Const strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR As String = ":"
Private Const strQUOTE As String = """"
Private Const strNULL_VALUE As String = "null"
Private Const strTRUE_VALUE As String = "true"
Private Const strFALSE_VALUE As String = "false"
Public Function ParseListOfObjects(ByVal strJson As String) As Collection
' Takes a JSON string that represents a list of objects (where each object has only simple value properties), and
' returns a collection of dictionary objects, where the keys and values of each dictionary represent the names and
' values of the JSON object properties.
Set ParseListOfObjects = New Collection
Dim strList As String: strList = Trim(strJson)
' Check we have a list
If Left(strList, Len(strSTART_OF_LIST)) <> strSTART_OF_LIST _
Or Right(strList, Len(strEND_OF_LIST)) <> strEND_OF_LIST Then
Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list (it does not start with '" & strSTART_OF_LIST & "' and end with '" & strEND_OF_LIST & "')"
End If
' Get the list item text (between the [ and ])
Dim strBody As String: strBody = Trim(Mid(strList, 1 + Len(strSTART_OF_LIST), Len(strList) - Len(strSTART_OF_LIST) - Len(strEND_OF_LIST)))
If strBody = "" Then
Exit Function
End If
' Check we have a list of objects
If Left(strBody, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
Err.Raise vbObjectError, Description:="The provided JSON does not appear to be a list of objects (the content of the list does not start with '" & strSTART_OF_OBJECT & "')"
End If
' We now have something like:
' {"property":"value", "property":"value"}, {"property":"value", "property":"value"}, ...
' so we can't just split on a comma to get the various items (because the items themselves have commas in them).
' HOWEVER, since we know we're dealing with very simple JSON that has no nested objects, we can split on "}," because
' that should only appear between items. That'll mean that all but the last item will be missing it's closing brace.
Dim astrItems() As String: astrItems = Split(strBody, strEND_OF_OBJECT & strLIST_DELIMITER)
Dim ixItem As Long
For ixItem = LBound(astrItems) To UBound(astrItems)
Dim strItem As String: strItem = Trim(astrItems(ixItem))
If Left(strItem, Len(strSTART_OF_OBJECT)) <> strSTART_OF_OBJECT Then
Err.Raise vbObjectError, Description:="Mal-formed list item (does not start with '" & strSTART_OF_OBJECT & "')"
End If
' Only the last item will have a closing brace (see comment above)
Dim bIsLastItem As Boolean: bIsLastItem = ixItem = UBound(astrItems)
If bIsLastItem Then
If Right(strItem, Len(strEND_OF_OBJECT)) <> strEND_OF_OBJECT Then
Err.Raise vbObjectError, Description:="Mal-formed list item (does not end with '" & strEND_OF_OBJECT & "')"
End If
End If
Dim strContent: strContent = Mid(strItem, 1 + Len(strSTART_OF_OBJECT), Len(strItem) - Len(strSTART_OF_OBJECT) - IIf(bIsLastItem, Len(strEND_OF_OBJECT), 0))
ParseListOfObjects.Add ParseObjectContent(strContent)
Next ixItem
End Function
Private Function ParseObjectContent(ByVal strContent As String) As Scripting.Dictionary
Set ParseObjectContent = New Scripting.Dictionary
ParseObjectContent.CompareMode = TextCompare
' The object content will look something like:
' "property":"value", "property":"value", ...
' ... although the value may not be in quotes, since numbers are not quoted.
' We can't assume that the property value won't contain a comma, so we can't just split the
' string on the commas, but it's reasonably safe to assume that the value won't contain further quotes
' (and we're already assuming no sub-structure).
' We'll need to scan for commas while taking quoted strings into account.
Dim ixPos As Long: ixPos = 1
Do While ixPos <= Len(strContent)
Dim strRemainder As String
' Find the opening quote for the name (names should always be quoted)
Dim ixOpeningQuote As Long: ixOpeningQuote = InStr(ixPos, strContent, strQUOTE)
If ixOpeningQuote <= 0 Then
' The only valid reason for not finding a quote is if we're at the end (though white space is permitted)
strRemainder = Trim(Mid(strContent, ixPos))
If Len(strRemainder) = 0 Then
Exit Do
End If
Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not start with a quote)"
End If
' Now find the closing quote for the name, which we assume is the very next quote
Dim ixClosingQuote As Long: ixClosingQuote = InStr(ixOpeningQuote + 1, strContent, strQUOTE)
If ixClosingQuote <= 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (the object name does not end with a quote)"
End If
If ixClosingQuote - ixOpeningQuote - Len(strQUOTE) = 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (the object name is blank)"
End If
Dim strName: strName = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
' The next thing after the quote should be the colon
Dim ixNameValueSeparator As Long: ixNameValueSeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)
If ixNameValueSeparator <= 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (missing '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
End If
' Check that there was nothing between the closing quote and the colon
strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixNameValueSeparator - ixClosingQuote - Len(strQUOTE)))
If Len(strRemainder) > 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (unexpected content between name and '" & strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR & "')"
End If
' What comes after the colon is the value, which may or may not be quoted (e.g. numbers are not quoted).
' If the very next thing we see is a quote, then it's a quoted value, and we need to find the matching
' closing quote while ignoring any commas inside the quoted value.
' If the next thing we see is NOT a quote, then it must be an unquoted value, and we can scan directly
' for the next comma.
' Either way, we're looking for a quote or a comma, whichever comes first (or neither, in which case we
' have the last - unquoted - value).
ixOpeningQuote = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strQUOTE)
Dim ixPropertySeparator As Long: ixPropertySeparator = InStr(ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), strContent, strLIST_DELIMITER)
If ixOpeningQuote > 0 And ixPropertySeparator > 0 Then
' Only use whichever came first
If ixOpeningQuote < ixPropertySeparator Then
ixPropertySeparator = 0
Else
ixOpeningQuote = 0
End If
End If
Dim strValue As String
Dim vValue As Variant
If ixOpeningQuote <= 0 Then ' it's not a quoted value
If ixPropertySeparator <= 0 Then ' there's no next value; this is the last one
strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
ixPos = Len(strContent) + 1
Else ' this is not the last value
strValue = Trim(Mid(strContent, ixNameValueSeparator + Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR), ixPropertySeparator - ixNameValueSeparator - Len(strOBJECT_PROPERTY_NAME_VALUE_SEPARATOR)))
ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
End If
vValue = ParseUnquotedValue(strValue)
Else ' It is a quoted value
' Find the corresponding closing quote, which should be the very next one
ixClosingQuote = InStr(ixOpeningQuote + Len(strQUOTE), strContent, strQUOTE)
If ixClosingQuote <= 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (the value does not end with a quote)"
End If
strValue = Mid(strContent, ixOpeningQuote + Len(strQUOTE), ixClosingQuote - ixOpeningQuote - Len(strQUOTE))
vValue = ParseQuotedValue(strValue)
' Re-scan for the property separator, in case we hit one that was part of the quoted value
ixPropertySeparator = InStr(ixClosingQuote + Len(strQUOTE), strContent, strLIST_DELIMITER)
If ixPropertySeparator <= 0 Then ' this was the last value
' Check that there's nothing between the closing quote and the end of the text
strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE)))
If Len(strRemainder) > 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
End If
ixPos = Len(strContent) + 1
Else ' this is not the last value
' Check that there's nothing between the closing quote and the property separator
strRemainder = Trim(Mid(strContent, ixClosingQuote + Len(strQUOTE), ixPropertySeparator - ixClosingQuote - Len(strQUOTE)))
If Len(strRemainder) > 0 Then
Err.Raise vbObjectError, Description:="Mal-formed object (there is content after the last value)"
End If
ixPos = ixPropertySeparator + Len(strLIST_DELIMITER)
End If
End If
ParseObjectContent.Add strName, vValue
Loop
End Function
Private Function ParseUnquotedValue(ByVal strValue As String) As Variant
If StrComp(strValue, strNULL_VALUE, vbTextCompare) = 0 Then
ParseUnquotedValue = Empty
ElseIf StrComp(strValue, strTRUE_VALUE, vbTextCompare) = 0 Then
ParseUnquotedValue = True
ElseIf StrComp(strValue, strFALSE_VALUE, vbTextCompare) = 0 Then
ParseUnquotedValue = False
ElseIf IsNumeric(strValue) Then
ParseUnquotedValue = CDbl(strValue)
Else
Err.Raise vbObjectError, Description:="Mal-formed value (not null, true, false or a number)"
End If
End Function
Private Function ParseQuotedValue(ByVal strValue As String) As Variant
' Both dates and strings are quoted; we'll treat it as a date if it has the expected date format.
' Dates are in the form:
' 2019-09-30T00:00:00
If strValue Like "####-##-##T##:00:00" Then
' NOTE: we just want the date part
ParseQuotedValue = CDate(Left(strValue, Len("####-##-##")))
Else
ParseQuotedValue = strValue
End If
End Function
A simple test:
Const strJSON As String = "[{""property1"":""foo""}]"
Dim oObjects As Collection: Set oObjects = Json.ParseListOfObjects(strJSON)
MsgBox oObjects(1)("property1") ' shows "foo"
Classifiers are just objects that can be pickled and dumped like any other. To continue your example:
import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
cPickle.dump(gnb, fid)
# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
gnb_loaded = cPickle.load(fid)
Edit: if you are using a sklearn Pipeline in which you have custom transformers that cannot be serialized by pickle (nor by joblib), then using Neuraxle's custom ML Pipeline saving is a solution where you can define your own custom step savers on a per-step basis. The savers are called for each step if defined upon saving, and otherwise joblib is used as default for steps without a saver.
In fact, Objective-C doesn't have abstract classes, but you can use Protocols to achieve the same effect. Here is the sample:
#import <Foundation/Foundation.h>
@protocol CustomProtocol <NSObject>
@required
- (void)methodA;
@optional
- (void)methodB;
@end
#import <Foundation/Foundation.h>
#import "CustomProtocol.h"
@interface TestProtocol : NSObject <CustomProtocol>
@end
#import "TestProtocol.h"
@implementation TestProtocol
- (void)methodA
{
NSLog(@"methodA...");
}
- (void)methodB
{
NSLog(@"methodB...");
}
@end
you need to use YYYY-MM-DD format to insert date in mysql
Try something like
$("#container").on('click', 'someLinkSelector', function(){ $("#container").html( <new html with new spans> ) });
You basically need to attach your events from a non-dynamic part of the DOM so it can watch for dynamically-created elements.
In my opinion a state machine is not only meant for changing states but also (very important) for handling triggers/events within a specific state. If you want to understand state machine design pattern better, a good description can be found within the book Head First Design Patterns, page 320.
It is not only about the states within variables but also about handling triggers within the different states. Great chapter (and no, there is no fee for me in mentioning this :-) which contains just an easy to understand explanation.
You can also do it this way, using structures :
function createCounter () {
var count = 0;
return {
increaseBy: function(nb) {
count += nb;
},
reset: function {
count = 0;
}
}
}
Then :
var counter1 = createCounter();
counter1.increaseBy(4);
If you want to extract from a
tag then
$('.dep_buttons').text().substr(0,25)
With the mouseover event,
$(this).text($(this).text().substr(0, 25));
The above will extract the text of a tag, then extract again assign it back.
I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:
So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)
EDIT 19-MAR-2014:
Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core
), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well.
So it just might be good choice, especially for smaller apps.
Here is what I use so I can throw my code anywhere without issue. __name__
is always defined, but __file__
is only defined when the code is run as a file (e.g. not in IDLE/iPython).
if '__file__' in globals():
self_name = globals()['__file__']
elif '__file__' in locals():
self_name = locals()['__file__']
else:
self_name = __name__
Alternatively, this can be written as:
self_name = globals().get('__file__', locals().get('__file__', __name__))
struct node{
int position;
char name[30];
struct node * next;
};
void free_list(node * list){
node* next_node;
printf("\n\n Freeing List: \n");
while(list != NULL)
{
next_node = list->next;
printf("clear mem for: %s",list->name);
free(list);
list = next_node;
printf("->");
}
}
You should be able to set the className property of the element. You could do a += to append it.
You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.
There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.
Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.
Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:
import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';
@Injectable()
export class MyResolver implements Resolve<MyData> {
constructor(private ms: MyService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
let id = route.params['id'];
return this.ms.getId(id).then(data => {
if (data) {
return data;
} else {
this.router.navigate(['/login']);
return;
}
});
}
}
and in the module:
import { MyResolver } from './my-resolver.service';
@NgModule({
imports: [
RouterModule.forChild(myRoutes)
],
exports: [
RouterModule
],
providers: [
MyResolver
]
})
export class MyModule { }
and you can access it in your Component like this:
/////
ngOnInit() {
this.route.data
.subscribe((data: { mydata: myData }) => {
this.id = data.mydata.id;
});
}
/////
And in the Route something like this (usually in the app.routing.ts file):
////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
You can use typeof(Guid), "00000000-0000-0000-0000-000000000000"
for DefaultValue of the property.
As a follow-up to the answer of @maciej-bukowski above ^^^, in modern browsers as of now (spring 2017) that support async/await you can load as follows. In this example we load the load html2canvas library:
async function loadScript(url) {_x000D_
let response = await fetch(url);_x000D_
let script = await response.text();_x000D_
eval(script);_x000D_
}_x000D_
_x000D_
let scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js'_x000D_
loadScript(scriptUrl);
_x000D_
If you run the snippet and then open your browser's console you should see the function html2canvas() is now defined.
If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.
This will install an apk directly on the device connected from the aab.
I am using this base class connection with mysql:
"base.js"
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 10,
host: Config.appSettings().database.host,
user: Config.appSettings().database.username,
password: Config.appSettings().database.password,
database: Config.appSettings().database.database
});
var DB = (function () {
function _query(query, params, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
callback(null, err);
throw err;
}
connection.query(query, params, function (err, rows) {
connection.release();
if (!err) {
callback(rows);
}
else {
callback(null, err);
}
});
connection.on('error', function (err) {
connection.release();
callback(null, err);
throw err;
});
});
};
return {
query: _query
};
})();
module.exports = DB;
Just use it like that:
var DB = require('../dal/base.js');
DB.query("select * from tasks", null, function (data, error) {
callback(data, error);
});
You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
Iterate as:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
this could cause of jdk libraries if you had imported into jre
this happen to me , so check installed jre jars
in eclipse click on Windows > Preferences > Java > Installed Jres > click on Jre and edit after that look into jar list make sure none is of jdk or corrupted ,
The $GLOBALS
array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
Really the ideal way to do this is to not use pull
at all, but instead fetch
and reset
:
git fetch origin master
git reset --hard FETCH_HEAD
git clean -df
(Altering master
to whatever branch you want to be following.)
pull
is designed around merging changes together in some way, whereas reset
is designed around simply making your local copy match a specific commit.
You may want to consider slightly different options to clean
depending on your system's needs.
Flex answer
.div1 {
width:300px;
background-color: grey;
border:1px solid;
overflow:auto;
display: flex;
}
.div2 {
width:150px;
background-color: #F4A460;
}
.div3 {
width:150px;
background-color: #FFFFE0;
}
Check the fiddle at http://jsfiddle.net/germangonzo/E4Zgj/575/
No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.
If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:
for ( i in 1..10) { if (i < 5) println i; else return}
becomes
(1..10).each{if (it < 5) println it}
becomes
(1..10).findAll{it < 5}.each{println it}
which also helps clarity. It states the intent of your code much better.
The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.
However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.
We can parse csv files with quoted strings and delimited by say | with following code
while read -r line
do
field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')
echo "$field1 $field2"
done < "$csvFile"
awk
parses the string fields to variables and tr
removes the quote.
Slightly slower as awk
is executed for each field.
I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me :(
after a while I saw in the documentation that in cases of dev branch you need to require with a 'dev-' prefix to the version and the following worked perfectly.
composer require [vendorName]/[packageName]:dev-[gitBranchName]
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
Change the file character encoding,
put below line to top of your code always
# -*- coding: utf-8 -*-
I like to give my input field a border, remove the outline on focus, and "outline" the border instead:
input {
border: 1px solid grey;
&:focus {
outline: none;
border-left: 1px solid violet;
}
}
You can also do it with a transparent border:
input {
border: 1px solid transparent;
&:focus {
outline: none;
border-left: 1px solid violet;
}
}
You also can use graceful restart the apache server with service apache2 reload
or apachectl -k graceful
.
As the apache doc says:
The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.
I just noticed that if you do:
monthCalendar1.SelectionRange.Start.ToShortDateString()
you will get only the date (e.g. 1/25/2014
) from a MonthCalendar
control.
It's opposite to:
monthCalendar1.SelectionRange.Start.ToString()
//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)
Because these MonthCalendar
properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.
If your <td>
is not empty, one popular trick is to insert a non breaking space
in it, such that:
<td id="td1"> </td>
Then you will be able to use:
document.getElementById('td1').firstChild.data = 'New Value';
Otherwise, if you do not fancy adding the meaningless  
you can use the solution that Jonathan Fingland described in the other answer.
Dialect means "the variant of a language". Hibernate, as we know, is database agnostic. It can work with different databases. However, databases have proprietary extensions/native SQL variations, and set/sub-set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL. Hibernate uses "dialect" configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary.
Try this:
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8,iso,utfBytes);
string msg = iso.GetString(isoBytes);
This answer may help if: 1) your site used to work with Windows authentication before upgrading to Visual Studio 2015 and 2) and your site is attempting to load /login.aspx
(even though there is no such file on your site).
Add the following two lines to the appSettings
section of your site's Web.config
.
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
EDIT
differences in usage:
std::vector<>::iterator it = ( v.begin() + index );
or
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
You have to use target attribute
<a href="newsletter_01.pdf" target="_blank">
This one works in iOS and Safari.
You need to use Stoive's ArrayBuffer solution but you can't use BlobBuilder, as vava720 indicates, so here's the mashup of both.
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: 'image/jpeg' });
}
Simply updated Xcode. Solved my problem
Save your python file in a spot where you will be able to find it again. Then navigate to that spot using the command line (cd /home/[profile]/spot/you/saved/file) or go to that location with the file browser. If you use the latter, right click and select "Open In Terminal." When the terminal opens, type "sudo chmod +x Yourfilename." After entering your password, type "python ./Yourfilename" which will open your python file in the command line. Hope this helps!
Running Linux Mint
For more information, the following page describes why you never need to use new Array()
You never need to use
new Object()
in JavaScript. Use the object literal{}
instead. Similarly, don’t usenew Array()
, use the array literal[]
instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.Do not use
new Number
,new String
, ornew Boolean
. These forms produce unnecessary object wrappers. Just use simple literals instead.
Also check out the comments - the new Array(length)
form does not serve any useful purpose (at least in today's implementations of JavaScript).
Well, there are more OS's than Unix and Windows (Portable devices, etc), and Java is known for its portability. The best practice is to use it, so the JVM could determine which one is the best for that OS.
You just have to execute this command as root
$ curl https://sdk.cloud.google.com | bash
Restart the terminal and that's it. Now all commands should be executed as root
Not sure if this is efficient or not, but strings in PowerShell can be referred to using array index syntax, in a similar fashion to Python.
It's not completely intuitive because of the fact the first letter is referred to by index = 0
, but it does:
Here are some examples:
PS > 'Hello World'[0..2]
Yields the result (index values included for clarity - not generated in output):
H [0]
e [1]
l [2]
Which can be made more useful by passing -join ''
:
PS > 'Hello World'[0..2] -join ''
Hel
There are some interesting effects you can obtain by using different indices:
Forwards
Use a first index value that is less than the second and the substring will be extracted in the forwards direction as you would expect. This time the second index value is far in excess of the string length but there is no error:
PS > 'Hello World'[3..300] -join ''
lo World
Unlike:
PS > 'Hello World'.Substring(3,300)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within
the string.
Backwards
If you supply a second index value that is lower than the first, the string is returned in reverse:
PS > 'Hello World'[4..0] -join ''
olleH
From End
If you use negative numbers you can refer to a position from the end of the string. To extract 'World'
, the last 5 letters, we use:
PS > 'Hello World'[-5..-1] -join ''
World
if false
then
...code...
fi
false
always returns false so this will always skip the code.
I found this maven
repo where you could download from directly a zip
file containing all the jars you need.
The solution I prefer is using Maven
, it is easy and you don't have to download each jar
alone. You can do it with the following steps:
Create an empty folder anywhere with any name you prefer, for example spring-source
Create a new file named pom.xml
Copy the xml below into this file
Open the spring-source
folder in your console
Run mvn install
After download finished, you'll find spring jars in /spring-source/target/dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-source-download</groupId>
<artifactId>SpringDependencies</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>download-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Also, if you need to download any other spring project, just copy the dependency
configuration from its corresponding web page.
For example, if you want to download Spring Web Flow
jars, go to its web page, and add its dependency
configuration to the pom.xml
dependencies
, then run mvn install
again.
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000
This should give you the milliseconds from the beginning of the day.
(Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000)/1000
This should give you seconds.
(Date.now()-(Date.now()/1000/60/60/24|0)*24*60*60*1000)/1000
Same as previous except uses a bitwise operator to floor the amount of days.
sometimes when programming recursivly, you call the function with the same parameters multiple times which is unnecassary.
The famous example Fibonacci numbers:
index: 1,2,3,4,5,6...
Fibonacci number: 1,1,2,3,5,8...
function F(n) {
if (n < 3)
return 1
else
return F(n-1) + F(n-2)
}
Let's run F(5):
F(5) = F(4) + F(3)
= {F(3)+F(2)} + {F(2)+F(1)}
= {[F(2)+F(1)]+1} + {1+1}
= 1+1+1+1+1
So we have called : 1 times F(4) 2 times F(3) 3 times F(2) 2 times F(1)
Dynamic Programming approach: if you call a function with the same parameter more than once, save the result into a variable to directly access it on next time. The iterative way:
if (n==1 || n==2)
return 1
else
f1=1, f2=1
for i=3 to n
f = f1 + f2
f1 = f2
f2 = f
Let's call F(5) again:
fibo1 = 1
fibo2 = 1
fibo3 = (fibo1 + fibo2) = 1 + 1 = 2
fibo4 = (fibo2 + fibo3) = 1 + 2 = 3
fibo5 = (fibo3 + fibo4) = 2 + 3 = 5
As you can see, whenever you need the multiple call you just access the corresponding variable to get the value instead of recalculating it.
By the way, dynamic programming doesn't mean to convert a recursive code into an iterative code. You can also save the subresults into a variable if you want a recursive code. In this case the technique is called memoization. For our example it looks like this:
// declare and initialize a dictionary
var dict = new Dictionary<int,int>();
for i=1 to n
dict[i] = -1
function F(n) {
if (n < 3)
return 1
else
{
if (dict[n] == -1)
dict[n] = F(n-1) + F(n-2)
return dict[n]
}
}
So the relationship to the Divide and Conquer is that D&D algorithms rely on recursion. And some versions of them has this "multiple function call with the same parameter issue." Search for "matrix chain multiplication" and "longest common subsequence" for such examples where DP is needed to improve the T(n) of D&D algo.
Ok, well it seems that you are confusing pass-by-reference with pass-by-value. Also, C and C++ are different languages. C doesn't support pass-by-reference.
Here are two C++ examples of pass by value:
// ex.1
int add(int a, int b)
{
return a + b;
}
// ex.2
void add(int a, int b, int *result)
{
*result = a + b;
}
void main()
{
int result = 0;
// ex.1
result = add(2,2); // result will be 4 after call
// ex.2
add(2,3,&result); // result will be 5 after call
}
When ex.1 is called, the constants 2
and 2
are passed into the function by making local copies of them on the stack. When the function returns, the stack is popped off and anything passed to the function on the stack is effectively gone.
The same thing happens in ex.2, except this time, a pointer to an int
variable is also passed on the stack. The function uses this pointer (which is simply a memory address) to dereference and change the value at that memory address in order to "return" the result. Since the function needs a memory address as a parameter, then we must supply it with one, which we do by using the &
"address-of" operator on the variable result
.
Here are two C++ examples of pass-by-reference:
// ex.3
int add(int &a, int &b)
{
return a+b;
}
// ex.4
void add(int &a, int &b, int &result)
{
result = a + b;
}
void main()
{
int result = 0;
// ex.3
result = add(2,2); // result = 2 after call
// ex.4
add(2,3,result); // result = 5 after call
}
Both of these functions have the same end result as the first two examples, but the difference is in how they are called, and how the compiler handles them.
First, lets clear up how pass-by-reference works. In pass-by-reference, generally the compiler implementation will use a "pointer" variable in the final executable in order to access the referenced variable, (or so seems to be the consensus) but this doesn't have to be true. Technically, the compiler can simply substitute the referenced variable's memory address directly, and I suspect this to be more true than generally believed. So, when using a reference, it could actually produce a more efficient executable, even if only slightly.
Next, obviously the way a function is called when using pass-by-reference is no different than pass-by-value, and the effect is that you have direct access to the original variables within the function. This has the result of encapsulation by hiding the implementation details from the caller. The downside is that you cannot change the passed in parameters without also changing the original variables outside of the function. In functions where you want the performance improvement from not having to copy large objects, but you don't want to modify the original object, then prefix the reference parameters with const
.
Lastly, you cannot change a reference after it has been made, unlike a pointer variable, and they must be initialized upon creation.
Hope I covered everything, and that it was all understandable.
Try this one -
WHERE DateDropped = 0
AND (
(ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0)
OR
(ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
)
You can define foreign key constraints on the tables with ON DELETE CASCADE
option.
Then deleting the record from parent table removes the records from child tables.
Check this link : http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
March 2014: Good news! Python 3.4 ships with Pip. Pip has long been Python's de-facto standard package manager. You can install a package like this:
pip install httpie
Wahey! This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup.
However, there remains a number of outstanding frustrations with the Python packaging experience. Cumulatively, they make Python very unwelcoming for newbies. Also, the long history of neglect (ie. not shipping with a package manager for 14 years from Python 2.0 to Python 3.3) did damage to the community. I describe both below.
It's important to understand that while experienced users are able to work around these frustrations, they are significant barriers to people new to Python. In fact, the difficulty and general user-unfriendliness is likely to deter many of them.
Every language with a package manager has an official (or quasi-official) repository for the community to download and publish packages. Python has the Python Package Index, PyPI. https://pypi.python.org/pypi
Let's compare its pages with those of RubyGems and Npm (the Node package manager).
rails
express
simplejson
You'll see the RubyGems and Npm pages both begin with a one-line description of the package, then large friendly instructions how to install it.
Meanwhile, woe to any hapless Python user who naively browses to PyPI. On https://pypi.python.org/pypi/simplejson/ , they'll find no such helpful instructions. There is however, a large green 'Download' link. It's not unreasonable to follow it. Aha, they click! Their browser downloads a .tar.gz
file. Many Windows users can't even open it, but if they persevere they may eventually extract it, then run setup.py
and eventually with the help of Google setup.py install
. Some will give up and reinvent the wheel..
Of course, all of this is wrong. The easiest way to install a package is with a Pip command. But PyPI didn't even mention Pip. Instead, it led them down an archaic and tedious path.
Numpy is one of Python's most popular libraries. Try to install it with Pip, you get this cryptic error message:
Error: Unable to find vcvarsall.bat
Trying to fix that is one of the most popular questions on Stack Overflow: "error: Unable to find vcvarsall.bat"
Few people succeed.
For comparison, in the same situation, Ruby prints this message, which explains what's going on and how to fix it:
Please update your PATH to include build tools or download the DevKit from http://rubyinstaller.org/downloads and follow the instructions at http://github.com/oneclick/rubyinstaller/wiki/Development-Kit
Ruby and Nodejs ship with full-featured package managers, Gem (since 2007) and Npm (since 2011), and have nurtured sharing communities centred around GitHub. Npm makes publishing packages as easy as installing them, it already has 64k packages. RubyGems lists 72k packages. The venerable Python package index lists only 41k.
Flying in the face of its "batteries included" motto, Python shipped without a package manager until 2014.
Until Pip, the de facto standard was a command easy_install
. It was woefully inadequate. The was no command to uninstall packages.
Pip was a massive improvement. It had most the features of Ruby's Gem. Unfortunately, Pip was--until recently--ironically difficult to install. In fact, the problem remains a top Python question on Stack Overflow: "How do I install pip on Windows?"
The simplest solutions are the best, so You just need:
var list = document.getElementById('list');_x000D_
while (list.firstChild) {_x000D_
list.removeChild(list.firstChild);_x000D_
}
_x000D_
<select id="list">_x000D_
<option value="0">0</option>_x000D_
<option value="1">1</option>_x000D_
</select>
_x000D_
There are basically two ways
store the previous value of window.onload
so your code can call a previous handler if present before or after your code executes
using the addEventListener
approach (that of course Microsoft doesn't like and requires you to use another different name).
The second method will give you a bit more safety if another script wants to use window.onload
and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.
Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.
what about this:
divH = divW = 0;
jQuery(document).ready(function(){
divW = jQuery("div").width();
divH = jQuery("div").height();
});
function checkResize(){
var w = jQuery("div").width();
var h = jQuery("div").height();
if (w != divW || h != divH) {
/*what ever*/
divH = h;
divW = w;
}
}
jQuery(window).resize(checkResize);
var timer = setInterval(checkResize, 1000);
BTW I suggest you to add an id to the div and change the $("div") to $("#yourid"), it's gonna be faster, and it won't break when later you add other divs
You have an extra closing }
in your function.
var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
nav[i].addEventListener('click',function(){
console.log('haha');
} // <== remove this brace
}, false);
};
You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.
You can retrieve all elements having the 'active' class using the following:
$('.active')
Checking wether or not there are any would, i belief, be with
if($('.active').length > 0)
{
// code
}
You may try adding an additional argument of type HttpServletRequest
to the getUrlValue()
method:
@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
String test = request.getRequestURI();
return test;
}
the best way to concat props/variables:
var sample = "test";
var result = `this is just a ${sample}`;
//this is just a test
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
Using dlpyr::mutate
and forcats::fct_recode
:
library(dplyr)
library(forcats)
iris <- iris %>%
mutate(Species = fct_recode(Species,
"Virginica" = "virginica",
"Versicolor" = "versicolor"
))
iris %>%
count(Species)
# A tibble: 3 x 2
Species n
<fctr> <int>
1 setosa 50
2 Versicolor 50
3 Virginica 50
C99 requires that when a/b
is representable:
(a/b) * b
+ a%b
shall equal a
This makes sense, logically. Right?
Let's see what this leads to:
Example A. 5/(-3)
is -1
=> (-1) * (-3)
+ 5%(-3)
= 5
This can only happen if 5%(-3)
is 2.
Example B. (-5)/3
is -1
=> (-1) * 3
+ (-5)%3
= -5
This can only happen if (-5)%3
is -2
$this->db->where('`id` IN (SELECT `someId` FROM `anotherTable` WHERE `someCondition`='condition')', NULL, FALSE);
htmlspecialchars
may be used:
When there is no need to encode all characters which have their HTML equivalents.
If you know that the page encoding match the text special symbols, why would you use htmlentities
? htmlspecialchars
is much straightforward, and produce less code to send to the client.
For example:
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.
When the data will be processed not only through a browser (to avoid decoding HTML entities),
If the output is XML (see the answer by Artefacto).
The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:
SELECT *
FROM server1table
INNER JOIN server2.database.dbo.server2table ON .....
Click here for a tutorial and working example from my website.
You no longer need to use hacks just to look jQuery Mobile Screen Orientation nor should you use PhoneGap anymore, unless you're actually using PhoneGap.
To make this work in the year 2015 we need:
And one of these plugins depending on your Cordova version:
cordova plugin add net.yoik.cordova.plugins.screenorientation
cordova plugin add cordova-plugin-screen-orientation
And to lock screen orientation just use this function:
screen.lockOrientation('landscape');
To unlock it:
screen.unlockOrientation();
Possible orientations:
portrait-primary The orientation is in the primary portrait mode.
portrait-secondary The orientation is in the secondary portrait mode.
landscape-primary The orientation is in the primary landscape mode.
landscape-secondary The orientation is in the secondary landscape mode.
portrait The orientation is either portrait-primary or portrait-secondary (sensor).
landscape The orientation is either landscape-primary or landscape-secondary (sensor).
The only way to really protect your php-applications from other, is to not share the source code. If you post you code somewhere online, or send it to you customers by some medium, other people than you have access to the code.
You could add an unique watermark to every single copy of your code. That way you can trace leaks back to a singe customer. (But will that help you, since the code already are outside of your control?)
Most code I see comes with a licence and maybe a warranty. A line at the top of the script telling people not to alter the script, will maybe be enought. Self; when I find non-open source code, I won't use it in my projects. Maybe I'm a bit dupe, but I expect ppl not to use my none-OSS code!
As @Clarke said, you can use java.io.FilenameFilter
to filter the file by specific condition.
As a complementary, I'd like to show how to use java.io.FilenameFilter
to search file in current directory and its subdirectory.
The common methods getTargetFiles and printFiles are used to search files and print them.
public class SearchFiles {
//It's used in dfs
private Map<String, Boolean> map = new HashMap<String, Boolean>();
private File root;
public SearchFiles(File root){
this.root = root;
}
/**
* List eligible files on current path
* @param directory
* The directory to be searched
* @return
* Eligible files
*/
private String[] getTargetFiles(File directory){
if(directory == null){
return null;
}
String[] files = directory.list(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.startsWith("Temp") && name.endsWith(".txt");
}
});
return files;
}
/**
* Print all eligible files
*/
private void printFiles(String[] targets){
for(String target: targets){
System.out.println(target);
}
}
}
I will demo how to use recursive, bfs and dfs to get the job done.
Recursive:
/**
* How many files in the parent directory and its subdirectory <br>
* depends on how many files in each subdirectory and their subdirectory
*/
private void recursive(File path){
printFiles(getTargetFiles(path));
for(File file: path.listFiles()){
if(file.isDirectory()){
recursive(file);
}
}
if(path.isDirectory()){
printFiles(getTargetFiles(path));
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.recursive(searcher.root);
}
Breadth First Search:
/**
* Search the node's neighbors firstly before moving to the next level neighbors
*/
private void bfs(){
if(root == null){
return;
}
Queue<File> queue = new LinkedList<File>();
queue.add(root);
while(!queue.isEmpty()){
File node = queue.remove();
printFiles(getTargetFiles(node));
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs != null){
for(File child: childs){
queue.add(child);
}
}
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.bfs();
}
Depth First Search:
/**
* Search as far as possible along each branch before backtracking
*/
private void dfs(){
if(root == null){
return;
}
Stack<File> stack = new Stack<File>();
stack.push(root);
map.put(root.getAbsolutePath(), true);
while(!stack.isEmpty()){
File node = stack.peek();
File child = getUnvisitedChild(node);
if(child != null){
stack.push(child);
printFiles(getTargetFiles(child));
map.put(child.getAbsolutePath(), true);
}else{
stack.pop();
}
}
}
/**
* Get unvisited node of the node
*
*/
private File getUnvisitedChild(File node){
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs == null){
return null;
}
for(File child: childs){
if(map.containsKey(child.getAbsolutePath()) == false){
map.put(child.getAbsolutePath(), false);
}
if(map.get(child.getAbsolutePath()) == false){
return child;
}
}
return null;
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.dfs();
}
There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-
var person = new Object();
person.name = "Anand",
person.getName = function(){
return this.name ;
};
var person = {
name : "Anand",
getName : function (){
return this.name
}
}
function Person(name){
this.name = name
this.getName = function(){
return this.name
}
}
function Person(){};
Person.prototype.name = "Anand";
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name
}
var person = new function(){
this.name = "Anand"
}
You can try it on console, if you have any confusion.
.
matches any character. Used in conjunction with the curly braces already mentioned:
$: cat > test
========
============================
oo
ooooooooooooooooooooooo
$: grep -E '(.)\1{10}' test
============================
ooooooooooooooooooooooo
I needed the ability to display quite a bit of info (without a tooltip) and it turned out quite nice. I used FullCalendars title
prop to store all my HTML. The only thing you have to do to ensure it works after render is to parse the title fields HTML.
// `data` ismy JSON object.
$.each(data, function(index, value) {
value.title = '<div class="title">' + value.title + '</div>';
value.title += '<div class="deets"><span class="time"><img src="/themes/custom/bp/images/clock.svg">' + value.start_time + ' - ' + value.end_time + '</span>';
value.title += '<span class="location"><img src="/themes/custom/bp/images/pin.svg">' + value.location + '</span></div>';
value.title += '<div class="learn-more">LEARN MORE <span class="arrow"></span></span>';
});
// Initialize the calendar object.
calendar = new FullCalendar.Calendar(cal, {
events: data,
plugins: ['dayGrid'],
eventRender: function(event) {
// This is required to parse the HTML.
const title = $(event.el).find('.fc-title');
title.html(title.text());
}
});
calendar.render();
I would have used template literals, but had to support IE11
try
{
//Handle the alert pop-up using seithTO alert statement
Alert alert = driver.switchTo().alert();
//Print alert is present
System.out.println("Alert is present");
//get the message which is present on pop-up
String message = alert.getText();
//print the pop-up message
System.out.println(message);
alert.sendKeys("");
//Click on OK button on pop-up
alert.accept();
}
catch (NoAlertPresentException e)
{
//if alert is not present print message
System.out.println("alert is not present");
}
Specifying a default value would also work, assuming a default value is appropriate.
Try to look at the following link: Python | change text color in shell
Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines
In general solution is to use ANSI codes while printing your string.
There is a solution that performs exactly what you need.
If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.
In your case, Var1
is considered as a local variable, and it's used before being set, thus the error.
To solve this problem, you can explicitly say it's a global by putting global Var1
in you function.
Var1 = 1
Var2 = 0
def function():
global Var1
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
Edit:
Ok, I understand your confusion so let me elaborate:
Case 1:
if (myDict.Contains(someKey))
someVal = myDict[someKey];
In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it
Case 2:
myDict.TryGetValue(somekey, out someVal)
In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.
Consider this situation: A sloppy API accepts GET requests like:
http://www.example.com/api?apikey=abcdef123456&action=deleteCategory&id=1
In some settings, when you request this URL and if there is an error/warning regarding the request, this whole line gets logged in the log file. Worse yet: if you forget to disable error messages in the production server, this information is just displayed in plain in the browser! Now you've just given your API key away to everyone.
Unfortunately, there are real API's working this way.
I wouldn't like the idea of having some sensitive info in the logs or displaying them in the browser. POST and GET is not the same. Use each where appropriate.
The SimpleDateFormat class allows you to parse a String
into a java.util.Date
object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime()
.
The full example:
String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();
Note that this gives you a long
and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat
class has tons on information on how to set it up to parse different formats.
Try this
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '03:30:00')
You can do this easily manually for each column like this:
df['A_perc'] = df['A']/df['sum']
If you want to do this in one step for all columns, you can use the div
method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):
ds.div(ds['sum'], axis=0)
And if you want this in one step added to the same dataframe:
>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
A B C D sum A_perc B_perc \
1 0.151722 0.935917 1.033526 0.941962 3.063127 0.049532 0.305543
2 0.033761 1.087302 1.110695 1.401260 3.633017 0.009293 0.299283
3 0.761368 0.484268 0.026837 1.276130 2.548603 0.298739 0.190013
C_perc D_perc sum_perc
1 0.337409 0.307517 1
2 0.305722 0.385701 1
3 0.010530 0.500718 1
If running a linux server, make sure that your IPTABLES configuration is correct.
Execute sudo iptables -L -n
, you will recieve a listing of your open ports. If there is not an Iptables Rule to open the port serving the fcgi script you will receive a 502 error. The Iptables Rule which opens the correct port must be listed before any rule which categorically rejects all packets (i.e. a rule of the form "REJECT ALL -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
or similar)
On my configuration, to properly open the port, I had to execute this command (assume my fcgi server is running at port 4567):
sudo iptables -I INPUT 1 -p tcp --dport 4567 -j ACCEPT
WARNING: This will open port 4567 to the whole world.
So it might be better to do something like this:
sudo iptables-save >> backup.iptables
sudo iptables -D INPUT 1 #Delete the previously entered rule
sudo iptables -I INPUT 1 -p tcp --dport 8080 -s localhost -j ACCEPT # Add new rule
Doing this removed the 502 error for me.
It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.
I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n
might need to be added. This list of characters is not authoritative, but I believe it covers everything else.
I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp
commands.
It can likely be implemented as a shell function as well
I therefore present escapify.c
. I use it like so:
scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c
PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char c='\0';
int i=0;
int j=1;
/* do not care if no args passed; escaped nothing is still nothing. */
if(argc < 2)
{
return 0;
}
while(j<argc)
{
while(i<strlen(argv[j]))
{
c=argv[j][i];
/* this switch has no breaks on purpose. */
switch(c)
{
case ';':
case '\'':
case ' ':
case '!':
case '"':
case '#':
case '$':
case '&':
case '(':
case ')':
case '|':
case '*':
case ',':
case '<':
case '>':
case '[':
case ']':
case '\\':
case '^':
case '`':
case '{':
case '}':
putchar('\\');
default:
putchar(c);
}
i++;
}
j++;
if(j<argc) {
putchar(' ');
}
i=0;
}
/* newline at end */
putchar ('\n');
return 0;
}
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
I faced the same issue but, in my case, I had only to point my project to a JDK instead of the JRE in the build path then it solved the issue and I was able to import all maven dependencies with no problem!
You set the style per element and not by its content:
function init() {
document.getElementById("about").style.color = 'blue';
}
With innerHTML
you get/set the content of an element. So if you would want to modify your title, innerHTML
would be the way to go.
In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style
property of the element itself.
For example for 3.6 version type py -3.6
.
If you have also 32bit and 64bit versions, you can just type py -3.6-64
or py -3.6-32
.
Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.
You can give the field name when calling that function:
max_rated_entry = YourModel.objects.latest('rating')
return max_rated_entry.details
Or you can already give that field name in your models meta data:
from django.db import models
class YourModel(models.Model):
#your class definition
class Meta:
get_latest_by = 'rating'
Now you can call 'latest()' without any parameters:
max_rated_entry = YourModel.objects.latest()
return max_rated_entry.details
I created my markup to insert as a string since it's less code and easier to read than working with the fancy dom stuff.
Then I made it innerHTML of a temporary element just so I could take the one and only child of that element and attach to the body.
var html = '<div>';
html += 'Hello div!';
html += '</div>';
var tempElement = document.createElement('div');
tempElement.innerHTML = html;
document.getElementsByTagName('body')[0].appendChild(tempElement.firstChild);
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.
A lot of answers have been given, but id like to add to them.
If you need the week to display as a year/week style (ex. 1953 - week 53 of 2019, 2001 - week 1 of 2020 etc.), you can do this:
import datetime
year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)
It will take the current year and week, and long_week_num in the day of writing this will be:
>>> 2006
Supposing your content is inside a string named mystring
...
You can use:
@Html.Raw(mystring)
Alternatively you can convert your string to HtmlString
or any other type that implements IHtmlString
in model or directly inline and use regular @
:
@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString
I would recommend checking out Gabor Grothendieck's sqldf package, which allows you to express these operations in SQL.
library(sqldf)
## inner join
df3 <- sqldf("SELECT CustomerId, Product, State
FROM df1
JOIN df2 USING(CustomerID)")
## left join (substitute 'right' for right join)
df4 <- sqldf("SELECT CustomerId, Product, State
FROM df1
LEFT JOIN df2 USING(CustomerID)")
I find the SQL syntax to be simpler and more natural than its R equivalent (but this may just reflect my RDBMS bias).
See Gabor's sqldf GitHub for more information on joins.
Here is a simple demo to create customview (compoundview) by inflating from xml
attrs.xml
<resources>
<declare-styleable name="CustomView">
<attr format="string" name="text"/>
<attr format="reference" name="image"/>
</declare-styleable>
</resources>
CustomView.kt
class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
ConstraintLayout(context, attrs, defStyleAttr) {
init {
init(attrs)
}
private fun init(attrs: AttributeSet?) {
View.inflate(context, R.layout.custom_layout, this)
val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
try {
val text = ta.getString(R.styleable.CustomView_text)
val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
if (drawableId != 0) {
val drawable = AppCompatResources.getDrawable(context, drawableId)
image_thumb.setImageDrawable(drawable)
}
text_title.text = text
} finally {
ta.recycle()
}
}
}
custom_layout.xml
We should use merge
here instead of ConstraintLayout
because
If we use ConstraintLayout
here, layout hierarchy will be ConstraintLayout
->ConstraintLayout
-> ImageView
+ TextView
=> we have 1 redundant ConstraintLayout
=> not very good for performance
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:parentTag="android.support.constraint.ConstraintLayout">
<ImageView
android:id="@+id/image_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="ContentDescription"
tools:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="@id/image_thumb"
app:layout_constraintStart_toStartOf="@id/image_thumb"
app:layout_constraintTop_toBottomOf="@id/image_thumb"
tools:text="Text" />
</merge>
Using activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f00"
app:image="@drawable/ic_android"
app:text="Android" />
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0f0"
app:image="@drawable/ic_adb"
app:text="ADB" />
</LinearLayout>
Result
In C, \0
denotes a character with value zero. The following are identical:
char a = 0;
char b = '\0';
The utility of this escape sequence is greater inside string literals, which are arrays of characters:
char arr[] = "abc\0def\0ghi\0";
(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)
In Swift 4 tableview add, swipe to delete UITableViewCell
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in
// delete item at indexPath
}
return [delete]
}
If you have imported the project, you may have to re-import it the proper way.
Steps :
Tested on AndroidStudio version 1.0.1
You could add a span before the link with a specific class like so:
<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>
And then give that a specific width and a background image just like you are doing with the button itself.
.btn span.icon {
background: url(imgs/icon.png) no-repeat;
float: left;
width: 10px;
height: 40px;
}
I am no CSS guru but off the top of my head I think that should work.
We need to wait for view will be drawn. For this purpose use OnPreDrawListener. Kotlin example:
val preDrawListener = object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
view.viewTreeObserver.removeOnPreDrawListener(this)
// code which requires view size parameters
return true
}
}
view.viewTreeObserver.addOnPreDrawListener(preDrawListener)
:g/^\s*$/d
^ begin of a line
\s* at least 0 spaces and as many as possible (greedy)
$ end of a line
paste
:command -range=% DBL :<line1>,<line2>g/^\s*$/d
in your .vimrc,then restart your vim. if you use command :5,12DBL it will delete all blank lines between 5th row and 12th row. I think my answer is the best answer!
If you use ng > 1.2, here is an example of using ng-repeat-start/end
without generating unnecessary tags:
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script>_x000D_
angular.module('mApp', []);_x000D_
</script>_x000D_
</head>_x000D_
<body ng-app="mApp">_x000D_
<table border="1" width="100%">_x000D_
<tr ng-if="0" ng-repeat-start="elem in [{k: 'A', v: ['a1','a2']}, {k: 'B', v: ['b1']}, {k: 'C', v: ['c1','c2','c3']}]"></tr>_x000D_
_x000D_
<tr>_x000D_
<td rowspan="{{elem.v.length}}">{{elem.k}}</td>_x000D_
<td>{{elem.v[0]}}</td>_x000D_
</tr>_x000D_
<tr ng-repeat="v in elem.v" ng-if="!$first">_x000D_
<td>{{v}}</td>_x000D_
</tr>_x000D_
_x000D_
<tr ng-if="0" ng-repeat-end></tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
The important point: for tags used for ng-repeat-start
and ng-repeat-end
set ng-if="0"
, to let not be inserted in the page. In this way the inner content will be handled exactly as it is in knockoutjs (using commands in <!--...-->
), and there will be no garbage.
In the form closest to your original:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return now
If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime
, use this instead:
return (now - datetime.datetime(1970, 1, 1)).total_seconds()
Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:
utc_now = datetime.datetime.utcnow
Removing double-quotes
solve my problem, now its:
DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug
You use:
yourcommand > /dev/null 2>&1
If it should run in the Background add an &
yourcommand > /dev/null 2>&1 &
>/dev/null 2>&1
means redirect stdout
to /dev/null
AND stderr
to the place where stdout
points at that time
If you want stderr
to occur on console and only stdout
going to /dev/null
you can use:
yourcommand 2>&1 > /dev/null
In this case stderr
is redirected to stdout
(e.g. your console) and afterwards the original stdout
is redirected to /dev/null
If the program should not terminate you can use:
nohup yourcommand &
Without any parameter all output lands in nohup.out
You can use split() to get string array from comma separated string. If you iterate and perform mathematical operation on element of string array then that element will be treated as number by run-time cast but still you have string array. To convert comma separated string int array see the edit.
arr = strVale.split(',');
var strVale = "130,235,342,124";
arr = strVale.split(',');
for(i=0; i < arr.length; i++)
console.log(arr[i] + " * 2 = " + (arr[i])*2);
Output
130 * 2 = 260
235 * 2 = 470
342 * 2 = 684
124 * 2 = 248
Edit, Comma separated string to int Array In the above example the string are casted to numbers in expression but to get the int array from string array you need to convert it to number.
var strVale = "130,235,342,124";
var strArr = strVale.split(',');
var intArr = [];
for(i=0; i < strArr.length; i++)
intArr.push(parseInt(strArr[i]));
I had same issue. No need to re install.
In Netbeans 6.0 , Find RunTime -> Servers - > Add server -> select Tomcat install 'root' directory
In Netbeans 7.x -> Tools -> Servers-> Add server -> select Tomcat install 'root' directory
Here is in Netbeans Wiki.
Your browser options must be set to open new windows in a new tab, otherwise a new browser window is opened.
Here you go:
data = []
table = soup.find('table', attrs={'class':'lineItemsTable'})
table_body = table.find('tbody')
rows = table_body.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele]) # Get rid of empty values
This gives you:
[ [u'1359711259', u'SRF', u'08/05/2013', u'5310 4 AVE', u'K', u'19', u'125.00', u'$'],
[u'7086775850', u'PAS', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'125.00', u'$'],
[u'7355010165', u'OMT', u'12/14/2013', u'3908 6th Ave', u'K', u'40', u'145.00', u'$'],
[u'4002488755', u'OMT', u'02/12/2014', u'NB 1ST AVE @ E 23RD ST', u'5', u'115.00', u'$'],
[u'7913806837', u'OMT', u'03/03/2014', u'5015 4th Ave', u'K', u'46', u'115.00', u'$'],
[u'5080015366', u'OMT', u'03/10/2014', u'EB 65TH ST @ 16TH AV E', u'7', u'50.00', u'$'],
[u'7208770670', u'OMT', u'04/08/2014', u'333 15th St', u'K', u'70', u'65.00', u'$'],
[u'$0.00\n\n\nPayment Amount:']
]
Couple of things to note:
You can start reading from here jQuery.ajax()
Actually Controller Action is a public method which can be accessed through Url. So any call of an Action from an Ajax call, either MicrosoftMvcAjax or jQuery can be made. For me, jQuery is the simplest one. It got a lots of examples in the link I gave above. The typical example for an ajax call is like this.
$.ajax({
// edit to add steve's suggestion.
//url: "/ControllerName/ActionName",
url: '<%= Url.Action("ActionName", "ControllerName") %>',
success: function(data) {
// your data could be a View or Json or what ever you returned in your action method
// parse your data here
alert(data);
}
});
More examples can be found in here
try this:
key=key.replace(/ /g,"_");
that'll do a global find/replace
The problem is when we have incoming changes that will merge untracked file, git complains. These commands helped me:
git clean -dxf
git pull origin master
On Linux or Mac, keep is simple and just use sed with the shell. No external libraries required. The following code works on Linux.
const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)
The sed syntax is a little different on Mac. I can't test it right now, but I believe you just need to add an empty string after the "-i":
const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)
The "g" after the final "!" makes sed replace all instances on a line. Remove it, and only the first occurrence per line will be replaced.
files directory:
Project->
-functions.php
-main.php
functions.php
function sum(a,b){
return a+b;
}
function product(a,b){
return a*b;
}
main.php
require_once "functions.php";
echo "sum of two numbers ". sum(4,2);
echo "<br>"; // create break line
echo "product of two numbers ".product(2,3);
The Output Is :
sum of two numbers 6 product of two numbers 6
Note: don't write public before function. Public, private, these modifiers can only use when you create class.
This seems a lot cleaner than the answer above...
<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
</script>
<table id="theTable">
<tr>
<td>id</td>
<td>name</td>
</tr>
<tr id="templateRow" style="display:none">
<td>{id}</td>
<td><input /></td>
</tr>
</table>
<button onclick="addRow();">Go</button>
Execute these commands in the terminal (excluding the lines with hashtags - they're comments):
# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*
If you would like to delete all projects:
rm -Rf ~/AndroidStudioProjects
To remove gradle related files (caches & wrapper)
rm -Rf ~/.gradle
Use the below command to delete all Android Virtual Devices(AVDs) and keystores.
Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)
rm -Rf ~/.android
To delete Android SDK tools
rm -Rf ~/Library/Android*
Emulator Console Auth Token
rm -Rf ~/.emulator_console_auth_token
Thanks to those who commented/improved on this answer!
rm
are case-sensitive1 (as with most other commands), which means that the f
flag must be in lower case. However, the r
flag can also be capitalised.rm
can be either combined together or separated. They don't have to be combined.r
flag indicates that the rm
command should-
attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
f
flag indicates that the rm
command should-
attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for
rm
(Seeman rm
for more info)
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
Just to add to the fix craze, putting {border:1px solid #???} around the badly looking object fixes the issue for me. In case you have a stable background colour, consider this too. This is so dumb noone thought about mentioning I guess, eh eh.
WHERE something IS NULL
and
WHERE something IS NOT NULL
HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();
public synchronized void addToList(String mapKey, Item myItem) {
List<Item> itemsList = items.get(mapKey);
// if list does not exist create it
if(itemsList == null) {
itemsList = new ArrayList<Item>();
itemsList.add(myItem);
items.put(mapKey, itemsList);
} else {
// add if item is not already in list
if(!itemsList.contains(myItem)) itemsList.add(myItem);
}
}
Using @angular/forms
when you use a <form>
tag it automatically creates a FormGroup
.
For every contained ngModel
tagged <input>
it will create a FormControl
and add it into the FormGroup
created above; this FormControl
will be named into the FormGroup
using attribute name
.
Example:
<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
<span>{{ f.controls['firstField']?.value }}</span>
</form>
Said this, the answer to your question follows.
When you mark it as standalone: true
this will not happen (it will not be added to the FormGroup
).
Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474
i know a way ny which you can call you private function to test in mockito
@Test
public void commandEndHandlerTest() throws Exception
{
Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
retryClientDetail_privateMethod.setAccessible(true);
retryClientDetail_privateMethod.invoke(yourclass.class, null);
}
When using promises they can be used in a promise chain. async=false will be deprecated so using promises is your best option.
function functABC() {
return new Promise(function(resolve, reject) {
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
resolve(data) // Resolve promise and go to then()
},
error: function(err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
functABC().then(function(data) {
// Run this when your request was successful
console.log(data)
}).catch(function(err) {
// Run this when promise was rejected via reject()
console.log(err)
})
This structure (function() {})();
is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:
(function($) {
// do something
})(jQuery);
this means, that the interpreter will invoke the function immediately, and will pass jQuery
as a parameter, which will be used inside the function as $
.
I'm leaving the below post for reference purposes.
Please read Apple's documentation Human Interface Guidelines - Launch Screens for details on launch screens and recommendations.
Thanks
Drekka
July 2012 - As this reply is rather old, but stills seems popular. I've written a blog post based on Apple's doco and placed it on my blog. I hope you guys find it useful.
Yes. In iPhone/iPad development the Default.png
file is displayed by the device automatically so you don't have to program it which is really useful. I don't have it with me, but you need different PNGs for the iPad with specific names. I googled iPad default png
and got this info from the phunkwerks site:
To deal with various orientation options, a new naming convention has been created for iPad launch images. The screen size of the iPad is 768×1024, notice in the dimensions that follow the height takes into account a 20 pixel status bar.
Default-Portrait.png
* — 768w x 1024hDefault-PortraitUpsideDown.png
— 768w x 1024hDefault-Landscape.png
** — 1024w x 748hDefault-LandscapeLeft.png
— 1024w x 748hDefault-LandscapeRight.png
— 1024w x 748hiPad-Retina–Portrait.png
— 1536w x 2048hiPad-Retina–Landscape.png
— 2048w x 1496hDefault.png
— Not recommended*—If you have not specified a Default-PortraitUpsideDown.png
file, this file will take precedence.
**—If you have not specified a Default-LandscapeLeft.png
or Default-LandscapeRight.png
image file, this file will take precedence.
This link to "Apple's Developer Library" is useful, too.
If someone needs to remove undefined
values from an object with deep search using lodash
then here is the code that I'm using. It's quite simple to modify it to remove all empty values (null
/undefined
).
function omitUndefinedDeep(obj) {
return _.reduce(obj, function(result, value, key) {
if (_.isObject(value)) {
result[key] = omitUndefinedDeep(value);
}
else if (!_.isUndefined(value)) {
result[key] = value;
}
return result;
}, {});
}
For those who didn't know already, you would have to put the declare
statement outside your class
just like this:
declare var Chart: any;
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent {
//you can use Chart now and compiler wont complain
private color = Chart.color;
}
In TypeScript
the declare keyword is used where you want to define a variable that may not have originated from a TypeScript
file.
It is like you tell the compiler that, I know this variable will have a value at runtime, so don't throw a compilation error.
It would be awesome if someone also knows the steps for setting this up in Eclipse (I assume it's as simple as setting up an annotation processor, but you never know)
Yes it is. Here are the implementations and instructions for the various JPA 2.0 implementations:
org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor
org.apache.openjpa.persistence.meta.AnnotationProcessor6
org.datanucleus.jpa.JPACriteriaProcessor
The latest Hibernate implementation is available at:
An older Hibernate implementation is at:
Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:
C#:
private void Page_Load(object sender, EventArgs e)
{
SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
}
Note: Ensure you don't set AutoEventWireup="false" in page header.
VB:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
End Sub
Note that time.gmtime
maps timestamp 0
to 1970-1-1 00:00:00
.
In [61]: import time
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
time.mktime(time.gmtime(0))
gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.
In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0
The inverse of time.gmtime
is calendar.timegm
:
In [62]: import calendar
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0
You can use something like this (C#):
driver.Manage().Window.Size = new Size(1024, 768);
public static String setPrecision(String number, int decimal) {
double nbr = Double.valueOf(number);
int integer_Part = (int) nbr;
double float_Part = nbr - integer_Part;
int floating_point = (int) (Math.pow(10, decimal) * float_Part);
String final_nbr = String.valueOf(integer_Part) + "." + String.valueOf(floating_point);
return final_nbr;
}
Email: {
group: '.col-sm-3',
enabled: false,
validators: {
//emailAddress: {
// message: 'Email not Valid'
//},
regexp: {
regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
message: 'Email not Valid'
},
}
},
Here are a couple methods I use without the need of Jquery:
You can encode every character in your string:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
Or just target the main safe encoding characters to worry about (&, inebreaks, <, >, " and ') like:
function encode(r){_x000D_
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})_x000D_
}_x000D_
_x000D_
test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');_x000D_
_x000D_
/*************_x000D_
* \x26 is &ersand (it has to be first),_x000D_
* \x0A is newline,_x000D_
*************/
_x000D_
<textarea id=test rows="9" cols="55">www.WHAK.com</textarea>
_x000D_
You can also use:
img{
filter:grayscale(100%);
}
img:hover{
filter:none;
}
The right combination of Windows SDK Version and Platform Toolset needs to be selected Depends of course what toolset you have currently installed
in spring boot 2.2.5
after adding getter and setter
i added @JsonIgnore on top of the field.
I tried trim(). It works well with white spaces as well as the '\n'.
x = '\n Harden, J.\n '
trim(x)
Calling .html()
serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
});
var parent = $('<tr><td></td></tr>').children().append(test).end();
$("#addNodeTable tr:last").before(parent);
});
Or,
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
}).wrap('<tr><td></td></tr>').closest('tr');
$("#addNodeTable tr:last").before(test);
});
If you don't like passing a map of properties to $()
, you can instead use
$('<button/>')
.text('Test')
.click(function () { alert('hi'); });
// or
$('<button>Test</button>').click(function () { alert('hi'); });
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
I spent days trying all the above answers and ensuring I had the proxy and other settings in my node config correct. All were and it was still failing. I was/am using a Windows 10 machine and behind a corp proxy.
For some legacy reason, I had HTTP_PROXY
and HTTPS_PROXY
set in my user environment variables which overrides the node ones (unknown to me), so correcting these (the HTTPS_PROXY
one was set to https, so I changed to HTTP) fixed the problem for me.
This is the problem when we can have the Same variables in Multiple places, you don't know what one is being used!
Starting with your data frame DF
, you could use the data.table
package:
library(data.table)
## EDIT: As suggested by @MichaelChirico, setDT converts a
## data.frame to a data.table by reference and is preferred
## if you don't mind losing the data.frame
setDT(DF)
# EDIT: To get the column name 'Mean':
DF[, .(Mean = rowMeans(.SD)), by = ID]
# ID Mean
# [1,] A 3.666667
# [2,] B 4.333333
# [3,] C 3.333333
# [4,] D 4.666667
# [5,] E 4.333333
You can use DataFrame.values
to get an numpy array of the data and then use NumPy functions such as argsort()
to get the most correlated pairs.
But if you want to do this in pandas, you can unstack
and sort the DataFrame:
import pandas as pd
import numpy as np
shape = (50, 4460)
data = np.random.normal(size=shape)
data[:, 1000] += data[:, 2000]
df = pd.DataFrame(data)
c = df.corr().abs()
s = c.unstack()
so = s.sort_values(kind="quicksort")
print so[-4470:-4460]
Here is the output:
2192 1522 0.636198
1522 2192 0.636198
3677 2027 0.641817
2027 3677 0.641817
242 130 0.646760
130 242 0.646760
1171 2733 0.670048
2733 1171 0.670048
1000 2000 0.742340
2000 1000 0.742340
dtype: float64
It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).
If it's a static array, you can sizeof it's size/the size of one element. For example:
int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);
Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.
Hope it helps.
Came cross same problem today. This is a mysql "Identifier Case Sensitivity" issue.
Please check corresponding data file. It is very likely that file name is in lower case on file system but table name listed in "show tables" command is in upper case. If system variable "lower_case_table_names
" is 0, the query will return "table not exist" because name comparisons are case sensitive when "lower_case_table_names
" is 0.
For renaming the columns here is the simple one which will work for both Default(0,1,2,etc;)
and existing columns but not much useful for a larger data sets(having many columns).
For a larger data set we can slice the columns that we need and apply the below code:
df.columns = ['new_name','new_name1','old_name']
For guys still coming around this thread:
For those using raw binary POST upload without encoding overhead you can use:
client:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload", true);
var blob = new Uint8Array([65,72,79,74]); // or e.g. recorder.getBlob()
xhr.send(blob);
server:
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.use (function(req, res, next) {
var data='';
req.setEncoding('binary');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
router.post('/api/upload', function(req, res, next) {
fs.writeFile("binaryFile.png", req.body, 'binary', function(err) {
res.send("Binary POST successful!");
});
});
Go to SQL command line:- type:
sql>connect / as sysdba;
then type:
sql>desc dba_users;
then type:
sql>select username,password from dba_users;
If sysdba
doesn't work then try connecting with username:scott and password: Tiger
You will be able to see all users with passwords. Probably you might find your's. Hope this helps
Here's a cute trick to deal with directories and make. Instead of using multiline strings, or "cd ;" on each command, define a simple chdir function as so:
CHDIR_SHELL := $(SHELL)
define chdir
$(eval _D=$(firstword $(1) $(@D)))
$(info $(MAKE): cd $(_D)) $(eval SHELL = cd $(_D); $(CHDIR_SHELL))
endef
Then all you have to do is call it in your rule as so:
all:
$(call chdir,some_dir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
You can even do the following:
some_dir/myTest:
$(call chdir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
Docker sets the hostname to the container ID by default, but users can override this with --hostname
. Instead, inspect /proc
:
$ more /proc/self/cgroup
14:name=systemd:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
13:pids:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
12:hugetlb:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
11:net_prio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
10:perf_event:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
9:net_cls:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
8:freezer:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
7:devices:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
6:memory:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
5:blkio:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
4:cpuacct:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
3:cpu:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
2:cpuset:/docker/7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
1:name=openrc:/docker
Here's a handy one-liner to extract the container ID:
$ grep "memory:/" < /proc/self/cgroup | sed 's|.*/||'
7be92808767a667f35c8505cbf40d14e931ef6db5b0210329cf193b15ba9d605
You may use str.isdigit()
and str.isalpha()
to check whether given string is positive integer and alphabet respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
As the Visual C# Program Manager linked above says, there are limited situations where the With statement is more efficient, the example he gives when it is being used as a shorthand to repeatedly access a complex expression.
Using an extension method and generics you can create something that is vaguely equivalent to a With statement, by adding something like this:
public static T With<T>(this T item, Action<T> action)
{
action(item);
return item;
}
Taking a simple example of how it could be used, using lambda syntax you can then use it to change something like this:
updateRoleFamily.RoleFamilyDescription = roleFamilyDescription;
updateRoleFamily.RoleFamilyCode = roleFamilyCode;
To this:
updateRoleFamily.With(rf =>
{
rf.RoleFamilyDescription = roleFamilyDescription;
rf.RoleFamilyCode = roleFamilyCode;
});
On an example like this, the only advantage is perhaps a nicer layout, but with a more complex reference and more properties, it could well give you more readable code.
The problem with your solution is you're putting a scrollbar around a ListBox where you probably want to put it inside the ListBox.
If you want to force a scrollbar in your ListBox, use the ScrollBar.VerticalScrollBarVisibility attached property.
<ListBox
ItemsSource="{Binding}"
ScrollViewer.VerticalScrollBarVisibility="Visible">
</ListBox>
Setting this value to Auto will popup the scrollbar on an as needed basis.
import codecs
import shutil
import sys
s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
sys.stdout.write(s)
shutil.copyfileobj(sys.stdin, sys.stdout)
Just type import pdb
in jupyter notebook, and then use this cheatsheet to debug. It's very convenient.
c
--> continue, s
--> step, b 12
--> set break point at line 12 and so on.
Some useful links: Python Official Document on pdb, Python pdb debugger examples for better understanding how to use the debugger commands.
I got this problem first: PM> add-migration first
No migrations configuration type was found in the assembly 'MyProjectName'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
then i tried this:
PM> Enable-Migrations No context type was found in the assembly 'MyProjectName'.
Then the right command for me :
PM> Enable-Migrations -ProjectName MyProjectName -ContextTypeName MyProjectName.Data.Context
After that i got this error message even though Context inherits from DbContext
The type 'Context' does not inherit from DbContext. The DbMigrationsConfiguration.ContextType property must be set to a type that inherits from DbContext.
Then i Installed Microsoft.EntityFrameworkCore.Tools
ITS OK NOW but the message is funny. i already tried add migrations at first :D
Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework6\Enable-Migrations' for Entity Framework 6. Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.
how to make transparent elements with css:
CSS for IE:
filter: alpha(opacity = 52);
CSS for other browsers:
opacity:0.52;
Use the git commit
command without any flags. The configured editor will open (Vim in this case):
To start typing press the INSERT key on your keyboard, then in insert mode create a better commit with description how do you want. For example:
Once you have written all that you need, to returns to git, first you should exit insert mode, for that press ESC. Now close the Vim editor with save changes by typing on the keyboard :wq
(w - write, q - quit):
and press ENTER.
On GitHub this commit will looks like this:
As a commit editor you can use VS Code:
git config --global core.editor "code --wait"
From VS Code docs website: VS Code as Git editor
Just for completeness and those unaware XSL 1 has choose for multiple conditions.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:when test="another-expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
A single line method within bash works like this.
[some out put] >$(date "+%Y.%m.%d-%H.%M.%S").ver
will create a file with a timestamp name with ver extension. A working file listing snap shot to a date stamp file name as follows can show it working.
find . -type f -exec ls -la {} \; | cut -d ' ' -f 6- >$(date "+%Y.%m.%d-%H.%M.%S").ver
Of course
cat somefile.log > $(date "+%Y.%m.%d-%H.%M.%S").ver
or even simpler
ls > $(date "+%Y.%m.%d-%H.%M.%S").ver
edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html
The book "TypeScript Revealed" says
"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:
// standard for loop
for (var i = 0; i < actors.length; i++)
{
console.log(actors[i]);
}
// for..in loop
for (var actor in actors)
{
console.log(actor);
}
"
Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.
map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:
this.notes = arr.map(state => new Note(state));
My wish list to TypeScript;
Turn if off:
You can use error_reporting();
or put an @ in front of your fileopen().
The code below creates a Documents directory and then a sub-directory for the application and saved the files to it.
public class loadDataTooDisk extends AsyncTask<String, Integer, String> {
String sdCardFileTxt;
@Override
protected String doInBackground(String... params)
{
//check to see if external storage is avalibel
checkState();
if(canW == canR == true)
{
//get the path to sdcard
File pathToExternalStorage = Environment.getExternalStorageDirectory();
//to this path add a new directory path and create new App dir (InstroList) in /documents Dir
File appDirectory = new File(pathToExternalStorage.getAbsolutePath() + "/documents/InstroList");
// have the object build the directory structure, if needed.
appDirectory.mkdirs();
//test to see if it is a Text file
if ( myNewFileName.endsWith(".txt") )
{
//Create a File for the output file data
File saveFilePath = new File (appDirectory, myNewFileName);
//Adds the textbox data to the file
try{
String newline = "\r\n";
FileOutputStream fos = new FileOutputStream (saveFilePath);
OutputStreamWriter OutDataWriter = new OutputStreamWriter(fos);
OutDataWriter.write(equipNo.getText() + newline);
// OutDataWriter.append(equipNo.getText() + newline);
OutDataWriter.append(equip_Type.getText() + newline);
OutDataWriter.append(equip_Make.getText()+ newline);
OutDataWriter.append(equipModel_No.getText()+ newline);
OutDataWriter.append(equip_Password.getText()+ newline);
OutDataWriter.append(equipWeb_Site.getText()+ newline);
//OutDataWriter.append(equipNotes.getText());
OutDataWriter.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
This one builds the file name
private String BuildNewFileName()
{ // creates a new filr name
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
StringBuilder sb = new StringBuilder();
sb.append(today.year + ""); // Year)
sb.append("_");
sb.append(today.monthDay + ""); // Day of the month (1-31)
sb.append("_");
sb.append(today.month + ""); // Month (0-11))
sb.append("_");
sb.append(today.format("%k:%M:%S")); // Current time
sb.append(".txt"); //Completed file name
myNewFileName = sb.toString();
//Replace (:) with (_)
myNewFileName = myNewFileName.replaceAll(":", "_");
return myNewFileName;
}
Hope this helps! It took me a long time to get it working.
There is actually a property for this in the CSS4 media query draft.
The ‘pointer’ media feature is used to query about the presence and accuracy of a pointing device such as a mouse. If a device has multiple input mechanisms, it is recommended that the UA reports the characteristics of the least capable pointing device of the primary input mechanisms. This media query takes the following values:
‘none’
- The input mechanism of the device does not include a pointing device.‘coarse’
- The input mechanism of the device includes a pointing device of limited accuracy.‘fine’
- The input mechanism of the device includes an accurate pointing device.
This would be used as such:
/* Make radio buttons and check boxes larger if we have an inaccurate pointing device */
@media (pointer:coarse) {
input[type="checkbox"], input[type="radio"] {
min-width:30px;
min-height:40px;
background:transparent;
}
}
I also found a ticket in the Chromium project related to this.
Browser compatibility can be tested at Quirksmode. These are my results (22 jan 2013):
Yet another solution for random colors:
function colorize(str) {
for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
color = Math.floor(Math.abs((Math.sin(hash) * 10000) % 1 * 16777216)).toString(16);
return '#' + Array(6 - color.length + 1).join('0') + color;
}
It's a mixed of things that does the job for me. I used JFreeman Hash function (also an answer in this thread) and Asykäri pseudo random function from here and some padding and math from myself.
I doubt the function produces evenly distributed colors, though it looks nice and does that what it should do.
You can open the project in the firebase, then you should click on the project overview, then goto project settings you will see the web API Key there.
You can use date
to get time and date of a day:
[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013
Also hwclock
would do:
[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST -0.516080 seconds
For customized output, you can either redirect the output of date
to something like awk
, or write your own program to do that.
Remember to put your own executable scripts/binary into your PATH
(e.g. /usr/bin) to make it invokable anywhere.
You can use ::after
to create a 0px
-height block after the <h4>
, which effectively moves anything after the <h4>
to the next line:
h4 {_x000D_
display: inline;_x000D_
}_x000D_
h4::after {_x000D_
content: "";_x000D_
display: block;_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
Text, text, text, text, text. <h4>Sub header</h4>_x000D_
Text, text, text, text, text._x000D_
</li>_x000D_
</ul>
_x000D_
IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.
Main.FragmentCallback FC= new Main.FragmentCallback(){
@Override
public void onTaskDone(String results) {
localText.setText(results); //example TextView
}
};
new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);
Remind: I used interface on the main activity thats where "Main" comes, like this:
public interface FragmentCallback {
public void onTaskDone(String results);
}
My API post execute looks like this:
@Override
protected void onPostExecute(String results) {
Log.i("TASK Result", results);
mFragmentCallback.onTaskDone(results);
}
The API constructor looks like this:
class API_CALL extends AsyncTask<String,Void,String> {
private Main.FragmentCallback mFragmentCallback;
private Context act;
private String method;
public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
act=ctx;
method=api_method;
mFragmentCallback = fragmentCallback;
}
for(int j=0;j<30;j++) {
LinearLayout childLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
childLayout.setLayoutParams(linearParams);
TextView mType = new TextView(MainActivity.this);
TextView mValue = new TextView(MainActivity.this);
mType.setLayoutParams(new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1f));
mValue.setLayoutParams(new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1f));
mType.setTextSize(17);
mType.setPadding(5, 3, 0, 3);
mType.setTypeface(Typeface.DEFAULT_BOLD);
mType.setGravity(Gravity.LEFT | Gravity.CENTER);
mValue.setTextSize(16);
mValue.setPadding(5, 3, 0, 3);
mValue.setTypeface(null, Typeface.ITALIC);
mValue.setGravity(Gravity.LEFT | Gravity.CENTER);
mType.setText("111");
mValue.setText("111");
childLayout.addView(mValue, 0);
childLayout.addView(mType, 0);
linear.addView(childLayout);
}
Corrected as of 25.06.2019:
var newDate = new Date(date.setMonth(date.getMonth()+8));
Old From here:
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009 = jan312009.setMonth(jan312009.getMonth()+8);
There's at least one situation in which you want sys.stdout
instead of print.
When you want to overwrite a line without going to the next line, for instance while drawing a progress bar or a status message, you need to loop over something like
Note carriage return-> "\rMy Status Message: %s" % progress
And since print adds a newline, you are better off using sys.stdout
.
The problem with the script is that the environment used for the script is not the same as the one used for your tests, so setting the environment variables there does nothing for your tests.
To properly set the variable you need to set it in Jenkins. Go to Manage Jenkins>Manage Nodes>Master>Configure. Check the Environment variables check box, then enter DISPLAY in the name box, and set the value to :1.0.
Additionally you'll need to set permissions, try disabling your xhost access controls using xhost +
in the terminal.
Your best bet is to use a JDialog instead of a JFrame if you want to make the window modal. Check out details on the introduction of the Modality API in Java 6 for info. There is also a tutorial.
Here is some sample code which will display a JPanel panel
in a JDialog
which is modal to Frame parentFrame
. Except for the constructor, this follows the same pattern as opening a JFrame
.
final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
Edit: updated Modality API link & added tutorial link (nod to @spork for the bump).
JAVA_HOME should be like this C:\PROGRA~1\Java\jdk
Hope this will work!
First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?
I think there is a workaround to make constructor private.
The following method is about 30 times faster than scipy.spatial.distance.pdist
. It works pretty quickly on large matrices (assuming you have enough RAM)
See below for a discussion of how to optimize for sparsity.
# base similarity matrix (all dot products)
# replace this with A.dot(A.T).toarray() for sparse representation
similarity = numpy.dot(A, A.T)
# squared magnitude of preference vectors (number of occurrences)
square_mag = numpy.diag(similarity)
# inverse squared magnitude
inv_square_mag = 1 / square_mag
# if it doesn't occur, set it's inverse magnitude to zero (instead of inf)
inv_square_mag[numpy.isinf(inv_square_mag)] = 0
# inverse of the magnitude
inv_mag = numpy.sqrt(inv_square_mag)
# cosine similarity (elementwise multiply by inverse magnitudes)
cosine = similarity * inv_mag
cosine = cosine.T * inv_mag
If your problem is typical for large scale binary preference problems, you have a lot more entries in one dimension than the other. Also, the short dimension is the one whose entries you want to calculate similarities between. Let's call this dimension the 'item' dimension.
If this is the case, list your 'items' in rows and create A
using scipy.sparse
. Then replace the first line as indicated.
If your problem is atypical you'll need more modifications. Those should be pretty straightforward replacements of basic numpy
operations with their scipy.sparse
equivalents.
Generally:
tmux kill-window -t window-number
So for example, if you are in window 1 and you want to kill window 9:
tmux kill-window -t 9
adbd
has a compilation flag/option to enable root access: ALLOW_ADBD_ROOT=1
.
Up to Android 9: If adbd
on your device is compiled without that flag, it will always drop privileges when starting up and thus "adb root" will not help at all.
I had to patch the calls to setuid()
, setgid()
, setgroups()
and the capability drops out of the binary myself to get a permanently rooted adbd on my ebook reader.
With Android 10 this changed; when the phone/tablet is unlocked (ro.boot.verifiedbootstate == "orange"
), then adb root mode is possible in any case.
The Oracle/PLSQL
CONCAT
function allows to concatenate two strings together.
CONCAT( string1, string2 )
string1
The first string to concatenate.
string2
The second string to concatenate.
E.g.
SELECT 'I like ' || type_column_name || ' cake with ' ||
icing_column_name || ' and a ' fruit_column_name || '.'
AS Cake FROM table;