In cell D2 and copied down:
=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))
The easiest way is probably with VLOOKUP()
. This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.
For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:
=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)
Then simply fill this formula down the rest of column D.
Explanation:
$D2
specifies the value to search for.Sheet2!$A$2:$B$65535
specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535
). Note I am assuming you have a header cell in row 1.2
specifies a 1-based index of the column to return from within the searched range. The value of 2
will return the second column in the range Sheet2!$A$2:$B$65535
, namely the value of the B
column.FALSE
says to only return exact matches.You can combine this all into one formula, but you need to use a regular IF
first to find out if the VLOOKUP
came back with something, then use your COUNTIF
if it did.
=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))
In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).
VLookup
You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4".
External Reference
To reference a cell of the same Workbook use the following pattern:
<Sheetname>!<Cell>
Example:
Table1!A1
To reference a cell of a different Workbook use this pattern:
[<Workbook_name>]<Sheetname>!<Cell>
Example:
[MyWorkbook]Table1!A1
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
use the val() function
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
=VLOOKUP(LEFT(A4,LEN(A4)-9),$D:$F,3,0)
I use this if my Lookup_Value
needs to be truncated because of the format the name is in the Table_Array. E.g. my Lookup_Value
is "Eastbay District", but the Table_Array
list I have only shows this as "Eastbay". "Eastbay District" minus 9 characters will result in "Eastbay".
I hope this helps!
This lookup only features exact matches. If you have an extra space in one of the columns or something similar it will not recognize it.
In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage
object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.
Consider using sessionStorage
directly:
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
After a little more research, I came across iText, a PDF and RTF-file creation API. I think I can use the RTF generation to create a Doc-readable file that can then be edited using Doc and re-saved.
Anyone have any experience with iText, used in this fashion?
Bill, the POI and iText API are very similar from a programming perspective. I've worked with both in the past and found them both easy to use and well documented.
With iText you gain the advantage of being able to switch between formats (RTF and PDF) with minor change to the code. If I remember correctly the content is laid out using the same calls and then set as PDF or RTF using a few lines of code.
However I believe the formatting in RTF is limited compared to DOC. I don't know if you'll be able to implement the advanced features you are looking for (tables, inline images) without a decent amount of hassle, if at all.
Given what you said that about HWPF not having enough functionality for your needs (I've only dealt with the Excel side of POI) your best bet may be to convince the powers that be that PDF is the best technology for the job.
The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:
namespace std {
template<class T, class Allocator = std::allocator<T>>
class list;
}
But to make even such a forward declaration in namespace std
is explicitly prohibited by the standard: the only thing you're allowed to put in std
is a template specialisation, commonly std::less
on a user-defined type. Someone else can cite the relevant text if necessary.
Just #include <list>
and don't worry about it.
Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H
instead of __TEST__
. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.
If you are working on a mac, then this is probably because you don't have permission to write to the directory. When I had this issue, I followed the following steps:
Execution of a python script would cause the byte code to be generated in memory and kept until the program is shutdown. In case a module is imported, for faster reusability, Python would create a cache .pyc (PYC is 'Python' 'Compiled') file where the byte code of the module being imported is cached. Idea is to speed up loading of python modules by avoiding re-compilation ( compile once, run multiple times policy ) when they are re-imported.
The name of the file is the same as the module name. The part after the initial dot indicates Python implementation that created the cache (could be CPython) followed by its version number.
Maybe a more simple solution.
if ($(document).height() > $(window).height()) {
// scrollbar
}
HTTP is an application protocol. REST is a set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.
If you are looking for the most significant constraints of REST that distinguish a RESTful application from just any HTTP application, I would say the "self-description" constraint and the hypermedia constraint (aka Hypermedia as the Engine of Application State (HATEOAS)) are the most important.
The self-description constraint requires a RESTful request to be completely self descriptive in the users intent. This allows intermediaries (proxies and caches) to act on the message safely.
The HATEOAS constraint is about turning your application into a web of links where the client's current state is based on its place in that web. It is a tricky concept and requires more time to explain than I have right now.
To Remove a Single character from The Given String please find my method hope it will be usefull. i have used str.replaceAll to remove the string but their are many ways to remove a character from a given string but i prefer replaceall method.
Code For Remove Char:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Removecharacter
{
public static void main(String[] args)
{
String result = removeChar("Java", 'a');
String result1 = removeChar("Edition", 'i');
System.out.println(result + " " + result1);
}
public static String removeChar(String str, char c) {
if (str == null)
{
return null;
}
else
{
return str.replaceAll(Character.toString(c), "");
}
}
}
Console image :
please find The Attached image of console,
Thanks For Asking. :)
I know this is too late for sure, but, this could help someone as well.
In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).
Make sure that you can copy from the command prompt,
First of all you use here two strings: "" marks a string it may be ""
-empty "s"
- string of lenght 1 or "aaa"
string of lenght 3, while '' marks chars . In order to be able to do String str = "a" + "aaa" + 'a'
you must use method Character.toString(char c) as @Thomas Keene said so an example would be String str = "a" + "aaa" + Character.toString('a')
--force-reinstall
doesn't appear to force reinstall using python2.7 with pip-1.5
I've had to use
--no-deps --ignore-installed
Why not use rs.getRow()?
int getRow()
throws SQLException
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
Note:Support for the getRow method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY
Returns:
the current row number; 0 if there is no current row
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
Since:
1.2
For me check "if (rs.getRow() != 0)" seems to work just fine.
You don't actually need to run a command from an xterm session, you can run it directly:
String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();
If the process responds interactively to the input stream, and you want to inject values, then do what you did before:
OutputStream out = proc.getOutputStream();
out.write("command\n");
out.flush();
Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.
I was also facing the same issue for 2 days but now finally it is working.
Step 1 : create a php script file with this content.
<?php
echo 'username : ' . `whoami`;
phpinfo();
?>
note down the username. note down open_basedir under core section of phpinfo. also note down upload_tmp_dir under core section of phpinfo.
Here two things are important , see if upload_tmp_dir value is inside one of open_basedir directory. ( php can not upload files outside open_basedir directory ).
Step 2 : Open terminal with root access and go to upload_tmp_dir location. ( In my case "/home/admin/tmp". )
=> cd /home/admin/tmp
But it was not found in my case so I created it and added chown for php user which I get in step 1 ( In my case "admin" ).
=> mkdir /home/admin/tmp
=> chown admin /home/admin/tmp
That is all you have to do to fix the file upload problem.
The best answer for this would be something like this:
function addhttp($url, $scheme="http://" )
{
return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}
The protocol flexible, so the same function can be used with ftp, https, etc.
Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1
(true
) or 0
(false
) depending on whether the arguments are equal or unequal, the spaceship operator will return 1
, 0
, or -1
depending on the value of the left argument relative to the right argument.
a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return nil
It's useful for sorting an array.
A different approach, because in my case I needed to also check whether it contained certain words (like 'test' in this example), not characters alone:
input_string = 'abc test'
input_string_test = input_string
allowed_list = ['a', 'b', 'c', 'test', ' ']
for allowed_list_item in allowed_list:
input_string_test = input_string_test.replace(allowed_list_item, '')
if not input_string_test:
# test passed
So, the allowed strings (char or word) are cut from the input string. If the input string only contained strings that were allowed, it should leave an empty string and therefore should pass if not input_string
.
Try this one:
import Data.List (unfoldr)
separateBy :: Eq a => a -> [a] -> [[a]]
separateBy chr = unfoldr sep where
sep [] = Nothing
sep l = Just . fmap (drop 1) . break (== chr) $ l
Only works for a single char, but should be easily extendable.
SurfaceView
probably does not work like a regular View
in this regard.
Instead, do the following:
SurfaceView
inside of a
FrameLayout
or RelativeLayout
in
your layout XML file, since both of
those allow stacking of widgets on
the Z-axisView
classFrameLayout
or
RelativeLayout
, but have it appear
after the SurfaceView
This will cause your custom View
class to appear to float above the SurfaceView
.
See here for a sample project that layers popup panels above a SurfaceView
used for video playback.
The node-mysql
library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values
I know this isn't as elegant as the other posts, but it's a more straightforward xaml/codebehind example of how to accomplish the same thing.
Xaml:
<StackPanel Orientation="Horizontal">
<TextBox Name="TextBox01" VerticalAlignment="Top" HorizontalAlignment="Left" Width="70" />
<Button Name="Button01" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,0" />
</StackPanel>
CodeBehind:
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Button01.IsEnabled = False
Button01.Content = "I am Disabled"
End Sub
Private Sub TextBox01_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox01.TextChanged
If TextBox01.Text.Trim.Length > 0 Then
Button01.IsEnabled = True
Button01.Content = "I am Enabled"
Else
Button01.IsEnabled = False
Button01.Content = "I am Disabled"
End If
End Sub
Select 3000 random records in Netezza:
WITH IDS AS (
SELECT ID
FROM MYTABLE;
)
SELECT ID FROM IDS ORDER BY mt_random() LIMIT 3000
Import module from a directory which is exactly one level above the current directory:
from .. import module
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
This is a function for calculating max valid length for varchar(Nn):
CREATE FUNCTION [dbo].[GetMaxVarcharColumnLength] (@TableSchema NVARCHAR(MAX), @TableName NVARCHAR(MAX), @ColumnName VARCHAR(MAX))
RETURNS INT
AS
BEGIN
RETURN (SELECT character_maximum_length FROM information_schema.columns
WHERE table_schema = @TableSchema AND table_name = @TableName AND column_name = @ColumnName);
END
Usage:
IF LEN(@Name) > [dbo].[GetMaxVarcharColumnLength]('person', 'FamilyStateName', 'Name')
RETURN [dbo].[err_Internal_StringForVarcharTooLong]();
You can get the mouse positions by using this snippet:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
};
}
This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left
) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width
see: Canvas width and height in HTML5).
Example: http://jsfiddle.net/sierawski/4xezb7nL/
Source: jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
You can simply do this with %w
notation in ruby arrays.
array = %w(1 2 3)
It will add the array values 1,2,3 to the arrayand print out the output as ["1", "2", "3"]
With NOLOCK hint, the transaction isolation level for the SELECT
statement is READ UNCOMMITTED
. This means that the query may see dirty and inconsistent data.
This is not a good idea to apply as a rule. Even if this dirty read behavior is OK for your mission critical web based application, a NOLOCK scan can cause 601 error which will terminate the query due to data movement as a result of lack of locking protection.
I suggest reading When Snapshot Isolation Helps and When It Hurts - the MSDN recommends using READ COMMITTED SNAPSHOT rather than SNAPSHOT under most circumstances.
I don't know if it is possible in XAML-only but try the following:
Give your ComboBox a name so you can access it in the codebehind: "typesComboBox1"
Now try the following
typesComboBox1.ItemsSource = Enum.GetValues(typeof(ExampleEnum));
Hardcoding a password in an expect script is the same as having a passwordless sudo, actually worse, since sudo at least logs its commands.
SELECT *
FROM table
ORDER BY id DESC
LIMIT 0, 1
Let's assume you can't change the input type, or even the src. You ONLY have css to play with.
If you know the height you want, and you have the url of a background image you want to use instead, you're in luck.
Set the height to zero and padding-top to the height you want. That'll shove the original image out of sight, giving you a perfectly clean space to show your css background-image.
Works in Chrome. No idea if it works in IE. Barely anything clever does, so probably not.
#daft {_x000D_
height: 0;_x000D_
padding-top: 100px;_x000D_
width: 100px;_x000D_
background-image: url(clever.jpg);_x000D_
}
_x000D_
<input type="image" src="daft.jpg" id="daft">
_x000D_
The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.
I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.
Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically.
Self-contained example
Same technique as in this answer but:
Source:
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = new Button(this);
button.setText("click me");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Notification notification = new Notification.Builder(Main.this)
/* Make app open when you click on the notification. */
.setContentIntent(PendingIntent.getActivity(
Main.this,
Main.this.i,
new Intent(Main.this, Main.class),
PendingIntent.FLAG_CANCEL_CURRENT))
.setContentTitle("title")
.setAutoCancel(true)
.setContentText(String.format("id = %d", Main.this.i))
// Starting on Android 5, only the alpha channel of the image matters.
// https://stackoverflow.com/a/35278871/895245
// `android.R.drawable` resources all seem suitable.
.setSmallIcon(android.R.drawable.star_on)
// Color of the background on which the alpha image wil drawn white.
.setColor(Color.RED)
.build();
final NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Main.this.i, notification);
// If the same ID were used twice, the second notification would replace the first one.
//notificationManager.notify(0, notification);
Main.this.i++;
}
});
this.setContentView(button);
}
}
Tested in Android 22.
Here is a sample code showing how to align text using UILabel:
label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;
You can read more about it here UILabel
It seems that Go have special form of switch dedicate to this (it is called type switch):
func (e *Easy)SetOption(option Option, param interface{}) {
switch v := param.(type) {
default:
fmt.Printf("unexpected type %T", v)
case uint64:
e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
case string:
e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
}
}
You can also get this error message on its own, without any stack trace or any further error message.
In this case you need to make sure your Android manifest is configured correctly (including any manifest merging happening from a library and any activity that would come from a library), and pay particular attention to the first activity displayed in your application in your manifest files.
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
data.frame[row_number, column_number] = new_value
For example, if x
is your data.frame:
x[1, 4] = 5
I am trying to explain by putting problem statement and solution to it. I hope it will help
Problem Statement:
Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-
Solution:
Below are the conditions that need to be taken care of
Below is the statement that applies above criterion to create query and fetch data.
$elements = $collection->find(
Array(
[price] => Array( [$lt] => 15 ),
[$or] => Array(
[0]=>Array(
[product_name]=>Array(
[$in]=>Array(
[0] => ABC Product,
[1]=> PQR Product
)
)
)
),
[state]=>Published
)
);
path = "C:\\Users\\Programming\\Downloads"
# Replace \\ with a \ along with any random key multiple times
path.replace('\\', '\pppyyyttthhhooonnn')
# Now replace pppyyyttthhhooonnn with a blank string
path.replace("pppyyyttthhhooonnn", "")
print(path)
#Output... C:\Users\Programming\Downloads
I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.
(Edit: Adding JSON from question for clarity)
{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}
With two classes representing the JSON-Structure you posted that may look like this:
public class Credentials
{
[JsonProperty("agent")]
public Agent Agent { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
[JsonProperty("token")]
public string Token { get; set; }
}
public class Agent
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("version")]
public int Version { get; set; }
}
you could have a method like this, which would do your POST request:
var payload = new Credentials {
Agent = new Agent {
Name = "Agent Name",
Version = 1
},
Username = "Username",
Password = "User Password",
Token = "xxxxx"
};
// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient()) {
// Do the actual request and await the response
var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);
// If the response contains content we want to read it!
if (httpResponse.Content != null) {
var responseContent = await httpResponse.Content.ReadAsStringAsync();
// From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
}
}
First creates the function
$.UrlExists = function(url) {_x000D_
var http = new XMLHttpRequest();_x000D_
http.open('HEAD', url, false);_x000D_
http.send();_x000D_
return http.status!=404;_x000D_
}
_x000D_
After using the function as follows
if($.UrlExists("urlimg")){_x000D_
foto = "img1.jpg";_x000D_
}else{_x000D_
foto = "img2.jpg";_x000D_
}_x000D_
_x000D_
$('<img>').attr('src',foto);
_x000D_
You can also use ls -w1
This allows to set number of columns. From manpage of ls:
-w, --width=COLS
set output width to COLS. 0 means no limit
Try this out. it works well for me. Make sure that before send email u need to give the access for less secure app in your gmail account. So go to the following link and try out with this java code.
Activate gmail for less secure app
You need to import javax.mail.jar file and activation.jar file to your project.
This is the full code for send email in java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendEmail {
final String senderEmail = "your email address";
final String senderPassword = "your password";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "587";
String receiverEmail = null;
String emailSubject = null;
String emailBody = null;
public SendEmail(String receiverEmail, String Subject, String message) {
this.receiverEmail = receiverEmail;
this.emailSubject = Subject;
this.emailBody = message;
Properties props = new Properties();
props.put("mail.smtp.user", senderEmail);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
SecurityManager security = System.getSecurityManager();
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
Message msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmail));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmail));
Transport.send(msg);
System.out.println("send successfully");
} catch (Exception ex) {
System.err.println("Error occurred while sending.!");
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmail, senderPassword);
}
}
public static void main(String[] args) {
SendEmail send = new SendEmail("receiver email address", "subject", "message");
}
}
It's really easy to do from the command line. I had a gist of a script for doing this. It has now been incorporated into the ipa_sign script in https://github.com/RichardBronosky/ota-tools which I use daily. If you have any questions about using these tools, don't hesitate to ask.
The heart of it is this:
CODESIGN_ALLOCATE=`xcrun --find codesign_allocate`; export CODESIGN_ALLOCATE
IPA="/path/to/file.ipa"
PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in keychain
# unzip the ipa
unzip -q "$IPA"
# remove the signature
rm -rf Payload/*.app/_CodeSignature
# replace the provision
cp "$PROVISION" Payload/*.app/embedded.mobileprovision
# sign with the new certificate (--resource-rules has been deprecated OS X Yosemite (10.10), it can safely be removed)
/usr/bin/codesign -f -s "$CERTIFICATE" Payload/*.app
# zip it back up
zip -qr resigned.ipa Payload
Your new signed app is called resigned.ipa
i did try the above steps for some reason it seams not to be working for me but this was my final solution to my own problem just maybe helpful to any one reading this :
let pst = post.likes.some( (like) => { //console.log(like.user, req.user.id);
if(like.user.toString() === req.user.id.toString()){
return true
} } )
here post.likes is an array of users who liked a post.
var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
g.DrawString( ... );
}
picturebox1.Image = bmp;
If you want every column and every row, then just pass in null
for the SQLiteDatabase
column
and selection
parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
The other answers use rawQuery
, but you can use Android's built in SQLiteDatabase
. The documentation for query
says that you can just pass in null
to the selection
parameter to get all the rows.
selection
Passing null will return all rows for the given table.
And while you can also pass in null
for the column
parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns
Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
the answers here are correct and i liked @Jyo the Whiff idea of a show and hide fragment implementation except the way he has it currently would hide the fragment on the first run so i added a slight change in that i added the isAdded check and show the fragment if its not already
public void showHideCardPreview(int id) {
FragmentManager fm = getSupportFragmentManager();
Bundle b = new Bundle();
b.putInt(Constants.CARD, id);
cardPreviewFragment.setArguments(b);
FragmentTransaction ft = fm.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
if (!cardPreviewFragment.isAdded()){
ft.add(R.id.full_screen_container, cardPreviewFragment);
ft.show(cardPreviewFragment);
} else {
if (cardPreviewFragment.isHidden()) {
Log.d(TAG,"++++++++++++++++++++ show");
ft.show(cardPreviewFragment);
} else {
Log.d(TAG,"++++++++++++++++++++ hide");
ft.hide(cardPreviewFragment);
}
}
ft.commit();
}
step 1: add
<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
</asp:FileUpload>
step 2: add
Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
Dim ImageFiles As HttpFileCollection = Request.Files
For i As Integer = 0 To ImageFiles.Count - 1
Dim file As HttpPostedFile = ImageFiles(i)
file.SaveAs(Server.MapPath("Uploads/") & ImageFiles(i).FileName)
Next
End Sub
The above answers did not work for me. The below does:
document.getElementById("input_field_id").setAttribute("readonly", true);
And to remove the readonly attribute:
document.getElementById("input_field_id").removeAttribute("readonly");
And for running when the page is loaded, it is worth referring to here.
You have to be very careful about the method names. In this case, the method name is just "lowercaseString
", not "lowercaseString:
" (note the absence of the colon). That's why you're getting NO
returned, because NSString
objects respond to the lowercaseString
message but not the lowercaseString:
message.
How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString
), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:
.
You can also look at the documentation and note the presence or absence of a trailing colon.
Anonymous FTP usage is covered by RFC 1635: How to Use Anonymous FTP:
What is Anonymous FTP?
Anonymous FTP is a means by which archive sites allow general access to their archives of information. These sites create a special account called "anonymous".
…
Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address. Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password. Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services.
These are general recommendations, though. Each FTP server may have its own guidelines.
For sample use of the ftp
command on anonymous FTP access, see appendix A:
atlas.arc.nasa.gov% ftp naic.nasa.gov Connected to naic.nasa.gov. 220 naic.nasa.gov FTP server (Wed May 4 12:15:15 PDT 1994) ready. Name (naic.nasa.gov:amarine): anonymous 331 Guest login ok, send your complete e-mail address as password. Password: 230----------------------------------------------------------------- 230-Welcome to the NASA Network Applications and Info Center Archive 230- 230- Access to NAIC's online services is also available through: 230- 230- Gopher - naic.nasa.gov (port 70) 230- World-Wide-Web - http://naic.nasa.gov/naic/naic-home.html 230- 230- If you experience any problems please send email to 230- 230- [email protected] 230- 230- or call +1 (800) 858-9947 230----------------------------------------------------------------- 230- 230-Please read the file README 230- it was last modified on Fri Dec 10 13:06:33 1993 - 165 days ago 230 Guest login ok, access restrictions apply. ftp> cd files/rfc 250-Please read the file README.rfc 250- it was last modified on Fri Jul 30 16:47:29 1993 - 298 days ago 250 CWD command successful. ftp> get rfc959.txt 200 PORT command successful. 150 Opening ASCII mode data connection for rfc959.txt (147316 bytes). 226 Transfer complete. local: rfc959.txt remote: rfc959.txt 151249 bytes received in 0.9 seconds (1.6e+02 Kbytes/s) ftp> quit 221 Goodbye. atlas.arc.nasa.gov%
See also the example session at the University of Edinburgh site.
Reference: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Classes
class Animal {
constructor(sound) {
this.sound = sound;
}
say() {
return `This animal does ${this.sound}`;}
};
const dog = new Animal('bark');
console.log(dog.say());
Setting locales in terminal resolved the issue for me. Open the terminal and
Check if locale settings are missing
> locale
LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=
Edit ~/.profile
or ~/.bashrc
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
Run . ~/.profile
or . ~/.bashrc
to read from the file.
Open a new terminal window and check that the locales are properly set
> locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
It could be a good idea to be careful with the Locale upon which c.getTime().toString();
depends.
One idea is to store the time in seconds (e.g. UNIX time). As an int
you can easily compare it, and then you just convert it to string when displaying it to the user.
test.html
is will be helpful for how to use VLC WebAPI.
test.html
is located in the directory where VLC was installed.
e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html
The following code is a quote from the test.html
.
HTML:
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
<param name="MRL" value="" />
<param name="ShowDisplay" value="True" />
<param name="AutoLoop" value="False" />
<param name="AutoPlay" value="False" />
<param name="Volume" value="50" />
<param name="toolbar" value="true" />
<param name="StartTime" value="0" />
<EMBED pluginspage="http://www.videolan.org"
type="application/x-vlc-plugin"
version="VideoLAN.VLCPlugin.2"
width="640"
height="360"
toolbar="true"
loop="false"
text="Waiting for video"
name="vlc">
</EMBED>
</object>
JavaScript:
You can get vlc object from getVLC()
.
It works on IE 10 and Chrome.
function getVLC(name)
{
if (window.document[name])
{
return window.document[name];
}
if (navigator.appName.indexOf("Microsoft Internet")==-1)
{
if (document.embeds && document.embeds[name])
return document.embeds[name];
}
else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
{
return document.getElementById(name);
}
}
var vlc = getVLC("vlc");
// do something.
// e.g. vlc.playlist.play();
I just had the same problem. It is not a network permission but rather thread issue. Below code helped me to solve it. Put is in main activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
I understand the need for packages in certain situations, but the base language is so elegant and so proven (and debugged and optimized).
Why not:
dt <- as.Date("2014-03-16")
dt2 <- as.POSIXlt(dt)
dt2$yday
[1] 74
And then your choice whether the first week of the year is zero (as in indexing in C) or 1 (as in indexing in R).
No packages to learn, update, worry about bugs in.
Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).
The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.
Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).
For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.
Use this code in your php script (first lines)
ini_set('allow_url_fopen',1);
As @figha says, if this is your own web page, you should just run whatever you need to run after you make the element visible.
However, for the purposes of answering the question (and anybody making Chrome or Firefox Extensions, where this is a common use case), Mutation Summary and Mutation Observer will allow DOM changes to trigger events.
For example, triggering an event for a elements with data-widget
attribute being added to the DOM. Borrowing this excellent example from David Walsh's blog:
var observer = new MutationObserver(function(mutations) {
// For the sake of...observation...let's output the mutation to console to see how this all works
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// Notify me of everything!
var observerConfig = {
attributes: true,
childList: true,
characterData: true
};
// Node, config
// In this case we'll listen to all changes to body and child nodes
var targetNode = document.body;
observer.observe(targetNode, observerConfig);
Responses include added
, removed
, valueChanged
and more. valueChanged
includes all attributes, including display
etc.
There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.
Look in your Windows directory for System32 and SysWOW64.
Repeat these steps for each directory:
Check the current setting for ExecutionPolicy:
Get-ExecutionPolicy -List
Set the ExecutionPolicy for the level and scope you want, for example:
Set-ExecutionPolicy -Scope LocalMachine Unrestricted
Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.
You can read a lot more here: Running Windows PowerShell Scripts
I ignore all classes residing in target folder from git. add following line in open .gitignore file:
/.class
OR
*/target/**
It is working perfectly for me. try it.
The Junction command line utility from SysInternals makes creating and deleting junctions easy.
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
There is an important and subtle issue that none of them addresses directly. There are two ways of considering type in C#: static type and run-time type.
Static type is the type of a variable in your source code. It is therefore a compile-time concept. This is the type that you see in a tooltip when you hover over a variable or property in your development environment.
You can obtain static type by writing helper generic method to let type inference take care of it for you:
Type GetStaticType<T>(T x) { return typeof(T); }
Run-time type is the type of an object in memory. It is therefore a run-time concept. This is the type returned by the GetType()
method.
An object's run-time type is frequently different from the static type of the variable, property, or method that holds or returns it. For example, you can have code like this:
object o = "Some string";
The static type of the variable is object
, but at run time, the type of the variable's referent is string
. Therefore, the next line will print "System.String" to the console:
Console.WriteLine(o.GetType()); // prints System.String
But, if you hover over the variable o
in your development environment, you'll see the type System.Object
(or the equivalent object
keyword). You also see the same using our helper function from above:
Console.WriteLine(GetStaticType(o)); // prints System.Object
For value-type variables, such as int
, double
, System.Guid
, you know that the run-time type will always be the same as the static type, because value types cannot serve as the base class for another type; the value type is guaranteed to be the most-derived type in its inheritance chain. This is also true for sealed reference types: if the static type is a sealed reference type, the run-time value must either be an instance of that type or null
.
Conversely, if the static type of the variable is an abstract type, then it is guaranteed that the static type and the runtime type will be different.
To illustrate that in code:
// int is a value type
int i = 0;
// Prints True for any value of i
Console.WriteLine(i.GetType() == typeof(int));
// string is a sealed reference type
string s = "Foo";
// Prints True for any value of s
Console.WriteLine(s == null || s.GetType() == typeof(string));
// object is an unsealed reference type
object o = new FileInfo("C:\\f.txt");
// Prints False, but could be true for some values of o
Console.WriteLine(o == null || o.GetType() == typeof(object));
// FileSystemInfo is an abstract type
FileSystemInfo fsi = new DirectoryInfo("C:\\");
// Prints False for all non-null values of fsi
Console.WriteLine(fsi == null || fsi.GetType() == typeof(FileSystemInfo));
Using JDK 1.6 or later
It has been pointed out by Justin in the comments below that keytool alone is capable of doing this using the following command (although only in JDK 1.6 and later):
keytool -importkeystore -srckeystore mypfxfile.pfx -srcstoretype pkcs12
-destkeystore clientcert.jks -deststoretype JKS
Using JDK 1.5 or below
OpenSSL can do it all. This answer on JGuru is the best method that I've found so far.
Firstly make sure that you have OpenSSL installed. Many operating systems already have it installed as I found with Mac OS X.
The following two commands convert the pfx file to a format that can be opened as a Java PKCS12 key store:
openssl pkcs12 -in mypfxfile.pfx -out mypemfile.pem
openssl pkcs12 -export -in mypemfile.pem -out mykeystore.p12 -name "MyCert"
NOTE that the name provided in the second command is the alias of your key in the new key store.
You can verify the contents of the key store using the Java keytool utility with the following command:
keytool -v -list -keystore mykeystore.p12 -storetype pkcs12
Finally if you need to you can convert this to a JKS key store by importing the key store created above into a new key store:
keytool -importkeystore -srckeystore mykeystore.p12 -destkeystore clientcert.jks -srcstoretype pkcs12 -deststoretype JKS
$(":button").click(function () {
$("#anchor_google")[0].click();
});
These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:
function encryptString($plaintext, $password, $encoding = null) {
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}
function decryptString($ciphertext, $password, $encoding = null) {
$ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}
Usage:
$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");
Here is the algorithm I use to crypt with MD5.It returns your crypted output.
public class CryptWithMD5 {
private static MessageDigest md;
public static String cryptWithMD5(String pass){
try {
md = MessageDigest.getInstance("MD5");
byte[] passBytes = pass.getBytes();
md.reset();
byte[] digested = md.digest(passBytes);
StringBuffer sb = new StringBuffer();
for(int i=0;i<digested.length;i++){
sb.append(Integer.toHexString(0xff & digested[i]));
}
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(CryptWithMD5.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
You cannot decrypt MD5, but you can compare outputs since if you put the same string in this method it will have the same crypted output.If you want to decrypt you need to use the SHA.You will never use decription for a users password.For that always use MD5.That exception is pretty redundant.It will never throw it.
I found this helpful for using an if statement in a rule.
max(X,Y,Z) :-
( X =< Y
-> Z = Y
; Z = X
).
Thanks to http://cs.union.edu/~striegnk/learn-prolog-now/html/node89.html
You can use menu left sidebar collapse accordion, animated with right arrow
Declare the Start and End date
DECLARE @SDATE AS DATETIME
TART_DATE AS DATETIME
DECLARE @END_-- Set Start and End date
SET @START_DATE = GETDATE()
SET @END_DATE = DATEADD(SECOND, 3910, GETDATE())
-- Get the Result in HH:MI:SS:MMM(24H) format
SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS, @START_DATE, @END_DATE), 0), 114) AS TimeDiff
How to open a new tab using Selenium WebDriver with Java for Chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.navigate().to("https://google.com");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
The above code will disable first extensions and using the robot class, a new tab will open.
In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).
Thus, it was failing as "Not allowed", since there was no method with POST type on my end.
Changing @GET
to @POST
above my WS method fixed the issue.
Here is he full function
function isMobile(){
return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i.test(navigator.userAgent||navigator.vendor||window.opera)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test((navigator.userAgent||navigator.vendor||window.opera).substr(0,4)))
}
jQuery.noConflict();
jQuery(document).ready(function(){
if(isMobile()) alert("Mobile"); else alert("Not Mobile");
});
I'd suggest to use jshint instead.
It allows to suppress this warning via /*jshint globalstrict: true*/
.
If you are writing a library, I would only suggest using global strict if your code is encapsulated into modules as is the case with nodejs.
Otherwise you'd force everyone who is using your library into strict mode.
you can add
<fieldset class="fieldset">
and then you can call
$('.fieldset').prop('disabled', true);
Double parenthesis (( ... ))
is used for arithmetic operations.
Double square brackets [[ ... ]]
can be used to compare and examine numbers (only integers are supported), with the following operators:
· NUM1 -eq NUM2 returns true if NUM1 and NUM2 are numerically equal.
· NUM1 -ne NUM2 returns true if NUM1 and NUM2 are not numerically equal.
· NUM1 -gt NUM2 returns true if NUM1 is greater than NUM2.
· NUM1 -ge NUM2 returns true if NUM1 is greater than or equal to NUM2.
· NUM1 -lt NUM2 returns true if NUM1 is less than NUM2.
· NUM1 -le NUM2 returns true if NUM1 is less than or equal to NUM2.
For example
if [[ $age > 21 ]] # bad, > is a string comparison operator
if [ $age > 21 ] # bad, > is a redirection operator
if [[ $age -gt 21 ]] # okay, but fails if $age is not numeric
if (( $age > 21 )) # best, $ on age is optional
This is the best way (IMHO).
List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);
This code works also:
String[] myArray = myArrayList.toArray(new String[0]);
But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()
) you should create array that is big enough to put all elements. In this case it is not re-allocated.
Old but gold!
On MacOS (Catalina 10.15.7) it was a bit weird:
I had to rename my dump.sql
into dump.zip
and after that, i had to use finder(!) to unzip it.
in terminal, unzip dump.zip
oder tar xfz dump.sql[or .gz .tar ...]
leads to error msgs.
Finally, finder has unziped it totally fine, after that i could import the file without problems.
I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image
plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)
I used the tick_params
call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.
you can also use OPEN Sql to find the number of rows using the COUNT Grouping clause and also there is system field SY-LINCT to count the lines(ROWS) of your table.
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.After lot of failed tried attempts ,I found the solution
It was the ";" at end of JAVA_HOME which I always put at end of each new variable I set. So get rid of the ;.
JAVA_HOME set it in User Variable also (without the ";" ofcourse)
(Not everyone likes doing things through the git command line interface)
Once this has been set up, you only need to do steps 7-13 from then on.
Fetch > checkout master branch > reset to their master > Push changes to server
Double click on your "master" branch to check it out if it is not checked out already.
Find the commit that you want to reset to, if you called the repo "master" you will most likely want to find the commit with the "master/master" tag on it.
Right click on the commit > "Reset current branch to this commit".
In the dialog, set the "Using mode:" field to "Hard - discard all working copy changes" then press "OK" (make sure to put any changes that you don't want to lose onto a separate branch first).
Your Done!
A more extensive version of https://stackoverflow.com/a/10786066/1794894
/"([^"\\]{50,}(\\.[^"\\]*)*)"|\'[^\'\\]{50,}(\\.[^\'\\]*)*\'|“[^”\\]{50,}(\\.[^“\\]*)*”/
This version also contains
“
and close ”
)I have set the ANDROID_HOME = [PATH_OF_MY_ANDROID_SDK] to my environment variable. That solution works for me.
Yes, it is universal.
Although '\n'
is the universal newline characters, you have to keep in mind that, depending on your input, new line characters might be preceded by carriage return characters ('\r'
).
One Additional point:
When you are converting from tsql
to plsql
you have to worry about no_data_found
exception
DECLARE
v_var NUMBER;
BEGIN
SELECT clmn INTO v_var FROM tbl;
Exception when no_data_found then v_var := null; --what ever handle the exception.
END;
In tsql
if no data found
then the variable will be null
but no exception
If you are trying to find the difference between timestamps that are in pandas columns, the the answer is fairly simple. If you need it in days or seconds then
# For difference in days:
df['diff_in_days']=(df['timestamp2'] - df['timestamp1']).dt.days
# For difference in seconds
df['diff_in_seconds']=(df['timestamp2'] - df['timestamp1']).dt.seconds
Now minute is tricky as dt.minute works only on datetime64[ns] dtype. whereas the column generated from subtracting two datetimes has format
AttributeError: 'TimedeltaProperties' object has no attribute 'm8'
So like mentioned by many above to get the actual value of the difference in minute you have to do:
df['diff_in_min']=df['diff_in_seconds']/60
But if just want the difference between the minute parts of the two timestamps then do the following
#convert the timedelta to datetime and then extract minute
df['diff_in_min']=(pd.to_datetime(df['timestamp2']-df['timestamp1'])).dt.minute
You can also read the article https://docs.python.org/3.4/library/datetime.html and see section 8.1.2 you'll see the read only attributes are only seconds,days and milliseconds. And this settles why the minute function doesn't work directly.
I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:
<script type="text/javascript" language="JavaScript">
$.ajax({
url: "x.html",
context: document.body,
success: function(response) {
$("#yourDiv").html(response);
}
});
</script>
$ranges = [
1 => [
'min_range' => 0.01,
'max_range' => 199.99
],
2 => [
'min_range' => 200.00,
],
];
foreach( $ranges as $value => $range ){
if( filter_var( $cartTotal, FILTER_VALIDATE_FLOAT, [ 'options' => $range ] ) ){
return $value;
}
}
If you use the gradle-android-plugin to build your app, then you can use
BuildConfig.APPLICATION_ID
to retrieve the package name from any scope, incl. a static one.
You can always wrap Double.parseDouble() in a try catch block.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
C:\>help if
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
You can use finds null separated output option with read to iterate over directory structures safely.
#!/bin/bash
find . -type f -print0 | while IFS= read -r -d $'\0' file;
do echo "$file" ;
done
So for your case
#!/bin/bash
find . -maxdepth 1 -type f -print0 | while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done
additionally
#!/bin/bash
while IFS= read -r -d $'\0' file; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$file" 'Logs/'"`basename "$file"`""$i"'.txt'
done
done < <(find . -maxdepth 1 -type f -print0)
will run the while loop in the current scope of the script ( process ) and allow the output of find to be used in setting variables if needed
A simple function in the bash config file (~/.bashrc
often) could work well.
function runx() {
for ((n=0;n<$1;n++))
do ${*:2}
done
}
Call it like this.
$ runx 3 echo 'Hello world'
Hello world
Hello world
Hello world
Have you tried:
sudo apt-get install ruby1.8-dev
Or it can be done using replace(), and replace each word's first letter with its "upperCase".
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
titleCase("I'm a little tea pot");
The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.
You simply want to pass the actual path to the UriSource:
logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");
In my opinion the best solution uses jQuery:
a.html
:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html
:
<p>This is my include file</p>
This method is a simple and clean solution to my problem.
The jQuery .load()
documentation is here.
In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:
get-qadgroupmember 'Domain Admins' | foreach { $_.Name }
This will get you a simple string[]
without column headings or empty lines. The Format-*
cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.
For multiple properties I'd probably go with the -f
format operator. Something along the lines of
alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }
which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)
If chmod not working then you also try
import os
os.system('sh script.sh')
#you can also use bash instead of sh
test by me thanks
You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'
SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code],
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title],
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]
I am using ubuntu 14.04. I have genymotion installed on virtualbox. Every time I start genymotion I had no problem, but suddenly one time it said unable to load virtualbox engine and it didn't open. I went through the log file and found out it could not create a new host only network because it has already created all possible host only networks. And the problem is that it cannot allocate memory for a new network.
Fix: go to your virtual box File --> Preferences --> Network
Click the host-only tab and just delete some of the host-only networks so that you will get some memory freed and next time, a new network can be created easily.
Deletion fixed my problem.
I'm expanding upon a comment that I posted here as most people won't notice the comment.
https://lifeboat.com/programs/console.exe is a compiled version of the Visual Basic program described at https://stackoverflow.com/a/4694566/1752929. My version simply sets the buffer height to 32766 which is the maximum buffer height available. It does not adjust anything else. If there is a lot of demand, I could create a more flexible program but generally you can just set other variables in your shortcut layout tab.
Following is the target I use in my shortcut where I wish to start in the f directory. (I have to set the directory this way as Windows won't let you set it any other way if you wish to run the command prompt as administrator.)
C:\Windows\System32\cmd.exe /k "console & cd /d c:\f"
If you are currently not on branch master, that's super easy:
git branch -f master 1258f0d0aae
This does exactly what you want: It points master
at the given commit, and does nothing else.
If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:
git checkout 1258f0d0aae #detach from master
git branch -f master HEAD #exactly as above
#optionally reattach to master
git checkout master
Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f
!
This method is better than the git reset --hard
approach, as it does not destroy anything in the index or working directory.
In flutter version 1.14.6, Dart version 28.
Below is what worked for me, You simply just need to bundle everything you want to happen after the build method into a separate method or function.
@override
void initState() {
super.initState();
print('hello girl');
WidgetsBinding.instance
.addPostFrameCallback((_) => afterLayoutWidgetBuild());
}
If you had two Strings and compared them using == by calling the getClass() method on them, it would return true. What you get is a reference on the same object.
This is because they are both references on the same class object. This is true for all classes in a java application. Java only loads the class once, so you have only one instance of a given class at a given time.
String hello = "Hello";
String world = "world";
if (hello.getClass() == world.getClass()) {
System.out.println("true");
} // prints true
You put the if
at the end:
[y for y in a if y not in b]
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
Your version tried to do this instead:
outputlist = []
if y not in b:
for y in a:
outputlist.append(y)
but a list comprehension must start with at least one outer loop.
Try Demo Here
var list ={}; var count= Object.keys(list).length;
You can remove the "bullets" by setting the "list-style-type: none;" Like
ul
{
list-style-type: none;
}
OR
<ul class="menu custompozition4" style="list-style-type: none;">
<li class="item-507"><a href=#">Strategic Recruitment Solutions</a>
</li>
<li class="item-508"><a href="#">Executive Recruitment</a>
</li>
<li class="item-509"><a href="#">Leadership Development</a>
</li>
<li class="item-510"><a href="#">Executive Capability Review</a>
</li>
<li class="item-511"><a href="#">Board and Executive Coaching</a>
</li>
<li class="item-512"><a href="#">Cross Cultutral Coaching</a>
</li>
<li class="item-513"><a href="#">Team Enhancement & Coaching</a>
</li>
<li class="item-514"><a href="#">Personnel Re-deployment</a>
</li>
</ul>
I've found the best way to edit tuples is to recreate the tuple using the previous version as the base.
Here's an example I used for making a lighter version of a colour (I had it open already at the time):
colour = tuple([c+50 for c in colour])
What it does, is it goes through the tuple 'colour' and reads each item, does something to it, and finally adds it to the new tuple.
So what you'd want would be something like:
values = ('275', '54000', '0.0', '5000.0', '0.0')
values = (tuple(for i in values: if i = 0: i = 200 else i = values[i])
That specific one doesn't work, but the concept is what you need.
tuple = (0, 1, 2)
tuple = iterate through tuple, alter each item as needed
that's the concept.
Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
This works too:
String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Note:
String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>
String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
Write Thread.sleep(1000);
it will make the thread sleep for 1000ms
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
The enctype attribute can be used only if method="post".
No characters are encoded. This value is required when you are using forms that have a file upload control
From W3Schools
Choosing a random pivot minimizes the chance that you will encounter worst-case O(n2) performance (always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data). Choosing the middle element would also be acceptable in the majority of cases.
Also, if you are implementing this yourself, there are versions of the algorithm that work in-place (i.e. without creating two new lists and then concatenating them).
If the content type is recognized as form data, request.data
will parse that into request.form
and return an empty string.
To get the raw data regardless of content type, call request.get_data()
. request.data
calls get_data(parse_form_data=True)
, while the default is False
if you call it directly.
Let arrList
be the ArrayList
and newValue
the new String
, then just do:
arrList.set(5, newValue);
This can be found in the java api reference here.
In Swift 4, as String
is a collection of Character
, you need to use map
let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\($0)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>
I think it's better to use importlib.import_module('.c', __name__)
since you don't need to know about a
and b
.
I'm also wondering that, if you have to use importlib.import_module('a.b.c')
, why not just use import a.b.c
?
I would expect this query to work with your program:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
Microsoft has listened to the cry for supporting installers (MSI) in Visual Studio and release the Visual Studio Installer Projects Extension. You can now create installers in VS2013, download the extension here from the visualstudiogallery.
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!
IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
For SQL Server 2005+:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
I've tried to load archive nearly 10 times (with all kinds of cleans and reloads, with different versions and provisioning files), still received the same error. Then suddenly on my next attempt it showed me: "cannot proceed with delivery an existing transporter instance is currently uploading this package", I did the following and it helped:
Basically, you need to clear out the transport tokens. This can happen if you were to close out of Xcode while in the middle of submitting an app to iTunes Connect.
/Users/<username>/.itmstransporter/UploadTokens/
Delete any .token files in this directory. If you are unable to find the .token files, this is because they are hidden in Finder. To hide/show hidden files in Finder, use the following Terminal command (TRUE = UNHIDE, FALSE = HIDE):
defaults write com.apple.finder AppleShowAllFiles TRUE;killall Finder
I did not find the answer to my question after searching Google & stackoverflow for a while so I would like to share my solution here.
git config --global credential.helper "/bin/bash /git_creds.sh"
echo '#!/bin/bash' > /git_creds.sh
echo "sleep 1" >> /git_creds.sh
echo "echo username=$SERVICE_USER" >> /git_creds.sh
echo "echo password=$SERVICE_PASS" >> /git_creds.sh
# to test it
git clone https://my-scm-provider.com/project.git
I did it for Windows too. Full answer here
Make sure your Facebook application is published. In order to receive data for email, public_profile and user_friends your app must be made available to public.
You can disable it later for development purposes and still get email field.
The best way to put is that hg forget
is identical to hg remove
except that it leaves the files behind in your working copy. The files are left behind as untracked files and can now optionally be ignored with a pattern in .hgignore
.
In other words, I cannot tell if you used hg forget
or hg remove
when I pull from you. A file that you ran hg forget
on will be deleted when I update to that changeset — just as if you had used hg remove
instead.
Hope this will work:
// create activity indicator
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]
initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
...
[self.view addSubview:activityIndicator];
// release it
[activityIndicator release];
Using ripgrep's replace option, it is possible to change the output to a capture group:
rg --only-matching --replace '$1' '(\d+) rofl'
--only-matching
or -o
outputs only the part that matches instead of the whole line.--replace '$1'
or -r
replaces the output by the first capture group.I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value
directly without relating to additional objects.
An Open Source alternative is Nominatim from Open Street Map. All you have to do is set the variables in an URL and it returns the city/country of that location. Please check the following link for official documentation: Nominatim
Type type = typeof(MessageProcessor<>).MakeGenericType(key);
That's the best you can do, however without actually knowing what type it is, there's really not much more you can do with it.
EDIT: I should clarify. I changed from var type to Type type. My point is, now you can do something like this:
object obj = Activator.CreateInstance(type);
obj will now be the correct type, but since you don't know what type "key" is at compile time, there's no way to cast it and do anything useful with it.
I would use the Apache Commons Lang library. It has a class called StringUtils that is useful for all sorts of String operations. For checking if a String is not all whitespaces, you can use the following:
StringUtils.isBlank(<your string>)
Here is the reference: StringUtils.isBlank
You have to use the SelectMany
extension method or its equivalent syntax in pure LINQ.
(from model in list
where model.application == "applicationname"
from user in model.users
where user.surname == "surname"
select new { user, model }).ToList();
No, this is not possible. However, one could do something like this:
List<Integer> temp = new ArrayList<Integer>();
temp.add(Integer.valueOf(0));
temp.add(Integer.valueOf(2));
temp.add(Integer.valueOf(3));
temp.add(Integer.valueOf(4));
List<Integer> immutable = Collections.unmodifiableList(temp);
This requires using wrappers, and is a List, not an array, but is the closest you will get.
For everyone saying to get the bytes, copy it to MemoryStream
, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader
's built in ReadLine()
or ReadToEnd()
? I saw these weren't even mentioned, and they do everything for you.
I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult
that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:
string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";
string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine(); // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();
return path;
If you REALLY need a byte[]
instead of a string
for some reason, using my example, you can always do:
byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();
return toBytes;
(Returning toBytes
instead of path
.)
If you don't want ASCII
you can easily replace that with UTF8
, Unicode
, etc.
Be aware that Build.VERSION.SDK_INT isn't reliable, it's mentioned by @Falcon165o and recently I ran into that one too.
So to get the String data (based on Android version list) of currently installed android, I made a code like this:
Java
//Current Android version data
public static String currentVersion(){
double release=Double.parseDouble(Build.VERSION.RELEASE.replaceAll("(\\d+[.]\\d+)(.*)","$1"));
String codeName="Unsupported";//below Jelly bean OR above Oreo
if(release>=4.1 && release<4.4)codeName="Jelly Bean";
else if(release<5)codeName="Kit Kat";
else if(release<6)codeName="Lollipop";
else if(release<7)codeName="Marshmallow";
else if(release<8)codeName="Nougat";
else if(release<9)codeName="Oreo";
return codeName+" v"+release+", API Level: "+Build.VERSION.SDK_INT;
}
Kotlin
fun currentVersion(): String {
val release = java.lang.Double.parseDouble(java.lang.String(Build.VERSION.RELEASE).replaceAll("(\\d+[.]\\d+)(.*)", "$1"))
var codeName = "Unsupported"//below Jelly bean OR above Oreo
if (release >= 4.1 && release < 4.4) codeName = "Jelly Bean"
else if (release < 5) codeName = "Kit Kat"
else if (release < 6) codeName = "Lollipop"
else if (release < 7) codeName = "Marshmallow"
else if (release < 8) codeName = "Nougat"
else if (release < 9) codeName = "Oreo"
return codeName + " v" + release + ", API Level: " + Build.VERSION.SDK_INT
}
Example of an output it produce:
Marshmallow v6.0, API Level: 23
You can do something like this:
var cubes = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
for(var i = 0; i < cubes.length; i++) {
var cube = cubes[i];
for(var j = 0; j < cube.length; j++) {
display("cube[" + i + "][" + j + "] = " + cube[j]);
}
}
Working jsFiddle:
The output of the above:
cube[0][0] = 1
cube[0][1] = 2
cube[0][2] = 3
cube[1][0] = 4
cube[1][1] = 5
cube[1][2] = 6
cube[2][0] = 7
cube[2][1] = 8
cube[2][2] = 9
The folder containing your Anaconda installation contains a subfolder called conda-meta
with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json
.
My file is called anaconda-5.0.1-py27hdb50712_1.json
, and at the bottom is more info about the version:
"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe",
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" },
"name": "anaconda",
"platform": "win",
"subdir": "win-64",
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2",
"version": "5.0.1"
(Slightly edited for brevity.)
The output from conda -V
is the conda version.
To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.
Now, add the style to the div class and use the text-align property with center as its value.
See the below example.
<style>
.myDivElement{
text-align:center;
}
.myDivElement ul li{
display:inline;
}
</style>
<div class="myDivElement">
<ul>
<li>Home</li>
<li>About</li>
<li>Gallery</li>
<li>Contact</li>
</ul>
</div>
Here is the reference website Center Align Unordered List
1 You can use string.Replace
method
var sample = "testtesttesttest#replace#testtesttest";
var result = sample.Replace("#replace#", yourValue);
2 You can also use string.Format
var result = string.Format("your right part {0} Your left Part", yourValue);
3 You can use Regex class
You can as well use $.when()
to wait until the promise
finished:
var myEvent = function() {
$( selector ).fadeOut( 'fast' );
};
$.when( myEvent() ).done( function() {
console.log( 'Task finished.' );
} );
In case you're doing a request that could as well fail, then you can even go one step further:
$.when( myEvent() )
.done( function( d ) {
console.log( d, 'Task done.' );
} )
.fail( function( err ) {
console.log( err, 'Task failed.' );
} )
// Runs always
.then( function( data, textStatus, jqXHR ) {
console.log( jqXHR.status, textStatus, 'Status 200/"OK"?' );
} );
The listen socket on a server can use linger with time 0 to have access to binding back to the socket immediately and to reset any clients whose connections are not yet finished connecting. TIME_WAIT is something that is only interesting when you have a multi-path network and can end up with miss-ordered packets or otherwise are dealing with odd network packet ordering/arrival-timing.
best way and more simple to center an iframe on your webpage is :
<p align="center"><iframe src="http://www.google.com/" width=500 height="500"></iframe></p>
where width and height will be the size of your iframe in your html page.
I found the error: I have a library that it was built using jdk 1.6. The Spring main controller and components are in this library. And how I use jdk 1.7, It does not find the classes built in 1.6.
The solution was built all using "compiler compliance level: 1.7" and "Generated .class files compatibility: 1.6", "Source compatibility: 1.6".
I setup this option in Eclipse: Preferences\Java\Compiler.
Thanks everybody.
What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub
and also very nice Modern UI on GitHub. (.NET4.5 only)
There is one more it's Elysium but I really didn't try this one.
The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.
Here is code (please note that it's targeting .NET4.5)
public class MyWindow : Window
{
public MyWindow()
{
this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));
}
private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
}
private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
}
private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
}
And here resources:
<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />
<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>
<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>
<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Padding" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter x:Name="contentPresenter"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyWindow">
<Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
<Grid>
<Border BorderThickness="1">
<AdornerDecorator>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
<Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
<Grid Margin="1,0,1,0">
<Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
<Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1" />
</Grid>
</Button.Content>
</Button>
<Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="31" Height="25">
<Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5" />
</Grid>
</Button.Content>
</Button>
</StackPanel>
<TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="8 -1 0 0" FontSize="16" Foreground="{TemplateBinding Foreground}"/>
<Grid Grid.Row="2">
<Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
</Grid>
</Grid>
</AdornerDecorator>
</Border>
<Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="WindowState" Value="Maximized">
<Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
<Setter TargetName="Restore" Property="Visibility" Value="Visible" />
<Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
</Trigger>
<Trigger Property="WindowState" Value="Normal">
<Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
<Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ResizeMode" Value="CanResizeWithGrip" />
<Condition Property="WindowState" Value="Normal" />
</MultiTrigger.Conditions>
<Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />
</Setter.Value>
</Setter>
</Style>
Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Array
s and anything that implements Iterator
(e.g. Collection
s) can be looped as such:
public static boolean inArray(int[] array, int check) {
for (int o : array){
if (o == check) {
return true;
}
}
return false;
}
In Java 8 you can also do something like:
// import java.util.stream.IntStream;
public static boolean inArray(int[] array, int check) {
return IntStream.of(array).anyMatch(val -> val == check);
}
Although converting to a stream for this is probably overkill.
In my project I had to pass dynamic html snippet from variable and render it inside component. So i did the following.
defaultSelection : {
innerHtml: {__html: '<strong>some text</strong>'}
}
defaultSelection object is passed to component from .js
file
<HtmlSnippet innerHtml={defaultSelection.innerHtml} />
HtmlSnippet component
var HtmlSnippet = React.createClass({
render: function() {
return (
<span dangerouslySetInnerHTML={this.props.innerHtml}></span>
);
}
});
Try the following:
<script>
//Functions to open database and to create, insert data into tables
getSelectedRow = function(val)
{
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);
});
};
selectedRowValues = function(transaction,results)
{
for(var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
alert(row['number']);
alert(row['name']);
}
};
</script>
You don't have access to javascript variable names in SQL, you must pass the values to the Database.
df.groupby('key you want to group by').apply(print)
As mentioned by an other member, this is the easiest and simplest solution to visualize a groupby object.
The good practice is to use like this:
$.ajax({
type: "POST",
url: "/ajax/request.html",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
console.log(response.blablabla);
// put on console what server sent back...
}
});
and the php part is:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo json_encode(array("blablabla"=>$variable));
}
?>
Your two examples are the only things I have ever used the Rows
and Columns
properties for, but in theory you could do anything with them that can be done with a Range
object.
The return type of those properties is itself a Range
, so you can do things like:
Dim myRange as Range
Set myRange = Sheet1.Range(Cells(2,2),Cells(8,8))
myRange.Rows(3).Select
Which will select the third row in myRange
(Cells B4:H4 in Sheet1).
update: To do what you want to do, you could use:
Dim interestingRows as Range
Set interestingRows = Sheet1.Range(startRow & ":" & endRow)
update #2: Or, to get a subset of rows from within a another range:
Dim someRange As Range
Dim interestingRows As Range
Set myRange = Sheet1.Range(Cells(2, 2), Cells(8, 8))
startRow = 3
endRow = 6
Set interestingRows = Range(myRange.Rows(startRow), myRange.Rows(endRow))
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var video = document.getElementById('video');
video.addEventListener('play', function () {
var $this = this; //cache
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
}, 0);
I guess the above code is self Explanatory, If not drop a comment below, I will try to explain the above few lines of code
Edit :
here's an online example, just for you :)
Demo
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
var video = document.getElementById('video');_x000D_
_x000D_
// set canvas size = video size when known_x000D_
video.addEventListener('loadedmetadata', function() {_x000D_
canvas.width = video.videoWidth;_x000D_
canvas.height = video.videoHeight;_x000D_
});_x000D_
_x000D_
video.addEventListener('play', function() {_x000D_
var $this = this; //cache_x000D_
(function loop() {_x000D_
if (!$this.paused && !$this.ended) {_x000D_
ctx.drawImage($this, 0, 0);_x000D_
setTimeout(loop, 1000 / 30); // drawing at 30fps_x000D_
}_x000D_
})();_x000D_
}, 0);
_x000D_
<div id="theater">_x000D_
<video id="video" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv" controls="false"></video>_x000D_
<canvas id="canvas"></canvas>_x000D_
<label>_x000D_
<br />Try to play me :)</label>_x000D_
<br />_x000D_
</div>
_x000D_
For what its worth, I am using EclipseLink 2.3.2.v20111125-r10461 and if I have a @ManyToMany unidirectional relationship I observe the problem that you describe. However, if I change it to be a bi-directional @ManyToMany relationship I am able to delete an entity from the non-owning side and the JOIN table is updated appropriately. This is all without the use of any cascade attributes.
Those who are new to aws ec2 and wants to access the instance from SSH, Broswer, Ping from system
then below is the inbound rule for these:-
What you're looking for is componentWillMount
.
From the documentation:
Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call
setState
within this method,render()
will see the updated state and will be executed only once despite the state change.
So you would do something like this:
componentWillMount : function () {
var data = this.getData();
this.setState({data : data});
},
This way, render()
will only be called once, and you'll have the data you're looking for in the initial render.
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
You could just use normal Python argument passing syntax to specify your crontab. For example, suppose we define an Event class as below:
from datetime import datetime, timedelta
import time
# Some utility classes / functions first
class AllMatch(set):
"""Universal set - match everything"""
def __contains__(self, item): return True
allMatch = AllMatch()
def conv_to_set(obj): # Allow single integer to be provided
if isinstance(obj, (int,long)):
return set([obj]) # Single item
if not isinstance(obj, set):
obj = set(obj)
return obj
# The actual Event class
class Event(object):
def __init__(self, action, min=allMatch, hour=allMatch,
day=allMatch, month=allMatch, dow=allMatch,
args=(), kwargs={}):
self.mins = conv_to_set(min)
self.hours= conv_to_set(hour)
self.days = conv_to_set(day)
self.months = conv_to_set(month)
self.dow = conv_to_set(dow)
self.action = action
self.args = args
self.kwargs = kwargs
def matchtime(self, t):
"""Return True if this event should trigger at the specified datetime"""
return ((t.minute in self.mins) and
(t.hour in self.hours) and
(t.day in self.days) and
(t.month in self.months) and
(t.weekday() in self.dow))
def check(self, t):
if self.matchtime(t):
self.action(*self.args, **self.kwargs)
(Note: Not thoroughly tested)
Then your CronTab can be specified in normal python syntax as:
c = CronTab(
Event(perform_backup, 0, 2, dow=6 ),
Event(purge_temps, 0, range(9,18,2), dow=range(0,5))
)
This way you get the full power of Python's argument mechanics (mixing positional and keyword args, and can use symbolic names for names of weeks and months)
The CronTab class would be defined as simply sleeping in minute increments, and calling check() on each event. (There are probably some subtleties with daylight savings time / timezones to be wary of though). Here's a quick implementation:
class CronTab(object):
def __init__(self, *events):
self.events = events
def run(self):
t=datetime(*datetime.now().timetuple()[:5])
while 1:
for e in self.events:
e.check(t)
t += timedelta(minutes=1)
while datetime.now() < t:
time.sleep((t - datetime.now()).seconds)
A few things to note: Python's weekdays / months are zero indexed (unlike cron), and that range excludes the last element, hence syntax like "1-5" becomes range(0,5) - ie [0,1,2,3,4]. If you prefer cron syntax, parsing it shouldn't be too difficult however.
A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.
Here's some code to illustrate. A point is time is captured in three different ways.
var moment = require( 'moment' );
var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );
//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );
//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate = ' + utcDate );
//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );
Which outputs this:
localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570
In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).
As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!
Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.
Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate )
, and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log
calls in the example.
rm !(textfile.txt|backup.tar.gz|script.php|database.sql|info.txt)
The extglob (Extended Pattern Matching) needs to be enabled in BASH (if it's not enabled):
shopt -s extglob
I was getting similar problem for other reason (url pattern test-response
not added in csrf token)
I resolved it by allowing my URL pattern in following property in config/local.properties
:
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$
modified to
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$,/[^/]+(/[^?])+(test-response)$
In most cases, you should use the instanceof
operator to test whether an object is an array.
Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a Integer[]
or an int[]
. You'd want to guard your casts with instanceof
:
if (obj instanceof Integer[]) {
Integer[] array = (Integer[]) obj;
/* Use the boxed array */
} else if (obj instanceof int[]) {
int[] array = (int[]) obj;
/* Use the primitive array */
} else ...
At the JVM level, the instanceof
operator translates to a specific "instanceof" byte code, which is optimized in most JVM implementations.
In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the isArray()
method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.
There are two special cases: null references and references to primitive arrays.
A null reference will cause instanceof
to result false
, while the isArray
throws a NullPointerException
.
Applied to a primitive array, the instanceof
yields false
unless the component type on the right-hand operand exactly matches the component type. In contrast, isArray()
will return true
for any component type.
A previous answer recommends setting to 512m. I'd say there are reasons to think that's counterproductive on a 64bit architecture. The documentation for core.packedGitLimit says:
Default is 256 MiB on 32 bit platforms and 32 TiB (effectively unlimited) on 64 bit platforms. This should be reasonable for all users/operating systems, except on the largest projects. You probably do not need to adjust this value.
If you want to try it out check if you have it set and then remove the setting:
git config --show-origin core.packedGitLimit
git config --unset --global core.packedGitLimit
Why Server.Transfer
? Response.Redirect(Request.RawUrl)
would get you what you need.
If you use Python's IDLE editor you can do as it suggests in one of similar error messages:
1) select all, e.g. Ctrl + A
2) Go to Format -> Untabify Region
3) Double check your indenting is still correct, save and rerun your program.
I'm using Python 2.5.4
Margin is usually used to create a space between the element itself and its surround.
for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.
I usually use when I've an element inside a border, <div>
or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.
So briefly, it's situational; it depends on what you are trying to do.
To read a line from a file, you should use the fgets
function: It reads a string from the specified file up to either a newline character or EOF
.
The use of sscanf
in your code would not work at all, as you use filename
as your format string for reading from line
into a constant string literal %s
.
The reason for SEGV is that you write into the non-allocated memory pointed to by line
.
You can use ARG
- see https://docs.docker.com/engine/reference/builder/#arg
The
ARG
instruction defines a variable that users can pass at build-time to the builder with thedocker build
command using the--build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.
If you're accessing this via a View then try sp_recompile
or refreshing views.
sp_recompile
:
Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.
Arguments
[ @objname= ] 'object'
The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.
Return Code Values
0 (success) or a nonzero number (failure)
Remarks
sp_recompile
looks for an object in the current database only.
The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.
But when I need something like a Singleton, I often end up using a Schwarz Counter to instantiate it.
There is also an alternative: you could use the open-source jTDS driver for MS-SQL Server, which is compatible although not made by Microsoft. For that driver, there is a maven artifact that you can use:
From http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds :
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
UPDATE nov 2016, Microsoft now published its MSSQL JDBC driver on github and it's also available on maven now:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
In the Terminal type
pip show some_package_name
Example
pip show matplotlib
I've just did a hard reset on wrong project. What saved my life was Eclipse's local history. IntelliJ Idea is said to have one, too, and so may your editor, it's worth checking:
Here, since onSaveInstanceState
in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView
and end onDestroyView
while onSaveInstanceState
is called between onDestroyView
and onDestroy
. My solution is create instance variable and init in onCreate
. Sample code:
private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
isDataLoading = false;
// init list at once when create fragment
listData = new ArrayList();
}
And check it in onActivityCreated
:
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(isDataLoading){
fetchData();
}else{
//get saved instance variable listData()
}
}
private void fetchData(){
// do fetch data into listData
}
The EntityManager doesn't flush change automatically by default. You should use the following option with your statement of query:
@Modifying(clearAutomatically = true)
@Query("update RssFeedEntry feedEntry set feedEntry.read =:isRead where feedEntry.id =:entryId")
void markEntryAsRead(@Param("entryId") Long rssFeedEntryId, @Param("isRead") boolean isRead);
Yeah, I know I don't "have" to do it this way. But I usually write:
/* Return type (8/16/32/64 int size) is specified by argument size. */
template<class TYPE> inline TYPE BIT(const TYPE & x)
{ return TYPE(1) << x; }
template<class TYPE> inline bool IsBitSet(const TYPE & x, const TYPE & y)
{ return 0 != (x & y); }
E.g.:
IsBitSet( foo, BIT(3) | BIT(6) ); // Checks if Bit 3 OR 6 is set.
Amongst other things, this approach:
Another option you could try is iptstate.
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
$protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';
These should both work
Try this:
created_at.strftime('%FT%T')
It's a time formatting function which provides you a way to present the string representation of the date. (http://ruby-doc.org/core-2.2.1/Time.html#method-i-strftime).
From APIdock:
%Y%m%d => 20071119 Calendar date (basic)
%F => 2007-11-19 Calendar date (extended)
%Y-%m => 2007-11 Calendar date, reduced accuracy, specific month
%Y => 2007 Calendar date, reduced accuracy, specific year
%C => 20 Calendar date, reduced accuracy, specific century
%Y%j => 2007323 Ordinal date (basic)
%Y-%j => 2007-323 Ordinal date (extended)
%GW%V%u => 2007W471 Week date (basic)
%G-W%V-%u => 2007-W47-1 Week date (extended)
%GW%V => 2007W47 Week date, reduced accuracy, specific week (basic)
%G-W%V => 2007-W47 Week date, reduced accuracy, specific week (extended)
%H%M%S => 083748 Local time (basic)
%T => 08:37:48 Local time (extended)
%H%M => 0837 Local time, reduced accuracy, specific minute (basic)
%H:%M => 08:37 Local time, reduced accuracy, specific minute (extended)
%H => 08 Local time, reduced accuracy, specific hour
%H%M%S,%L => 083748,000 Local time with decimal fraction, comma as decimal sign (basic)
%T,%L => 08:37:48,000 Local time with decimal fraction, comma as decimal sign (extended)
%H%M%S.%L => 083748.000 Local time with decimal fraction, full stop as decimal sign (basic)
%T.%L => 08:37:48.000 Local time with decimal fraction, full stop as decimal sign (extended)
%H%M%S%z => 083748-0600 Local time and the difference from UTC (basic)
%T%:z => 08:37:48-06:00 Local time and the difference from UTC (extended)
%Y%m%dT%H%M%S%z => 20071119T083748-0600 Date and time of day for calendar date (basic)
%FT%T%:z => 2007-11-19T08:37:48-06:00 Date and time of day for calendar date (extended)
%Y%jT%H%M%S%z => 2007323T083748-0600 Date and time of day for ordinal date (basic)
%Y-%jT%T%:z => 2007-323T08:37:48-06:00 Date and time of day for ordinal date (extended)
%GW%V%uT%H%M%S%z => 2007W471T083748-0600 Date and time of day for week date (basic)
%G-W%V-%uT%T%:z => 2007-W47-1T08:37:48-06:00 Date and time of day for week date (extended)
%Y%m%dT%H%M => 20071119T0837 Calendar date and local time (basic)
%FT%R => 2007-11-19T08:37 Calendar date and local time (extended)
%Y%jT%H%MZ => 2007323T0837Z Ordinal date and UTC of day (basic)
%Y-%jT%RZ => 2007-323T08:37Z Ordinal date and UTC of day (extended)
%GW%V%uT%H%M%z => 2007W471T0837-0600 Week date and local time and difference from UTC (basic)
%G-W%V-%uT%R%:z => 2007-W47-1T08:37-06:00 Week date and local time and difference from UTC (extended)
Not directly. Software such as Selenium have features like this and can be controlled by PHP but have other dependencys (such as running their java-based server on the computer with the browser you want to screenshot)
Using Linq to find the object you can do:
var obj = myList.FirstOrDefault(x => x.MyProperty == myValue);
if (obj != null) obj.OtherProperty = newValue;
But in this case you might want to save the List into a Dictionary and use this instead:
// ... define after getting the List/Enumerable/whatever
var dict = myList.ToDictionary(x => x.MyProperty);
// ... somewhere in code
MyObject found;
if (dict.TryGetValue(myValue, out found)) found.OtherProperty = newValue;
While the original question may not have been specific to a web service, here is a complete testWebService you can add to display a web service non-cached response plus the file version. We use file version instead of assembly version because we want to know a version, but with all assembly versions 1.0.0.0, the web site can be easily patched (signing and demand link still active!). Replace @Class@ with the name of the web api controller this service is embedded in. It's good for a go/nogo on a web service plus a quick version check.
[Route("api/testWebService")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage TestWebService()
{
HttpResponseMessage responseMessage = Request.CreateResponse(HttpStatusCode.OK);
string loc = Assembly.GetAssembly(typeof(@Class@)).Location;
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(loc);
responseMessage.Content = new StringContent($"<h2>The XXXXX web service GET test succeeded.</h2>{DateTime.Now}<br/><br/>File Version: {versionInfo.FileVersion}");
responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
Request.RegisterForDispose(responseMessage);
return responseMessage;
}
I found it also necessary to add the following to web.config under configuration to make it truly anonymous
<location path="api/testwebservice">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
I've just go my head around these, and so I'll share an example as you already have descriptions but at the moment one advantage I see is to get around the Circular Reference style warnings where you can't have 2 projects referencing each other.
Let's assume an application downloads an XML, and then saves the XML to a database.
I have 2 projects here which build my solution: FTP and a SaveDatabase.
So, our application starts by looking for any downloads and downloading the file(s) then it calls the SaveDatabase project.
Now, our application needs to notify the FTP site when a file is saved to the database by uploading a file with Meta data (ignore why, it's a request from the owner of the FTP site). The issue is at what point and how? We need a new method called NotifyFtpComplete() but in which of our projects should it be saved too - FTP or SaveDatabase? Logically, the code should live in our FTP project. But, this would mean our NotifyFtpComplete will have to be triggered or, it will have to wait until the save is complete, and then query the database to ensure it is in there. What we need to do is tell our SaveDatabase project to call the NotifyFtpComplete() method direct but we can't; we'd get a ciruclar reference and the NotifyFtpComplete() is a private method. What a shame, this would have worked. Well, it can.
During our application's code, we would have passed parameters between methods, but what if one of those parameters was the NotifyFtpComplete method. Yup, we pass the method, with all of the code inside as well. This would mean we could execute the method at any point, from any project. Well, this is what the delegate is. This means, we can pass the NotifyFtpComplete() method as a parameter to our SaveDatabase() class. At the point it saves, it simply executes the delegate.
See if this crude example helps (pseudo code). We will also assume that the application starts with the Begin() method of the FTP class.
class FTP
{
public void Begin()
{
string filePath = DownloadFileFromFtpAndReturnPathName();
SaveDatabase sd = new SaveDatabase();
sd.Begin(filePath, NotifyFtpComplete());
}
private void NotifyFtpComplete()
{
//Code to send file to FTP site
}
}
class SaveDatabase
{
private void Begin(string filePath, delegateType NotifyJobComplete())
{
SaveToTheDatabase(filePath);
/* InvokeTheDelegate -
* here we can execute the NotifyJobComplete
* method at our preferred moment in the application,
* despite the method being private and belonging
* to a different class.
*/
NotifyJobComplete.Invoke();
}
}
So, with that explained, we can do it for real now with this Console Application using C#
using System;
namespace ConsoleApplication1
{
/* I've made this class private to demonstrate that
* the SaveToDatabase cannot have any knowledge of this Program class.
*/
class Program
{
static void Main(string[] args)
{
//Note, this NotifyDelegate type is defined in the SaveToDatabase project
NotifyDelegate nofityDelegate = new NotifyDelegate(NotifyIfComplete);
SaveToDatabase sd = new SaveToDatabase();
sd.Start(nofityDelegate);
Console.ReadKey();
}
/* this is the method which will be delegated -
* the only thing it has in common with the NofityDelegate
* is that it takes 0 parameters and that it returns void.
* However, it is these 2 which are essential.
* It is really important to notice that it writes
* a variable which, due to no constructor,
* has not yet been called (so _notice is not initialized yet).
*/
private static void NotifyIfComplete()
{
Console.WriteLine(_notice);
}
private static string _notice = "Notified";
}
public class SaveToDatabase
{
public void Start(NotifyDelegate nd)
{
/* I shouldn't write to the console from here,
* just for demonstration purposes
*/
Console.WriteLine("SaveToDatabase Complete");
Console.WriteLine(" ");
nd.Invoke();
}
}
public delegate void NotifyDelegate();
}
I suggest you step through the code and see when _notice is called and when the method (delegate) is called as this, I hope, will make things very clear.
However, lastly, we can make it more useful by changing the delegate type to include a parameter.
using System.Text;
namespace ConsoleApplication1
{
/* I've made this class private to demonstrate that the SaveToDatabase
* cannot have any knowledge of this Program class.
*/
class Program
{
static void Main(string[] args)
{
SaveToDatabase sd = new SaveToDatabase();
/* Please note, that although NotifyIfComplete()
* takes a string parameter, we do not declare it,
* all we want to do is tell C# where the method is
* so it can be referenced later,
* we will pass the parameter later.
*/
var notifyDelegateWithMessage = new NotifyDelegateWithMessage(NotifyIfComplete);
sd.Start(notifyDelegateWithMessage );
Console.ReadKey();
}
private static void NotifyIfComplete(string message)
{
Console.WriteLine(message);
}
}
public class SaveToDatabase
{
public void Start(NotifyDelegateWithMessage nd)
{
/* To simulate a saving fail or success, I'm just going
* to check the current time (well, the seconds) and
* store the value as variable.
*/
string message = string.Empty;
if (DateTime.Now.Second > 30)
message = "Saved";
else
message = "Failed";
//It is at this point we pass the parameter to our method.
nd.Invoke(message);
}
}
public delegate void NotifyDelegateWithMessage(string message);
}
Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
for($i = 0; $i < 6; $i++) {
$string .= $character_array[rand(0, (count($character_array) - 1))];
}
echo $string;
?>
This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().
inline bool exist(const std::string& name)
{
ifstream file(name);
if(!file) // If the file was not found, then file is 0, i.e. !file=1 or true.
return false; // The file was not found.
else // If the file was found, then file is non-0.
return true; // The file was found.
}
There are several possibilities for concatenating 1D arrays, e.g.,
numpy.r_[a, a],
numpy.stack([a, a]).reshape(-1),
numpy.hstack([a, a]),
numpy.concatenate([a, a])
All those options are equally fast for large arrays; for small ones, concatenate
has a slight edge:
The plot was created with perfplot:
import numpy
import perfplot
perfplot.show(
setup=lambda n: numpy.random.rand(n),
kernels=[
lambda a: numpy.r_[a, a],
lambda a: numpy.stack([a, a]).reshape(-1),
lambda a: numpy.hstack([a, a]),
lambda a: numpy.concatenate([a, a]),
],
labels=["r_", "stack+reshape", "hstack", "concatenate"],
n_range=[2 ** k for k in range(19)],
xlabel="len(a)",
)
Just add the following in your connection string:
MultipleActiveResultSets=True;
As an alternative to installing Visual C++, there is a way by installing an additional package in Conda (this option doesn't require admin rights). This worked for me:
conda install libpython m2w64-toolchain -c msys2
Maven versions can contain a string literal "SNAPSHOT" to signify that a project is currently under active development.
For example, if your project has a version of “1.0-SNAPSHOT” and you deploy this project’s artifacts to a Maven repository, Maven would expand this version to “1.0-20080207-230803-1” if you were to deploy a release at 11:08 PM on February 7th, 2008 UTC. In other words, when you deploy a snapshot, you are not making a release of a software component; you are releasing a snapshot of a component at a specific time.
So mainly snapshot versions are used for projects under active development. If your project depends on a software component that is under active development, you can depend on a snapshot release, and Maven will periodically attempt to download the latest snapshot from a repository when you run a build. Similarly, if the next release of your system is going to have a version “1.8,” your project would have a “1.8-SNAPSHOT” version until it was formally released.
For example , the following dependency would always download the latest 1.8 development JAR of spring:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>1.8-SNAPSHOT”</version>
</dependency>
An example of maven release process
If I remember from your previous questions, you're binding to a DataTable. Try this:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable sourceData = (DataTable)GridView1.DataSource;
sourceData.Rows[e.RowIndex].Delete();
GridVie1.DataSource = sourceData;
GridView1.DataBind();
}
Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.
Basically an XSD file defines how the XML file is going to look like. It's a Schema file which defines the structure of the XML file. So it specifies what the possible fields are and what size they are going to be.
An XML file is an instance of XSD as it uses the rules defined in the XSD.
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
Just to add to all the conversation. Since arrays requires consecutive memory locations to store the item, so if we create an array of references then it's not guaranteed that they will be at consecutive memory location so accessing will be a problem and hence we can't even apply all the mathematical operations on array.
Super-brief summary from what Professor Brasilford explains in this video.
Turing Complete ? do anything that a Turing Machine can do.
It has conditional branching (i.e. "if statement"). Also, implies "go to" and thus permitting loop.
It has arbitrary amount of memory (e.g. long enough tape) that the program needs.