w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Having trouble format a string into a date object
You should not use Date#getYear. It's deprecated. As for the result you get, it's as specified in the Javadoc: Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone. Use Calendar API instead. Or even better, if you can use 3rd party library, then I would really suggest you to try Joda Time. Or wait for Java 8 to come next year, that has a new Date Time API.

Categories : Java

Where is this ASP.NET feature documented? <%= string format, params object[] args %>
This is close and perhaps related http://msdn.microsoft.com/en-us/library/586y06yf.aspx but it's not an explanation for why the <%= does it...

Categories : Asp Net

fprintf, error: format not a string literal and no format arguments [-Werror=format-security
You should use fputs(Usage, stderr); There is no need to use fprintf if you arn't doing formatting. If you want to use fprintf, use fprintf(stderr, "%s", Usage); The default compiler flags on Ubuntu includes -Wformat -Wformat-security which is what gives this error. That flag is used as a precaution against introducing security related bugs, imagine what would happen if you somehow did this: char *Usage = "Usage %s, [options] ... "; ... fprintf(stderr, Usage); This would be the same as fprintf(stderr, "Usage %s, [options] ... ]"); which is wrong. Now the Usage string includes a format specifier, %s, but you do not provide that argument to fprintf, resulting in undefined behavior, possibly crashing your program or allowing it to be exploited. This is more relevant if the string yo

Categories : C

cocos2d-x-2.1.4 : error: format not a string literal and no format arguments [-Werror=format-security]
Note that cocos2d-x-2.1.4 may not be compatible with ndk-r9, have you try out r8e instead? You can also put this in your Application.mk to disable treating those warnings as errors: APP_CFLAGS += -Wno-error=format-security There are more solutions for the same problem in this thread: http://www.cocos2d-x.org/boards/6/topics/32437?r=33260#message-33260 reference: http://www.cocos2d-x.org/boards/6/topics/33525?r=33579

Categories : Android

Convert a "big" Hex number (string format) to a decimal number (string format) without BigInteger Class
An easy way would be to use a big number library that supports your version of .NET. I'd recommend GnuMpDotNet, which uses the excellent GMP library. By default it targets .NET 3.5, but you can change that to .NET 2.0 without breaking anything (just remove the references and using statement that refer to new things), as it doesn't use anything from .NET 3.5. Here is an example using GnuMpDotNet: BigInt e = new BigInt(hexString, 16); string decimalStr = e.ToString();

Categories : C#

Safe and secure Object Oriented insertion with PDO
Probably not. You have introduced injection in the field names. If you can guarantee the field names are always generated by your code and never from an outside source, that might be OK. But this is a public method. So any bit of code in the system might try to do something "smart" and end up opening up a hole by passing a parameter to your insert method. You should escape your incoming field names by putting them in quotes (or if you are using MySQL and haven't enabled ANSI compatibility, use backtics). You also must escape any quotes within the name. $fields = implode(',', array_map(function($name) { return '"' . str_replace('"', '""', $name) . '"' ; }, array_keys($values))); For the values, you should just use positional paramters (?) or make up your own names. I don't thi

Categories : PHP

Create custom format strings for a new .NET type, for use in String.Format?
There is the IFormattable interface... class MyObject : IFormattable { public string ToString(string format, IFormatProvider formatProvider) { throw new NotImplementedException(); } } Probably you only have to implement it. The IFormattable interface converts an object to its string representation based on a format string and a format provider. Try with class Foo : IFormattable { public string ToString(string format, IFormatProvider formatProvider) { return string.Format("Foo formatted as {0}", format != null ? format : "(null)"); } } Console.WriteLine("{0}, {0:xxx}", new Foo()); The {0} is passed as null, while the {0:xxx} is passed as xxx

Categories : Dotnet

Input String not in correct format (Format Exception not handled)
Don't do the string conversion in the first place: double hours = (double) oleDbDataReader1["Hours"]; Unless your value is actually a string in the database (in which case you should fix that) there's no reason to convert it into a string. (If it's not a type mapped to double, you should change what you cast it to, of course.) EDIT: If it's non-numeric in the database, then you probably do need to use double.Parse - but you might want to specify the culture. For example, assuming they're all of the form "10.2" rather than "10,2" (as some cultures would use) you would want something like: double hours = double.Parse((string) oleDbDataReader1["Hours"], CultureInfo.InvariantCulture);

Categories : C#

The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption
Is it databaseName=MyDB or database=MyDB ? Try the latter. Are you on a Windows Machine? http://www.microsoft.com/en-us/download/details.aspx?id=24009 Download that and try to talk to your server outside of your code. The port query tool will show you if its a firewall (or similar) issue, outside of the code.

Categories : Java

Secure API access: best strategy to secure readonly rails api for android client
The most secure method for APIs is to give each user a different authentication token for API. On the other hand, if you want to make it even more secure, I personally suggest you a SSL, because SSL encrypts the packages between server and client, therefore it will be impossible (not impossible but near impossible depending on your SSL certificate) to hijack the communications between server and client.

Categories : Android

Powershell - Secure String for Passwords and SFTP
If your SFTP is wanting to use a decrypted version of your secured password then you'll want to extract it from your $mycred by: $userpassword = $mycred.getnetworkcredential().password.tostring()

Categories : Powershell

How to convert currency from string format to number format?
You can make switch cases according to your denominations. By choosing particular switch case you can choose the desired value. I don't think there is predefined method to accomplish this. hope this helps.

Categories : Iphone

How do I format a string to Credit card format
For that particular format, you could do something like the following, which extracts the individual substrings: NSString *string = @"1234567890123456789"; NSMutableArray *array = [NSMutableArray array]; for (NSInteger i = 0; i < [string length]; i += 4) [array addObject:[string substringWithRange:NSMakeRange(i, MIN(4, [string length] - i))]]; NSString *result = [array componentsJoinedByString:@" "]; The thing is, not all credit cards conform to the xxxx xxxx xxxx xxxx format. E.g., Amex uses a xxxx xxxxxx xxxxx format. You really should look at the first digits of the card, determine the type of card, and format it accordingly. You asked if you could do it with a regular expression. Consider this regex: NSString *result = [string stringByReplacingOccurrencesOfString:@"^[\s-]

Categories : Objective C

generate cryptographically-secure random number/string in perl
Math::Random::Secure is one solution (utilizes /dev/urandom on Linux). Crypt::Random is probably a better solution (utilizes /dev/random, and as such, may block).

Categories : Perl

Least worst option to secure database connection string for distributed wpf application to users with local admin rights
You are right: you cannot prevent a determined local admin to get access to this database. Here's what I -- as a determined user -- would do (I have done it in the past with other programs): I would attach a debugger to the running process and look at the memory to find the plain connection string (of course I am simplifying -- but it works). Another option would be to use the debugger to hijack your IDbCommand objects to execute arbitrary SQL code, no need for me to find the connection credentials, your application manages the connection for me. So it really comes down to: how competent and determined are your users? how important is your database? how determined are you? It's the classical hacker trade-off: how much effort do you want to put into this to discourage your users from cra

Categories : C#

Objective-C: "format string is not a string literal (potentially insecure)" warning with macro
The Clang & GCC compilers check that format strings and the supplied arguments conform, they cannot do this if the format string is not a literal - hence the error message you see as you are obtaining the format string from the bundle. To address this issue there is an attribute, format_arg(n) (docs), to mark functions which take a format string; alter it in some way without changing the actual format specifiers, e.g translate it; and then return it. Cocoa provides the convenient macro NS_FORMAT_ARG(n) for this attribute. To fix your problem you need to do two things: Wrap up the call to NSBundle in a function with this attribute specified; and Change your "key" to include the format specifiers. Second first, your strings file should contain: "name %@" = "My name is %@" so the

Categories : IOS

Considerations on choosing from String.Format, sprintf, or concatenation for building a string in F#
In general, you should use the printf-based functions (e.g., sprintf, bprintf) in F# code they're type-safe: the compiler checks the format strings at compile-time and makes sure you're passing the correct argument types. This does have one drawback, however -- in F# 2.0 and 3.0, the printf-based functions are quite slow (search StackOverflow or Google, you'll find questions and blog posts about it). They won't impact the overall performance of your application if you use them occasionally, but if you're calling them frequently you will notice your application slowing down. Thankfully, this has been fixed for the upcoming F# 3.1 release. As for the other options, you should avoid string concatenation whenever possible, as it's relatively slow and also incurs extra memory/GC overhead. If

Categories : F#

input string not in correct format...when converting a string to datetime...error?
Make sure your input string is using decimal point symbol for your current culture!. If your input string does not match these rules, decimal.Parse throws the Input string was not in a correct format exception If you for instance use the invariant culture: decimal.Parse("17.5", CultureInfo.InvariantCulture) The dot will be the accepted decimal point. You can read more about it over at MSDN There they also mention that the decimal.TryParse method is better suited for invariant culture parsing Also (obviously), make sure your input string is not null, empty, or containing any non-numerical characters (except for the one, optional, dot or comma, depending on your culture)

Categories : C#

Input String was not in correct format (CONVERTING STRING TO DECIMAL)
Have you tried doing this? - dailyCollection.Notes_1000 = Convert.ToDecimal(Request["note1000"].ToString()); also, you should use Decimal.TryParse instead, which would handle such error conditions. Eg: decimal temp; dailyCollection.Notes_1000 = Decimal.TryParse(Request["note1000"].ToString(),out temp)?temp:0.0M;

Categories : C#

How to check input string format correctness, without reading the string?
You can try something like that : time1 = '10:21'; if isempty(regexp(time1,'^d{2}:d{2}')) disp('the format is wrong') %won't display because the format if ok end And to check other format : time1 = '100:21'; if isempty(regexp(time1,'^d{2}:d{2}')) disp('the format is wrong') %will display because the format is wrong end EDIT If you want to accept 'HHH:MMM' and other cases use: regexp(time1,'^d+:d+') And for the negative case ('-HHH:MMM' or other negative cases) use: regexp(time1,'^-d+:d+') Second edit And if you want to test it in only one line : regexp(time1,'^(-|.){1}d+:d+$') % however this one doesn't support 'HH:MM AM' regexp(time1,'^(-|.){1}d+:d+.+$') % Now support 'HH:MM AM' I tested it and it returns 1 for every case you mentionned.

Categories : Matlab

Making JSESSIONID secure creating an issue for login issue from no-secure context
Is there any way to move from secure page(https) to unsecured page(http) or vice versa if JSEESIONID is secure Not with a single cookie. The whole point of secure is to stop the cookie being sent in the clear to an HTTP page, where an eavesdropper can purloin it and use it to access the HTTPS page. To have a system where compromise of an HTTP cookie didn't break the HTTPS cookie too, you'd have to have two separate session cookies with different names and values. eg: an http_session cookie, without secure that only the HTTP version of the site reads, and an https_session cookie, with secure, that only the HTTPS version reads. The login process would have to set both cookies, and the session system would have to be tinkered with to tie both session IDs to the same bag of session stora

Categories : Java

RegEx. Check and pad string to ensure certain string format is used
You can replace space character with a blank one. In JS for example : "66882 5F 2".replace(' ','') // Will output "668825F2" "66882 5 F 2".replace(' ','') // Will output "668825F2" With regex, you can use "s" delimiter for white spaces First you eliminate spaces by replacing blank characters, then you use this regex ^1[5|6]([0-9]{5})0[5|6][A-Z]([0-9]{2})$

Categories : Regex

Is there a way to find the first string that matches a DateTime format string?
I'm not aware of anything other than DateTime.TryParse (or alternately, a RegEx) for doing this in .NET. I would set up a stream tokenizer, passing only candidate token pairs into DateTime.TryParse (based on some combination of minimum string length, an maybe substring checks for a pair of dashes on token 0 and a pair of colons on token 1, etc. Exact checks would depend on how many date/time formats you're supporting)

Categories : C#

Combined usage of String and Varargs in String.format()
You can do it like this: String strFormat(String template, String str, String... moreStrs) { String[] args = new String[moreStrs.length + 1]; // fill the array 'args' System.arraycopy(moreStrs, 0, args, 0, moreStrs.length); args[moreStrs.length] = str; return String.format(template, args); }

Categories : Java

Input string was not in a correct format. Converting string to int
It looks as though you're getting your input from controls accepting user input, which is just asking for failure, since a user can potentially enter something that doesn't represent an integer value. You can use TryParse to avoid this: var result = 0; if (int.TryParse(TaskText.Text, out result)) { return result; } return 0; So, if the value of TaskText.Text == "1", this will succeed; if the value of TaskText.Text == "aaaa", this will fail - and return zero. You example would raise the appropriate exception, as experienced. However, an exception might be the right thing to happen here, if you can't handle a bad value, don't have an alternative, and the application relies on the input to move forward. More likely, you could do with some validation on your input fields to prevent bad d

Categories : C#

Expand all environment variables in string (Format string)
Why not replace? Sorry, I didn't notice it was VB.Net. My original answer was in C#, I haven't used VB in years, but here is the code for vb. Dim strpath as String strpath = "%homedrive%labla\%Username%labla\%computername%\%PercentCharacters%blabla" strpath.Replace("%homedrive%","X:").Replace("%Username%","blabla").Replace("%computername%","MyComputerName")

Categories : Dotnet

How to do a string-based query against an object? (Like LINQ-string to object)
Dynamic LINQ sounds good. If you would prefer to use javascript you could use a script engine. See parse and execute JS by C#

Categories : C#

Secure Store .... EndpointNotFoundException: Secure Store Service did not performed the operation.
See the code below - we use it in our back-end Timer jobs and front-end usecases without a problem for months now. The only difference seems to be the recreation of SPServiceContext every time a credential is requested. Try that instead of reusing the current context. public class ExternalCredentialsRepository { private readonly string webUrl; public ExternalCredentialsRepository(string webUrl) { this.webUrl = webUrl; } public NetworkCredential GetCredentials(string applicationId) { var credentialMap = new Dictionary<string, string>(); using (var site = new SPSite(webUrl)) { var serviceContext = SPServiceContext.GetContext(site); var secureStoreProvider = new SecureStoreProvider {Context = serviceCo

Categories : C#

create constructor string string1,string string2,string string3,Object object1
you should pass View.OnClickListener to your MyCard constructor instead of Object Change public MyCard(String title, String desc, String string, Object setOnClickListener){ super(title, desc); } with public MyCard(String title, String desc, String string, View.OnClickListener setOnClickListener){

Categories : Java

MultiLine string inside String.Format()?
You can do: Dim multi As String = <![CDATA[ Some multiline text ]]>.Value Now you can do: Console.WriteLine(String.Format("multi{0} string = {1}", "line", multi))

Categories : Dotnet

How to convert a UTC date format String to Date format in java?
You can try this java.util.Date dt = new java.util.Date("Thu Jan 1 19:30:00 UTC+0530 1970"); String newDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(dt); System.out.println(""+newDateFormat);

Categories : Java

How do I convert string date format to datetime date format?
This should do it: SELECT CONVERT(DATETIME, REPLACE('Sept. 23, 2013','.',''), 107) This removes dot in string and converts to datetime format 107. And this returns the string you wanted (MM/DD/YYYY): SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, REPLACE('Sept. 23, 2013','.',''), 107), 101) For other format types see: http://www.sqlusa.com/bestpractices/datetimeconversion/ and http://www.sql-server-helper.com/tips/date-formats.aspx Edit: It turns out it works for me because of Slovenian locale (Sept.). This one should work in English locale: SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, SUBSTRING('Sept. 23, 2013', 0, 4) + ' ' + SUBSTRING('Sept. 23, 2013',6,9), 107), 101) As a function.

Categories : Asp Net

How to convert Map to Map in java?
Map<String,String> getPropInMap(Properties prop){ Map<String, String> myMap = new HashMap<String, String>(); for (Object key : prop .keySet()) { myMap.put(key.toString(), prop .get(key).toString()); } return myMap; }

Categories : Java

String flashvar coming out as [Object object] rather than string
The problem is that you are making an incorrect assignment. When your ternary expression is true, you set the variable xmlLocation equal to FlexGlobals.topLevelApplication.parameters. So now xmlLocation is the parameters object, not the String you are expecting. Instead do this: xmlLocation = (FlexGlobals.topLevelApplication.parameters.location) ? FlexGlobals.topLevelApplication.parameters.location : "";

Categories : Actionscript

How to Convert String to another String format
You can split() the String using a regex , like "(?<!(^|[A-Z0-9]))(?=[A-Z0-9])|(?<!^)(?=[A-Z][a-z])" and then append - at the end of each split . public String camelCaseToDashSeparated(String initialString) { if(initialString==null || initialString.length()<1) return initialString; StringBuilder str = new StringBuilder(); for (String w : "eyesOfTheTiger".split("(?<!(^|[A-Z0-9]))(?=[A-Z0-9])|(?<!^)(?=[A-Z][a-z])")) { str.append(w.toLowerCase()+"-"); } return str.substring(0, str.length()-1); } Another way would be : Travel through the String , char by char , keep adding the characters to the StringBuilder. Once you find a char in uppercase , append - to the StringBuilder with the lowercase of the char. public static String camelCase

Categories : Java

Objective C why format string as string
The argument that is passed in could be any subclass of string, including NSMutableString. This code creates an immutable copy of it. This means that you can store the returned string without having to worry about someone else modifying it. A better way of doing this would be: NSString *string2 = [string copy]; According to the NSCopying Protocol reference: The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object.

Categories : IOS

Format as Table an Array of Object
You may want to try setting up the format for the table before you call the "Format-Table" Like this: $myformat = @{Expression={$_.*one*};Label="*name*";width=10}, @{Expression={$_.*two*};Label="*Two*";width=50}, $Result = $object | Format-Table $myformat -Wrap | Out-String Write-Host $Result Microsoft's Documentation

Categories : Powershell

javascript exception object format
Well, it's not entirely code. It's based on JavaScript's literals syntax, but is just a representation of a the object that's generated from util.inspect() (or a similar internal function). The square brackets mention the type of Error before its message. And, the rest is a list of enumerable properties and their values that were added to it. To create it yourself: var error = new Error("ENOENT, no such file or directory 'InvalidFile'"); error.errno = 34; error.code = 'ENOENT'; error.path = 'InvalidFile'; error.syscall = 'open' console.log(error); // uses `util.inspect()` console.log(util.inspect(error)); // or use it directly console.log(error.message); // "ENOENT, no such ..." console.log(Object.prototype.toString.call(error)); // "[object Error]" And, for a larger s

Categories : Javascript

creating an object in json format
You can build your object like this: var availability = {"someTshirt": { 'small': 'available', 'med' : 'available', 'large' : 'not available' } }; Then you can access this object with: availability.someTshirt.small >>> 'available' availability.someTshirt.large >>> 'not available' However I'd recommend you to use booleans instead of strings, which are easier to manipulate. You can still change the display string later: var availability = {"someTshirt": { 'small': true, 'med' : true, 'large' : false } }; if (availability.someTshirt.small) { console.log('available'); } >>> 'available' [edit] Response to the comment: If you want to create your objects dynamically, you can do the followin

Categories : Javascript

How can I suggest a preferred format for a New-Object?
The only way I know to get a standard format for a type is to create and load a format file (see about_Format.ps1xml). Format files "decide" which format to use based on the object's type name. So, when you create your custom object, make sure to also give it a custom type name, so you can write a custom view for it: $res = New-Object PSObject $res.PSTypeNames.Insert(0, 'Result') Then, in your format file, use Result as the type name. Probably a good idea to use a better name than Results. Format files have to be loaded before they can be used. This is easy if the format file is part of a module, a little more work if it's a loose format file your scripts will load individually. You can also write your own format function which uses Format-Table and/or Format-List internally, to d

Categories : Powershell



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.