It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.
The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.
The easiest solution would be to close the file after you've read it in, then reopen it for writing.
with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)
Alternatively, you can use seek()
to move the cursor back to the beginning of the file then start writing, followed by a truncate()
to deal with the case where the new data is smaller than the previous.
with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)
data["location"] = "NewPath"
jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()
If you have one more missing nuget package that giving your error while building your solution use following command using Nuget Command Console from Tools > Nuget Package Manager > Package Manager Console. It will reinstall your all current packages.
Update-Package –reinstall
Update:
You can pass specific project name as a parameter.
Update-Package –reinstall -ProjectName SampleApp
Try this:
<select id="nameSelect" onfocus="javascript:document.getElementById('nameSelect').selectedIndex=-1;" onchange="doSomething(this);">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
Extending @oopbase's answer with return;
statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch
block or handled if(null != session.getAttribute("attr_name"))
everytime.
So by putting a return;
statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).
You can also change the port when starting up:
$ pg_ctl -o "-F -p 5433" start
Or
$ postgres -p 5433
More about this in the manual.
adding an invisible submit button does the trick
<input type="submit" style="display: none;">
In Kotlin will be :
activity?.applicationContext?.let {
it//<- you context
}
create a view for each subquery is the way to go. Got it working like a charm.
I have the same problem with Windows 7 Pro. Have tried everything suggested by the Microsoft people, including uninstalling, cleaning up, reinstalling both from the web installer and the VS2010 Express iso - with the same result every time.
To say it's frustrating is an understatement and the disinterest from Microsoft in fixing what appears to be a common problem (you can find lots of search engine 'hits' for the problem, none for a solution) is quite unbelievable.
Since this is virtually a virgin Win7 install, the only conclusion is that MS have broken their licesing checks again (why check for a license on a free product?).
Edit: Following further investigation I have concluded that the advice given by Microsoft is useless and does not attempt to diagnose the problem. It simply assumes a corrupt installation source. I believe that the problem is in fact corrupt permissions/ownership of registry keys. HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Licenses and subkeys needs to be owned by SYSTEM with admins having full access. On my affected system the owner cannot be displayed and no permissions are shown when viewed by admin.
I don't have the definitive fix for this so far, as I cannot adequately edit the permissions for the affected registry keys.
Re-installing Windows is an almost certain fix, but also an extremely drastic one.
Although the CONVERT thing works, you actually shouldn't use it. You should ask yourself why you are parsing string values in SQL-Server. If this is a one-time job where you are manually fixing some data you won't get that data another time, this is ok, but if any application is using this, you should change something. Best way would be to use the "date" data type. If this is user input, this is even worse. Then you should first do some checking in the client. If you really want to pass string values where SQL-Server expects a date, you can always use ISO format ('YYYYMMDD') and it should convert automatically.
json_obj=json.dumps(a_dict, ensure_ascii=False)
Try this:
$('.pickupDate').change(function() {
var date2 = $('.pickupDate').datepicker('getDate', '+1d');
date2.setDate(date2.getDate()+1);
$('.dropoffDate').datepicker('setDate', date2);
});
Here is how I styled my colored buttons with an icon in the background
I used "background-color" property for the color and "background" property for the image.
<style>
.btn {
display: inline-block;
line-height: 1em;
padding: .1em .3em .15em 2em
border-radius: .2em;
border: 1px solid #d8d8d8;
background-color: #cccccc;
}
.thumb-up {
background: url('/icons/thumb-up.png') no-repeat 3px center;
}
.thumb-down {
background: url('/icons/thumb-down.png') no-repeat 3px center;
}
</style>
<span class="btn thumb-up">Thumb up</span>
<span class="btn thumb-down">Thumb down</span>
Dictionary is a key value pair. Catch Key by
dic["cat"]
and assign its value like
dic["cat"] = 5
If anyone is interested in getting the localized string from the property with DisplayAttribute and ResourceType like this:
[Display(Name = "Year", ResourceType = typeof(ArrivalsResource))]
public int Year { get; set; }
Use the following after displayAttribute != null
(as shown above by @alex' answer):
ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
var entry = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(p => p.Key.ToString() == displayAttribute.Name);
return entry.Value.ToString();
Thanks to everyone who answered the question, it really helped clarify things for me. In the end Scott Stanchfield's answer got the closest to how I ended up understanding it, but since I didn't understand him when he first wrote it, I am trying to restate the problem so that hopefully someone else will benefit.
I'm going to restate the question in terms of List, since it has only one generic parameter and that will make it easier to understand.
The purpose of the parametrized class (such as List<Date>
or Map<K, V>
as in the example) is to force a downcast and to have the compiler guarantee that this is safe (no runtime exceptions).
Consider the case of List. The essence of my question is why a method that takes a type T and a List won't accept a List of something further down the chain of inheritance than T. Consider this contrived example:
List<java.util.Date> dateList = new ArrayList<java.util.Date>();
Serializable s = new String();
addGeneric(s, dateList);
....
private <T> void addGeneric(T element, List<T> list) {
list.add(element);
}
This will not compile, because the list parameter is a list of dates, not a list of strings. Generics would not be very useful if this did compile.
The same thing applies to a Map<String, Class<? extends Serializable>>
It is not the same thing as a Map<String, Class<java.util.Date>>
. They are not covariant, so if I wanted to take a value from the map containing date classes and put it into the map containing serializable elements, that is fine, but a method signature that says:
private <T> void genericAdd(T value, List<T> list)
Wants to be able to do both:
T x = list.get(0);
and
list.add(value);
In this case, even though the junit method doesn't actually care about these things, the method signature requires the covariance, which it is not getting, therefore it does not compile.
On the second question,
Matcher<? extends T>
Would have the downside of really accepting anything when T is an Object, which is not the APIs intent. The intent is to statically ensure that the matcher matches the actual object, and there is no way to exclude Object from that calculation.
The answer to the third question is that nothing would be lost, in terms of unchecked functionality (there would be no unsafe typecasting within the JUnit API if this method was not genericized), but they are trying to accomplish something else - statically ensure that the two parameters are likely to match.
EDIT (after further contemplation and experience):
One of the big issues with the assertThat method signature is attempts to equate a variable T with a generic parameter of T. That doesn't work, because they are not covariant. So for example you may have a T which is a List<String>
but then pass a match that the compiler works out to Matcher<ArrayList<T>>
. Now if it wasn't a type parameter, things would be fine, because List and ArrayList are covariant, but since Generics, as far as the compiler is concerned require ArrayList, it can't tolerate a List for reasons that I hope are clear from the above.
Use this code.
driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");
If you want use Services in Ubuntu(Upstart): Node as a service in Ubuntu 11.04 with upstart, monit and forever.js
Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.
You have to understand how Unix interprets your input.
The standard Unix shell interpolates environment variables, and what are called globs before it passes the parameters to your program. This is a bit different from Windows which makes the program interpret the expansion.
Try this:
$ echo *
This will echo all the files and directories in your current directory. Before the echo
command acts, the shell interpolates the *
and expands it, then passes that expanded parameter back to your command. You can see it in action by doing this:
$ set -xv
$ echo *
$ set +xv
The set -xv
turns on xtrace and verbose. Verbose echoes the command as entered, and xtrace echos the command that will be executed (that is, after the shell expansion).
Now try this:
$ echo "*"
Note that putting something inside quotes hides the glob expression from the shell, and the shell cannot expand it. Try this:
$ foo="this is the value of foo"
$ echo $foo
$ echo "$foo"
$ echo '$foo'
Note that the shell can still expand environment variables inside double quotes, but not in single quotes.
Now let's look at your statement:
file="home/edward/bank1/fiche/Test*"
The double quotes prevent the shell from expanding the glob expression, so file
is equal to the literal home/edward/bank1/finche/Test*
. Therefore, you need to do this:
file=/home/edward/bank1/fiche/Test*
The lack of quotes (and the introductory slash which is important!) will now make file equal to all files that match that expression. (There might be more than one!). If there are no files, depending upon the shell, and its settings, the shell may simply set file to that literal string anyway.
You certainly have the right idea:
file=/home/edward/bank1/fiche/Test*
if test -s $file
then
echo "found one"
else
echo "found none"
fi
However, you still might get found none returned if there is more than one file. Instead, you might get an error in your test
command because there are too many parameters.
One way to get around this might be:
if ls /home/edward/bank1/finche/Test* > /dev/null 2>&1
then
echo "There is at least one match (maybe more)!"
else
echo "No files found"
fi
In this case, I'm taking advantage of the exit code of the ls
command. If ls
finds one file it can access, it returns a zero exit code. If it can't find one matching file, it returns a non-zero exit code. The if
command merely executes a command, and then if the command returns a zero, it assumes the if
statement as true and executes the if
clause. If the command returns a non-zero value, the if
statement is assumed to be false, and the else
clause (if one is available) is executed.
The test
command works in a similar fashion. If the test
is true, the test
command returns a zero. Otherwise, the test
command returns a non-zero value. This works great with the if
command. In fact, there's an alias to the test
command. Try this:
$ ls -li /bin/test /bin/[
The i
prints out the inode. The inode is the real ID of the file. Files with the same ID are the same file. You can see that /bin/test
and /bin/[
are the same command. This makes the following two commands the same:
if test -s $file
then
echo "The file exists"
fi
if [ -s $file ]
then
echo "The file exists"
fi
First up, you're going to need at least a URLStreamHandler. This will actually open the connection to a given URL. Notice that this is simply called Handler
; this allows you to specify java -Djava.protocol.handler.pkgs=org.my.protocols
and it will automatically be picked up, using the "simple" package name as the supported protocol (in this case "classpath").
new URL("classpath:org/my/package/resource.extension").openConnection();
package org.my.protocols.classpath;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class Handler extends URLStreamHandler {
/** The classloader to find resources from. */
private final ClassLoader classLoader;
public Handler() {
this.classLoader = getClass().getClassLoader();
}
public Handler(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
final URL resourceUrl = classLoader.getResource(u.getPath());
return resourceUrl.openConnection();
}
}
If you control the code, you can do
new URL(null, "classpath:some/package/resource.extension", new org.my.protocols.classpath.Handler(ClassLoader.getSystemClassLoader()))
and this will use your handler to open the connection.
But again, this is less than satisfactory, as you don't need a URL to do this - you want to do this because some lib you can't (or don't want to) control wants urls...
The ultimate option is to register a URLStreamHandlerFactory
that will handle all urls across the jvm:
package my.org.url;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map;
class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory {
private final Map<String, URLStreamHandler> protocolHandlers;
public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) {
protocolHandlers = new HashMap<String, URLStreamHandler>();
addHandler(protocol, urlHandler);
}
public void addHandler(String protocol, URLStreamHandler urlHandler) {
protocolHandlers.put(protocol, urlHandler);
}
public URLStreamHandler createURLStreamHandler(String protocol) {
return protocolHandlers.get(protocol);
}
}
To register the handler, call URL.setURLStreamHandlerFactory()
with your configured factory. Then do new URL("classpath:org/my/package/resource.extension")
like the first example and away you go.
Note that this method may only be called once per JVM, and note well that Tomcat will use this method to register a JNDI handler (AFAIK). Try Jetty (I will be); at worst, you can use the method first and then it has to work around you!
I release this to the public domain, and ask that if you wish to modify that you start a OSS project somewhere and comment here with the details. A better implementation would be to have a URLStreamHandlerFactory
that uses ThreadLocal
s to store URLStreamHandler
s for each Thread.currentThread().getContextClassLoader()
. I'll even give you my modifications and test classes.
Harm, the problem is you don't have a T.
you only have a Type variable.
Hint to MS, if you could do something like
TryCast<typeof(MyClass)>
if would solve all our problems.
I think I've got it.
.wrapper {_x000D_
background:#DDD;_x000D_
display:inline-block;_x000D_
padding: 10px;_x000D_
height: 20px;_x000D_
width:auto;_x000D_
}_x000D_
_x000D_
.label {_x000D_
display: inline-block;_x000D_
width: 1em;_x000D_
}_x000D_
_x000D_
.contents, .contents .inner {_x000D_
display:inline-block;_x000D_
}_x000D_
_x000D_
.contents {_x000D_
white-space:nowrap;_x000D_
margin-left: -1em;_x000D_
padding-left: 1em;_x000D_
}_x000D_
_x000D_
.contents .inner {_x000D_
background:#c3c;_x000D_
width:0%;_x000D_
overflow:hidden;_x000D_
-webkit-transition: width 1s ease-in-out;_x000D_
-moz-transition: width 1s ease-in-out;_x000D_
-o-transition: width 1s ease-in-out;_x000D_
transition: width 1s ease-in-out;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
.wrapper:hover .contents .inner {_x000D_
_x000D_
width:100%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<span class="label">+</span><div class="contents">_x000D_
<div class="inner">_x000D_
These are the contents of this div_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Animating to 100%
causes it to wrap because the box is bigger than the available width (100% minus the +
and the whitespace following it).
Instead, you can animate an inner element, whose 100%
is the total width of .contents
.
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This answer doesn't require that you know the what type of display (inline, etc.) the hideable element is supposed to be when being shown:
.hoverable:not(:hover) + .show-on-hover {_x000D_
display: none;_x000D_
}
_x000D_
<a class="hoverable">Hover over me!</a>_x000D_
<div class="show-on-hover">I'm a block element.</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<a class="hoverable">Hover over me also!</a>_x000D_
<span class="show-on-hover">I'm an inline element.</span>
_x000D_
This uses the adjacent sibling selector and the not selector.
body{
background-image: url('../img/bg.png');
}
I tried this on my project where I need to set the background image of a div so I used this and it worked!
This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.
In this case, tester method needs to have access to Class, and you can construct
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, Foo.class)
and then
List<Foo> list = mapper.readValue(new File("input.json"), type);
Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.
Visual Studio 2013 onwards have this built-in.
(Image courtesy: robert.muehsig)
In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.
My example code
$rexpenditure = <<<Expenditure
<tr>
<td>$row->payment_referencenumber</td>
<td>$row->payment_requestdate</td>
<td>$row->payment_description</td>
<td>$row->payment_fundingsource</td>
<td>$row->payment_agencyulo</td>
<td>$row->payment_agencyproject</td>
<td>$$row->payment_disbustment</td>
<td>$row->payment_payeename</td>
<td>$row->payment_processpayment</td>
</tr>
Expenditure;
It will error if there is a space on PHP 7.0.33.
If you are using Express as back-end you just have to install cors and import and use it in app.use(cors());. If it is not resolved then try switching ports. It will surely resolve after switching ports
u can use this :
@Override
public void afterTextChanged(Editable s) {
super.afterTextChanged(s);
if (s.length() == Bank.PAN_MINIMUM_RECOGNIZABLE_LENGTH + 10) {
Bank bank = BankUtil.findByPan(s.toString());
if (null != bank && mNewPanEntered && !mNameDefined) {
mNewPanEntered = false;
suggestCardName(bank);
}
private void suggestCardName(Bank bank) {
mLastSuggestTime = System.currentTimeMillis();
if (!bank.getName().trim().matches(getActivity().getString(R.string.bank_eghtesadnovin))) {
inputCardNumber.setError(R.string.balance_not_enmb, true);
}
}
Steps :
su
-- To switch to super user.setprop service.adb.tcp.port 5555
- To specify the tcp Port - 5555 is the port number herestop adbd
- To stop the adbd service.start adbd
- To start adbd service.this works perfectly with ssh
from my windows PC
I try to do this on the boot on my cyanogen mobile or launch this with plink. With plink I can't launch shell with su right ... sudo or su command not works. On boot I don't know how it's works!
My shell program works from ssh with su -c "sh /storage/sdcard1/start_adb.sh"
with the last 3 commands (without su --)
Thanks
When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.
1) When the user logs out (Forms signout in Action) I want to redirect to a login page.
public ActionResult Logout() {
//log out the user
return RedirectToAction("Login");
}
2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)
Why would you want to redirect from a controller init?
the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:
public ActionResult Index() {
return RedirectToAction("whateverAction", "whateverController");
}
I was working on a project that I needed a functionality like python set
which removes all duplicates values and returns a new list, so I wrote this function maybe useful to someone
function set(arr) {
var res = [];
for (var i = 0; i < arr.length; i++) {
if (res.indexOf(arr[i]) === -1) {
res.push(arr[i]);
}
}
return res;
}
If you've tried the other answers and your include file still can't be found, here are some additional debugging steps and sanity-checks:
#include
the whole absolute path of the header file instead, and see if the file can be found now. If not, copy-paste the path from your source code into a command line to validate that the file exists at that full path with no typos. Open the header file to ensure you have read access. (Change the source code back when done.) Additional Include Directories
, try clicking the drop-down combo box for Additional Include Directories
, and select <Edit...>
. This will show you evaluated values
of paths. (If it does not show the correct evaluated values, variables in your path might not be set. Click Macros>>
to see variables.) Copy-paste the evaluated path into windows explorer to validate that the path exists. You can add New Symbol Image Set in .xcassets, then you can add SVG file in it
and use it same like image.
Note: This doesn't work on all SVG. You can have a look at the apple documentation
I use the following code inside my onCreate function:
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
Source: https://developer.android.com/guide/topics/ui/actionbar.html
If you use delay frequently in your app, use this utility class
import android.os.Handler;
public class Utils {
// Delay mechanism
public interface DelayCallback{
void afterDelay();
}
public static void delay(int secs, final DelayCallback delayCallback){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
}
}
Usage:
// Call this method directly from java file
int secs = 2; // Delay in seconds
Utils.delay(secs, new Utils.DelayCallback() {
@Override
public void afterDelay() {
// Do something after delay
}
});
To substantiate @deceze's claim that the default JSON encoding is UTF-8...
From IETF RFC4627:
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.
Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.
00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8
If you are using eclipse to start the server then check for the server location being used and the deployment path:
In my case changing this to Tomcat installation
instead of workspace metadata
worked for me.
Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium
git ls-files -o --exclude-standard
gives untracked files, so you can do something like below ( or add an alias to it):
git add $(git ls-files -o --exclude-standard)
If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers().disable()
...;
}
}
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.
If the --dry-run flag is used then no changes will actually be made.
If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.
In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.
If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.
npm dedupe
npm ddp
Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.
For example, consider this dependency graph:
a
+-- b <-- depends on [email protected]
| `-- [email protected]
`-- d <-- depends on c@~1.0.9
`-- [email protected]
In this case, npm-dedupe will transform the tree to:
a
+-- b
+-- d
`-- [email protected]
Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.
The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.
$("#YOUR-BUTTON").on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $("#YOUR-TARGET").offset().top
}, 300);
});
In my case it was a property that gave me the error, the correct writing and still gave me the error in the console. I searched so much and nothing worked for me, until I gave him Ctrl + F5 and Voilá! error was removed. :'v
Simply try this,
<TextView
.......................................
.......................................
.......................................
android:layout_gravity="center_vertical|end"
android:justificationMode="inter_word"
.......................................
.......................................
/>
Hope this help!
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
You can use the Dictionary
data type in python. It's very very similar to the hash—and it also supports nesting, similar to the to nested hash.
Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
For more information, please reference this tutorial on the dictionary data type.
If you're using Maven and don't want to link Tomcat in the Targeted Runtimes in Eclipse, you can simply add the dependency with scope provided in your pom.xml:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
public Main()
{
InitializeComponent();
Process current = Process.GetCurrentProcess();
string currentmd5 = md5hash(current.MainModule.FileName);
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (process.Id != current.Id)
{
try
{
if (currentmd5 == md5hash(process.MainModule.FileName))
{
SetForegroundWindow(process.MainWindowHandle);
Environment.Exit(0);
}
}
catch (/* your exception */) { /* your exception goes here */ }
}
}
}
private string md5hash(string file)
{
string check;
using (FileStream FileCheck = File.OpenRead(file))
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] md5Hash = md5.ComputeHash(FileCheck);
check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
}
return check;
}
it checks only md5 sums by process id.
if an instance of this application was found, it focuses the running application and exit itself.
you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.
may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.
From Regular expression
The standard quantifiers in regular expressions are greedy, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex.
By using a lazy quantifier, the expression tries the minimal match first.
Well in general index is a B-tree
. There are two types of indexes: clustered and nonclustered.
Clustered index creates a physical order of rows (it can be only one and in most cases it is also a primary key - if you create primary key on table you create clustered index on this table also).
Nonclustered index is also a binary tree but it doesn't create a physical order of rows. So the leaf nodes of nonclustered index contain PK (if it exists) or row index.
Indexes are used to increase the speed of search. Because the complexity is of O(log N). Indexes is very large and interesting topic. I can say that creating indexes on large database is some kind of art sometimes.
You can find an example below. Basically you attach a function to window
's scroll
event and trace scrollTop
property and if it's higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {_x000D_
$(window).scroll(function fix_element() {_x000D_
$('#target').css(_x000D_
$(window).scrollTop() > 100_x000D_
? { 'position': 'fixed', 'top': '10px' }_x000D_
: { 'position': 'relative', 'top': 'auto' }_x000D_
);_x000D_
return fix_element;_x000D_
}());_x000D_
});
_x000D_
body {_x000D_
height: 2000px;_x000D_
padding-top: 100px;_x000D_
}_x000D_
code {_x000D_
padding: 5px;_x000D_
background: #efefef;_x000D_
}_x000D_
#target {_x000D_
color: #c00;_x000D_
font: 15px arial;_x000D_
padding: 10px;_x000D_
margin: 10px;_x000D_
border: 1px solid #c00;_x000D_
width: 200px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="target">This <code>div</code> is going to be fixed</div>
_x000D_
Changing Bundle Identifier worked for me.
If it still doesn't work, try again with these steps before:
cd /Users/my_username/Library/MobileDevice/Provisioning Profiles && rm *
(in my case)Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
For React Native version = 0.60, in your root file create a file called react-native.config.js
and put the followings, then just run react-native link
module.exports = {
assets: ["./assets/fonts"]
}
The accepted answer gave two locations:
here
C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache
and possibly here
C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache
Did you try those?
Edited to add
On my Windows Vista machine, it's located in
%Temp%\VWDWebCache
and in
%LocalAppData%\Microsoft\WebsiteCache
From your additional information (regarding team edition) this comes from Clear Client TFS Cache:
Clear Client TFS Cache
Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.
To solve it..
For Windows Vista delete contents of this folder
%LocalAppData%\Microsoft\Team Foundation\1.0\Cache
I believe that the most reliable way to get the external server ip address would be to use an external service.
ipaddr=$(curl -s http://whatismyip.akamai.com/)
Spring 3 supports ${my.server.port:defaultValue}
syntax.
private List<Url> AddURLToFile(Urls urls, Url url)
{
string filePath = @"D:\test\file.json";
urls.UrlList.Add(url);
//if (!System.IO.File.Exists(filePath))
// using (System.IO.File.Delete(filePath));
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(urls.UrlList));
//using (StreamWriter sw = (System.IO.File.Exists(filePath)) ? System.IO.File.AppendText(filePath) : System.IO.File.CreateText(filePath))
//{
// sw.WriteLine(JsonConvert.SerializeObject(urls.UrlList));
//}
return urls.UrlList;
}
private List<Url> ReadURLToFile()
{
// string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"App_Data\file.json");
string filePath = @"D:\test\file.json";
List<Url> result = new List<Url>(); ;
if (!System.IO.File.Exists(filePath))
using (System.IO.File.CreateText(filePath)) ;
using (StreamReader file = new StreamReader(filePath))
{
result = JsonConvert.DeserializeObject<List<Url>>(file.ReadToEnd());
file.Close();
}
if (result == null)
result = new List<Url>();
return result;
}
Using CSS only:
#blockContainer {
display: -webkit-box;
display: -moz-box;
display: box;
-webkit-box-orient: vertical;
-moz-box-orient: vertical;
box-orient: vertical;
}
#blockA {
-webkit-box-ordinal-group: 2;
-moz-box-ordinal-group: 2;
box-ordinal-group: 2;
}
#blockB {
-webkit-box-ordinal-group: 3;
-moz-box-ordinal-group: 3;
box-ordinal-group: 3;
}
<div id="blockContainer">
<div id="blockA">Block A</div>
<div id="blockB">Block B</div>
<div id="blockC">Block C</div>
</div>
assign
is good, but I have not found a function for referring back to the variable you've created in an automated script. (as.name
seems to work the opposite way). More experienced coders will doubtless have a better solution, but this solution works and is slightly humorous perhaps, in that it gets R to write code for itself to execute.
Say I have just assigned value 5 to x
(var.name <- "x"; assign(var.name, 5)
) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name
) will be (which seems to be the point of the assign
function), I can't simply put x <- 6
because var.name
might have been "y"
. So I do:
var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...
#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")
x
will be changed to 6, and if the variable name was anything other than "x"
, that variable will similarly have been changed to 6.
I don't think it's possible to do it in the way you are trying to do it.
Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like
/resources/resource
and GET /resources/resource
returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:
/resources/resource.xml
You have to do the accepted content type determination magic on the server side, then.
Or use Javascript as James suggests.
Although the answers are 100% correct, a small suggestion to improve null
case handling of the list itself with Optional:
List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList)
will allow you to handle nicely the case when listOfStuff
is null and return an emptyList instead of failing with NullPointerException.
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:
public async Task<object> MethodName()
{
return await Task.FromResult<object>(null);
}
Here is an example with no return value:
public async Task MethodName()
{
await Task.CompletedTask;
}
Read these:
TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx
Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx
I usually start with something like:
set lines 256
set trimout on
set tab off
Have a look at help set
if you have the help information installed. And then select name,address
rather than select *
if you really only want those two columns.
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
This work for me: (Only google chrome)
<html>
<head>
<script>
function draw(){
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
ctx.fillRect(25,25,100,100);
ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
ctx.fillRect(58, 74, 125, 100);
}
function downloadImage()
{
var canvas = document.getElementById("thecanvas");
var image = canvas.toDataURL();
var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = 'image.png';
aLink.href = image;
aLink.dispatchEvent(evt);
}
</script>
</head>
<body onload="draw()">
<canvas width=200 height=200 id="thecanvas"></canvas>
<div><button onclick="downloadImage()">Download</button></div>
<image id="theimage"></image>
</body>
</html>
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
ng g c COMPONENTNAME
should work, if your are getting module not found exception then try these things-
There is not.
Why? Probably because a table with two columns will do.
the solution here worked for me : https://community.hortonworks.com/articles/4427/fix-under-replicated-blocks-in-hdfs-manually.html
su - <$hdfs_user>
bash-4.1$ hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files
-bash-4.1$ for hdfsfile in `cat /tmp/under_replicated_files`; do echo "Fixing $hdfsfile :" ; hadoop fs -setrep 3 $hdfsfile; done
You may just need to add @Transient
annotations on roles to not serialize the set.
You could write an extension method:
public static void InvokeIfRequired(this Control c, Action<Control> action)
{
if(c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
And use it like this:
object1.InvokeIfRequired(c => { c.Visible = true; });
EDIT: As Simpzon points out in the comments you could also change the signature to:
public static void InvokeIfRequired<T>(this T c, Action<T> action)
where T : Control
var words_in_text = function (text) {
var regex = /([\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]+)/g;
return text.match(regex);
};
words_in_text('Düsseldorf, Köln, ??????, ???, ??????? !@#$');
// returns array ["Düsseldorf", "Köln", "??????", "???", "???????"]
This regex will match all words in the text of any language...
I was able to accomplish editing the default.aspx
page by:
By doing that I was able to remove the tagprefix causing a problem on my page.
Almost all Magento Models have a corresponding Collection object that can be used to fetch multiple instances of a Model.
To instantiate a Product collection, do the following
$collection = Mage::getModel('catalog/product')->getCollection();
Products are a Magento EAV style Model, so you'll need to add on any additional attributes that you want to return.
$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and orig_price into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
There's multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.
The following shows how to filter by a range of values (greater than AND less than)
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
array('attribute'=>'orig_price','gt'=>'100'),
));
//AND filter for products whose orig_price is less than (lt) 130
$collection->addFieldToFilter(array(
array('attribute'=>'orig_price','lt'=>'130'),
));
While this will filter by a name that equals one thing OR another.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
array('attribute'=>'name','eq'=>'Widget A'),
array('attribute'=>'name','eq'=>'Widget B'),
));
A full list of the supported short conditionals (eq,lt, etc.) can be found in the _getConditionSql
method in lib/Varien/Data/Collection/Db.php
Finally, all Magento collections may be iterated over (the base collection class implements on of the the iterator interfaces). This is how you'll grab your products once filters are set.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
array('attribute'=>'name','eq'=>'Widget A'),
array('attribute'=>'name','eq'=>'Widget B'),
));
foreach ($collection as $product) {
//var_dump($product);
var_dump($product->getData());
}
I guess ch
is a declared as char
. Since char
is a primitive data type and not and object, you can't call any methof from it. You should use Character.isLetter(ch)
.
String payloadRequest = getBody(request);
Using this method
public static String getBody(HttpServletRequest request) throws IOException {
String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
return body;
}
Modify the JavaScript property document.body.style.background
.
For example:
function changeBackground(color) {
document.body.style.background = color;
}
window.addEventListener("load",function() { changeBackground('red') });
Note: this does depend a bit on how your page is put together, for example if you're using a DIV container with a different background colour you will need to modify the background colour of that instead of the document body.
Try including stdint.h
or inttypes.h
.
As suggested by Adam Miller in the comments, I'll add another solution.
The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:
MailMessage Msg = new MailMessage(fromMail, addresses);
In this particular case, we can replace the ';' for ',' and still make use of the constructor.
MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));
Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.
The default display style for a div is "block." This means that each new div will be under the prior one.
You can:
Override the flow style by using float as @Sarfraz suggests.
or
Change your html to use something other than divs for elements you want on the same line. I suggest that you just leave out the divs for the "last_name" field
<form action="/users" method="post"><div style="margin:0;padding:0">
<div>
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
... rest is same
Use __new__
to return value from a class.
As others suggest __repr__
,__str__
or even __init__
(somehow) CAN give you what you want, But __new__
will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.
Read this answer for more insights into __str__
and __repr__
https://stackoverflow.com/a/19331543/4985585
class MyClass():
def __new__(cls):
return list() #or anything you want
>>> MyClass()
[] #Returns a true list not a repr or string
There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).
You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.
Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.
It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.
Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.
Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc
to process your Jenkinsfile
(s).
First, groovydoc
chokes on files without extensions with the wonderful error
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
... 6 more
... and second, as far as I can tell Javadoc-style commments at the start of a groovy
script are ignored. So even if you copy/rename your Jenkinsfile
to Jenkinsfile.groovy
, you won't get much useful output.
I want to be able to use a
/**
* Document my Jenkinsfile's overall purpose here
*/
comment at the start of my Jenkinsfile. No such luck (yet).
groovydoc
will process classes and methods defined in your Jenkinsfile
if you pass -private
to the command, though.
set @n = (select sum(Amount) from Expense)
print 'n=' + @n
Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..
Create Proc SP1
(
@ID int,
@Name varchar(40)
-- etc parameter list, If you don't have any parameter then no need to pass.
)
AS
BEGIN
-- Here we have some opereations
-- If there is any Error Before Executing SP2 then SP will stop executing.
Exec SP2 @ID,@Name,@SomeID OUTPUT
-- ,etc some other parameter also we can use OutPut parameters like
-- @SomeID is useful for some other operations for condition checking insertion etc.
-- If you have any Error in you SP2 then also it will stop executing.
-- If you want to do any other operation after executing SP2 that we can do here.
END
yes, this is valid, and under some circumstances it is even useful. Generally, if you don't need it, don't do it.
I was facing this issue for long time. Finally it was issue of ssh-add. Git ssh credentials were not taken into consideration.
Check following command might work for you:
ssh-add
str.startswith
allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])
Return
True
if string starts with theprefix
, otherwise returnFalse
.prefix
can also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
Another way of doing the same could be using the Gson Class
String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);
This will give an object obtained after parsing the json string to work with.
how about sysdate?
SELECT field,datetime_field
FROM database
WHERE datetime_field > (sysdate-1)
Try float
property. Here's an example: http://jsfiddle.net/mLmHR/
you can use ![ ](any link of image)
Also I would suggest to use https://stackedit.io/ for markdown formating and wring it is much easy than remembering all the markdown syntax
Use jquery starts with attribute selector
$('[id^=editDialog]')
Alternative solution - 1 (highly recommended)
A cleaner solution is to add a common class to each of the divs & use
$('.commonClass')
.
But you can use the first one if html markup is not in your hands & cannot change it for some reason.
Alternative solution - 2 (not recommended if n is a large number
)
(as per @Mihai Stancu's suggestion)
$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')
Note: If there are 2 or 3 selectors and if the list doesn't change, this is probably a viable solution but it is not extensible because we have to update the selectors when there is a new ID in town.
Simplest example to making any function in jQuery is
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something here*/}
For Mac users in the 17.06.0-ce-mac19 version you can simply move the Disk Image location from the user interface in the preferences option Just change the location of the disk image and it will work (by clicking Move disk Image) and restarting the docker. Using this approach I was able to use my external hardisk for storing docker images.
you can do some thing like this:
a {
color: #0060B6;
text-decoration: none;
}
a:hover
{
color:#00A0C6;
text-decoration:none;
cursor:pointer;
}
if text-decoration doesn't work then include text-decoration: none !important;
Try:
In the controller:
ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");
In the View:
@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })
or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".
You could also change select.options.selectedIndex DOM attribute like this:
function selectOption(index){ _x000D_
document.getElementById("select_id").options.selectedIndex = index;_x000D_
}
_x000D_
<p>_x000D_
<select id="select_id">_x000D_
<option selected>first option</option>_x000D_
<option>second option</option>_x000D_
<option>third option</option>_x000D_
</select>_x000D_
</p>_x000D_
<p>_x000D_
<button onclick="selectOption(0);">Select first option</button>_x000D_
<button onclick="selectOption(1);">Select second option</button>_x000D_
<button onclick="selectOption(2);">Select third option</button>_x000D_
</p>
_x000D_
This might be due to a security check. This thread might help you.
There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...
You can use the following command to clear out ALL variables. Be careful because it you cannot get your variables back.
rm(list=ls(all=TRUE))
Make sure you're in the right database context in SSMS. Got the same error as you, but I knew the schema already existed. Didn't realize I was in 'MASTER' context. ALTER worked after I changed context to my database.
There are obviously plenty of answers, but this one answers it very nicely (with source)
#pragma omp for
only delegates portions of the loop for different threads in the current team. A team is the group of threads executing the program. At program start, the team consists only of a single member: the master thread that runs the program.To create a new team of threads, you need to specify the parallel keyword. It can be specified in the surrounding context:
#pragma omp parallel { #pragma omp for for(int n = 0; n < 10; ++n) printf(" %d", n); }
and:
What are: parallel, for and a team
The difference between parallel, parallel for and for is as follows:
A team is the group of threads that execute currently. At the program beginning, the team consists of a single thread. A parallel construct splits the current thread into a new team of threads for the duration of the next block/statement, after which the team merges back into one. for divides the work of the for-loop among the threads of the current team.
It does not create threads, it only divides the work amongst the threads of the currently executing team. parallel for is a shorthand for two commands at once: parallel and for. Parallel creates a new team, and for splits that team to handle different portions of the loop. If your program never contains a parallel construct, there is never more than one thread; the master thread that starts the program and runs it, as in non-threading programs.
You can use below query to update or create comment on already created table.
SYNTAX:
COMMENT ON COLUMN TableName.ColumnName IS 'comment text';
Example:
COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';
i think that is what you want.
SELECT
A.SalesOrderID,
A.OrderDate,
FooFromB.*
FROM A,
(SELECT TOP 1 B.Foo
FROM B
WHERE A.SalesOrderID = B.SalesOrderID
) AS FooFromB
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
You can use push and pull to change column ordering. You pull one column and push the other on large devices:
<div class="row">
<div class="col-lg-6 col-md-6 col-lg-pull-6">elements 1</div>
<div class="col-lg-6 col-md-6 col-lg-push-6">
<div>
elements 2
</div>
</div>
</div>
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
I know this post is old but here is what I found.
It doesn't work when I link it this way(with /
before css/style.css
on the href
attribute.
<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />
However, when I removed /
I'm able to link properly with the css file
It should be like this(without /
).
<link rel="stylesheet" media="all" href="CSS/Style.css" type="text/css" />
This was giving me trouble on my project. Hope it will help somebody else.
Seems you are looking for ORDER BY
in DESC
ending order with LIMIT clause:
SELECT
*
FROM
scores
ORDER BY score DESC
LIMIT 10
Of course SELECT *
could seriously affect performance, so use it with caution.
You can use jstat, like :
jstat -gc pid
Full docs here : http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html
I usually combine CSS and JavaScript approaches, so that it works without JavaScript in all browsers but IE6/7, and in IE6/7 with JavaScript on (but not off), since they does not support the :last-child
pseudo-class.
$("li:last-child").addClass("last-child");
li:last-child,li.last-child{ /* ... */ }
A slightly shorter solution, that only moves the item to the end, not anywhere is this:
l += [l.pop(0)]
For example:
>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]
Steps:
Navigate to your project folder and open the /app sub-folder.
Paste the .json file here.
Rebuild the project.
Try this command:
pip install pywin32
Note
If it gives the following error:
Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions:)
No matching distribution found for pywin32>=223 (from pypiwin32)
upgrade 'pip', using:
pip install --upgrade pip
df -tk
for Disk Free size in 1024 byte blocks
Create an init() function and point the table layout. Then create the needed rows and columns.
public void init() {
TableLayout stk = (TableLayout) findViewById(R.id.table_main);
TableRow tbrow0 = new TableRow(this);
TextView tv0 = new TextView(this);
tv0.setText(" Sl.No ");
tv0.setTextColor(Color.WHITE);
tbrow0.addView(tv0);
TextView tv1 = new TextView(this);
tv1.setText(" Product ");
tv1.setTextColor(Color.WHITE);
tbrow0.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setText(" Unit Price ");
tv2.setTextColor(Color.WHITE);
tbrow0.addView(tv2);
TextView tv3 = new TextView(this);
tv3.setText(" Stock Remaining ");
tv3.setTextColor(Color.WHITE);
tbrow0.addView(tv3);
stk.addView(tbrow0);
for (int i = 0; i < 25; i++) {
TableRow tbrow = new TableRow(this);
TextView t1v = new TextView(this);
t1v.setText("" + i);
t1v.setTextColor(Color.WHITE);
t1v.setGravity(Gravity.CENTER);
tbrow.addView(t1v);
TextView t2v = new TextView(this);
t2v.setText("Product " + i);
t2v.setTextColor(Color.WHITE);
t2v.setGravity(Gravity.CENTER);
tbrow.addView(t2v);
TextView t3v = new TextView(this);
t3v.setText("Rs." + i);
t3v.setTextColor(Color.WHITE);
t3v.setGravity(Gravity.CENTER);
tbrow.addView(t3v);
TextView t4v = new TextView(this);
t4v.setText("" + i * 15 / 32 * 10);
t4v.setTextColor(Color.WHITE);
t4v.setGravity(Gravity.CENTER);
tbrow.addView(t4v);
stk.addView(tbrow);
}
}
Call init function in your onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
init();
}
Layout file like:
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#3d455b"
android:layout_alignParentLeft="true" >
<HorizontalScrollView
android:id="@+id/hscrll1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="@+id/table_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</TableLayout>
</RelativeLayout>
</HorizontalScrollView>
</ScrollView>
Will look like:
Basically all you need to do is add $ as prefix at column letter and row number. Please see image below
The return type of a procedure is int.
You can also return result sets (as your code currently does) (okay, you can also send messages, which are strings)
Those are the only "returns" you can make. Whilst you can add table-valued parameters to a procedure (see BOL), they're input only.
Edit:
(Or as another poster mentioned, you could also use a Table Valued Function, rather than a procedure)
If you're looking for a 1 liner, this does well.
new Point(Mouse.GetPosition(mWindow).X + mWindow.Left, Mouse.GetPosition(mWindow).Y + mWindow.Top)
The + mWindow.Left
and + mWindow.Top
makes sure the position is in the right place even when the user drags the window around.
Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))
If you then try predict(m)
, you get the same error as in this question.
$percentage = 50;
$totalWidth = 350;
$new_width = ($percentage / 100) * $totalWidth;
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
This happened to me when I upgraded. I had to downgrade back.
react-redux ^5.0.6 ? ^7.1.3
The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use:
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Or using Joda Time, you can use ISODateTimeFormat.dateTime()
.
I selected Automatic option to select the ViewController.swift file. And then I can able to take outlets.
onActivityCreated()
is now deprecated as Fragments Version 1.3.0-alpha02
The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.
Detailed information can be found here
In your app/build.gradle
file, you can set the minSdkVersion
inside defaultConfig
.
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.name.app"
minSdkVersion 19 // This over here
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
- (void)performAndWait:(void (^)(dispatch_semaphore_t semaphore))perform;
{
NSParameterAssert(perform);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
perform(semaphore);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
Example usage:
[self performAndWait:^(dispatch_semaphore_t semaphore) {
[self someLongOperationWithSuccess:^{
dispatch_semaphore_signal(semaphore);
}];
}];
jQuery offers $.inArray
:
Note that inArray returns the index of the element found, so 0
indicates the element is the first in the array. -1
indicates the element was not found.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Edit 3.5 years later
$.inArray
is effectively a wrapper for Array.prototype.indexOf
in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype
, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
Edit another 3 years later
Gosh, 6.5 years?!
The best option for this in modern Javascript is Array.prototype.includes
:
var found = categories.includes('specialword');
No comparisons and no confusing -1
results. It does what we want: it returns true
or false
. For older browsers it's polyfillable using the code at MDN.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
Without jQuery:
textContent:
var text = document.querySelector('.someClassname').textContent;
Markup:
var text = document.querySelector('.someClassname').innerHTML;
Markup including the matched element:
var text = document.querySelector('.someClassname').outerHTML;
though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.
A few line of java code.
public static void main(String args[]) throws Exception{
String str="test string";
MessageDigest messageDigest=MessageDigest.getInstance("MD5");
messageDigest.update(str.getBytes(),0,str.length());
System.out.println("MD5: "+new BigInteger(1,messageDigest.digest()).toString(16));
}
You may want trigger action to execute once after the client executes a statement that modifies a million rows (statement-level trigger). Or, you may want to trigger the action once for every row that is modified (row-level trigger).
EXAMPLE: Let's say you have a trigger that will make sure all high school seniors graduate. That is, when a senior's grade is 12, and we increase it to 13, we want to set the grade to NULL
.
For a statement level trigger, you'd say, after the increase-grade statement runs, check the whole table once to update any nows with grade 13 to NULL
.
For a row-level trigger, you'd say, after every row that is updated, update the new row's grade to NULL
if it is 13.
A statement-level trigger would look like this:
create trigger stmt_level_trigger
after update on Highschooler
begin
update Highschooler
set grade = NULL
where grade = 13;
end;
and a row-level trigger would look like this:
create trigger row_level_trigger
after update on Highschooler
for each row
when New.grade = 13
begin
update Highschooler
set grade = NULL
where New.ID = Highschooler.ID;
end;
Note that SQLite doesn't support statement-level triggers, so in SQLite, the FOR EACH ROW
is optional.
Yes, you can do print all keys using below bash script,
for key in $(redis-cli -p 6379 keys \*);
do echo "Key : '$key'"
redis-cli -p 6379 GET $key;
done
where, 6379 is a port on which redis is running.
Since you're going to be dealing with data of a variable length (names, email addresses), then you'd be wanting to use VARCHAR. The amount of space taken up by a VARCHAR field is [field length]
+ 1 bytes, up to max length 255, so I wouldn't worry too much about trying to find a perfect size. Take a look at what you'd imagine might be the longest length might be, then double it and set that as your VARCHAR limit. That said...:
I generally set email fields to be VARCHAR(100) - i haven't come up with a problem from that yet. Names I set to VARCHAR(50).
As the others have said, phone numbers and zip/postal codes are not actually numeric values, they're strings containing the digits 0-9 (and sometimes more!), and therefore you should treat them as a string. VARCHAR(20) should be well sufficient.
Note that if you were to store phone numbers as integers, many systems will assume that a number starting with 0 is an octal (base 8) number! Therefore, the perfectly valid phone number "0731602412" would get put into your database as the decimal number "124192010"!!
You can declare the array in C++ in these type of ways.
If you know the array size then you should declare the array for:
integer: int myArray[array_size];
Double: double myArray[array_size];
Char and string : char myStringArray[array_size];
The difference between char and string is as follows
char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";
If you don't know the size of array then you should leave the array blank like following.
integer: int myArray[array_size];
Double: double myArray[array_size];
Nowdays, Primefaces 5.x have a attribute in panelGrid named "columnClasses".
.no-border {
border-style: hidden !important ; /* or none */
}
So, to a panelGrid with 2 columns, repeat two times the css class.
<p:panelGrid columns="2" columnClasses="no-border, no-border">
To other elements, the ugly " !important " is not necessary, but to the border just with it work fine to me.
If you are using SQL Server, Use the LEN
(Length) function:
SELECT EmployeeName FROM EmployeeTable WHERE LEN(EmployeeName) > 4
MSDN for it states:
Returns the number of characters of the specified string expression,
excluding trailing blanks.
For oracle/plsql you can use Length()
, mysql also uses Length.
Here is the Oracle documentation:
http://www.techonthenet.com/oracle/functions/length.php
And here is the mySQL Documentation of Length(string)
:
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length
For PostgreSQL, you can use length(string)
or char_length(string)
. Here is the PostgreSQL documentation:
http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL
If like me you just updated your password and ran
git push
to run into this issue, then there's a super easy fix.
For Mac users only. You need to delete your OSX Keychain access entries for GitHub. You can do it via terminal by running the following commands.
Through the command line, you can use the credential helper directly to erase the keychain entry.
To do this, type the following command:
git credential-osxkeychain erase
host=github.com
protocol=https
# [Now Press Return]
If it's successful, nothing will print out. To test that it works, try and clone a repository from GitHub or run your previous action again like in my case git push
. If you are prompted for a password, the keychain entry was deleted.
If you are using Ubuntu, you should try install build-essential
apt install build-essential
I had troubles with gems installation on fresh installation of ubuntu, and this solution worked for me.
Simple and straightforward:
1) Create your recaptcha fields normally with this:
<div class="g-recaptcha" data-sitekey="YOUR_KEY_HERE"></div>
2) Load the script with this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
3) Now call this to iterate over the fields and create the recaptchas:
<script type="text/javascript">
var CaptchaCallback = function() {
jQuery('.g-recaptcha').each(function(index, el) {
grecaptcha.render(el, {
'sitekey' : jQuery(el).attr('data-sitekey')
,'theme' : jQuery(el).attr('data-theme')
,'size' : jQuery(el).attr('data-size')
,'tabindex' : jQuery(el).attr('data-tabindex')
,'callback' : jQuery(el).attr('data-callback')
,'expired-callback' : jQuery(el).attr('data-expired-callback')
,'error-callback' : jQuery(el).attr('data-error-callback')
});
});
};
</script>
Eclipse failed to connect to SVN https repositories (should also apply to any app using SSL/TLS).
svn: E175002: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints
The issue was caused by latest Java 8 OpenJDK update that disabled MD5 related algorithms. As a workaround until new certificates are issued (if ever), change the following keys at java.security file
WARNING
Keep in mind that this could have security implications as disabled algorithms are considered weak. As an alternative, the workaround can be applied on a JVM basis by a command line option to use an external java.security file with this changes, e.g.:
java -Djava.security.properties=/etc/sysconfig/noMD5.java.security
For Eclipse, add a line on eclipse.ini below -vmargs
-Djava.security.properties=/etc/sysconfig/noMD5.java.security
jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, DH keySize < 768
java.security file is located in linux 64 at /usr/lib64/jvm/java/jre/lib/security/java.security
Steps (These apply for Linux. For other OS, visit here) -
platform-tools
in android-sdk linux
folder../adb install FileName.apk
For more info can check this link : android videos
@ is used as a prefix denoting stored procedure and function parameter names, and also variable names
for full url use
$('#imageContainerId').prop('src')
for relative image url use
$('#imageContainerId').attr('src')
function showImgUrl(){_x000D_
console.log('for full image url ' + $('#imageId').prop('src') );_x000D_
console.log('for relative image url ' + $('#imageId').attr('src'));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>_x000D_
_x000D_
<input type='button' onclick='showImgUrl()' value='click to see the url of the img' />
_x000D_
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
I believe the best practice should be to go through the official Java JSON API which are still work in progress.
You can use PycURL on Python 2 and 3.
import pycurl
FILE_DEST = 'pycurl.html'
FILE_SRC = 'http://pycurl.io/'
with open(FILE_DEST, 'wb') as f:
c = pycurl.Curl()
c.setopt(c.URL, FILE_SRC)
c.setopt(c.WRITEDATA, f)
c.perform()
c.close()
The correct shorthand is this:
$(function() {
// this behaves as if within document.ready
});
The code you posted…
(function($){
//some code
})(jQuery);
…creates an anonymous function and executes it immediately with jQuery
being passed in as the arg $
. All it effectively does is take the code inside the function and execute it like normal, since $
is already an alias for jQuery
. :D
To explain the difference between these two let me explain the difference between encodeURI
and encodeURIComponent
.
The main difference is that:
encodeURI
function is intended for use on the full URI.encodeURIComponent
function is intended to be used on .. well .. URI components that is
any part that lies between separators (; / ? : @ & = + $ , #).So, in encodeURIComponent
these separators are encoded also because they are regarded as text and not special characters.
Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.
One way or another you must tell boto3 in which region you wish the kms
client to be created. This could be done explicitly using the region_name
parameter as in:
kms = boto3.client('kms', region_name='us-west-2')
or you can have a default region associated with your profile in your ~/.aws/config
file as in:
[default]
region=us-west-2
or you can use an environment variable as in:
export AWS_DEFAULT_REGION=us-west-2
but you do need to tell boto3 which region to use.
If you're going to nest ternary operators, I believe you'd want to do something like this:
var audience = (countrycode == 'eu') ? 'audienceEU' :
(countrycode == 'jp') ? 'audienceJP' :
(countrycode == 'cn') ? 'audienceCN' :
'audienceUS';
It's a lot more efficient to write/read than:
var audience = 'audienceUS';
if countrycode == 'eu' {
audience = 'audienceEU';
} else if countrycode == 'jp' {
audience = 'audienceJP';
} else if countrycode == 'cn' {
audience = 'audienceCN';
}
As with all good programming, whitespace makes everything nice for people who have to read your code after you're done with the project.
If you can use jquery then you can put the alert inside the $(document).ready()
function. it would look something like this:
<script>
$(document).ready(function(){
alert('<%: TempData["Resultat"]%>');
});
</script>
To include jQuery, include the following in the <head>
tag of your code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
Here's a quick example in jsFiddle: http://jsfiddle.net/ChaseWest/3AaAx/
I dislike "Don't" answers, but... don't.
make
's variables are global and are supposed to be evaluated during makefile's "parsing" stage, not during execution stage.
In this case, as long as the variable local to a single target, follow @nobar's answer and make it a shell variable.
Target-specific variables, too, are considered harmful by other make implementations: kati, Mozilla pymake. Because of them, a target can be built differently depending on if it's built standalone, or as a dependency of a parent target with a target-specific variable. And you won't know which way it was, because you don't know what is already built.
You just need to return false from the
function jsFunction() {
try {
// Logic goes here
return false; // true for postback and false for not postback
} catch (e) {
alert(e.message);
return false;
}
}
_x000D_
<asp:button runat="server" id="btnSubmit" OnClientClick="return jsFunction()" />
_x000D_
JavaScript function like below.
Note*: Always use try-catch blocks and return false from catch block to prevent incorrect calculation in javaScript function.
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
Try:
itemsCard.ToList().Select(c=>c.Price).Sum();
Actually this would perform better:
var itemsInCart = from o in db.OrderLineItems
where o.OrderId == currentOrder.OrderId
select new { o.WishListItem.Price };
var sum = itemsCard.ToList().Select(c=>c.Price).Sum();
Because you'll only be retrieving one column from the database.
One usual solution is to wrap your function foo
with a decorator like
result = queue.Queue()
def task_wrapper(*args):
result.put(target(*args))
Then the whole code may looks like that
result = queue.Queue()
def task_wrapper(*args):
result.put(target(*args))
threads = [threading.Thread(target=task_wrapper, args=args) for args in args_list]
for t in threads:
t.start()
while(True):
if(len(threading.enumerate()) < max_num):
break
for t in threads:
t.join()
return result
One important issue is that the return values may be unorderred.
(In fact, the return value
is not necessarily saved to the queue
, since you can choose arbitrary thread-safe data structure )
For this you need to run the "tomcat6w" application that is part of the standard Tomcat distribution in the "bin" directory. E.g. for windows the default is "C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin\tomcat6w.exe". The "tomcat6w" application starts a GUI. If you select the "Java" tab you can enter all Java options.
It is also possible to pass JVM options via the command line to tomcat. For this you need to use the command:
<tomcatexecutable> //US//<tomcatservicename> ++JvmOptions="<JVMoptions>"
where "tomcatexecutable" refers to your tomcat application, "tomcatservicename" is the tomcat service name you are using and "JVMoptions" are your JVM options. For instance:
"tomcat6.exe" //US//tomcat6 ++JvmOptions="-XX:MaxPermSize=128m"
you can apply two commands
git diff --patch > mypatch.patch // to generate the patch
git apply mypatch.patch // to apply the patch
Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest
You could name the select and use this:
$("select[name='theNameYouChose']").find("option[value='theValueYouWantSelected']").attr("selected",true);
It should select the option you want.
Looks like the image is too big and the window simply doesn't fit the screen.
Create window with the cv2.WINDOW_NORMAL
flag, it will make it scalable. Then you can resize it to fit your screen like this:
from __future__ import division
import cv2
img = cv2.imread('1.jpg')
screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)
cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
According to the OpenCV documentation CV_WINDOW_KEEPRATIO
flag should do the same, yet it doesn't and it's value not even presented in the python module.
Google's Guava library has a Primitives utility that check if a class is a wrapper type for a primitive: Primitives.isWrapperType(class)
.
Class.isPrimitive() works for primitives
To trigger an event you basically just call the event handler for that element. Slight change from your code.
var a = document.getElementById("element");
var evnt = a["onclick"];
if (typeof(evnt) == "function") {
evnt.call(a);
}
I suggest you use Promise
myApp.service('dataService', function($http,$q) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
deferred = $q.defer();
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, we can resolve promise and we can access it in controller
deferred.resolve();
}).error(function(){
alert("error");
//let the function caller know the error
deferred.reject(error);
});
return deferred.promise;
}
});
so In your controller you can use the method
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.
In concerns make file filename.rb
For example I want in my application where attribute create_by exist update there value by 1, and 0 for updated_by
module TestConcern
extend ActiveSupport::Concern
def checkattributes
if self.has_attribute?(:created_by)
self.update_attributes(created_by: 1)
end
if self.has_attribute?(:updated_by)
self.update_attributes(updated_by: 0)
end
end
end
If you want to pass arguments in action
included do
before_action only: [:create] do
blaablaa(options)
end
end
after that include in your model like this:
class Role < ActiveRecord::Base
include TestConcern
end
I solved the same problem by adding text-indent to the nested list.
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea
<ul id="list2">
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
#list2
{
text-indent:50px;
}
Add a reference to System.Web.dll and then you can use the System.Web.HtmlUtility class
Combining two of the previous results, we have:
int(round(some_float))
This converts a float to an integer fairly dependably.
If you remove the href
attribute the anchor will be not focusable and it will look like simple text, but it will still be clickable.
Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository
in your settings.xml
or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.
A workaround is as follows. In the value:
releases::default::https://YOUR_NEXUS_URL/releases
you need to remove the default
section, making it:
releases::https://YOUR_NEXUS_URL/releases
The prior version 2.8.2 does not have this bug.
When you send parameters by x-www-form-urlencoded
then you need to set header for the request as using Content-Type
as application/x-www-form-urlencoded
You can achieve this with just CSS and your down arrow as an image positioned absolute with a "pointer-events: none;" see my example below:
<select>
<option value="1">1 Person</option>
<option value="2">2 People</option>
</select>
<img class="passthrough" src="downarrow.png" />
.passthrough {
pointer-events: none;
position: absolute;
right: 0;
}
There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>
StringUtils is a utility class from Apache commons-lang (many libraries have it but this is the most common library). You need to download the jar and add it to your applications classpath.
my way to reset all submodules (WITHOUT detaching & keeping their "master" branch):
git submodule foreach 'git checkout master && git reset --hard $sha1'
Both are valid but I normally choose interfaces. A class (abstract or not) is not needed if there is no implementations.
As an advise, try to choose the location of your constants wisely, they are part of your external contract. Do not put every single constant in one file.
For example, if a group of constants is only used in one class or one method put them in that class, the extended class or the implemented interfaces. If you do not take care you could end up with a big dependency mess.
Sometimes an enumeration is a good alternative to constants (Java 5), take look at: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html
Use array_unshift($array, $item);
$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);
will give you
Array
(
[0] => item1
[1] => item2
[2] => item3
[3] => item4
)
@Shoban It looks like the question is tagged c# so here is the appropriate snipped http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx
public MyClass()
{
// Create a new DateTimePicker
DateTimePicker dateTimePicker1 = new DateTimePicker();
Controls.Add(dateTimePicker1);
MessageBox.Show(dateTimePicker1.Value.ToString());
dateTimePicker1.Value = DateTime.Now.AddDays(1);
MessageBox.Show(dateTimePicker1.Value.ToString());
}
SELECT SUBSTRING(ParentBGBU,0,CHARINDEX('-',ParentBGBU,0)) FROM dbo.tblHCMMaster;
Solution:
Use the Search all shortcut: Ctrl+Shift+F, then select the folder in the "Where:" box below. (And for Mac, it's ?+Shift+F).
If the root directory for the project is proj, with subdirectories src and aux and you want to search in all subfolders, use the proj folder. To restrict the search to only the src folder, use proj/src in the "Where: " box.
let dateString = '13-02-2021' //date string in dd-mm-yyyy format
let dateArray = dateString.split("-");
//dateArray[2] equals to 2021
//dateArray[1] equals to 02
//dateArray[0] equals to 13
// using template literals below
let dateObj = new Date(`${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`);
// dateObj equals to Sat Feb 13 2021 05:30:00 GMT+0530 (India Standard Time)
//I'm from India so its showing GMT+0530
_x000D_
If you mean with "Web Service" something accessed by other Programms SimpleXMLRPCServer might be right for you. It is included with every Python install since Version 2.2.
For Simple human accessible things I usually use Pythons SimpleHTTPServer which also comes with every install. Obviously you also could access SimpleHTTPServer by client programs.
The two answers are good. And I also suggest you a similar method:
<% @images.each.with_index do |page, index| %>
<% end %>
You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index
see how it's .each
and then .with_index
.
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
Well the above answers have give a good explanations to half of the question. For the other half.
Why don't just hide the scroll bar itself. This way it will look more appealing as most of the people ( including me ) hate the scroll bar. You can use this code
::-webkit-scrollbar {
width: 0px; /* Remove scrollbar space */
background: transparent; /* Optional: just make scrollbar invisible */
}
You're essentially running out of memory to run the process smoothly. Options that come to mind:
-Xmx512m
firstHashMap
objects to process at once if possibleString.intern()
on them before putting them into the HashMap
HashMap(int initialCapacity, float loadFactor)
constructor to tune for your casetry below code:
>>> d2 = dict([('one',1), ('two', 2), ('three', 3)])
>>> d2
{'three': 3, 'two': 2, 'one': 1}