For VB.NET, you can place the following before your web request:
Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12
This solved my security issue on .NET 3.5.
You are close, but the parameter you pass to SecureStringToBSTR
must be a SecureString
. You appear to be passing the result of ConvertFrom-SecureString
, which is an encrypted standard string. So call ConvertTo-SecureString
on this before passing to SecureStringToBSTR
.
$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:
$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose
Verbosity is optional in the last line
I was successfully available to get Application User By Following Piece of Code
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
ApplicationUser EmpUser = user;
Please confirm that your firewall is allowing outbound traffic and that you are not being blocked by antivirus software.
I received the same issue and the culprit was antivirus software.
It formats the string as two uppercase hexadecimal characters.
In more depth, the argument "X2"
is a "format string" that tells the ToString()
method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.
byte.ToString()
without any arguments returns the number in its natural decimal representation, with no padding.
Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString()
methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString()
.
I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:
...
var signature = Get(url); // base64_encoded signature received from server
var inputtext= "inputtext"; // this is main text signature was created for
bool result = VerifySignature(inputtext, signature);
...
private bool VerifySignature(string input, string signature)
{
var result = false;
using (var cps=new RSACryptoServiceProvider())
{
// converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
byte[] signatureBytes = Convert.FromBase64String(signature);
cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes );
}
return result;
}
I also had this problem with another style of implementation but I forgot where I got it since it was 2 years ago.
static string sha256(string randomString)
{
var crypt = new SHA256Managed();
string hash = String.Empty;
byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(randomString));
foreach (byte theByte in crypto)
{
hash += theByte.ToString("x2");
}
return hash;
}
When I input something like abcdefghi2013
for some reason it gives different results and results in errors in my login module.
Then I tried modifying the code the same way as suggested by Quuxplusone and changed the encoding from ASCII
to UTF8
then it finally worked!
static string sha256(string randomString)
{
var crypt = new System.Security.Cryptography.SHA256Managed();
var hash = new System.Text.StringBuilder();
byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(randomString));
foreach (byte theByte in crypto)
{
hash.Append(theByte.ToString("x2"));
}
return hash.ToString();
}
Thanks again Quuxplusone for the wonderful and detailed answer! :)
Did you try using System.Net.WebClient
?
$url = 'https://IPADDRESS/resource'
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("username","password")
$wc.DownloadString($url)
It looks like you want:
public static string GetRandomBits()
Without static
, you would need an object before you can call the GetRandomBits()
method. However, since the implementation of GetRandomBits()
does not depend on the state of any Program
object, it's best to declare it static
.
Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.
The finally implemented code started like this:
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.ECB;
myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
myAes.Key = CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.None;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// TODO: perform the encryption / decryption as required...
}
catch (Exception ex)
{
// TODO: Log the error
throw ex;
}
If you're using membership you can do: Membership.GetUser()
Your code is returning the Windows account which is assigned with ASP.NET.
Additional Info Edit: You will want to include System.Web.Security
using System.Web.Security
If your URL has dots in the domain name, IE will treat it like it's an internet address and not local. You have at least two options:
Go to the site and cancel the login dialog. Let this happen:
In IE’s settings:
If you're on .NET 3.5 or up, you can use the new System.DirectoryServices.AccountManagement
(S.DS.AM) namespace which makes this a lot easier than it used to be.
Read all about it here: Managing Directory Security Principals in the .NET Framework 3.5
Update: older MSDN magazine articles aren't online anymore, unfortunately - you'll need to download the CHM for the January 2008 MSDN magazine from Microsoft and read the article in there.
Basically, you need to have a "principal context" (typically your domain), a user principal, and then you get its groups very easily:
public List<GroupPrincipal> GetGroups(string userName)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// establish domain context
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);
// if found - grab its groups
if(user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
// iterate over all groups
foreach(Principal p in groups)
{
// make sure to add only group principals
if(p is GroupPrincipal)
{
result.Add((GroupPrincipal)p);
}
}
}
return result;
}
and that's all there is! You now have a result (a list) of authorization groups that user belongs to - iterate over them, print out their names or whatever you need to do.
Update: In order to access certain properties, which are not surfaced on the UserPrincipal
object, you need to dig into the underlying DirectoryEntry
:
public string GetDepartment(Principal principal)
{
string result = string.Empty;
DirectoryEntry de = (principal.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
return result;
}
Update #2: seems shouldn't be too hard to put these two snippets of code together.... but ok - here it goes:
public string GetDepartment(string username)
{
string result = string.Empty;
// if you do repeated domain access, you might want to do this *once* outside this method,
// and pass it in as a second parameter!
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username);
// if user is found
if(user != null)
{
// get DirectoryEntry underlying it
DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
}
return result;
}
Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).
# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'
# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'
# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions
# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)
# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'
Each of the values in the $permissions
variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.
Courtesy of this page.
This code worked for me. I had to add TLS2 because that's what the URL I am interested in was using.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(UserDataUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
Task<string> response = client.GetStringAsync(UserDataUrl);
response.Wait();
if (response.Exception != null)
{
return null;
}
return JsonConvert.DeserializeObject<UserData>(response.Result);
}
Complementing the answers this is a guide to find the private key of the certificate and add the permissions.
This is the guide to get FindPrivateKey.exe found in the guide for find the private key of the certificate.
I couldn't get GetAccessControl() to throw an exception on Windows 7 as recommended in the accepted answer.
I ended up using a variation of sdds's answer:
try
{
bool writeable = false;
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
DirectorySecurity security = Directory.GetAccessControl(pstrPath);
AuthorizationRuleCollection authRules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));
foreach (FileSystemAccessRule accessRule in authRules)
{
if (principal.IsInRole(accessRule.IdentityReference as SecurityIdentifier))
{
if ((FileSystemRights.WriteData & accessRule.FileSystemRights) == FileSystemRights.WriteData)
{
if (accessRule.AccessControlType == AccessControlType.Allow)
{
writeable = true;
}
else if (accessRule.AccessControlType == AccessControlType.Deny)
{
//Deny usually overrides any Allow
return false;
}
}
}
}
return writeable;
}
catch (UnauthorizedAccessException)
{
return false;
}
Hope this helps.
For me ony granting 'Read' permissions for 'NetworkService' to the whole 'EventLog' branch worked.
Don't checksum the entire file, create checksums every 100mb or so, so each file has a collection of checksums.
Then when comparing checksums, you can stop comparing after the first different checksum, getting out early, and saving you from processing the entire file.
It'll still take the full time for identical files.
I derived from This answer by sclarke81. I like his answer and I'm using the derivative but sclarke81's has a bug. I don't have reputation so I can't comment. The problem seems small enough that it didn't warrant another answer and I could edit it. So I did. It got rejected. So now we have another answer.
sclarke81 I hope you see this (in finally):
Marshal.Copy(new byte[length], 0, insecureStringPointer, length);
should be:
Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);
And the full answer with the bug fix:
///
/// Allows a decrypted secure string to be used whilst minimising the exposure of the
/// unencrypted string.
///
/// Generic type returned by Func delegate.
/// The string to decrypt.
///
/// Func delegate which will receive the decrypted password as a string object
///
/// Result of Func delegate
///
/// This method creates an empty managed string and pins it so that the garbage collector
/// cannot move it around and create copies. An unmanaged copy of the the secure string is
/// then created and copied into the managed string. The action is then called using the
/// managed string. Both the managed and unmanaged strings are then zeroed to erase their
/// contents. The managed string is unpinned so that the garbage collector can resume normal
/// behaviour and the unmanaged string is freed.
///
public static T UseDecryptedSecureString(this SecureString secureString, Func action)
{
int length = secureString.Length;
IntPtr sourceStringPointer = IntPtr.Zero;
// Create an empty string of the correct size and pin it so that the GC can't move it around.
string insecureString = new string('\0', length);
var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();
try
{
// Create an unmanaged copy of the secure string.
sourceStringPointer = Marshal.SecureStringToBSTR(secureString);
// Use the pointers to copy from the unmanaged to managed string.
for (int i = 0; i < secureString.Length; i++)
{
short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
}
return action(insecureString);
}
finally
{
// Zero the managed string so that the string is erased. Then unpin it to allow the
// GC to take over.
Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);
insecureStringHandler.Free();
// Zero and free the unmanaged string.
Marshal.ZeroFreeBSTR(sourceStringPointer);
}
}
///
/// Allows a decrypted secure string to be used whilst minimising the exposure of the
/// unencrypted string.
///
/// The string to decrypt.
///
/// Func delegate which will receive the decrypted password as a string object
///
/// Result of Func delegate
///
/// This method creates an empty managed string and pins it so that the garbage collector
/// cannot move it around and create copies. An unmanaged copy of the the secure string is
/// then created and copied into the managed string. The action is then called using the
/// managed string. Both the managed and unmanaged strings are then zeroed to erase their
/// contents. The managed string is unpinned so that the garbage collector can resume normal
/// behaviour and the unmanaged string is freed.
///
public static void UseDecryptedSecureString(this SecureString secureString, Action action)
{
UseDecryptedSecureString(secureString, (s) =>
{
action(s);
return 0;
});
}
}
Based on some answers I found here, I made myself a small helper file to source for my projects:
#!/bin/bash
function try()
{
[[ $- = *e* ]]; SAVED_OPT_E=$?
set +e
}
function throw()
{
exit $1
}
function catch()
{
export ex_code=$?
(( $SAVED_OPT_E )) && set +e
return $ex_code
}
function throwErrors()
{
set -e
}
function ignoreErrors()
{
set +e
}
here is an example how it looks like in use:
#!/bin/bash
export AnException=100
export AnotherException=101
# start with a try
try
( # open a subshell !!!
echo "do something"
[ someErrorCondition ] && throw $AnException
echo "do something more"
executeCommandThatMightFail || throw $AnotherException
throwErrors # automaticatly end the try block, if command-result is non-null
echo "now on to something completely different"
executeCommandThatMightFail
echo "it's a wonder we came so far"
executeCommandThatFailsForSure || true # ignore a single failing command
ignoreErrors # ignore failures of commands until further notice
executeCommand1ThatFailsForSure
local result = $(executeCommand2ThatFailsForSure)
[ result != "expected error" ] && throw $AnException # ok, if it's not an expected error, we want to bail out!
executeCommand3ThatFailsForSure
echo "finished"
)
# directly after closing the subshell you need to connect a group to the catch using ||
catch || {
# now you can handle
case $ex_code in
$AnException)
echo "AnException was thrown"
;;
$AnotherException)
echo "AnotherException was thrown"
;;
*)
echo "An unexpected exception was thrown"
throw $ex_code # you can rethrow the "exception" causing the script to exit if not caught
;;
esac
}
I encountered this error when using Travis CI to deploy content, which involved pushing edits to a repository.
I eventually solved the issue by updating the GitHub personal access token associated with the Travis account with the public_repo
scope access permission:
This is perhaps more succinct:
function toggle(element, klass) {
var classes = element.className.match(/\S+/g) || [],
index = classes.indexOf(klass);
index >= 0 ? classes.splice(index, 1) : classes.push(klass);
element.className = classes.join(' ');
}
You should return json always, but change its status, or in following example the ResponseCode property:
if(callbackResults.ResponseCode!="200"){
/* Some error, you can add a message too */
} else {
/* All fine, proceed with code */
};
Your problem is that you have key
and value
in quotes making them strings, i.e. you're setting aKey
to contain the string "key"
and not the value of the variable key
. Also, you're not clearing out the temp
list, so you're adding to it each time, instead of just having two items in it.
To fix your code, try something like:
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
You don't need to copy the loop variables key
and value
into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value])
if we wanted to be as brief as possible.
Or just use dict.items()
as has been suggested.
Kotlin example:
private val SPLASH_DELAY: Long = 1000
internal val mRunnable: Runnable = Runnable {
if (!isFinishing) {
val intent = Intent(applicationContext, HomeActivity::class.java)
startActivity(intent)
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
finish()
}
}
private fun navigateToHomeScreen() {
//Initialize the Handler
mDelayHandler = Handler()
//Navigate with delay
mDelayHandler!!.postDelayed(mRunnable, SPLASH_DELAY)
}
public override fun onDestroy() {
if (mDelayHandler != null) {
mDelayHandler!!.removeCallbacks(mRunnable)
}
super.onDestroy()
}
put animations in anim folder:
slide_in.xml
<?xml version="1.0" encoding="utf-8"?>
<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@android:integer/config_longAnimTime"
android:fromXDelta="100%p"
android:toXDelta="0%p">
</translate>
slide_out.xml
<?xml version="1.0" encoding="utf-8"?>
<translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@android:integer/config_longAnimTime"
android:fromXDelta="0%p"
android:toXDelta="-100%p">
</translate>
USAGE
navigateToHomeScreen();
Here is an answer that works with data.table and is simpler. This assumes your data.table is named yourDF
:
j1 <- max.col(yourDF[, .(V1, V2, V3, V4)], "first")
yourDF$newCol <- c("V1", "V2", "V3", "V4")[j1]
Replace ("V1", "V2", "V3", "V4")
and (V1, V2, V3, V4)
with your column names
$('#' + catId).parent().remove('.subcatBtns');
Declare @phoneNumber int
select @phoneNumber=Isnull('08041159620',0);
Give error :
The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)
AS
Integer is defined as :
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
Solution
Declare @phoneNumber bigint
pd.concat
accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.
pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)
Or,
pd.concat({
k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
},
axis=0)
att_1 att_2
12 Category 1 1 whatever
Category 2 23 another
15 Category 1 10 foo
Category 2 30 bar
The connection URL should look like this for SQL Server:
jdbc:sqlserver://serverName[\instanceName][:port][;databaseName=your_db_name]
Examples:
jdbc:sqlserver://localhost
jdbc:sqlserver://127.0.0.1\INGESQL:1433;databaseName=datatest
...
Wrap the xml in another element
<wrapper>
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</wrapper>
To select by class
, you can do this:
$("input.className:checkbox:not(:checked)")
If you can repeat the whole thing, or subset it first then repeat that, then this similar question may be helpful. Once again:
library(mefa)
rep(mtcars,10)
or simply
mefa:::rep.data.frame(mtcars)
Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.
That's the default assumption -- exceptions are not raised.
If you say nothing else, that's assumed in every single test.
You don't have to actually write an any assertion for that.
The information there is I think partially correct:
That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.
As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the +
is defined, though %20
is standard.
[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*
This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.
Using Angular 2 (RC5) and hash-based routes, I do this:
const appRoutes: Routes = [
...
{path: '_', redirectTo: '/facebookLoginSuccess'},
...
]
and
export const routing = RouterModule.forRoot(appRoutes, { useHash: true });
As far as I understand, the =
character in the route is interpreted as part of optional route parameters definition (see https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters), so not involved in the route matching.
Since Maven 3.5.0 you can use the ${revision}
placeholder for that. The use is documented here: Maven CI Friendly Versions.
In short the parent pom looks like this (quoted from the Apache documentation):
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache</groupId>
<artifactId>apache</artifactId>
<version>18</version>
</parent>
<groupId>org.apache.maven.ci</groupId>
<artifactId>ci-parent</artifactId>
<name>First CI Friendly</name>
<version>${revision}</version>
...
<properties>
<revision>1.0.0-SNAPSHOT</revision>
</properties>
<modules>
<module>child1</module>
..
</modules>
</project>
and the child pom like this
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.maven.ci</groupId>
<artifactId>ci-parent</artifactId>
<version>${revision}</version>
</parent>
<groupId>org.apache.maven.ci</groupId>
<artifactId>ci-child</artifactId>
...
</project>
You also have to use the Flatten Maven Plugin to generate pom documents with the dedicated version number included for deployment. The HowTo is documented in the linked documentation.
Also @khmarbaise wrote a nice blob post about this feature: Maven: POM Files Without a Version in It?
I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.
If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.
As an example, see it here a JavaScript that make select like editable.
If you are not sure how many parameters are you going to be passed into callback functions, use apply
function.
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester(callback,params){
callback.apply(this,params);
}
callbackTester(tryMe,['hello','goodbye']);
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
It's really hard to tell, but one of the 9001 ads on the page may be clobbering the $
object.
jQuery provides the global jQuery
object (which is present on your page). You can do the following to "get" $
back:
jQuery(document).ready(function ($) {
// Your code here
});
If you think you're having jQuery problems, please use the debug (non-production) versions of the library.
Also, it's probably not best to be editing a live site like that ...
If the were checked as plugin-projects, than you just need to check them out. But do not select the "trunk"(for example) to speed it up. You must select all the projects you want to check out and proceed. Eclipse will than recognize them as such.
Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);
Swift 3 here's how i do it.
{
import UIKit
import AVFoundation
let url = Bundle.main.url(forResource: "yoursoundname", withExtension: "wav")!
do {
player = try AVAudioPlayer(contentsOf: url); guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as Error {
print(error)
}
}
I'am posting this answer because many visitors enter here from google for this problem.
string result = this.GetType().GetMethod("Print").Invoke(this, new object[]{"firstParam", 157, "third_Parammmm" } );
when external .dll -instead of this.GetType()
, you might use typeof(YourClass)
.
On your project folder, open up the bin\Debug subfolder and you'll see the compiled result.
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
I know this topic is old, but I have a simpler working solution without export the variables. Can be a oneliner, but I prefer to split using \
on line end.
var1='myVar1'\
var2=2\
var3=${var1}\
envsubst '$var1,$var3' < "source.txt" > "destination.txt"
# ^^^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^^^^^^^^^
# define which to replace input output
The variables need to be defined to the same line as envsubst
is to get considered as environment variables.
The '$var1,$var3'
is optional to only replace the specified ones. Imagine an input file containing ${VARIABLE_USED_BY_JENKINS}
which should not be replaced.
Try this:
case $VAR in
normal)
echo "This doesn't do fallthrough"
;;
special)
echo -n "This does "
;&
fallthrough)
echo "fall-through"
;;
esac
I am not sure what you understand by "execute from the Command line interface", but you're probably looking after the following select statement:
select * from dba_users;
or
select username from dba_users;
You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file
I don't think you properly understood what you read. If it gets compiled to the correct type, then there is no difference. When I do this:
var i = 42;
The compiler knows it's an int, and generate code as if I had written
int i = 42;
As the post you linked to says, it gets compiled to the same type. It's not a runtime check or anything else requiring extra code. The compiler just figures out what the type must be, and uses that.
var getKeyByDinner = function(obj, dinner) {
var returnKey = -1;
$.each(obj, function(key, info) {
if (info.dinner == dinner) {
returnKey = key;
return false;
};
});
return returnKey;
}
So long as -1
isn't ever a valid key.
The functionality is indeed similar (apart from the calling semantics, where call-template
requires a name
attribute and a corresponding names template).
However, the parser will not execute the same way.
From MSDN:
Unlike
<xsl:apply-templates>
,<xsl:call-template>
does not change the current node or the current node-list.
If you are using Typescript 3.x, you may be able to omit the declare global
part in the other answers and instead just use:
interface Window {
someValue: string
another: boolean
}
This worked with me when using Typescript 3.3, WebPack and TSLint.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
request.getParameterValues("select2")
returns an array of all submitted values.
You don't need FileInputStream to calculate file size, new File(path_to_file).length()
is enough. Or, if you insist, use fileinputstream.getChannel().size()
.
If you are using Java version 7 or higher, you can use try-with-resources to properly close the FileOutputStream
. The following code use IOUtils.copy()
from commons-io.
public void copyToFile(InputStream inputStream, File file) throws IOException {
try(OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(inputStream, outputStream);
}
}
This is the solution . Its quite simple as a matter of fact
function binaries(num1){
var str = num1.toString(2)
return(console.log('The binary form of ' + num1 + ' is: ' + str))
}
binaries(3
)
/*
According to MDN, Number.prototype.toString() overrides
Object.prototype.toString() with the useful distinction that you can
pass in a single integer argument. This argument is an optional radix,
numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to
get a string representation of the binary for the base 10 number 100,
i.e. 1100100.
*/
You need to create your own converter and implement it before making a GET request.
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
Instead of using RequestContextHolder
directly, you can also use ServletUriComponentsBuilder
and its static methods:
ServletUriComponentsBuilder.fromCurrentContextPath()
ServletUriComponentsBuilder.fromCurrentServletMapping()
ServletUriComponentsBuilder.fromCurrentRequestUri()
ServletUriComponentsBuilder.fromCurrentRequest()
They use RequestContextHolder
under the hood, but provide additional flexibility to build new URLs using the capabilities of UriComponentsBuilder
.
Example:
ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequestUri();
builder.scheme("https");
builder.replaceQueryParam("someBoolean", false);
URI newUri = builder.build().toUri();
if you want to concatenate the string representation of the values of two variables, use the +
sign :
var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1
But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:
function Container(){
this.variables = [];
}
Container.prototype.addVar = function(var){
this.variables.push(var);
}
Container.prototype.toString = function(){
var result = '';
for(var i in this.variables)
result += this.variables[i];
return result;
}
var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1
the advantage is that you can get the string representation of the two variables, bit you can modify them later :
container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3
Following are few libraries to create PDF with Java:
I have used iText for genarating PDF's with a little bit of pain in the past.
Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
Bootstrap's default setting is to keep the menu open when you click on a menu item. You can manually override this behaviour by calling .collapse('hide');
on the jQuery element that you want to collapse.
You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="@+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="@+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Add" />
</RelativeLayout>
Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int pos) {
return list.get(pos);
}
@Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_custom_list_layout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
Hope this helps!
Your code doesn't work (parse) because you have an extra )
at the end that causes a Parse Error. Count, you have 2 (
and 3 )
. It would work fine if you fix that, but strtotime()
returns a timestamp, so to get a human readable time use date()
.
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the )
is the main issue here.
To add to all the wonderful answers here
First of all float and double are both used for representation of numbers fractional numbers. So, the difference between the two stems from the fact with how much precision they can store the numbers.
For example: I have to store 123.456789 One may be able to store only 123.4567 while other may be able to store the exact 123.456789.
So, basically we want to know how much accurately can the number be stored and is what we call precision.
Quoting @Alessandro here
The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.
Float can accurately store about 7-8 digits in the fractional part while Double can accurately store about 15-16 digits in the fractional part
So, float can store double the amount of fractional part. That is why Double is called double the float
Adding the "x_ua_compatible" tag to the page didn't work for me. Instead I added it as an HTTP Respone Header via IIS and that worked fine.
In IIS Manager select the site then open HTTP Response Headers and click Add:
The site didn't need restarting, but I did need to Ctrl+F5 to force the page to reload.
It is a long time. Maybe like this:
public int smallestValue(int[] values)
{
int smallest = int.MaxValue;
for (int i = 0; i < values.Length; i++)
{
smallest = (values[i] < smallest ? values[i] : smallest);
}
return smallest;
}
public static int largestvalue(int[] values)
{
int largest = int.MinValue;
for (int i = 0; i < values.Length; i++)
{
largest = (values[i] > largest ? values[i] : largest);
}
return largest;
}
You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip
the list with a slice of itself such that you can sum the pairs.
b = [i + j for i, j in zip(a, a[1:])]
For Firefox/Chrome users, a nice way to achieve 100% width is to use a custom TamperMonkey script.
The benefits are
This script works for me https://gist.githubusercontent.com/mrk-andreev/2a9c2538fad0b687c27e192d5948834f/raw/6aa1148573dc20a22fca126e56e3b03f4abf281b/jpn_tmonkey.js
Is a good idea named the functions with commun alias on the first words for filtre the name with LIKE
Example with public schema in Postgresql 9.4, be sure to replace with his scheme
SELECT routine_name
FROM information_schema.routines
WHERE routine_type='FUNCTION'
AND specific_schema='public'
AND routine_name LIKE 'aliasmyfunctions%';
After 48 hours of the still not being updated I removed the app from sale on Pricing and Availability.
Then I waited 1 hour.
Then I ticked All Territories Selected again.
After the app came available for download again the version number was updated.
Here use asp:CompareValidator, and compare the value to "select" option.
Use Operator="NotEqual" ValueToCompare="0"
to prevent the user from submitting the "select".
<asp:CompareValidator ControlToValidate="ddlReportType" ID="CompareValidator1"
ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
runat="server" Display="Dynamic"
Operator="NotEqual" ValueToCompare="0" Type="Integer" />
When you do above, if you select the "select " option from dropdown it will show the ErrorMessage
.
Go to run as and choose Run Configurations
-> Common
and in the Standard Input and Output you can choose a File also.
Adapt-Strap. Here is the fiddle.
It is extremely lightweight and has dynamic row heights.
<ad-table-lite table-name="carsForSale"
column-definition="carsTableColumnDefinition"
local-data-source="models.carsForSale"
page-sizes="[7, 20]">
</ad-table-lite>
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
The error SyntaxError: invalid character in identifier
means you have some character in the middle of a variable name, function, etc. that's not a letter, number, or underscore. The actual error message will look something like this:
File "invalchar.py", line 23
values = list(analysis.values ())
^
SyntaxError: invalid character in identifier
That tells you what the actual problem is, so you don't have to guess "where do I have an invalid character"? Well, if you look at that line, you've got a bunch of non-printing garbage characters in there. Take them out, and you'll get past this.
If you want to know what the actual garbage characters are, I copied the offending line from your code and pasted it into a string in a Python interpreter:
>>> s=' values ??= list(analysis.values ??())'
>>> s
' values \u200b\u200b= list(analysis.values \u200b\u200b())'
So, that's \u200b
, or ZERO WIDTH SPACE. That explains why you can't see it on the page. Most commonly, you get these because you've copied some formatted (not plain-text) code off a site like StackOverflow or a wiki, or out of a PDF file.
If your editor doesn't give you a way to find and fix those characters, just delete and retype the line.
Of course you've also got at least two IndentationError
s from not indenting things, at least one more SyntaxError
from stay spaces (like = =
instead of ==
) or underscores turned into spaces (like analysis results
instead of analysis_results
).
The question is, how did you get your code into this state? If you're using something like Microsoft Word as a code editor, that's your problem. Use a text editor. If not… well, whatever the root problem is that caused you to end up with these garbage characters, broken indentation, and extra spaces, fix that, before you try to fix your code.
gcc -I/path -L/path
-I /path
path to include, gcc will find .h files in this path
-L /path
contains library files, .a
, .s
o
Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP
Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object
Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB
Although this question is being asked for 5 years ago. I just want to share my answer. Below is how I detect whether someone is clicked cancel and OK button in input box:
Public sName As String
Sub FillName()
sName = InputBox("Who is your name?")
' User is clicked cancel button
If StrPtr(sName) = False Then
MsgBox ("Please fill your name!")
Exit Sub
End If
' User is clicked OK button whether entering any data or without entering any datas
If sName = "" Then
' If sName string is empty
MsgBox ("Please fill your name!")
Else
' When sName string is filled
MsgBox ("Welcome " & sName & " and nice see you!")
End If
End Sub
this
is a reference for the DOM element for which the event is being handled (the current target). event.target
refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.
You can get a good sense of this by reviewing the jQuery event docs, but in summary:
event.currentTarget
The current DOM element within the event bubbling phase.
event.delegateTarget
The element where the currently-called jQuery event handler was attached.
event.relatedTarget
The other DOM element involved in the event, if any.
event.target
The DOM element that initiated the event.
To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this)
or $(evt.target)
.
The .attr()
method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href')
or simply evt.target.href
will give you what you want.
It depends on where it is located. If it is a common header, then you are diminishing the value of the namespace by merging it into the global namespace. Keep in mind, this could be a neat way of making module globals.
Just go to the Readme.md file and use this code.
<div align="center">
<img src=https://newfastuff.com/wp-content/uploads/2019/05/bW7QXVB.png" >
<p>Perfectly balanced</p>
</div>
<div align=”center”> [ Your content here ]</div>
fits everything in the page and center aligns it according to the dimensions of the page.
Just call plt.show()
at the end:
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0,50,60,80])
for i in np.arange(1,5):
z = 68 + 4 * np.random.randn(50)
zm = np.cumsum(z) / range(1,len(z)+1)
plt.plot(zm)
n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)
plt.plot(n,su,n,sl)
plt.show()
One thing you might want to consider besides the other issues mentioned is that isEmpty()
was introduced in 1.6, so if you use it you won't be able to run the code on Java 1.5 or below.
I would omit the * { text-align:center }
declaration, as it sets center alignment for all elements.
Usually with a fixed width container margin: 0 auto
should be enough
You could use JavaScript and trigger the hidden file input when the button input has been clicked.
http://jsfiddle.net/gregorypratt/dhyzV/ - simple
http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery
Or, you could style a div directly over the file input and set pointer-events
in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events
The following approach worked in Angular 5 CLI.
For sake of simplicity, I used similar d3gauge.js demo created and provided by oliverbinns - which you may easily find on Github.
So first, I simply created a new folder named externalJS on same level as the assets folder. I then copied the 2 following .js files.
I then made sure to declare both linked directives in main index.html
<script src="./externalJS/d3.v3.min.js"></script>
<script src="./externalJS/d3gauge.js"></script>
I then added a similar code in a gauge.component.ts component as followed:
import { Component, OnInit } from '@angular/core';
declare var d3gauge:any; <----- !
declare var drawGauge: any; <-----!
@Component({
selector: 'app-gauge',
templateUrl: './gauge.component.html'
})
export class GaugeComponent implements OnInit {
constructor() { }
ngOnInit() {
this.createD3Gauge();
}
createD3Gauge() {
let gauges = []
document.addEventListener("DOMContentLoaded", function (event) {
let opt = {
gaugeRadius: 160,
minVal: 0,
maxVal: 100,
needleVal: Math.round(30),
tickSpaceMinVal: 1,
tickSpaceMajVal: 10,
divID: "gaugeBox",
gaugeUnits: "%"
}
gauges[0] = new drawGauge(opt);
});
}
}
and finally, I simply added a div in corresponding gauge.component.html
<div id="gaugeBox"></div>
et voilà ! :)
And, of course
("ABCD"[2] == 2["ABCD"]) && (2["ABCD"] == 'C') && ("ABCD"[2] == 'C')
The main reason for this was that back in the 70's when C was designed, computers didn't have much memory (64KB was a lot), so the C compiler didn't do much syntax checking. Hence "X[Y]
" was rather blindly translated into "*(X+Y)
"
This also explains the "+=
" and "++
" syntaxes. Everything in the form "A = B + C
" had the same compiled form. But, if B was the same object as A, then an assembly level optimization was available. But the compiler wasn't bright enough to recognize it, so the developer had to (A += C
). Similarly, if C
was 1
, a different assembly level optimization was available, and again the developer had to make it explicit, because the compiler didn't recognize it. (More recently compilers do, so those syntaxes are largely unnecessary these days)
To convert any type object to a generic type T
, the trick is to first assign to an object of any higher type then cast that to the generic type.
object temp = otherTypeObject;
T result = (T)temp;
Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
In your adapter class, in onBindViewHolder method, set ViewHolder to setIsRecyclable(false) as in below code.
@Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder p1, int p2)
{
// TODO: Implement this method
p1.setIsRecyclable(false);
// Then your other codes
}
You either follow above approach or this one
Create the config file in the .ssh directory and add these line.
host xxx.xxx
Hostname xxx.xxx
IdentityFile ~/.ssh/id_rsa
User xxx
KexAlgorithms +diffie-hellman-group1-sha1
The following works fine:
backgroundColor: 'rgba(52, 52, 52, alpha)'
You could also try:
backgroundColor: 'transparent'
Try this...
* {
transition: all .2s linear;
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
-o-transition: all .2s linear;
}
a {
-webkit-transition: background-position 1ms linear;
-moz-transition: background-position 1ms linear;
-o-transition: background-position 1ms linear;
transition: background-position 1ms linear;
}
If you are using Netbeans, there is a nice shortcut to this.
Just define a goal exec:java
and add the property jpda.listen=maven
Tested on Netbeans 7.3
You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:
char **orderedIds;
orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...
Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"
According to the documentation, timestamp
is a synonym for rowversion
- it's automatically generated and guaranteed1 to be unique. datetime
isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.
1 Assuming you use it properly, of course. See comments.
They have the same speed. Maybe in some special architecture what he/she said is right, but in the x86 family at least I know they are the same. Because for doing this the CPU will do a substraction (a - b) and then check the flags of the flag register. Two bits of that register are called ZF (zero Flag) and SF (sign flag), and it is done in one cycle, because it will do it with one mask operation.
The following is an example of using SharedPreferences
to achieve a 'first run' check.
public class MyActivity extends Activity {
SharedPreferences prefs = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
When the code runs prefs.getBoolean(...)
if there isn't a boolean
saved in SharedPreferences
with the key "firstrun" then that indicates the app has never been run (because nothing has ever saved a boolean with that key or the user has cleared the app data in order to force a 'first run' scenario). If this isn't the first run then the line prefs.edit().putBoolean("firstrun", false).commit();
will have been executed and therefore prefs.getBoolean("firstrun", true)
will actually return false as it overrides the default true provided as the second parameter.
Use this.
$('#mydiv').load(document.URL + ' #mydiv');
Note, include a space before the hastag.
StringComparison.InvariantCultureIgnoreCase just do the job for me:
.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));
Use the iFrame's .onload
function of JavaScript:
<iframe id="my_iframe" src="http://www.test.tld/">
<script type="text/javascript">
document.getElementById('my_iframe').onload = function() {
__doPostBack('ctl00$ctl00$bLogout','');
}
</script>
<!--OTHER STUFF-->
</iframe>
In my case it was from "Automatic Backlink Checker" extension. Maybe this will help some other users to fix their problem easier. I went from disabling all of the extensions at once to disabling them one by one. This way the mole.
Regards
Just two lines of code, it works.
#content {
background-image: url('../images/bg.png');
background-size: cover;
}
There are several ways:
Instantiating the array:
var arr;
arr = new Array(); // empty array
// ---
arr = []; // empty array
// ---
arr = new Array(3);
alert(arr.length); // 3
alert(arr[0]); // undefined
// ---
arr = [3];
alert(arr.length); // 1
alert(arr[0]); // 3
Pushing to the array:
arr = [3]; // arr == [3]
arr[1] = 4; // arr == [3, 4]
arr[2] = 5; // arr == [3, 4, 5]
arr[4] = 7; // arr == [3, 4, 5, undefined, 7]
// ---
arr = [3];
arr.push(4); // arr == [3, 4]
arr.push(5); // arr == [3, 4, 5]
arr.push(6, 7, 8); // arr == [3, 4, 5, 6, 7, 8]
Using .push()
is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.
sentence="one;two;three"
a="${sentence};"
while [ -n "${a}" ]
do
echo ${a%%;*}
a=${a#*;}
done
Try the below code it should work
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked == false)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = chk.TrueValue;
}
}
else if (checkBox2.Checked == true)
{
foreach (DataGridViewRow row in dGV1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = 1;
if (row.IsNewRow)
{
chk.Value = 0;
}
}
}
}
I had the same issue on my Xamarin application in visual studio and it was resolved by unplugging my test mobile device. The application was closed and the debugger was stopped but the error was still happening when trying to build or rebuild the solution. It only stopped after i unplugged the device because i had to receive a call.
It's called spread attributes and its aim is to make the passing of props easier.
Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.
<Component x={} y={} z={} />
Thus instead you do this, wrap them up in an object and use the spread notation
var props = { x: 1, y: 1, z:1 };
<Component {...props} />
which will unpack it into the props on your component, i.e., you "never" use {... props}
inside your render()
function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x
.
Incidentally, if your span
class is even-numbered (e.g. span8
) you can add an offset
class to center it – for span8
that would be offset2
(assuming the default 12-column grid), for span6
it would be offset3
and so on (basically, half the number of remaining columns if you subtract the span
-number from the total number of columns in the grid).
UPDATE
Bootstrap 3 renamed a lot of classes so all the span*
classes should be col-md-*
and the offset
classes should be col-md-offset-*
, assuming you're using the medium-sized responsive grid.
I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.
There are two steps here: troubleshooting and then fixing the issue:
To troubleshoot, check to see if it is a browser and/or extension problem. Chrome, Firefox and others have incognito or private mode which does not load extensions or the basic database of passwords and cookies.
In the case of ERR_BLOCKED_BY_CLIENT that is usually some kind of blocking software, such as Adblock, Ghostery, or some other kind of privacy/anti-spyware tool.
There's a Babel plugin that allows you to write conditional statements inside JSX without needing to escape them with JavaScript or write a wrapper class. It's called JSX Control Statements:
<View style={styles.container}>
<If condition={ this.state == 'news' }>
<Text>data</Text>
</If>
</View>
It takes a bit of setting up depending on your Babel configuration, but you don't have to import anything and it has all the advantages of conditional rendering without leaving JSX which leaves your code looking very clean.
I actually ended up with something like this to allow for the navbar collapse.
@media (min-width: 768px) { //set this to wherever the navbar collapse executes
.navbar-nav > li > a{
line-height: 7em; //set this height to the height of the logo.
}
}
I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)}
>
</div>
)
}
There is no datetime dtype to be set for read_csv as csv files can only contain strings, integers and floats.
Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string.
The pandas.read_csv()
function has a keyword argument called parse_dates
Using this you can on the fly convert strings, floats or integers into datetimes using the default date_parser
(dateutil.parser.parser
)
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = {'col1': 'str', 'col2': 'str', 'col3': 'str', 'col4': 'float'}
parse_dates = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes, parse_dates=parse_dates)
This will cause pandas to read col1
and col2
as strings, which they most likely are ("2016-05-05" etc.) and after having read the string, the date_parser for each column will act upon that string and give back whatever that function returns.
The pandas.read_csv()
function also has a keyword argument called date_parser
Setting this to a lambda function will make that particular function be used for the parsing of the dates.
You have to give it the function, not the execution of the function, thus this is Correct
date_parser = pd.datetools.to_datetime
This is incorrect:
date_parser = pd.datetools.to_datetime()
pd.datetools.to_datetime
has been relocated to date_parser = pd.to_datetime
Thanks @stackoverYC
function deleteEmpty(obj){
for(var k in obj)
if(k == "children"){
if(obj[k]){
deleteEmpty(obj[k]);
}else{
delete obj.children;
}
}
}
for(var i=0; i< a.children.length; i++){
deleteEmpty(a.children[i])
}
I've tested the performance of all the proposed approaches.
Here is the fastest variant I've got.
String.prototype.repeat = function(count) {
if (count < 1) return '';
var result = '', pattern = this.valueOf();
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
};
Or as stand-alone function:
function repeat(pattern, count) {
if (count < 1) return '';
var result = '';
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
return result + pattern;
}
It is based on artistoex algorithm.
It is really fast. And the bigger the count
, the faster it goes compared with the traditional new Array(count + 1).join(string)
approach.
I've only changed 2 things:
pattern = this
with pattern = this.valueOf()
(clears one obvious type conversion);if (count < 1)
check from prototypejs to the top of function to exclude unnecessary actions in that case.UPD
Created a little performance-testing playground here for those who interested.
variable count
~ 0 .. 100:
constant count
= 1024:
Use it and make it even faster if you can :)
Yes. It is done with a filter on the appender.
Here is the appender configuration I normally use, limited to only INFO level.
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="${HOMEDRIVE}\\PI.Logging\\PI.ECSignage.${COMPUTERNAME}.log" />
<appendToFile value="true" />
<maxSizeRollBackups value="30" />
<maximumFileSize value="5MB" />
<rollingStyle value="Size" /> <!--A maximum number of backup files when rolling on date/time boundaries is not supported. -->
<staticLogFileName value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.ffff} [%2thread] %-5level %20.20type{1}.%-25method at %-4line| (%-30.30logger) %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="INFO" />
</filter>
</appender>
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
I've had the same problem from Azure DevOps (Visual Studio). Finally I've decided to clone my repo using SSH protocol because of i've prefered it instead of disabling SSL verification.
You only need to generate a SSH Key, you can do it so... SSH documentation
ssh-keygen
And then, import your public key on yout git host (like Azure Devops, Github, Bitbucket, Gitlab, etc.)
ul {
list-style-type: none;
}
ul li:before {
content:'*'; /* Change this to unicode as needed*/
width: 1em !important;
margin-left: -1em;
display: inline-block;
}
android.os.Build.VERSION.SDK_INT
Here you can find the possible values: VERSION_CODES
.
you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number
#!/usr/bin/ruby
first_number = ARGV[0].to_i
second_number = ARGV[1].to_i
puts first_number + second_number
and you call it like this
% ./plus.rb 5 6
==> 11
You can do this without jquery...
<select onchange="event.target.selectedIndex = 0">
...
</select>
or you can do a function to check your condition
<select onchange="check(event)">
...
</select>
<script>
function check(e){
if (my_condition){
event.target.selectedIndex = 0;
}
}
</script>
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
Jquery Code
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
HTML CODE
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Pure javascript would be like this
var children = document.getElementById('test').children;
If you are using jQuery it would be like this
$("#test").children()
If you have seaborn
installed, an easier method that does not require you to perform pivot
:
import seaborn as sns
sns.lineplot(data=df, x='x', y='y', hue='color')
To complement the two previous answers, Angular2 supports both query parameters and path variables within routing. In @RouteConfig
definition, if you define parameters within a path, Angular2 handles them as path variables and as query parameters if not.
Let's take a sample:
@RouteConfig([
{ path: '/:id', component: DetailsComponent, name: 'Details'}
])
If you call the navigate
method of the router like this:
this.router.navigate( [
'Details', { id: 'companyId', param1: 'value1'
}]);
You will have the following address: /companyId?param1=value1
. The way to get parameters is the same for both, query parameters and path variables. The difference between them is that path variables can be seen as mandatory parameters and query parameters as optional ones.
Hope it helps you, Thierry
UPDATE: After changes in router alpha.31 http query params no longer work (Matrix params #2774). Instead angular router uses so called Matrix URL notation.
Reference https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters:
The optional route parameters are not separated by "?" and "&" as they would be in the URL query string. They are separated by semicolons ";" This is matrix URL notation — something you may not have seen before.
I think that the problem is in the nesting of the elements. Once you attach an event to the outer element the clicks on the inner elements are actually firing the same click event for the outer element. So, you actually never go to the second state. What you can do is to check the clicked element. And if it is the close button then to avoid the class changing. Here is my solution:
var element = $(".clickable");
var closeButton = element.find(".close_button");
var onElementClick = function(e) {
if(e.target !== closeButton[0]) {
element.removeClass("spot").addClass("grown");
element.off("click");
closeButton.on("click", onCloseClick);
}
}
var onCloseClick = function() {
element.removeClass("grown").addClass("spot");
closeButton.off("click");
element.on("click", onElementClick);
}
element.on("click", onElementClick);
In addition I'm adding and removing event handlers.
JSFiddle -> http://jsfiddle.net/zmw9E/1/
I found a notable exception that in Windows 10, using the described route only wrote the files to the folder if the file names where not specified in the ssh-keygen generator.
giving a custom key name caused the files containing the RSA public and private keys not to be written to the folder.
ssh-keygen
c:/Users/YourUserName/.ssh/
(using Admin Command Line and Windows 10 Pro)
I still think that Harry's answer is the simplest and completed but if you need something even simpler, then use:
struct AppError {
let message: String
init(message: String) {
self.message = message
}
}
extension AppError: LocalizedError {
var errorDescription: String? { return message }
// var failureReason: String? { get }
// var recoverySuggestion: String? { get }
// var helpAnchor: String? { get }
}
And use or test it like this:
printError(error: AppError(message: "My App Error!!!"))
func print(error: Error) {
print("We have an ERROR: ", error.localizedDescription)
}
you can use 'email' or 'emailx' command.
(1) $ vim /etc/mail.rc # or # vim /etc/nail.rc
set from = [email protected] #
set smtp = smtp.exmail.gmail.com #gmail's smtp server
set smtp-auth-user = [email protected] #sender's email address
set smtp-auth-password = xxxxxxx #get from gmail, not your email account passwd
set smtp-auth=login
(2) $ echo "Pls remember to remove unused ons topics!" | mail -s "waste topics" -a a.txt [email protected] #send to group user '[email protected]'
$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"<br/>";
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
In case you want to use bootstrap radio to check one of them depends on the result of your checked var in the .ts file.
component.html
<h1>Radio Group #1</h1>
<div class="btn-group btn-group-toggle" data-toggle="buttons" >
<label [ngClass]="checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio1" value="option1" type="radio"> TRUE
</label>
<label [ngClass]="!checked ? 'active' : ''" class="btn btn-outline-secondary">
<input name="radio" id="radio2" value="option2" type="radio"> FALSE
</label>
</div>
component.ts file
@Component({
selector: '',
templateUrl: './.component.html',
styleUrls: ['./.component.css']
})
export class radioComponent implements OnInit {
checked = true;
}
Your @POST
method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:
@XmlRootElement
public class MyJaxBean {
@XmlElement public String param1;
@XmlElement public String param2;
}
Then your @POST
method would look like the following:
@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
System.out.println("param1 = " + input.param1);
System.out.println("param2 = " + input.param2);
}
This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input
in this case. The actual message would look something like:
POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com
{"param1":"hello","param2":"world"}
Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.
HTML <FORM>
The parameters would be annotated using @FormParam:
@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
@FormParam("param2") String param2) {
...
}
The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:
POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25
param1=hello¶m2=world
The content is URL encoded in this case.
If you do not know the names of the FormParam's you can do the following:
@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
...
}
HTTP Headers
You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:
@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
@HeaderParam("param2") String param2) {
...
}
Here's what the HTTP message would look like. Note that this POST does not have a body.
POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world
I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.
HTTP Query Parameters
This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.
@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
@QueryParam("param2") String param2) {
...
}
Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:
POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com
You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.
HTTP Path Parameters
Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:
@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
@PathParam("param2") String param2) {
...
}
The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.
POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com
This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.
As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM
-based HTML pages, then use @FormParam
. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer
implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM
encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.
Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.
You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:
function PersonListCtrl($scope, $http) {
$scope.loadData = function () {
$http.get('/persons').success(function(data) {
$scope.persons = data;
});
};
//initial load
$scope.loadData();
}
then in your markup
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="loadData()">Refresh</button>
</div>
As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:
for example (just puedo code) in your controller:
$scope.addPerson = function() {
$scope.persons.push({ name: 'Test Monkey' });
};
Then you could use that in your view or whatever you'd want to do.
For me this error wouldn't go away and allow PUT methods, whatever i did.. uninstalled webdav, put configuration in web.config to remove webdav from handlers and modules, and set up PUT as an allowed verb on the request filters on iis.. and ensure iis handler mappings handling the request had PUT configured..
My problem was eventually due to bad installation of ASP.NET 4.5 Extensions. Removed everything related to asp.net from server roles and features. restarted. readded the roles and restarted. everything worked with above config.
--- The below will make PUT be accepted, but will send it to the wrong handler. --ignore the below
finally, adding PUT verb as allowed verb on TRACE handler mapping on iis worked.. since i had enabled failed error tracing, and this verb was not allowing the verb.
last time i had the same problem on another server's IIS, it was due to a missing '/' at the end of the URL since it was using a default handler without using the default document probably and now i realize that.. so check IIS handler mappings if nothing else helps.
what jamietre said, but
Private Sub SomeVBASub
Cancel=False
DoStuff
If not Cancel Then DoAnotherStuff
If not Cancel Then AndFinallyDothis
End Sub
take a look at the jquery selectedbox plugin
selectOptions(value[, clear]):
Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");
, or a regular expression $("#myselect2").selectOptions(/^val/i);
.
You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
BTW. you should prefer coding against an Interface.
private ArrayList<String[]> action = new ArrayList<String[]>();
Should be
private List<String[]> action = new ArrayList<String[]>();
Yes, cd; and cd - would work. The reason It can see is that, directory is being deleted from any other terminal or any other program and recreate it. So i-node entry is modified so program can not access old i-node entry.
Just for me reading this snippet of code was hard, I just divided it into 2 readable lines :
// assuming that the Generic Type parameter is of type "T"
ParameterizedType p = (ParameterizedType) getClass().getGenericSuperclass();
Class<T> c =(Class<T>)p.getActualTypeArguments()[0];
I wanted to create an instance of the Type parameter without having any parameters to my method :
publc T getNewTypeInstance(){
ParameterizedType p = (ParameterizedType) getClass().getGenericSuperclass();
Class<T> c =(Class<T>)p.getActualTypeArguments()[0];
// for me i wanted to get the type to create an instance
// from the no-args default constructor
T t = null;
try{
t = c.newInstance();
}catch(Exception e){
// no default constructor available
}
return t;
}
This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.
public class sample6
{
public static void main(String... asf)
{
for(int i =0; i<256; i++)
{
System.out.println( i + ". " + (char)i);
}
}
}
A ReentrantLock is unstructured, unlike synchronized
constructs -- i.e. you don't need to use a block structure for locking and can even hold a lock across methods. An example:
private ReentrantLock lock;
public void foo() {
...
lock.lock();
...
}
public void bar() {
...
lock.unlock();
...
}
Such flow is impossible to represent via a single monitor in a synchronized
construct.
Aside from that, ReentrantLock
supports lock polling and interruptible lock waits that support time-out. ReentrantLock
also has support for configurable fairness policy, allowing more flexible thread scheduling.
The constructor for this class accepts an optional fairness parameter. When set
true
, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimedtryLock
method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.
ReentrantLock
may also be more scalable, performing much better under higher contention. You can read more about this here.
This claim has been contested, however; see the following comment:
In the reentrant lock test, a new lock is created each time, thus there is no exclusive locking and the resulting data is invalid. Also, the IBM link offers no source code for the underlying benchmark so its impossible to characterize whether the test was even conducted correctly.
When should you use ReentrantLock
s? According to that developerWorks article...
The answer is pretty simple -- use it when you actually need something it provides that
synchronized
doesn't, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling.ReentrantLock
also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority ofsynchronized
blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming "the performance will be better" if you useReentrantLock
. Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.
One final aspect that's gonna become more relevant in the near future has to do with Java 15 and Project Loom. In the (new) world of virtual threads, the underlying scheduler would be able to work much better with ReentrantLock
than it's able to do with synchronized
, that's true at least in the initial Java 15 release but may be optimized later.
In the current Loom implementation, a virtual thread can be pinned in two situations: when there is a native frame on the stack — when Java code calls into native code (JNI) that then calls back into Java — and when inside a
synchronized
block or method. In those cases, blocking the virtual thread will block the physical thread that carries it. Once the native call completes or the monitor released (thesynchronized
block/method is exited) the thread is unpinned.
If you have a common I/O operation guarded by a
synchronized
, replace the monitor with aReentrantLock
to let your application benefit fully from Loom’s scalability boost even before we fix pinning by monitors (or, better yet, use the higher-performanceStampedLock
if you can).
os.system()
returns the (encoded) process exit value. 0
means success:
On Unix, the return value is the exit status of the process encoded in the format specified for
wait()
. Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.
The output you see is written to stdout
, so your console or terminal, and not returned to the Python caller.
If you wanted to capture stdout
, use subprocess.check_output()
instead:
x = subprocess.check_output(['whoami'])
Without annotations, inferred property name (to match from JSON) would be "set", and not -- as seems to be the intent -- "isSet". This is because as per Java Beans specification, methods of form "isXxx" and "setXxx" are taken to mean that there is logical property "xxx" to manage.
Create below class in base class. Class To get all controls:
public static class ControlExtensions
{
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
}
From Database: Get All Actions IDs (like divAction1,divAction2 ....) dynamic in DATASET (DTActions) allow on specific User.
In Aspx: in HTML Put Action(button,anchor etc) in div or span and give them id like
<div id="divAction1" visible="false" runat="server" clientidmode="Static">
<a id="anchorAction" runat="server">Submit
</a>
</div>
IN CS: Use this function on your page:
private void ShowHideActions()
{
var controls = Page.GetAllControlsOfType<HtmlGenericControl>();
foreach (DataRow dr in DTActions.Rows)
{
foreach (Control cont in controls)
{
if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
{
cont.Visible = true;
}
}
}
}
For new version aws2.
aws2 s3 sync s3://SOURCE_BUCKET_NAME s3://NEW_BUCKET_NAME
The printStackTrace()
helps the programmer understand where the actual problem occurred. The printStackTrace()
method is a member of the class Throwable
in the java.lang
package.
I hope this will help you
Create table :
create table users (id int,first_name varchar(10),last_name varchar(10));
Insert values into the table :
insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');
In JAVA 8 its much easy now.
List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");
List<String> alphaNumbersUpperCase = alphaNumbers.stream()
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); // [FOUR, ONE, THREE, TWO]
-- For reverse use this
.sorted(Comparator.reverseOrder())
thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D
import java.util.*;
public class HelloWorld {
public static void main(String[] Args) {
Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);
int First = list.get(1);
int Second = list.get(2);
if (First < Second) {
System.out.println("One or more of your items have been restocked. The current stock is: " + First);
Random rn = new Random();
int answer = rn.nextInt(99) + 1;
System.out.println("You are buying " + answer + " New stock");
First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}
}
}
If you use old version of MySQL you can always use \P combined with some nice piece of awk code. Interesting example here
http://www.dbasquare.com/2012/03/28/how-to-work-with-a-long-process-list-in-mysql/
Isn't it exactly what you need?
I couldn't get the compiler (x64
version) to use the sysroot
until I added SET(CMAKE_SYSROOT $ENV{HOME}/raspberrypi/rootfs)
to pi.cmake
.
You can just convert everything to lowercase for the purposes of sorting:
SELECT * FROM NOTES ORDER BY LOWER(title);
If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:
SELECT * FROM NOTES ORDER BY LOWER(title), title;
I have Visual Studio 2013 installed. This worked for me:
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' != ''">12.0</VisualStudioVersion>`
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
So I've changed the condition from ==
to !=
and the value from 10.0
to 12.0
.
Where you have written the code
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.
You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
First of All Theory
Big O = Upper Limit O(n)
Theta = Order Function - theta(n)
Omega = Q-Notation(Lower Limit) Q(n)
In many Blogs & Books How this Statement is emphasised is Like
"This is Big O(n^3)" etc.
and people often Confuse like weather
O(n) == theta(n) == Q(n)
But What Worth keeping in mind is They Are Just Mathematical Function With Names O, Theta & Omega
so they have same General Formula of Polynomial,
Let,
f(n) = 2n4 + 100n2 + 10n + 50 then,
g(n) = n4, So g(n) is Function which Take function as Input and returns Variable with Biggerst Power,
Same f(n) & g(n) for Below all explainations
Big O(n4) = 3n4, Because 3n4 > 2n4
3n4 is value of Big O(n4) Just like f(x) = 3x
n4 is playing a role of x here so,
Replacing n4 with x'so, Big O(x') = 2x', Now we both are happy General Concept is
So 0 = f(n) = O(x')
O(x') = cg(n) = 3n4
Putting Value,
0 = 2n4 + 100n2 + 10n + 50 = 3n4
3n4 is our Upper Bound
Theta(n4) = cg(n) = 2n4 Because 2n4 = Our Example f(n)
2n4 is Value of Theta(n4)
so, 0 = cg(n) = f(n)
0 = 2n4 = 2n4 + 100n2 + 10n + 50
2n4 is our Lower Bound
This is Calculated to find out that weather lower Bound is similar to Upper bound,
Case 1). Upper Bound is Similar to Lower Bound
if Upper Bound is Similar to Lower Bound, The Average Case is Similar
Example, 2n4 = f(x) = 2n4,
Then Omega(n) = 2n4
Case 2). if Upper Bound is not Similar to Lower Bound
in this case, Omega(n) is Not fixed but Omega(n) is the set of functions with the same order of growth as g(n).
Example 2n4 = f(x) = 3n4, This is Our Default Case,
Then, Omega(n) = c'n4, is a set of functions with 2 = c' = 3
Hope This Explained!!
A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.
From Security Researcher, Scott Helme, here:
It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.
Well the hardest part probably is selecting the second "column" since I wouldn't know of an easy way to treat multiple spaces as one. For the rest it's easy. Use bash substitutions.
# cat bla.txt
something1: +12.0 (some unnecessary trailing data (this must go))
something2: +15.5 (some more unnecessary trailing data)
something4: +9.0 (some other unnecessary data)
something1: +13.5 (blah blah blah)
# cat bla.sh
OLDIFS=$IFS
IFS=$'\n'
for i in $(cat bla.txt); do
i=$(echo "$i" | awk '{print $2}')
u="${u:+$u, }$i"
done
IFS=$OLDIFS
echo "$u"
# bash ./bla.sh
+12.0, +15.5, +9.0, +13.5
I ran into the same issue and it's even worse: I needed both "import" and "require"
Here is what worked for me:
Turn your js file into .mjs as suggested in other answers
"require" is not defined with ES6 module, so you can define it this way:
import { createRequire } from 'module'
const require = createRequire(import.meta.url);
Now 'require' can be used in the usual way.
Use import for ES6 modules and require for commonJS.
Some useful links: node.js's own documentation. difference between import and require. Mozilla has some nice documentation about import
By JQuery using selectors
$("video_selector").trigger('play');
$("video_selector").trigger('pause');
$("div.video:first").trigger('play');$("div.video:first").trigger('pause');
$("#video_ID").trigger('play');$("#video_ID").trigger('pause');
By Javascript using ID
video_ID.play(); video_ID.pause();
OR
document.getElementById('video_ID').play(); document.getElementById('video_ID').pause();
.erb-image-wrapper img{
max-width:100% !important;
height:auto;
display:block;
}
Worked for me.
Thanks for MrMisterMan for his assistance.
Check this Official Link
In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/
.
In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".
If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs
If the server is already running you should see an Output
tab in NetBeans which is named similar to GlassFish Server x.x.x
You can also use cat
or tail -F
on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log
. If you are using a different domain then domain1
you have to adjust the path for that.
Prototype is the template of the class; which applies to all future instances of it. Whereas this is the particular instance of the object.
Setup JAVA_OPTS as a system variable with the following content:
JAVA_OPTS="-Xms256m -Xmx512m"
After that in a command prompt run the following commands:
SET JAVA_OPTS="-Xms256m -Xmx512m"
This can be explained as follows:
These values should be changed according to application requirements.
EDIT:
You can also try adding it through the Environment Properties menu which can be found at:
EDIT 2:
JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.
To setup a system variable you have to complete the steps listed above from 1 to 4.
Hive supports bigint literal since 0.8 version. So, additional "L" is enough:
COALESCE(column, 0L)
axis([xmin, xmax, ymin, ymax])
So you could add something like this at the end:
plt.axis([min(x_arr), max(x_arr), max(y_arr), 0])
Although you might want padding at each end so that the extreme points don't sit on the border.
The easiest way to add utility functions is to leave them at the global level:
function myUtilityFunction(x) { return "do something with "+x; }
Then, the simplest way to add a utility function (to a controller) is to assign it to $scope
, like this:
$scope.doSomething = myUtilityFunction;
Then you can call it like this:
{{ doSomething(x) }}
or like this:
ng-click="doSomething(x)"
EDIT:
The original question is if the best way to add a utility function is through a service. I say no, if the function is simple enough (like the isNotString()
example provided by the OP).
The benefit of writing a service is to replace it with another (via injection) for the purpose of testing. Taken to an extreme, do you need to inject every single utility function into your controller?
The documentation says to simply define behavior in the controller (like $scope.double
): http://docs.angularjs.org/guide/controller
This is what Array#map are good at
var arr = oFullResponse.results.map(obj => ({
key: obj.label,
sortable: true,
resizeable: true
}))
With the help of jquery it can be done as follows.
$("#color").prop('disabled', true);
To change the color of button programmatically
Button b1;
//colorAccent is the resource made in the color.xml file , you can change it.
b1.setBackgroundResource(R.color.colorAccent);
If you only got one IP on the server, there is no chance to do that. DNS is a simple name to number (IP) resolver. If you have two IPs on the server, you can point each subdomain to each of the IP-addresses and run both servers on the default port on each IP.
one.example.com -> 127.0.0.1 (server: 127.0.0.1:25565)
two.example.com -> 127.0.0.2 (server: 127.0.0.2:25565)
For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:
<?php
require_once('mylib.php');
session_start();
?>
In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.
HTH
Simple way, when you have just few fields one by one:
Need to set
android:maxLines="1"
android:imeOptions="actionNext"
android:inputType=""
<- Set your type of text, in other case it will be Multiline and prevent to go next
Sample:
<EditText android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/text_large"
android:maxLines="1"
android:inputType="textEmailAddress"
android:imeOptions="actionNext"
android:layout_marginLeft="@dimen/element_margin_large"
android:layout_marginRight="@dimen/element_margin_large"
android:layout_marginTop="0dp"/>
The long answer is available here, so I'll give you the short one.
When you do this:
String str = "abc";
You are calling the intern()
method on String. This method references an internal pool of String
objects. If the String you called intern()
on already resides in the pool, then a reference to that String
is assigned to str
. If not, then the new String
is placed in the pool, and a reference to it is then assigned to str
.
Given the following code:
String str = "abc";
String str2 = "abc";
boolean identity = str == str2;
When you check for object identity by doing ==
(you are literally asking: do these two references point to the same object?), you get true
.
However, you don't need to intern()
Strings
. You can force the creation on a new Object
on the Heap by doing this:
String str = new String("abc");
String str2 = new String("abc");
boolean identity = str == str2;
In this instance, str
and str2
are references to different Objects
, neither of which have been interned, so that when you test for Object
identity using ==
, you will get false
.
In terms of good coding practice: do not use ==
to check for String equality, use .equals()
instead.
If you're going to use the split function to extract the class names, then you're going to have to compensate for potential formatting variations that could produce unexpected results. For example:
" myclass1 myclass2 ".split(' ').join(".")
produces
".myclass1..myclass2."
I think you're better off using a regular expression to match on set of allowable characters for class names. For example:
" myclass1 myclass2 ".match(/[\d\w-_]+/g);
produces
["myclass1", "myclass2"]
The regular expression is probably not complete, but hopefully you understand my point. This approach mitigates the possibility of poor formatting.
You can try this :
git remote show origin | grep "branch_name"
branch_name
needs to be replaced with your branch
$ENV{FOO}
for usage, where FOO
is being picked up from the environment variable. otherwise use as ${FOO}
, where FOO
is some other variable. For setting, SET(FOO "foo")
would be used in CMake.
To write simpler,
enum class Color
{
Red = 1,
Green = 11,
Blue = 111
};
int value = static_cast<int>(Color::Blue); // 111
Try this [reverse order traversal]:
var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
console.log('node: ', childs[len]);
} while(len --);
OR [in order traversal]
var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
console.log('node: ', childs[i]);
} while(++i < len);
it takes this command about 2 mins to return the data as there is a lot of data
Probably, Bad Design. Consider using paging here.
default connection time is 30 secs, how do I increase this
As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this
// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;
What worked for me was:
.git/logs/refs/remotes/origin/branch
.git/refs/remotes/origin/branch
git gc --prune=now
There is something fundamentally wrong with what you're trying to do. Binary floating-points values do not have decimal places. You cannot meaningfully round one to a given number of decimal places, because most "round" decimal values simply cannot be represented as a binary fraction. Which is why one should never use float
or double
to represent money.
So if you want decimal places in your result, that result must either be a String
(which you already got with the DecimalFormat
), or a BigDecimal
(which has a setScale()
method that does exactly what you want). Otherwise, the result cannot be what you want it to be.
Read The Floating-Point Guide for more information.
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
What's this "other information"? An IP address?
In PHP, you use $_SERVER['REMOTE_ADDR']
to get the IP address of the remote client, then you can use gethostbyaddr()
to try and conver that IP into a hostname - but not all IPs have a reverse mapping configured.
Just be careful, .Contains()
will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A")
will return you both A and AA which you might not want. I have been bitten by it.
.Any()
or .Exists()
is safer choice
As from Android developer guide :
"orientation" The screen orientation has changed — the user has rotated the device. Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.
"screenSize" The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device). Added in API level 13.
So, in the AndroidManifest.xml file, we can put:
<activity
android:name=".activities.role_activity.GeneralViewPagerActivity"
android:label="@string/title_activity_general_view_pager"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden|screenSize"
>
</activity>
You can try below solutions to run build in your device.
Restart your iOS device (If device is recently updated) and your Xcode.
Make Sure that in build settings "iOS Deployment Target" is <= the version of your iDevice.
Otherwise you can goto - Product > Destination, select your device which would be showing as ineligible device.You will be able to select your device and run your build.
I also came across that if you have the iOS 8.4 then your Xcode doesn't have the SDK for iOS 8.4 due to which devices show as ineligible. To solve this issue
Download Xcode 6.4
Testing for name pointing to None
and name existing are two semantically different operations.
To check if val
is None:
if val is None:
pass # val exists and is None
To check if name exists:
try:
val
except NameError:
pass # val does not exist at all
this
is the element, $(this)
is the jQuery object constructed with that element
$(".class").each(function(){
//the iterations current html element
//the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
var HTMLElement = this;
//the current HTML element is passed to the jQuery constructor
//the jQuery API is exposed here (such as .html() and .append())
var jQueryObject = $(this);
});
A deeper look
this
MDN is contained in an execution context
The scope refers to the current Execution ContextECMA. In order to understand this
, it is important to understand the way execution contexts operate in JavaScript.
execution contexts bind this
When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this
occurs.
jQuery binds this
Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using apply
MDN.
callback.apply( obj[ i ] )//where obj[i] is the current element
The result of calling apply
is that inside of jQuery callback functions, this
refers to the current element being used by the callback function.
For example, in .each
, the callback function commonly used allows for .each(function(index,element){/*scope*/})
. In that scope, this == element
is true.
jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.
$(selector)
calls the jQuery function (remember that $
is a reference to jQuery
, code: window.jQuery = window.$ = jQuery;
). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $()
internally uses new jQuery()
. Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this
to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this
).
Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this
to the current element. This call can be seen in the code snippet above where obj
is the array-like structure, and i
is the iterator used for the position in the array of the current element.
How about writing a filter like below,
$('[myc="blue"]').filter(function () {
return (this.id == '1' || this.id == '3');
});
Edit: @Jack Thanks.. totally missed it..
$('[myc="blue"]').filter(function() {
var myId = $(this).attr('myid');
return (myId == '1' || myId == '3');
});
Your best bet is to have a look at strptime()
Something along the lines of
>>> from datetime import datetime
>>> date_str = 'Tue May 08 15:14:45 +0800 2012'
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y')
>>> date
datetime.datetime(2012, 5, 8, 15, 14, 45)
Im not sure how to do the +0800 timezone unfortunately, maybe someone else can help out with that.
The formatting strings can be found at http://docs.python.org/library/time.html#time.strftime and are the same for formatting the string for printing.
Hope that helps
Mark
PS, Your best bet for timezones in installing pytz from pypi. ( http://pytz.sourceforge.net/ ) in fact I think pytz has a great datetime parsing method if i remember correctly. The standard lib is a little thin on the ground with timezone functionality.
Return data as XML
SELECT CONVERT(XML, [Data]) AS [Value]
FROM [dbo].[FormData]
WHERE [UID] LIKE '{my-uid}'
Make sure you set a reasonable limit in the SSMS options window, depending on the result you're expecting.
This will work if the text you're returning doesn't contain unencoded characters like &
instead of &
that will cause the XML conversion to fail.
Returning data using PowerShell
For this you will need the PowerShell SQL Server module installed on the machine on which you'll be running the command.
If you're all set up, configure and run the following script:
Invoke-Sqlcmd -Query "SELECT [Data] FROM [dbo].[FormData] WHERE [UID] LIKE '{my-uid}'" -ServerInstance "database-server-name" -Database "database-name" -Username "user" -Password "password" -MaxCharLength 10000000 | Out-File -filePath "C:\db_data.txt"
Make sure you set the -MaxCharLength
parameter to a value that suits your needs.
Old post, but here's what I did using background-size:cover;
(hat tip to @Ceylan Pamir)...
EXAMPLE USAGE
Horizontal circle flipper (hover on front side image, flips to back with different image).
EXAMPLE SPRITE
480px x 240px
EXAMPLE FINAL SIZE
Single image @ 120px x 120px
GENERIC CODE
.front {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:0px 0px;}
.back {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:-120px 0px;}
ABBREVIATED CASE FIDDLE
http://jsfiddle.net/zuhloobie/133esq63/2/
OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:
myView.setOnTouchListener(new View.OnTouchListener()
{
// Implementation;
});
Easiest way my friends, is to open the server explorer tab on visual studio 2019 (in my case), and then try to create the connection to the database. After creating a succesful connection just right click on it and go to propierties. There you will find a string connection field with the correct syntax!...This worked for me because I knew my server's name before hand....just couldn't figure out the correct syntax to run my ef scaffold...
It is a good practice get the amount you need to store first then initialize the array.
for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store.
if you want a dynamic array you could use ArrayList()
and use al.add();
function to keep adding, then you can transfer it to a fixed array.
//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList();
//add a certain amount of data
for(int i=0;i<x;i++)
{
al.add("data "+i);
}
//get size of data inside
int size = al.size();
//initialize String array with the size you have
String strArray[] = new String[size];
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
strArray[i] = al.get(i);
}
doing so is redundant but just to show you the idea, ArrayList
can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List
and Stack
This is also found in the UINavigationController class documentation:
navigationItem.hidesBackButton = true
If it helps, I tend to conceive "lists" in R as "records" in other pre-OO languages:
The name "record" would clash with the standard meaning of "records" (aka rows) in database parlance, and may be this is why their name suggested itself: as lists (of fields).
Use include("class.classname.php");
And class should use <?php //code ?> not <? //code ?>
Using plain vanilla html and javascript
<input type='text' id='txtMyInputBox' />
<script language='javascript' type='text/javascript'>
function SetFocus()
{
// safety check, make sure its a post 1999 browser
if (!document.getElementById)
{
return;
}
var txtMyInputBoxElement = document.getElementById("txtMyInputBox");
if (txtMyInputBoxElement != null)
{
txtMyInputBoxElement.focus();
}
}
SetFocus();
</script>
For those out there using the .net framework and asp.net 2.0 or above, its trivial. If you are using older versions of the framework, you'd need to write some javascript similar to above.
In your OnLoad handler (generally page_load if you are using the stock page template supplied with visual studio) you can use:
C#
protected void PageLoad(object sender, EventArgs e)
{
Page.SetFocus(txtMyInputBox);
}
VB.NET
Protected Sub PageLoad(sender as Object, e as EventArgs)
Page.SetFocus(txtMyInputBox)
End Sub
(* Note I removed the underscore character from the function name that is generally Page_Load since in a code block it refused to render properly! I could not see in the markup documentation how to get underscores to render unescaped.)
Hope this helps.
you can do something like that:
where regexp_like(name, 'string$', 'i');
A functional approach must consider using only pure functions without side effects, each of which is only concerned with a single job.
These restrictions enhance the composability and reusability of the functions involved.
// small, reusable auxiliary functions_x000D_
_x000D_
const createSet = xs => new Set(xs);_x000D_
const filter = f => xs => xs.filter(apply(f));_x000D_
const apply = f => x => f(x);_x000D_
_x000D_
_x000D_
// intersection_x000D_
_x000D_
const intersect = xs => ys => {_x000D_
const zs = createSet(ys);_x000D_
return filter(x => zs.has(x)_x000D_
? true_x000D_
: false_x000D_
) (xs);_x000D_
};_x000D_
_x000D_
_x000D_
// mock data_x000D_
_x000D_
const xs = [1,2,2,3,4,5];_x000D_
const ys = [0,1,2,3,3,3,6,7,8,9];_x000D_
_x000D_
_x000D_
// run it_x000D_
_x000D_
console.log( intersect(xs) (ys) );
_x000D_
Please note that the native Set
type is used, which has an advantageous
lookup performance.
Obviously repeatedly occurring items from the first Array
are preserved, while the second Array
is de-duplicated. This may be or may be not the desired behavior. If you need a unique result just apply dedupe
to the first argument:
// auxiliary functions_x000D_
_x000D_
const apply = f => x => f(x);_x000D_
const comp = f => g => x => f(g(x));_x000D_
const afrom = apply(Array.from);_x000D_
const createSet = xs => new Set(xs);_x000D_
const filter = f => xs => xs.filter(apply(f));_x000D_
_x000D_
_x000D_
// intersection_x000D_
_x000D_
const intersect = xs => ys => {_x000D_
const zs = createSet(ys);_x000D_
return filter(x => zs.has(x)_x000D_
? true_x000D_
: false_x000D_
) (xs);_x000D_
};_x000D_
_x000D_
_x000D_
// de-duplication_x000D_
_x000D_
const dedupe = comp(afrom) (createSet);_x000D_
_x000D_
_x000D_
// mock data_x000D_
_x000D_
const xs = [1,2,2,3,4,5];_x000D_
const ys = [0,1,2,3,3,3,6,7,8,9];_x000D_
_x000D_
_x000D_
// unique result_x000D_
_x000D_
console.log( intersect(dedupe(xs)) (ys) );
_x000D_
Array
sIf you want to compute the intersection of an arbitrarily number of Array
s just compose intersect
with foldl
. Here is a convenience function:
// auxiliary functions_x000D_
_x000D_
const apply = f => x => f(x);_x000D_
const uncurry = f => (x, y) => f(x) (y);_x000D_
const createSet = xs => new Set(xs);_x000D_
const filter = f => xs => xs.filter(apply(f));_x000D_
const foldl = f => acc => xs => xs.reduce(uncurry(f), acc);_x000D_
_x000D_
_x000D_
// intersection_x000D_
_x000D_
const intersect = xs => ys => {_x000D_
const zs = createSet(ys);_x000D_
return filter(x => zs.has(x)_x000D_
? true_x000D_
: false_x000D_
) (xs);_x000D_
};_x000D_
_x000D_
_x000D_
// intersection of an arbitrarily number of Arrays_x000D_
_x000D_
const intersectn = (head, ...tail) => foldl(intersect) (head) (tail);_x000D_
_x000D_
_x000D_
// mock data_x000D_
_x000D_
const xs = [1,2,2,3,4,5];_x000D_
const ys = [0,1,2,3,3,3,6,7,8,9];_x000D_
const zs = [0,1,2,3,4,5,6];_x000D_
_x000D_
_x000D_
// run_x000D_
_x000D_
console.log( intersectn(xs, ys, zs) );
_x000D_