First, modify your search filter to only look for users and not contacts:
(&(objectCategory=person)(objectClass=user)(sAMAccountName=BTYNDALL))
You can enumerate all of the domains of a forest by connecting to the configuration partition and enumerating all the entries in the partitions container. Sorry I don't have any C# code right now but here is some vbscript code I've used in the past:
Set objRootDSE = GetObject("LDAP://RootDSE")
AdComm.Properties("Sort on") = "name"
AdComm.CommandText = "<LDAP://cn=Partitions," & _
objRootDSE.Get("ConfigurationNamingContext") & ">;" & _
"(&(objectcategory=crossRef)(systemFlags=3));" & _
"name,nCName,dnsRoot;onelevel"
set AdRs = AdComm.Execute
From that you can retrieve the name and dnsRoot of each partition:
AdRs.MoveFirst
With AdRs
While Not .EOF
dnsRoot = .Fields("dnsRoot")
Set objOption = Document.createElement("OPTION")
objOption.Text = dnsRoot(0)
objOption.Value = "LDAP://" & dnsRoot(0) & "/" & .Fields("nCName").Value
Domain.Add(objOption)
.MoveNext
Wend
End With
I came to this question looking to restore a file I just deleted but I hadn't yet committed the change. Just in case you find yourself in this situation, all you need to do is the following:
git checkout HEAD -- path/to/file.ext
It just needs to be in the classpath (aka make sure it ends up under /WEB-INF/classes in the .war as part of the build).
When buffer size gets full. There are several options you can try:
1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000
2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.
3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.
DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output
You can also create your custom output display.something like below snippets
create or replace procedure cust_output(input_string in varchar2 )
is
out_string_in long default in_string;
string_lenth number;
loop_count number default 0;
begin
str_len := length(out_string_in);
while loop_count < str_len
loop
dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) );
loop_count := loop_count +255;
end loop;
end;
Link -Ref :Alternative to dbms_output.putline @ By: Alexander
if you put the alter into a transaction the table should not be locked:
BEGIN;
ALTER TABLE "public"."mytable" ALTER COLUMN "mycolumn" TYPE varchar(40);
COMMIT;
this worked for me blazing fast, few seconds on a table with more than 400k rows.
The Bootstrap3 .form-control
is cool but for those who love or need the drop-down with button and ul option, here is the updated code. I have edited the code by Steve to fix jumping to the hash link and closing the drop-down after selection.
Thanks to Steve, Ben and Skelly!
$(".dropdown-menu li a").click(function () {
var selText = $(this).text();
$(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
$(this).closest('.dropdown').removeClass("open");
return false;
});
You can use Jackson Mixins. For example:
class YourClass {
public int ignoreThis() { return 0; }
}
With this Mixin
abstract class MixIn {
@JsonIgnore abstract int ignoreThis(); // we don't need it!
}
With this:
objectMapper.getSerializationConfig().addMixInAnnotations(YourClass.class, MixIn.class);
Edit:
Thanks to the comments, with Jackson 2.5+, the API has changed and should be called with objectMapper.addMixIn(Class<?> target, Class<?> mixinSource)
VBA Function
1) .Formula = "=""THEFORMULAFUNCTION ""&(CHAR(34) & ""STUFF"" & CHAR(34))"
2) .Formula = "THEFORMULAFUNCTION ""STUFF"""
The first method uses vba to write a formula in a cell which results in the calculated value:
THEFORMULAFUNCTION "STUFF"
The second method uses vba to write a string in a cell which results in the value:
THEFORMULAFUNCTION "STUFF"
Excel Result/Formula
1) ="THEFORMULAFUNCTION "&(CHAR(34) & "STUFF" & CHAR(34))
2) THEFORMULAFUNCTION "STUFF"
What clean does (common in both the commands) - removes all files generated by the previous build
Coming to the difference between the commands package and install, you first need to understand the lifecycle of a maven project
These are the default life cycle phases in maven
How Maven works is, if you run a command for any of the lifecycle phases, it executes each default life cycle phase in order, before executing the command itself.
order of execution
validate >> compile >> test (optional) >> package >> verify >> install >> deploy
So when you run the command mvn package, it runs the commands for all lifecycle phases till package
validate >> compile >> test (optional) >> package
And as for mvn install, it runs the commands for all lifecycle phases till install, which includes package as well
validate >> compile >> test (optional) >> package >> verify >> install
So, effectively what it means is, install commands does everything that package command does and some more (install the package into the local repository, for use as a dependency in other projects locally)
Source: Maven lifecycle reference
The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.
If you are working in Ubuntu,follow the steps:
/
and type word to search*
key#
key It wasn't working for me in all cases when I set
self.navigationItem.hidesBackButton = YES;
in viewWillAppear or ViewDidLoad, but worked perfectly when I set it in init of the viewController.
What you see is the interpreter echoing back the return value of next()
in addition to i
being printed each iteration:
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... next(a)
...
0
1
2
3
4
5
6
7
8
9
So 0
is the output of print(i)
, 1
the return value from next()
, echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.
If you assign the output of next()
things work as expected:
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... _ = next(a)
...
0
2
4
6
8
or print extra information to differentiate the print()
output from the interactive interpreter echo:
>>> a = iter(list(range(10)))
>>> for i in a:
... print('Printing: {}'.format(i))
... next(a)
...
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9
In other words, next()
is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.
If BranchA has not been pushed to a remote then you can reorder the commits using rebase
and then simply merge
. It's preferable to use merge
over rebase
when possible because it doesn't create duplicate commits.
git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]
What I'd try first is
to drop all constraints, indexes, triggers and full text indexes first before you update.
If above wasn't performant enough, my next move would be
to create a CSV file with 12 million records and bulk import it using bcp.
Lastly, I'd create a new heap table (meaning table with no primary key) with no indexes on a different filegroup, populate it with -1. Partition the old table, and add the new partition using "switch".
I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.
You can create a DIV
component using the <h:panelGroup/>
.
By default, the <h:panelGroup/>
will generate a SPAN in the HTML code.
However, if you specify layout="block"
, then the component will be a DIV
in the generated HTML code.
<h:panelGroup layout="block"/>
Simple, use static.
In activity you have the method you want to call:
private static String name = "Robert";
...
public static String getData() {
return name;
}
And in your activity where you make the call:
private static String name;
...
name = SplashActivity.getData();
Have done a number of comparisons between left outer and inner joins and have not been able to find a consisten difference. There are many variables. Am working on a reporting database with thousands of tables many with a large number of fields, many changes over time (vendor versions and local workflow) . It is not possible to create all of the combinations of covering indexes to meet the needs of such a wide variety of queries and handle historical data. Have seen inner queries kill server performance because two large (millions to tens of millions of rows) tables are inner joined both pulling a large number of fields and no covering index exists.
The biggest issue though, doesn't seem to appeaer in the discussions above. Maybe your database is well designed with triggers and well designed transaction processing to ensure good data. Mine frequently has NULL values where they aren't expected. Yes the table definitions could enforce no-Nulls but that isn't an option in my environment.
So the question is... do you design your query only for speed, a higher priority for transaction processing that runs the same code thousands of times a minute. Or do you go for accuracy that a left outer join will provide. Remember that inner joins must find matches on both sides, so an unexpected NULL will not only remove data from the two tables but possibly entire rows of information. And it happens so nicely, no error messages.
You can be very fast as getting 90% of the needed data and not discover the inner joins have silently removed information. Sometimes inner joins can be faster, but I don't believe anyone making that assumption unless they have reviewed the execution plan. Speed is important, but accuracy is more important.
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
I got it working by
Unfortunately if you're looking to apply UIPopoverController
in iOS9, you'll get a deprecated class warning. Instead you need to set your desired view's UIModalPresentationPopover
property to achieve the same result.
Popover
In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.
In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.
Available in iOS 8.0 and later.
Reference: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621355-modalpresentationstyle
This can also be easily achieved with SourceTree:
done :)
Many sites use AJAX/XHR/fetch to add, show, modify content dynamically and window.history API instead of in-site navigation so current URL is changed programmatically. Such sites are called SPA, short for Single Page Application.
MutationObserver (docs) to literally detect DOM changes:
Performance of MutationObserver to detect nodes in entire DOM.
Simple example:
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
onUrlChange();
}
}).observe(document, {subtree: true, childList: true});
function onUrlChange() {
console.log('URL changed!', location.href);
}
Event listener for sites that signal content change by sending a DOM event:
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,yt-navigate-finish
used by Youtube,Periodic checking of DOM via setInterval:
Obviously this will work only in cases when you wait for a specific element identified by its id/selector to appear, and it won't let you universally detect new dynamically added content unless you invent some kind of fingerprinting the existing contents.
Cloaking History API:
let _pushState = History.prototype.pushState;
History.prototype.pushState = function (state, title, url) {
_pushState.call(this, state, title, url);
console.log('URL changed', url)
};
Listening to hashchange, popstate events:
window.addEventListener('hashchange', e => {
console.log('URL hash changed', e);
doSomething();
});
window.addEventListener('popstate', e => {
console.log('State changed', e);
doSomething();
});
All above-mentioned methods can be used in a content script. Note that content scripts aren't automatically executed by the browser in case of programmatic navigation via window.history in the web page because only the URL was changed but the page itself remained the same (the content scripts run automatically only once in page lifetime).
Now let's look at the background script.
There are advanced API to work with navigation: webNavigation, webRequest, but we'll use simple chrome.tabs.onUpdated event listener that sends a message to the content script:
manifest.json:
declare background/event page
declare content script
add "tabs"
permission.
background.js
var rxLookfor = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (rxLookfor.test(changeInfo.url)) {
chrome.tabs.sendMessage(tabId, 'url-update');
}
});
content.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'url-update') {
// doSomething();
}
});
You can also use Bash on Ubuntu on Windows
directly. E.g.,
bash -c "ssh -t user@computer 'cd /; sudo my-command'"
Per Martin Prikryl's comment below:
The -t enables terminal emulation. Whether you need the terminal emulation for sudo depends on configuration (and by default you do no need it, while many distributions override the default). On the contrary, many other commands need terminal emulation.
someone before uses a similar solution to mine, but I find it easier to think as below:
> text<-"some text in a string" # we want to have only the last word "string" with 6 letter
> n<-5 #as the last character will be counted with nchar(), here we discount 1
> substr(x=text,start=nchar(text)-n,stop=nchar(text))
This will bring the last characters as desired.
String x = "stackoverflow";
String [] y = x.split("");
I was looking for the same answer, and I have come up with this solution for PHP 5.3 or later:
$dtz = new DateTimeZone("Europe/Madrid"); //Your timezone
$now = new DateTime(date("Y-m-d"), $dtz);
echo $now->format("Y-m-d H:i:s");
Set server timezone and use NTP sync. Here is one better solution to change server time.
To list timezones
timedatectl list-timezones
To set timezone
sudo timedatectl set-timezone America/New_York
Verify time zone
timedatectl
I prefer using UTC timezone for my servers and databases. Any conversions must be handled on client. We can make used of moment.js on client side.
It will be easy to maintain many instances as well,
I used this to retrieve data from MySql Database:
AccessText a = new AccessText();
a.Text=reader[1].ToString(); // MySql reader
a.Width = 70;
a.TextWrapping = TextWrapping.WrapWithOverflow;
labels[i].Content = a;
Explicit Wait
public static WebDriverWait wait = new WebDriverWait(driver, 60);
Example:
wait.until(ExpectedConditions.visibilityOfElementLocated(UiprofileCre.UiaddChangeUserLink));
You can't and shouldn't modify a list while iterating over it. You can solve this by temporarely saving the objects to remove:
List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
if(a.getXXX().equalsIgnoreCase("AAA")){
toRemove.add(a);
}
}
list.removeAll(toRemove);
Here's a simple example that simply returns the last line without need to sort anything from any column:
"SELECT * FROM TableName ORDER BY rowid DESC LIMIT 1;"
Create a ComboBox SelectionChanged Event and set ItemsSource="{Binding}" in the WPF design:
Code:
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string ob = ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();
MessageBox.Show(ob);
}
Try getting hold of a URL for your classpath resource:
URL url = this.getClass().getResource("/com/path/to/file.txt")
Then create a file using the constructor that accepts a URI:
File file = new File(url.toURI());
we can be submit multiple updates together in JDBC to submit batch updates.
we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit
addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate
here addBatch() method adds a set of statements or parameters to the current batch.
The line #!/bin/bash/python3
or #!/bin/bash/python
specifies which python compiler to use. You might have multiple python versions installed. For example,
a.py :
#!/bin/bash/python3
print("Hello World")
is a python3 script, and
b.py :
#!/bin/bash/python
print "Hello World"
is a python 2.x script
In order to run this file ./a.py
or ./b.py
is used, you need to give the files execution privileges before hand, otherwise executing will lead to Permission denied
error.
For giving execution permission,
chmod +x a.py
if (itemdescription != null && itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38)));
} else {
pstmt2.setString(3, "_");
}
You can also do this with ArgueJS:
function (){
arguments = __({nodebox: undefined, str: [String: "hai"]})
// and now on, you can access your arguments by
// arguments.nodebox and arguments.str
}
One difference that's not at the language level but the popular implementation level: certain versions of gcc will remove unreferenced static inline
functions from output by default, but will keep plain static
functions even if unreferenced. I'm not sure which versions this applies to, but from a practical standpoint it means it may be a good idea to always use inline
for static
functions in headers.
As @Mehmet is pointing out, if your result is returning more then 1 elerment then you need to look into you data as i suspect that its not by design that you have customers sharing a customernumber.
But to the point i wanted to give you a quick overview.
//success on 0 or 1 in the list, returns dafault() of whats in the list if 0
list.SingleOrDefault();
//success on 1 and only 1 in the list
list.Single();
//success on 0-n, returns first element in the list or default() if 0
list.FirstOrDefault();
//success 1-n, returns the first element in the list
list.First();
//success on 0-n, returns first element in the list or default() if 0
list.LastOrDefault();
//success 1-n, returns the last element in the list
list.Last();
for more Linq expressions have a look at System.Linq.Expressions
It sounds like you are talking about aggregation. Each instance of your player
class can contain zero or more instances of Airplane
, which, in turn, can contain zero or more instances of Flight
. You can implement this in Python using the built-in list
type to save you naming variables with numbers.
class Flight(object):
def __init__(self, duration):
self.duration = duration
class Airplane(object):
def __init__(self):
self.flights = []
def add_flight(self, duration):
self.flights.append(Flight(duration))
class Player(object):
def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
self.stock = stock
self.bank = bank
self.fuel = fuel
self.total_pax = total_pax
self.airplanes = []
def add_planes(self):
self.airplanes.append(Airplane())
if __name__ == '__main__':
player = Player()
player.add_planes()
player.airplanes[0].add_flight(5)
You can use range quantifier {min,max}
to specify minimum of 1 digit and maximum of 6 digits as:
^[0-9]{1,6}$
Explanation:
^ : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$ : End anchor
Why did your regex not work ?
You were almost close on the regex:
^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$
Since you had escaped the ?
by preceding it with the \
, the ?
was no more acting as a regex meta-character ( for 0
or 1
repetitions) but was being treated literally.
To fix it just remove the \
and you are there.
The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.
Your second regex:
^[0-999999]$
is equivalent to:
^[0-9]$
which matches strings with exactly one digit. They are equivalent because a character class [aaaab]
is same as [ab]
.
Source: java-implementation-of-rubys-gsub
Usage:
// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
public String replacement() {
float inches = Float.parseFloat(group(1));
return Float.toString(2.54f * inches) + " cm";
}
}.rewrite("a 17 inch display");
System.out.println(result);
// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
public String replacement() {
return group(1).toUpperCase();
}
}.rewrite("ab12 cd efg34");
System.out.println(result);
Implementation (redesigned):
import static java.lang.String.format;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class Rewriter {
private Pattern pattern;
private Matcher matcher;
public Rewriter(String regularExpression) {
this.pattern = Pattern.compile(regularExpression);
}
public String group(int i) {
return matcher.group(i);
}
public abstract String replacement() throws Exception;
public String rewrite(CharSequence original) {
return rewrite(original, new StringBuffer(original.length())).toString();
}
public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
try {
this.matcher = pattern.matcher(original);
while (matcher.find()) {
matcher.appendReplacement(destination, "");
destination.append(replacement());
}
matcher.appendTail(destination);
return destination;
} catch (Exception e) {
throw new RuntimeException("Cannot rewrite " + toString(), e);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(pattern.pattern());
for (int i = 0; i <= matcher.groupCount(); i++)
sb.append(format("\n\t(%s) - %s", i, group(i)));
return sb.toString();
}
}
I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?
If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.
Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.
That worked for me:
$ export LC_ALL=en_US.UTF-8
$ export LANG=en_US.UTF-8
If you use apachectl to start or stop, then you can find it with this command
apachectl -t -D DUMP_RUN_CFG
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
import urllib2
Traceback (most recent call last):
File "", line 1, in
import urllib2
ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.
Here is the PEP link (Python Enhancement Proposals )
http://www.python.org/dev/peps/pep-3108/#urllib-package
so instead of urllib2 you can now import urllib.request and then use it like this:
>>>import urllib.request
>>>urllib.request.urlopen('http://www.placementyogi.com')
Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x
alternatively you can retrieve DOM properties
with .prop
here is sample code for select box
if( ctrl.prop('type') == 'select-one' ) { // for single select }
if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
for textbox
if( ctrl.prop('type') == 'text' ) { // for text box }
I found this question because I wanted to generate a web page with links to all the websites running on my IIS instance. I used Alexander Shapkin's answer to come up with the following to generate a bunch of links.
$hostname = "localhost"
Foreach ($Site in get-website) {
Foreach ($Bind in $Site.bindings.collection) {
$data = [PSCustomObject]@{
name=$Site.name;
Protocol=$Bind.Protocol;
Bindings=$Bind.BindingInformation
}
$data.Bindings = $data.Bindings -replace '(:$)', ''
$html = "<a href=""" + $data.Protocol + "://" + $data.Bindings + """>" + $data.name + "</a>"
$html.Replace("*", $hostname);
}
}
Then I paste the results into this hastily written HTML:
<html>
<style>
a { display: block; }
</style>
{paste PowerShell results here}
</body>
</html>
To get the URL of the parent window from within an iframe:
$(window.parent.location).attr('href');
NB: only works on same domain
The best Linux-specific solution is to use sysfs:
$ IFACE=eth0
$ read MAC </sys/class/net/$IFACE/address
$ echo $IFACE $MAC
eth0 00:ab:cd:12:34:56
This method is extremely clean compared to the others and spawns no additional processes since read
is a builtin command for POSIX shells, including non-BASH shells. However, if you need portability to OS X, then you'll have to use ifconfig
and sed
methods, since OS X does not have a virtual filesystem interface like sysfs.
Through SSMS, I created a new schema by:
I found this post to change the schema, but was also getting the same permissions error when trying to change to the new schema. I have several databases listed in my SSMS, so I just tried specifying the database and it worked:
USE (yourservername)
ALTER SCHEMA exe TRANSFER dbo.Employees
On Windows 2008 R2 servers you have two means of viewing what files are open and closing those connections.
Via Share and Storage Management
Server Manager > Roles > File Services > Share and Storage Management > right-click on SaSM > Manage Open File
Via OpenFiles
CMD > Openfiles.exe /query /s SERVERNAME
See http://technet.microsoft.com/en-us/library/bb490961.aspx.
Personally, I use ... | Out-Null
because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null
and [void] ...
. $null = ...
is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null
and ... > $null
come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null
), compared to putting $null =
or [void]
before the expression to determine what happens after executing it.
Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help
command or your favorite search engine to try to find out what Out-Null
does. You get a useful result immediately, right? Now try to do the same with [void]
and $null =
. Not so easy, is it?
Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void]
, $null =
, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*
* I am presuming that Out-Null
is clear and well-known, which I don't know to be $true
. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.
try this code worked for me
SELECT user_display_image AS user_image,
user_display_name AS user_name,
invitee_phone,
(CASE WHEN invitee_status = 1 THEN "attending"
WHEN invitee_status = 2 THEN "unsure"
WHEN invitee_status = 3 THEN "declined"
WHEN invitee_status = 0 THEN "notreviwed"
END) AS invitee_status
FROM your_table
Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:
Check if $n is between $a and $b even if:
$a < $b
$a > $b
$a = $b
All numbers can be real, not only integer.
There is an easy way to test.
I base the test it in the fact that ($n-$a)
and ($n-$b)
have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.
function between($n, $a, $b)
{
return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}
You can also try something like the following:
function clicked() {
var myDiv = $("#my-div");
$.post("someurl.php",someData,function(data){
doSomething(data, myDiv);
},"json");
}
function doSomething(curData, curDiv) {
}
Had a similar problem. I updated my Genymotion and my android SDK's/libraries/dependencies and all seemed to work. To update my SDK's I used android sdk manager {ANDROID_SDK_FOLDER}/tools/android sdk
If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:
<script>
const meta = document.querySelector('[property="og:image"]');
const body = document.querySelector("body");
body.style.background = `url(${meta.content})`;
</script>
The above uses document.querySelector
and Attribute Selectors to assign meta
the first Open Graph image it selects. A similar task is performed to get the body
. Finally, string interpolation is used to assign body
the background.style
the value of the path to the Open Graph image.
If you want the image to cover the entire viewport and stay fixed set background-size
like so:
body.style.background = `url(${meta.content}) center center no-repeat fixed`;
body.style.backgroundSize = 'cover';
Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload
event, thereby reducing perceived latency.
You can call more than one target goal with maven. mvn clean install
calls clean
first, then install
. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.
clean
removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean
, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).
we call it target in ant and goal in maven
Windows INI API support for:
;
The authoritative source is the Windows API function that reads values out of INI files
GetPrivateProfileString
Retrieves a string from the specified section in an initialization file.
The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini
file contents:
[Application]
UseLiveData=1
;coke=zero
pepsi=diet ;gag
#stackoverflow=splotchy
Reading the values:
UseLiveData
: 1
coke
: not present;coke
: not presentpepsi
: diet ;gag
stackoverflow
: not present#stackoverflow
: splotchy
Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow
is because the name stackoverflow
no longer exists. And it turns out that semi-colon (;
) is a line-comment.
But there is no support for trailing comments.
Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section
within your _Layout
which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
@RenderSection("Scripts",false/*required*/)
</head>
<body>
@RenderBody()
</body>
</html>
@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
<script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}
Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script>
declaration within the view.
And when I debug this the logic does fall into the sentence.replace.
Yes, and then you discard the return value.
Strings in Java are immutable - when you call replace
, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
sentence = sentence.replace("and", " ");
This applies to all the methods in String (substring
, toLowerCase
etc). None of them change the contents of the string.
Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and"
, it does no harm to perform the replacement:
String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.
HTML
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
</a></div>
CSS
.navbar-toggle, .icon-bar {
border:1px solid orange;
}
BOOM...
I wanted to programmatically -- using only Bash -- kill the process listening on a given port.
Let's say the port is 8089, then here is how I did it:
badPid=$(netstat --listening --program --numeric --tcp | grep "::8089" | awk '{print $7}' | awk -F/ '{print $1}' | head -1)
kill -9 $badPid
I hope this helps someone else! I know it is going to help my team.
I also came from Angular.js area and the services and factories in React.js are more simple.
You can use plain functions or classes, callback style and event Mobx like me :)
// Here we have Service class > dont forget that in JS class is Function_x000D_
class HttpService {_x000D_
constructor() {_x000D_
this.data = "Hello data from HttpService";_x000D_
this.getData = this.getData.bind(this);_x000D_
}_x000D_
_x000D_
getData() {_x000D_
return this.data;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
// Making Instance of class > it's object now_x000D_
const http = new HttpService();_x000D_
_x000D_
_x000D_
// Here is React Class extended By React_x000D_
class ReactApp extends React.Component {_x000D_
state = {_x000D_
data: ""_x000D_
};_x000D_
_x000D_
componentDidMount() {_x000D_
const data = http.getData();_x000D_
_x000D_
this.setState({_x000D_
data: data_x000D_
});_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <div>{this.state.data}</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<ReactApp />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Here is simple example :
After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:
impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
remap_tablespace=user1:user2 directory=EXPORTDIR \
dumpfile=user1.dmp logfile=E:\Data\user1.log
EXPORTDIR must be defined in oracle as a directory as the system user
create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;
I've used the base idea from @Jonathan. I've set the windows with: set JAVA_HOME=C:\Program Files\java\AdoptOpenJDK-11.0.8+10 call mvn clean package -DskipTests
Use string append operator on the serial.read()
. It works better than string.concat()
char r;
string mystring = "";
while(serial.available()){
r = serial.read();
mystring = mystring + r;
}
After you are done saving the stream in a string(mystring, in this case), use SubString functions to extract what you are looking for.
This work for me:
app.use('*/css',express.static('public/css'));
app.use('*/js',express.static('public/js'));
app.use('*/images',express.static('public/images'));
Try this:
if (dgv.SelectedRows.Count>0)
{
dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
}
I was/am in the same boat as you for different reasons (partly educational, partly constraints). I had to re-write all the containers of the standard library and the containers had to conform to the standard. That means, if I swap out my container with the stl version, the code would work the same. Which also meant that I had to re-write the iterators.
Anyway, I looked at EASTL. Apart from learning a ton about containers that I never learned all this time using the stl containers or through my undergraduate courses. The main reason is that EASTL is more readable than the stl counterpart (I found this is simply because of the lack of all the macros and straight forward coding style). There are some icky things in there (like #ifdefs for exceptions) but nothing to overwhelm you.
As others mentioned, look at cplusplus.com's reference on iterators and containers.
You could try the FLOOR function like this:
SELECT FLOOR(columnName), moreColumns, etc
FROM myTable
WHERE ...
You could also try the FORMAT function, provided you know the decimal places can be omitted:
SELECT FORMAT(columnName,0), moreColumns, etc
FROM myTable
WHERE ...
You could combine the two functions
SELECT FORMAT(FLOOR(columnName),0), moreColumns, etc
FROM myTable
WHERE ...
In python, when you have an iterable, usually you iterate without an index:
letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
print(l)
If you need to traverse the iterable in reverse order, you would do:
for l in letters[::-1]:
print(l)
When for any reason you need the index, you can use enumerate
:
for i, l in enumerate(letters, start=1): #start is 0 by default
print(i,l)
You can enumerate in reverse order too...
for i, l in enumerate(letters[::-1])
print(i,l)
ON ANOTHER NOTE...
Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map
:
If we need to capitilize each letter:
map(str.upper, letters)
Or get the Unicode code of each letter:
map(ord, letters)
To trim any set of characters from the beginning and end of a string, you can do the following code where @TrimPattern defines the characters to be trimmed. In this example, Space, tab, LF and CR characters are being trimmed:
Declare @Test nvarchar(50) = Concat (' ', char(9), char(13), char(10), ' ', 'TEST', ' ', char(9), char(10), char(13),' ', 'Test', ' ', char(9), ' ', char(9), char(13), ' ')
DECLARE @TrimPattern nvarchar(max) = '%[^ ' + char(9) + char(13) + char(10) +']%'
SELECT SUBSTRING(@Test, PATINDEX(@TrimPattern, @Test), LEN(@Test) - PATINDEX(@TrimPattern, @Test) - PATINDEX(@TrimPattern, LTRIM(REVERSE(@Test))) + 2)
Another easy way is to use fire the method before the view is rendered. This is better than postConstruct because for sessionScope, postConstruct will fire only once every session. This will fire every time the page is loaded. This is ofcourse only for JSF 2.0 and not for JSF 1.2.
This is how to do it -
<html xmlns:f="http://java.sun.com/jsf/core">
<f:metadata>
<f:event type="preRenderView" listener="#{myController.onPageLoad}"/>
</f:metadata>
</html>
And in the myController.java
public void onPageLoad(){
// Do something
}
EDIT - Though this is not a solution for the question on this page, I add this just for people using higher versions of JSF.
JSF 2.2 has a new feature which performs this task using viewAction
.
<f:metadata>
<f:viewAction action="#{myController.onPageLoad}" />
</f:metadata>
Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file
Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:
wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz
And then proceed to install it.
UPDATE: Adding complete instructions (copied from the comment below)
run the following to extract the tar:
tar xvf apache-maven-3.2.1-bin.tar.gz
Next add the env varibles such as
export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Verify
mvn -version
The difference between these two approaches is as follows:
Synchronous way:
It waits for each operation to complete, after that only it executes the next operation.
For your query:
The console.log()
command will not be executed until & unless the query has finished executing to get all the result from Database.
Asynchronous way:
It never waits for each operation to complete, rather it executes all operations in the first GO only. The result of each operation will be handled once the result is available.
For your query:
The console.log()
command will be executed soon after the Database.Query()
method. While the Database query runs in the background and loads the result once it is finished retrieving the data.
Use cases
If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.
In Asynchronous way you can show some Progress indicator to the user while in background you can continue with your heavy weight works. This is an ideal scenario for GUI apps.
To produce the same results:
MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("1.3.14.3.2.26");
AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);
byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);
For that you can use the Application
object.
Startup path, just the folder, use Application.StartupPath()
Dim appPath As String = Application.StartupPath()
Full .exe path, including the program.exe name on the end:, use Application.ExecutablePath()
Dim exePath As String = Application.ExecutablePath()
IIRC, it involves garbage collection strategies. The theory is that a client and server will be different in terms of short-lived objects, which is important for modern GC algorithms.
Here is a link on server mode. Alas, they don't mention client mode.
Here is a very thorough link on GC in general; this is a more basic article. Not sure if either address -server vs -client but this is relevant material.
At No Fluff Just Stuff, both Ken Sipe and Glenn Vandenburg do great talks on this kind of thing.
I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.
Short answer: No. Use WebM or Ogg instead.
This article covers just about everything you need to know about the <video>
element, including which browsers support which container formats and codecs.
This can be done using Actions
class in java
Use following code -
new Actions(driver).moveByOffset(x coordinate, y coordinate).click().build().perform();
Note: Selenium 3 doesn't support Actions
class for geckodriver
Also, note that x and y co-ordinates are relative values from current mouse position. Assuming mouse co-ordinates are at (0,0) to start with, if you want to use absolute values, you can perform the below action immediately after you clicked on it using the above code.
new Actions(driver).moveByOffset(-x coordinate, -y coordinate).perform();
Use the JSON.stringify() to get the string in JSON format, ensure that while making the AJAX call you pass below mentioned attributes:
Below is the give jquery code to make ajax post call to asp.net web api:
var product =_x000D_
JSON.stringify({_x000D_
productGroup: "Fablet",_x000D_
productId: 1,_x000D_
productName: "Lumia 1525 64 GB",_x000D_
sellingPrice: 700_x000D_
});_x000D_
_x000D_
$.ajax({_x000D_
URL: 'http://localhost/api/Products',_x000D_
type: 'POST',_x000D_
contentType: 'application/json',_x000D_
data: product,_x000D_
success: function (data, status, xhr) {_x000D_
alert('Success!');_x000D_
},_x000D_
error: function (xhr, status, error) {_x000D_
alert('Update Error occurred - ' + error);_x000D_
}_x000D_
});
_x000D_
Try this one in Java
for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int j = 0; j < k; j++) {
System.out.print("*");
}
for (int j = 1; j < k; j++) {
System.out.print("*");
}
System.out.println();
}
There are 2 ways:
ScrollView.setScrollbarFadingEnabled(false);
android:fadeScrollbars="false"
Simple as that!
You can't resolve a promise with multiple properties just like you can't return multiple values from a function. A promise conceptually represents a value over time so while you can represent composite values you can't put multiple values in a promise.
A promise inherently resolves with a single value - this is part of how Q works, how the Promises/A+ spec works and how the abstraction works.
The closest you can get is use Q.spread
and return arrays or use ES6 destructuring if it's supported or you're willing to use a transpilation tool like BabelJS.
As for passing context down a promise chain please refer to Bergi's excellent canonical on that.
Add this android:screenOrientation="landscape"
to your <activity>
tag in the manifest for the specific activity that you want to be in landscape.
Edit:
To toggle the orientation from the Activity
code, call setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
other parameters can be found in the Android docs for ActivityInfo.
promises
, a JavaScript feature of the ECMAScript 6
standard. If your target platform does not support promises
, polyfill it with PromiseJs.Look at my answer here Wait till a Function with animations is finished until running another Function if you want to use jQuery
animations.
Here is what your code would look like with ES6 Promises
and jQuery animations
.
Promise.resolve($('#art1').animate({ 'width': '1000px' }, 1000).promise()).then(function(){
return Promise.resolve($('#art2').animate({ 'width': '1000px' }, 1000).promise());
}).then(function(){
return Promise.resolve($('#art3').animate({ 'width': '1000px' }, 1000).promise());
});
Normal methods can also be wrapped in Promises
.
new Promise(function(fulfill, reject){
//do something for 5 seconds
fulfill(result);
}).then(function(result){
return new Promise(function(fulfill, reject){
//do something for 5 seconds
fulfill(result);
});
}).then(function(result){
return new Promise(function(fulfill, reject){
//do something for 8 seconds
fulfill(result);
});
}).then(function(result){
//do something with the result
});
The then
method is executed as soon as the Promise
finished. Normally, the return value of the function
passed to then
is passed to the next one as result.
But if a Promise
is returned, the next then
function waits until the Promise
finished executing and receives the results of it (the value that is passed to fulfill
).
I know this is an old question, but still is hard to find a solution.
To start, this worked for me on a project built with Rails 4, Paperclip 4, CamanJS, Heroku and AWS S3.
You have to request your image using the crossorigin: "anonymous"
parameter.
<img href="your-remote-image.jpg" crossorigin="anonymous">
Add your site URL to CORS in AWS S3. Here is a refference from Amazon about that. Pretty much, just go to your bucket, and then select "Properties" from the tabs on the right, open "Permissions tab and then, click on "Edit CORS Configuration".
Originally, I had
< AllowedOrigin>
set to*
. Just change that asterisk to your URL, be sure to include options likehttp://
andhttps://
in separate lines. I was expecting that the asterisk accepts "All", but apparently we have to be more specific than that.
This is how it looks for me.
This was simple for me -
Solution
Create the directory (RemoteSystemsTempFiles) where it is looking
Restart Eclipse, problem solved!
Example Problem Message
Not sure why this took me so long to resolve, but quite easy now, and quite obvious in retrospect! ;)...
I published one here: FullParam SQL Blog
/* Reto Egeter, fullparam.wordpress.com */
DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))
WHILE @TableName IS NOT NULL
BEGIN
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
IF @TableName IS NOT NULL
BEGIN
DECLARE @sql VARCHAR(MAX)
SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(''' + @TableName + ''', 2)
AND TABLE_NAME = PARSENAME(''' + @TableName + ''', 1)
AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END + ',COLUMN_NAME)'
INSERT INTO @ColumnNameTable
EXEC (@sql)
WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
BEGIN
PRINT @ColumnName
SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),'''
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + '''
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
INSERT INTO #Results
EXEC(@sql)
IF @@ROWCOUNT > 0 IF @FullRowResult = 1
BEGIN
SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
' FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))'
WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
EXEC(@sql)
END
DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
END
END
END
SET NOCOUNT OFF
SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType
No need to set SQL_SAFE_UPDATES to 0, I would really discourage it to do it that way. SAFE_UPDATES is by default on for a REASON. You can drive a car without safety belts and other things if you know what I mean ;) Just add in the WHERE clause a KEY-value that matches everything like a primary-key comparing to 0, so instead of writing:
UPDATE customers SET countryCode = 'USA'
WHERE country = 'USA'; -- which gives the error, you just write:
UPDATE customers SET countryCode = 'USA'
WHERE (country = 'USA' AND customerNumber <> 0); -- Because customerNumber is a primary key you got no error 1175 any more.
Now you can be assured every record is (ALWAYS) updated as you expect.
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
I found the right answer just by comparing the conversion to 1/1/1970 w/o the local time adjustment;
DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (date - epoch);
double unixTime =span.TotalSeconds;
You can't do it like this, but you can execute the entire query storing it in a variable.
For example:
DECLARE @listOfIDs NVARCHAR(MAX) =
'1,2,3'
DECLARE @query NVARCHAR(MAX) =
'Select *
From TabA
Where TabA.ID in (' + @listOfIDs + ')'
Exec (@query)
For percise time measurements (like GetTickCount), also take a look at mach_absolute_time and this Apple Q&A: http://developer.apple.com/qa/qa2004/qa1398.html.
\begin{figure}[H]
\centering
{\includegraphics[width=1.0\textwidth]{image}}
\caption{captiontext\protect\footnotemark}
\label{fig:}
\end{figure}
\footnotetext{Footnotetext}
You were close. The key is to have the hidden layout inflate to match_parent
in both height and weight. Simply start it off as View.GONE
. This way, using the percentage in the animators works properly.
Layout (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_screen"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="@string/hello_world" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/hello_world" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="slideUpDown"
android:text="Slide up / down" />
<RelativeLayout
android:id="@+id/hidden_panel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:visibility="gone" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:layout_centerInParent="true"
android:onClick="slideUpDown" />
</RelativeLayout>
</RelativeLayout>
Activity (MainActivity.java):
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
public class OffscreenActivity extends Activity {
private View hiddenPanel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
hiddenPanel = findViewById(R.id.hidden_panel);
}
public void slideUpDown(final View view) {
if (!isPanelShown()) {
// Show the panel
Animation bottomUp = AnimationUtils.loadAnimation(this,
R.anim.bottom_up);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
}
else {
// Hide the Panel
Animation bottomDown = AnimationUtils.loadAnimation(this,
R.anim.bottom_down);
hiddenPanel.startAnimation(bottomDown);
hiddenPanel.setVisibility(View.GONE);
}
}
private boolean isPanelShown() {
return hiddenPanel.getVisibility() == View.VISIBLE;
}
}
Only other thing I changed was in bottom_up.xml
. Instead of
android:fromYDelta="75%p"
I used:
android:fromYDelta="100%p"
But that's a matter of preference, I suppose.
It is going to write the value of your property model.Destination
This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.
Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:
To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
There are still some small thing with the code above that you should notice:
.Close
and DisplayAlerts=True
should be in a finally clause, but I don't know how to do it in VBA- 5
to - 4
when setting MyFileName.Edit: put Local:=True
to save with my locale CSV delimiter.
Your problem is that your phones object doesn't have a length property (unless you define it somewhere in the JSON that you return) as objects aren't the same as arrays, even when used as associative arrays. If the phones object was an array it would have a length. You have two options (maybe more).
Change your JSON structure (assuming this is possible) so that 'phones' becomes
"phones":[{"number":"XXXXXXXXXX","type":"mobile"},{"number":"XXXXXXXXXX","type":"mobile"}]
(note there is no word-numbered identifier for each phone as they are returned in a 0-indexed array). In this response phones.length
will be valid.
Iterate through the objects contained within your phones object and count them as you go, e.g.
var key, count = 0;
for(key in data.phones) {
if(data.phones.hasOwnProperty(key)) {
count++;
}
}
If you're only targeting new browsers option 2 could look like this
Note that Charity Leschinski's answer may have a bit of an issue when there is some delay in the response. eg:
lparstat 1 5 returns one response line and works,
lparstat 5 1 should return 5 lines, but only returns the first
I've put the command output while inside another ... I'm sure there is a better way, I had to do this as a quick fix
while (commandOutput.available() > 0) {
while (readByte != 0xffffffff) {
outputBuffer.append((char) readByte);
readByte = commandOutput.read();
}
try {Thread.sleep(1000);} catch (Exception ee) {}
}
Build your project and get the apk
from your_project\app\build\apk
some resources:
ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:
arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]
or using fromELF utility(built in most IDEs such as ADS though):
fromelf -bin -o [binary-output-file] [elf-input-file]
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element? If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
There is a pseudocolumn called %%physloc%% that shows the physical address of the row.
To fix that error on OS X, I restarted and stopped the service:
$ brew services restart mongodb
$ brew services stop mongodb
Then I ran mongod --config /usr/local/etc/mongod.conf
, and the problem was gone.
The error seemed to arise after upgrading the mongodb homebrew package.
This error also may occur if you're trying to profile an app where the device is not included in the provisioning profile.
Make sure your device is included in the dev provisioning profile you want to use. Somehow the error message is misleading. My entitlements were actually ok.
try to put your script and link on the head like this:
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous">
</script>
</head>
<body>
<div class="row">
<h3 class="one">Text</h3>
<button class="btn btn-secondary pull-right">Button</button>
</div>
</body>
</html>
Using underscore.js or lodash.js, you can do the following on an array of strings:
var contacts = ['Billy Bob', 'John', 'Bill', 'Sarah'];
var filters = ['Bill', 'Sarah'];
contacts = _.filter(contacts, function(contact) {
return _.every(filters, function(filter) { return (contact.indexOf(filter) === -1); });
});
// ['John']
And on a single string:
var contact = 'Billy';
var filters = ['Bill', 'Sarah'];
_.every(filters, function(filter) { return (contact.indexOf(filter) >= 0); });
// true
_x000D_
_x000D_
function insertAtCaret(text) {_x000D_
const textarea = document.querySelector('textarea')_x000D_
textarea.setRangeText(_x000D_
text,_x000D_
textarea.selectionStart,_x000D_
textarea.selectionEnd,_x000D_
'end'_x000D_
)_x000D_
}_x000D_
_x000D_
setInterval(() => insertAtCaret('Hello'), 3000)
_x000D_
<textarea cols="60">Stack Overflow Stack Exchange Starbucks Coffee</textarea>
_x000D_
_x000D_
_x000D_
JSTool is the best for stability.
Steps:
Reference:
Which Boost library? Many of them are pure templates and do not require linking.
Now with that actually shown concrete example which tells us that you want Boost program options (and even more told us that you are on Ubuntu), you need to do two things:
libboost-program-options-dev
so that you can link against it.cmake
to link against libboost_program_options
.I mostly use Makefiles so here is the direct command-line use:
$ g++ boost_program_options_ex1.cpp -o bpo_ex1 -lboost_program_options
$ ./bpo_ex1
$ ./bpo_ex1 -h
$ ./bpo_ex1 --help
$ ./bpo_ex1 -help
$
It doesn't do a lot it seems.
For CMake, you need to add boost_program_options to the list of libraries, and IIRC this is done via SET(liblist boost_program_options)
in your CMakeLists.txt
.
You can wrap the following in a DIV:
<div class="your-class">
<label for="First_Name">First Name:</label>
<input name="first_name" id="First_Name" type="text" />
<label for="Name">Last Name:</label>
<input name="last_name" id="Last_Name" type="text" />
</div>
Give each input float:left
in your CSS:
.your-class input{
float:left;
}
example only
You might have to adjust margins.
Remember to apply clear:left
or both to whatever comes after ".your-class"
I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on
git branch -f <branchname> <commit>
Here is a scenario where I have needed to do this.
Develop on the wrong branch and hence need to reset it.
Cleanly develop and release some software.
Mistake: Accidentally stay on the release branch while developing further.
"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.
Create a branch for the development that is up to date holding the work committed so far and switch to it.
git branch development
git checkout development
Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.
Correct the release branch to point back to the last real release.
git branch -f release release2
The release branch is now correct again, like this ...
git push -f <remote> <branch>
is well described in another thread, though the word "overwrite" in the title is misleading.
Force "git push" to overwrite remote files
This can happen when trying to install a debug/unsigned APK on top of a signed release APK from the Play store.
H:\>adb install -r "Signed.apk"
2909 KB/s (220439 bytes in 0.074s)
pkg: /data/local/tmp/Signed.apk
Success
H:\>adb install -r "AppName.apk"
2753 KB/s (219954 bytes in 0.078s)
pkg: /data/local/tmp/AppName.apk
Failure [INSTALL_FAILED_VERSION_DOWNGRADE]
The solution to this is to uninstall and then reinstall or re run it from the IDE.
You can use
select from_unixtime(1300464000,"%Y-%m-%d %h %i %s") from table;
For in details description about
Use:
window.location.href
As noted in the comments, the line below works, but it is bugged for Firefox.
document.URL
Use something like this:
page1.php
<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start()
BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
To resolve this problem set value for apc.shm_size as integer Locate your apc.ini file (In my system apc.ini file location /etc/php5/conf.d/apc.ini) and set: apc.shm_size = 1000
To get the build in classes (like Array and Hash) to support as_json
and to_json
, you need to require 'json/add/core'
(see the readme for details)
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.
Hope that will help.
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965
df['mean'] = df.iloc[:, 0:4].mean(axis=1)
And if you want to select individual columns
df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)
You can cast datetime to time
select CAST(GETDATE() as time)
If you want a hh:mm format
select cast(CAST(GETDATE() as time) as varchar(5))
Using Xamarin now we can develop iPhone applications in Windows machine itself with the help of Xamarin Live Player.
Using this Xamarin live player dev/deploy/debug cycle can now be done without an Apple system.
But to sign and release the app Apple system is required.
Find the reference here
I checked the reference nothing dodgy
I've never really seen a point in using it. Provides very little advantage, and might even make things harder to use.
Unless you happen to have hundreds or thousands of links, all to the same sub-directory. Then it might save you a few bytes of bandwidth.
As an afterthought, I seem to recall there being some problem with the tag in IE6. You could place them anywhere in the body, redirecting different portions of the site to different locations. This was fixed in IE7, which broke a lot of sites.
I've successfully mount /home/<user-name>
folder of my host to the /mnt
folder of the existing (not running) container. You can do it in the following way:
Open configuration file corresponding to the stopped container, which can be found at /var/lib/docker/containers/99d...1fb/config.v2.json
(may be config.json
for older versions of docker).
Find MountPoints
section, which was empty in my case: "MountPoints":{}
. Next replace the contents with something like this (you can copy proper contents from another container with proper settings):
"MountPoints":{"/mnt":{"Source":"/home/<user-name>","Destination":"/mnt","RW":true,"Name":"","Driver":"","Type":"bind","Propagation":"rprivate","Spec":{"Type":"bind","Source":"/home/<user-name>","Target":"/mnt"},"SkipMountpointCreation":false}}
or the same (formatted):
"MountPoints": {
"/mnt": {
"Source": "/home/<user-name>",
"Destination": "/mnt",
"RW": true,
"Name": "",
"Driver": "",
"Type": "bind",
"Propagation": "rprivate",
"Spec": {
"Type": "bind",
"Source": "/home/<user-name>",
"Target": "/mnt"
},
"SkipMountpointCreation": false
}
}
service docker restart
This works for me with Ubuntu 18.04.1 and Docker 18.09.0
git pull origin master
this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.
Try to organize by folder:
baseTypes.ts
export class Animal {
move() { /* ... */ }
}
export class Plant {
photosynthesize() { /* ... */ }
}
dog.ts
import b = require('./baseTypes');
export class Dog extends b.Animal {
woof() { }
}
tree.ts
import b = require('./baseTypes');
class Tree extends b.Plant {
}
LivingThings.ts
import dog = require('./dog')
import tree = require('./tree')
export = {
dog: dog,
tree: tree
}
main.ts
import LivingThings = require('./LivingThings');
console.log(LivingThings.Tree)
console.log(LivingThings.Dog)
The idea is that your module themselves shouldn't care / know they are participating in a namespace, but this exposes your API to the consumer in a compact, sensible way which is agnostic to which type of module system you are using for the project.
for method parameters you can use Objects.requireNonNull() like this:
test(String str) {
Objects.requireNonNull(str);
}
But this is only checked at runtime and throws an NPE if null. It is like a preconditions check. But that might be what you are looking for.
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
Is your webservice configured correctly in IIS? The pool its using, the version of ASP.NET (2.0) is set? Can you browse the .asmx?
Talking about exceptions, try to put an try-catch block in the line that access your webservice. Put and catch(System.Web.Services.Protocolos.SoapException).
Also, you can set a Timeout for your webservice object.
The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.
You can't do that using open. use codecs.
when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:
import codecs
file = codecs.open('data.txt','w','utf-8')
For Files - svn revert filename
For Folders - svn revert -R folder
You could use the HTML5 Tag <mark>
:
<p>Enter the competition by
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing
<mark class="blue">summer</mark> trips!</p>
And use this in the CSS:
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
mark.red {
color:#ff0000;
background: none;
}
mark.blue {
color:#0000A0;
background: none;
}
The tag <mark>
has a default background color...at least in Chrome.
I have started Activity A->B->C->D. When the back button is pressed on Activity D I want to go to Activity A. Since A is my starting point and therefore already on the stack all the activities in top of A is cleared and you can't go back to any other Activity from A.
This actually works in my code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent a = new Intent(this,A.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
}
return super.onKeyDown(keyCode, event);
}
Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.
This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input:
N = n_neurons * ( n_inputs + 1)
.
I fixed my issue on Windows 2012 server by Installing ALL WCF Features.
A) Server Manager > Manage[link top left] > Add Roles and Features
B) In Features > .Net Framework 4.5 Features > WCF Services
C) Check (enable) the features. I checked all.
D) Install
if you have for example config folder under Resources folder I tried this Class working perfectly hope be useful
File file = ResourceUtils.getFile("classpath:config/sample.txt")
//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
In my case, I was simply unobservant at first and didn't see that one of the 30+ projects in my solution said "(load failed)" even though one of its files was still loaded in the editor, but had no intellisense. Reloading the project did the trick.
Merge replication. You can create the subscriber (2008) from the distributor (2008). After the database has fully synchronized, drop the subscription and the publication.
Try as following, should return "exists" or "non exists":
<?php
echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';
Use Parameter Binding as describe completely here : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
Just search for "ab" in the string then negate the result:
!/ab/.test("bamboo"); // true
!/ab/.test("baobab"); // false
It seems easier and should be faster too.
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
subWindowHandler = iterator.next();
driver.switchTo().window(subWindowHandler); // switch to popup window
// Now you are in the popup window, perform necessary actions here
driver.switchTo().window(parentWindowHandler); // switch back to parent window
This works well for console in debug mode
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n
Use <br />
OR <br>
-
<li>Post by<br /><a>Author</a></li>
OR
<li>Post by<br><a>Author</a></li>
or
make the a
element display:block;
<li>Post by <a style="display:block;">Author</a></li>
You can create script /etc/cron.hourly/php and put there:
#!/bin/bash
max=24
tmpdir=/tmp
nice find ${tmpdir} -type f -name 'sess_*' -mmin +${max} -delete
Then make the script executable (chmod +x).
Now every hour will be deleted all session files with data modified more than 24 minutes ago.
You Can use this query to generate all tablenames with their counts
select ' select '''|| tablename ||''', count(*) from ' || tablename ||'
union' from pg_tables where schemaname='public';
the result from the above query will be
select 'dim_date', count(*) from dim_date union
select 'dim_store', count(*) from dim_store union
select 'dim_product', count(*) from dim_product union
select 'dim_employee', count(*) from dim_employee union
You'll need to remove the last union and add the semicolon at the end !!
select 'dim_date', count(*) from dim_date union
select 'dim_store', count(*) from dim_store union
select 'dim_product', count(*) from dim_product union
select 'dim_employee', count(*) from dim_employee **;**
RUN !!!
You can specify how many times you want the previous item to match by using {min,max}
.
{[0-9]{1,3}:[0-9]{1,3}}
Also, you can use \d
for digits instead of [0-9]
for most regex flavors:
{\d{1,3}:\d{1,3}}
You may also want to consider escaping the outer {
and }
, just to make it clear that they are not part of a repetition definition.
This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer
There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.
The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.
Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.
You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:
SELECT TO_CHAR(
TO_DATE('15/August/2009,4:30 PM'
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM DUAL;
15-08-2009
For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:
SELECT TO_CHAR(
TO_DATE(MYDATESTRING
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM MYTABLE;
Assuming Java (JDK + JRE) is installed in your system, do the following:
C:/>javap javax.servlet.http.HttpServletRequest
It should show a bunch of classes
In case you're using YAML and Twig for translations in Symfony, and want to use multi-line translations in Javascript, a carriage return is added right after the translation. So even the following code:
var javascriptVariable = "{{- 'key'|trans -}}";
Which has the following yml translation:
key: >
This is a
multi line
translation.
Will still result into the following code in html:
var javascriptVariable = "This is a multi line translation.
";
So, the minus sign in Twig does not solve this. The solution is to add this minus sign after the greater than sign in yml:
key: >-
This is a
multi line
translation.
Will have the proper result, multi line translation on one line in Twig:
var javascriptVariable = "This is a multi line translation.";
As mentioned above the port is in use already. This could be due to several reasons
close_wait
state when your program is waiting for the other end to close the program.refer (https://unix.stackexchange.com/questions/10106/orphaned-connections-in-close-wait-state).time_wait
state. you can wait or use socket option SO_REUSEADDR
as mentioned in another post.Do netstat -a | grep <portno>
to check the port state.
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x
will be true otherwise it will be false.
java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.
I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.
add one ArrayList to second ArrayList as:
Arraylist1.addAll(Arraylist2);
EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:
ArrayList<String> arraylist3=new ArrayList<String>();
arraylist3.addAll(Arraylist1); // add first arraylist
arraylist3.addAll(Arraylist2); // add Second arraylist
Use a special catch block for the exception of the Response.End() method
{
...
context.Response.End(); //always throws an exception
}
catch (ThreadAbortException e)
{
//this is special for the Response.end exception
}
catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write(e.Message);
}
Or just remove the Response.End() if your building a filehandler
Recursion used for Kaprekar's constant
function KaprekarsConstant($num, $count = 1) {
$input = str_split($num);
sort($input);
$ascendingInput = implode($input);
$descendingInput = implode(array_reverse($input));
$result = $ascendingInput > $descendingInput
? $ascendingInput - $descendingInput
: $descendingInput - $ascendingInput;
if ($result != 6174) {
return KaprekarsConstant(sprintf('%04d', $result), $count + 1);
}
return $count;
}
The function keeps calling itself with the result of the calculation until it reaches Kaprekars constant, at which it will return the amount of times the calculations was made.
/edit For anyone that doesn't know Kaprekars Constant, it needs an input of 4 digits with at least two distinct digits.
<script>
function checkusers()
{
var shouldEnable = document.getElementById('checkbox').value == 0;
document.getElementById('add_button').disabled = shouldEnable;
}
</script>
#include <math.h>
double round(double x);
float roundf(float x);
Don't forget to link with -lm. See also ceil(), floor() and trunc().
You can try below code in Global.asax file.
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:
echo array_keys($array)[$i];
Angular has several timepoints to start executing functions. If you seek for something like jQuery's
$(document).ready();
You may find this analog in angular to be very useful:
$scope.$watch('$viewContentLoaded', function(){
//do something
});
This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.
UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:
$scope.$watch('$viewContentLoaded',
function() {
$timeout(function() {
//do something
},0);
});
Simply create an instance of Class2
and call the desired method.
Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/
$('body').on('mouseenter mouseleave','.dropdown',function(e){_x000D_
var _d=$(e.target).closest('.dropdown');_x000D_
if (e.type === 'mouseenter')_d.addClass('show');_x000D_
setTimeout(function(){_x000D_
_d.toggleClass('show', _d.is(':hover'));_x000D_
$('[data-toggle="dropdown"]', _d).attr('aria-expanded',_d.is(':hover'));_x000D_
},300);_x000D_
});_x000D_
_x000D_
/* this is not needed, just prevents page reload when a dd link is clicked */_x000D_
$('.dropdown a').on('click tap', e => e.preventDefault())
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href>Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href>Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href>Features</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href>Pricing</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
Dropdown link_x000D_
</a>_x000D_
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<a class="dropdown-item" href>Action</a>_x000D_
<a class="dropdown-item" href>Another action</a>_x000D_
<a class="dropdown-item" href>Something else here</a>_x000D_
</div>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
__FUNCTION__
is non standard, __func__
exists in C99 / C++11. The others (__LINE__
and __FILE__
) are just fine.
It will always report the right file and line (and function if you choose to use __FUNCTION__
/__func__
). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.
Try this..
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
First you should take a note about difference between git am
and git apply
When you are using git am
you usually wanna to apply many patches. Thus should use:
git am *.patch
or just:
git am
Git will find patches automatically and apply them in order ;-)
UPD
Here you can find how to generate such patches
Delays can be also implemented by using the following methods.
The first method:
import time
time.sleep(5) # Delay for 5 seconds.
The second method to delay would be using the implicit wait method:
driver.implicitly_wait(5)
The third method is more useful when you have to wait until a particular action is completed or until an element is found:
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))
A version using SCAN rather than KEYS (as recommended for production servers) and --pipe
rather than xargs.
I prefer pipe over xargs because it's more efficient and works when your keys contain quotes or other special characters that your shell with try and interpret. The regex substitution in this example wraps the key in double quotes, and escapes any double quotes inside.
export REDIS_HOST=your.hostname.com
redis-cli -h "$REDIS_HOST" --scan --pattern "YourPattern*" > /tmp/keys
time cat /tmp/keys | perl -pe 's/"/\\"/g;s/^/DEL "/;s/$/"/;' | redis-cli -h "$REDIS_HOST" --pipe
The draft CSS Selectors Level 4 proposes to add an of <other-selector>
grammar within the :nth-child
selector. This would allow you to pick out the nth child matching a given other selector:
:nth-child(1 of p.myclass)
Previous drafts used a new pseudo-class, :nth-match()
, so you may see that syntax in some discussions of the feature:
:nth-match(1 of p.myclass)
This has now been implemented in WebKit, and is thus available in Safari, but that appears to be the only browser that supports it. There are tickets filed for implementing it Blink (Chrome), Gecko (Firefox), and a request to implement it in Edge, but no apparent progress on any of these.
I found
dmesg | grep tty
doing the job.
<html>
<head></head>
<title></title>
<script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<body>
Type here:<input type="text" id="inputbox" value="type here"/>
<br>
Length:<input type="text" id="length"/>
<script type='text/javascript'>
$(window).keydown(function (e) {
//use e.which
var length = 0;
if($('#inputbox').val().toString().trim().length > 0)
{
length = $('#inputbox').val().toString().trim().length;
}
$('#length').val(length.toString());
})
</script>
</body>
</html>
It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:
#define FOO(n) foo(n);bar(n)
and you do:
void foobar(int n) {
if (n)
FOO(n);
}
then this expands to:
void foobar(int n) {
if (n)
foo(n);bar(n);
}
Notice that the second call bar(n)
is not part of the if
statement anymore.
Wrap both into do { } while(0)
, and you can also use the macro in an if
statement.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
I know this is an old post, but I thought this may be of some help to the next person who stumbles along.
As long as you don't assign an object to anything it maintains no reference in memory. So to make an object that you want to share among other objects, you'll have to create a factory like so:
var a = function(){
return {
father:'zacharias'
};
},
b = a(),
c = a();
c.father = 'johndoe';
alert(b.father);
Starting from support library version 24.0.0 you can call FragmentTransaction.commitNow()
method which commits this transaction synchronously instead of calling commit()
followed by executePendingTransactions()
what i have experienced is that this exception raise when updating object have an id which not exist in table. if you read exception message it says "Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1" which means it was unable to found record with your given id.
To avoid this i always read record with same id if i found record back then i call update otherwise throw "exception record not found".
Architecture and design are closely related; the main difference between them is really about which way we face. Architecture faces towards strategy, structure and purpose, towards the abstract. Design faces towards implementation and practice, towards the concrete.
You could do it like that:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
Do you want to only get JPEG files or all files?
I was receiving this error for different reasons.
Steps to reproduce:
~> My issue was that I created a brand new blank application.
~> I then generated a custom fragment from the File ~> New File Menu.
~> Proceeded to customize the fragment by adding layouts and buttons etc.
~> Referenced the new custom fragment in the auto generated activity_my.xml that was generated for me when creating the application. Doing this allowed the XML to generate the objects for me.
Heres is the catch when generating the custom fragment via File ~> New File Menu it auto generates an interface function stub and places it at the bottom of the fragment class file.
This means that your MyActivity class must implement this interface. If it does not then the the above error occurs only when referencing the fragment from xml. By removing the reference for the Fragment in the XML completely, and creating the fragment through code in the MyActivity.java class file Logcat generates a more concise error explaining the issue in detail and complaining about the interface. This is demonstrated in the Project Template Activity+Fragment. Although, <~that Project Template does not generate the interface stub.
Calling Exception.ToString()
gives you more information than just using the Exception.Message
property. However, even this still leaves out lots of information, including:
Data
collection property found on all exceptions.There are times when you want to capture this extra information. The code below handles the above scenarios. It also writes out the properties of the exceptions in a nice order. It's using C# 7 but should be very easy for you to convert to older versions if necessary. See also this related answer.
public static class ExceptionExtensions
{
public static string ToDetailedString(this Exception exception) =>
ToDetailedString(exception, ExceptionOptions.Default);
public static string ToDetailedString(this Exception exception, ExceptionOptions options)
{
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
var stringBuilder = new StringBuilder();
AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);
foreach (PropertyInfo property in exception
.GetType()
.GetProperties()
.OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
.ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
{
var value = property.GetValue(exception, null);
if (value == null && options.OmitNullProperties)
{
if (options.OmitNullProperties)
{
continue;
}
else
{
value = string.Empty;
}
}
AppendValue(stringBuilder, property.Name, value, options);
}
return stringBuilder.ToString().TrimEnd('\r', '\n');
}
private static void AppendCollection(
StringBuilder stringBuilder,
string propertyName,
IEnumerable collection,
ExceptionOptions options)
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);
var i = 0;
foreach (var item in collection)
{
var innerPropertyName = $"[{i}]";
if (item is Exception)
{
var innerException = (Exception)item;
AppendException(
stringBuilder,
innerPropertyName,
innerException,
innerOptions);
}
else
{
AppendValue(
stringBuilder,
innerPropertyName,
item,
innerOptions);
}
++i;
}
}
private static void AppendException(
StringBuilder stringBuilder,
string propertyName,
Exception exception,
ExceptionOptions options)
{
var innerExceptionString = ToDetailedString(
exception,
new ExceptionOptions(options, options.CurrentIndentLevel + 1));
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
stringBuilder.AppendLine(innerExceptionString);
}
private static string IndentString(string value, ExceptionOptions options)
{
return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
}
private static void AppendValue(
StringBuilder stringBuilder,
string propertyName,
object value,
ExceptionOptions options)
{
if (value is DictionaryEntry)
{
DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
}
else if (value is Exception)
{
var innerException = (Exception)value;
AppendException(
stringBuilder,
propertyName,
innerException,
options);
}
else if (value is IEnumerable && !(value is string))
{
var collection = (IEnumerable)value;
if (collection.GetEnumerator().MoveNext())
{
AppendCollection(
stringBuilder,
propertyName,
collection,
options);
}
}
else
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
}
}
}
public struct ExceptionOptions
{
public static readonly ExceptionOptions Default = new ExceptionOptions()
{
CurrentIndentLevel = 0,
IndentSpaces = 4,
OmitNullProperties = true
};
internal ExceptionOptions(ExceptionOptions options, int currentIndent)
{
this.CurrentIndentLevel = currentIndent;
this.IndentSpaces = options.IndentSpaces;
this.OmitNullProperties = options.OmitNullProperties;
}
internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }
internal int CurrentIndentLevel { get; set; }
public int IndentSpaces { get; set; }
public bool OmitNullProperties { get; set; }
}
Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.
You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog.
JS:
<div onclick="location.href='url'">content</div>
jQuery:
$("div").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
Make sure to use cursor:pointer
for these DIVs
Just for the sake of completeness I want to provide some implementation. Generally speaking Regex is an expensive approach, especially if the string is large (which happens when transferring large files). The following approach tries the fastest ways of detection first.
public static class HelperExtensions {
// Characters that are used in base64 strings.
private static Char[] Base64Chars = new[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
/// <summary>
/// Extension method to test whether the value is a base64 string
/// </summary>
/// <param name="value">Value to test</param>
/// <returns>Boolean value, true if the string is base64, otherwise false</returns>
public static Boolean IsBase64String(this String value) {
// The quickest test. If the value is null or is equal to 0 it is not base64
// Base64 string's length is always divisible by four, i.e. 8, 16, 20 etc.
// If it is not you can return false. Quite effective
// Further, if it meets the above criterias, then test for spaces.
// If it contains spaces, it is not base64
if (value == null || value.Length == 0 || value.Length % 4 != 0
|| value.Contains(' ') || value.Contains('\t') || value.Contains('\r') || value.Contains('\n'))
return false;
// 98% of all non base64 values are invalidated by this time.
var index = value.Length - 1;
// if there is padding step back
if (value[index] == '=')
index--;
// if there are two padding chars step back a second time
if (value[index] == '=')
index--;
// Now traverse over characters
// You should note that I'm not creating any copy of the existing strings,
// assuming that they may be quite large
for (var i = 0; i <= index; i++)
// If any of the character is not from the allowed list
if (!Base64Chars.Contains(value[i]))
// return false
return false;
// If we got here, then the value is a valid base64 string
return true;
}
}
EDIT
As suggested by Sam, you can also change the source code slightly. He provides a better performing approach for the last step of tests. The routine
private static Boolean IsInvalid(char value) {
var intValue = (Int32)value;
// 1 - 9
if (intValue >= 48 && intValue <= 57)
return false;
// A - Z
if (intValue >= 65 && intValue <= 90)
return false;
// a - z
if (intValue >= 97 && intValue <= 122)
return false;
// + or /
return intValue != 43 && intValue != 47;
}
can be used to replace if (!Base64Chars.Contains(value[i]))
line with if (IsInvalid(value[i]))
The complete source code with enhancements from Sam will look like this (removed comments for clarity)
public static class HelperExtensions {
public static Boolean IsBase64String(this String value) {
if (value == null || value.Length == 0 || value.Length % 4 != 0
|| value.Contains(' ') || value.Contains('\t') || value.Contains('\r') || value.Contains('\n'))
return false;
var index = value.Length - 1;
if (value[index] == '=')
index--;
if (value[index] == '=')
index--;
for (var i = 0; i <= index; i++)
if (IsInvalid(value[i]))
return false;
return true;
}
// Make it private as there is the name makes no sense for an outside caller
private static Boolean IsInvalid(char value) {
var intValue = (Int32)value;
if (intValue >= 48 && intValue <= 57)
return false;
if (intValue >= 65 && intValue <= 90)
return false;
if (intValue >= 97 && intValue <= 122)
return false;
return intValue != 43 && intValue != 47;
}
}
For passing an object (including String) by reference in java, you might pass it as member of a surrounding adapter. A solution with a generic is here:
import java.io.Serializable;
public class ByRef<T extends Object> implements Serializable
{
private static final long serialVersionUID = 6310102145974374589L;
T v;
public ByRef(T v)
{
this.v = v;
}
public ByRef()
{
v = null;
}
public void set(T nv)
{
v = nv;
}
public T get()
{
return v;
}
// ------------------------------------------------------------------
static void fillString(ByRef<String> zText)
{
zText.set(zText.get() + "foo");
}
public static void main(String args[])
{
final ByRef<String> zText = new ByRef<String>(new String(""));
fillString(zText);
System.out.println(zText.get());
}
}