You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.
The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String path = file.getAbsolutePath().toLowerCase();
for (int i = 0, n = extensions.length; i < n; i++) {
String extension = extensions[i];
if ((path.endsWith(extension) && (path.charAt(path.length()
- extension.length() - 1)) == '.')) {
return true;
}
}
}
return false;
}
Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.
I often use a blank label as the TargetControlID. ex. <asp:Label ID="lblghost" runat="server" Text="" />
I've seen two things that cause the click event not fire:
1. you have to remove the OKControlID (as others have mentioned)
2. If you are using field validators you should add CausesValidation="false" on the button.
Both scenarios behaved the same way for me.
dtype('O')
inside dataframe this means Pandas string.What is dtype
?
Something that belongs to pandas
or numpy
, or both, or something else? If we examine pandas code:
df = pd.DataFrame({'float': [1.0],
'int': [1],
'datetime': [pd.Timestamp('20180310')],
'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype
It will output like this:
float int datetime string
0 1.0 1 2018-03-10 foo
---
float64 int64 datetime64[ns] object
---
dtype('O')
You can interpret the last as Pandas dtype('O')
or Pandas object which is Python type string, and this corresponds to Numpy string_
, or unicode_
types.
Pandas dtype Python type NumPy type Usage
object str string_, unicode_ Text
Like Don Quixote is on ass, Pandas is on Numpy and Numpy understand the underlying architecture of your system and uses the class numpy.dtype
for that.
Data type object is an instance of numpy.dtype
class that understand the data type more precise including:
In the context of this question dtype
belongs to both pands and numpy and in particular dtype('O')
means we expect the string.
Here is some code for testing with explanation: If we have the dataset as dictionary
import pandas as pd
import numpy as np
from pandas import Timestamp
data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe
print(df)
print(df.dtypes)
The last lines will examine the dataframe and note the output:
id date role num fnum
0 1 2018-12-12 Support 123 3.14
1 2 2018-12-12 Marketing 234 2.14
2 3 2018-12-12 Business Development 345 -0.14
3 4 2018-12-12 Sales 456 41.30
4 5 2018-12-12 Engineering 567 3.14
id int64
date datetime64[ns]
role object
num int64
fnum float64
dtype: object
All kind of different dtypes
df.iloc[1,:] = np.nan
df.iloc[2,:] = None
But if we try to set np.nan
or None
this will not affect the original column dtype. The output will be like this:
print(df)
print(df.dtypes)
id date role num fnum
0 1.0 2018-12-12 Support 123.0 3.14
1 NaN NaT NaN NaN NaN
2 NaN NaT None NaN NaN
3 4.0 2018-12-12 Sales 456.0 41.30
4 5.0 2018-12-12 Engineering 567.0 3.14
id float64
date datetime64[ns]
role object
num float64
fnum float64
dtype: object
So np.nan
or None
will not change the columns dtype
, unless we set the all column rows to np.nan
or None
. In that case column will become float64
or object
respectively.
You may try also setting single rows:
df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object
And to note here, if we set string inside a non string column it will become string or object dtype
.
I found this to be a more elegant solution, without flex:
.wrapper {
overflow: hidden;
}
.wrapper img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* height: 100%; */ /* optional */
}
If the string should be of fixed length, then substr
from base R
can be used. But, we can get the position of the .
with regexpr
and use that in substr
substr(a, 1, regexpr("\\.", a)-1)
#[1] "NM_020506" "NM_020519" "NM_001030297" "NM_010281" "NM_011419" "NM_053155"
Mongoose 4.4.0 introduces --true-- bulk insert with the model method .insertMany()
. It is way faster than looping on .create()
or providing it with an array.
Usage:
var rawDocuments = [/* ... */];
Book.insertMany(rawDocuments)
.then(function(mongooseDocuments) {
/* ... */
})
.catch(function(err) {
/* Error handling */
});
Or
Book.insertMany(rawDocuments, function (err, mongooseDocuments) { /* Your callback function... */ });
You can track it on:
For iOS 10 beta 7, add the following link on the command line:
sudo ln -s /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0\ \(14A5339a\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
Given that the accepted answer is outdated and I see nothing in the other answers regarding this I am creating a new one. In .Net 2, and earlier, you had to manually close the stream before closing the connection. That bug is fixed in all later versions of TcpClient
in C# and as stated in the doc of the Close method a call to the method Close
closes both the connection and the stream
EDIT according to Microsoft Docs
The Close method marks the instance as disposed and requests that the associated Socket close the TCP connection. Based on the LingerState property, the TCP connection may stay open for some time after the Close method is called when data remains to be sent. There is no notification provided when the underlying connection has completed closing.
Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created.
One place where it's useful is for UI activities, like setting a spinner before a lengthy operation:
- (void) handleDoSomethingButton{
[mySpinner startAnimating];
(do something lengthy)
[mySpinner stopAnimating];
}
will not work, because you are blocking the main thread during your lengthy thing and not letting UIKit actually start the spinner.
- (void) handleDoSomethingButton{
[mySpinner startAnimating];
dispatch_async (dispatch_get_main_queue(), ^{
(do something lengthy)
[mySpinner stopAnimating];
});
}
will return control to the run loop, which will schedule UI updating, starting the spinner, then will get the next thing off the dispatch queue, which is your actual processing. When your processing is done, the animation stop is called, and you return to the run loop, where the UI then gets updated with the stop.
You can try to hide characters using html entities in hexa (ex: @ for @). This is convenient solution, as a correct browser will translate it, and you can have a normal link. The drawback is that a bot can translate it theorically, but it's a bit unusual. I use this to protect my e-mail on my blog.
Another solution is to use javascript to assemble part of the address and to decode on-the-fly the address. The drawback is that a javascript-disabled browser won't show your adress.
The most effective solution is to use an image, but it's a pain for the user to have to copy the address by hand.
Your solution is pretty good, as you only add a drawback (writing manually the @) only for user that have javascript disabled. You can also be more secure with :
onclick="this.href='mailto:' + 'admin' + '@' + 'domain.com'"
Use actionListener
if you want have a hook before the real business action get executed, e.g. to log it, and/or to set an additional property (by <f:setPropertyActionListener>
), and/or to have access to the component which invoked the action (which is available by ActionEvent
argument). So, purely for preparing purposes before the real business action gets invoked.
The actionListener
method has by default the following signature:
import javax.faces.event.ActionEvent;
// ...
public void actionListener(ActionEvent event) {
// ...
}
And it's supposed to be declared as follows, without any method parentheses:
<h:commandXxx ... actionListener="#{bean.actionListener}" />
Note that you can't pass additional arguments by EL 2.2. You can however override the ActionEvent
argument altogether by passing and specifying custom argument(s). The following examples are valid:
<h:commandXxx ... actionListener="#{bean.methodWithoutArguments()}" />
<h:commandXxx ... actionListener="#{bean.methodWithOneArgument(arg1)}" />
<h:commandXxx ... actionListener="#{bean.methodWithTwoArguments(arg1, arg2)}" />
public void methodWithoutArguments() {}
public void methodWithOneArgument(Object arg1) {}
public void methodWithTwoArguments(Object arg1, Object arg2) {}
Note the importance of the parentheses in the argumentless method expression. If they were absent, JSF would still expect a method with ActionEvent
argument.
If you're on EL 2.2+, then you can declare multiple action listener methods via <f:actionListener binding>
.
<h:commandXxx ... actionListener="#{bean.actionListener1}">
<f:actionListener binding="#{bean.actionListener2()}" />
<f:actionListener binding="#{bean.actionListener3()}" />
</h:commandXxx>
public void actionListener1(ActionEvent event) {}
public void actionListener2() {}
public void actionListener3() {}
Note the importance of the parentheses in the binding
attribute. If they were absent, EL would confusingly throw a javax.el.PropertyNotFoundException: Property 'actionListener1' not found on type com.example.Bean
, because the binding
attribute is by default interpreted as a value expression, not as a method expression. Adding EL 2.2+ style parentheses transparently turns a value expression into a method expression. See also a.o. Why am I able to bind <f:actionListener> to an arbitrary method if it's not supported by JSF?
Use action
if you want to execute a business action and if necessary handle navigation. The action
method can (thus, not must) return a String
which will be used as navigation case outcome (the target view). A return value of null
or void
will let it return to the same page and keep the current view scope alive. A return value of an empty string or the same view ID will also return to the same page, but recreate the view scope and thus destroy any currently active view scoped beans and, if applicable, recreate them.
The action
method can be any valid MethodExpression
, also the ones which uses EL 2.2 arguments such as below:
<h:commandXxx value="submit" action="#{bean.edit(item)}" />
With this method:
public void edit(Item item) {
// ...
}
Note that when your action method solely returns a string, then you can also just specify exactly that string in the action
attribute. Thus, this is totally clumsy:
<h:commandLink value="Go to next page" action="#{bean.goToNextpage}" />
With this senseless method returning a hardcoded string:
public String goToNextpage() {
return "nextpage";
}
Instead, just put that hardcoded string directly in the attribute:
<h:commandLink value="Go to next page" action="nextpage" />
Please note that this in turn indicates a bad design: navigating by POST. This is not user nor SEO friendly. This all is explained in When should I use h:outputLink instead of h:commandLink? and is supposed to be solved as
<h:link value="Go to next page" outcome="nextpage" />
See also How to navigate in JSF? How to make URL reflect current page (and not previous one).
Since JSF 2.x there's a third way, the <f:ajax listener>
.
<h:commandXxx ...>
<f:ajax listener="#{bean.ajaxListener}" />
</h:commandXxx>
The ajaxListener
method has by default the following signature:
import javax.faces.event.AjaxBehaviorEvent;
// ...
public void ajaxListener(AjaxBehaviorEvent event) {
// ...
}
In Mojarra, the AjaxBehaviorEvent
argument is optional, below works as good.
public void ajaxListener() {
// ...
}
But in MyFaces, it would throw a MethodNotFoundException
. Below works in both JSF implementations when you want to omit the argument.
<h:commandXxx ...>
<f:ajax execute="@form" listener="#{bean.ajaxListener()}" render="@form" />
</h:commandXxx>
Ajax listeners are not really useful on command components. They are more useful on input and select components <h:inputXxx>
/<h:selectXxx>
. In command components, just stick to action
and/or actionListener
for clarity and better self-documenting code. Moreover, like actionListener
, the f:ajax listener
does not support returning a navigation outcome.
<h:commandXxx ... action="#{bean.action}">
<f:ajax execute="@form" render="@form" />
</h:commandXxx>
For explanation on execute
and render
attributes, head to Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
The actionListener
s are always invoked before the action
in the same order as they are been declared in the view and attached to the component. The f:ajax listener
is always invoked before any action listener. So, the following example:
<h:commandButton value="submit" actionListener="#{bean.actionListener}" action="#{bean.action}">
<f:actionListener type="com.example.ActionListenerType" />
<f:actionListener binding="#{bean.actionListenerBinding()}" />
<f:setPropertyActionListener target="#{bean.property}" value="some" />
<f:ajax listener="#{bean.ajaxListener}" />
</h:commandButton>
Will invoke the methods in the following order:
Bean#ajaxListener()
Bean#actionListener()
ActionListenerType#processAction()
Bean#actionListenerBinding()
Bean#setProperty()
Bean#action()
The actionListener
supports a special exception: AbortProcessingException
. If this exception is thrown from an actionListener
method, then JSF will skip any remaining action listeners and the action method and proceed to render response directly. You won't see an error/exception page, JSF will however log it. This will also implicitly be done whenever any other exception is being thrown from an actionListener
. So, if you intend to block the page by an error page as result of a business exception, then you should definitely be performing the job in the action
method.
If the sole reason to use an actionListener
is to have a void
method returning to the same page, then that's a bad one. The action
methods can perfectly also return void
, on the contrary to what some IDEs let you believe via EL validation. Note that the PrimeFaces showcase examples are littered with this kind of actionListener
s over all place. This is indeed wrong. Don't use this as an excuse to also do that yourself.
In ajax requests, however, a special exception handler is needed. This is regardless of whether you use listener
attribute of <f:ajax>
or not. For explanation and an example, head to Exception handling in JSF ajax requests.
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
I wrote a module win-node-env with which you can run your command just like you would in *nix.
NODE_ENV=production node myapp/app.js
It works by creating a NODE_ENV.cmd
that sets the NODE_ENV
environment variable and spawns a child process with the rest of the command and its args.
Just install it (globally), and run your npm script commands, it should automatically make them work.
npm install -g win-node-env
select to_char(sysdate, 'DD-fmMONTH-YYYY') "Date" from Dual;
The above query result will be as given below.
01-APRIL-2019
One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment
) in the manifest file (manifest.mf
) defined. For example:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
org.jdom;bundle-version="1.0.0",
org.apache.commons.codec;bundle-version="1.3.0",
bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...
In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.
Can also see here on how to turn on MSDTC from the Control Panel's services.msc.
On the server where the trigger resides, you need to turn the MSDTC service on. You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.
This worked for me:
Remove-Item $folderPath -Force -Recurse -ErrorAction SilentlyContinue
Thus the folder is removed with all files in there and it is not producing error if folder path doesn't exists.
You can try this from the console:
adb logcat --buffer=crash
More info on this option:
adb logcat --help
...
-b <buffer>, --buffer=<buffer> Request alternate ring buffer, 'main',
'system', 'radio', 'events', 'crash', 'default' or 'all'.
Multiple -b parameters or comma separated list of buffers are
allowed. Buffers interleaved. Default -b main,system,crash.
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked
property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
I don't believe there's currently any way to do this. The Razor engine does not parse Javascript files, only Razor views. However, you can accomplish what you want by setting the variables inside your Razor view:
<script>
var someStringValue = '@(ViewBag.someStringValue)';
var someNumericValue = @(ViewBag.someNumericValue);
</script>
<!-- "someStringValue" and "someNumericValue" will be available in script -->
<script src="js/myscript.js"></script>
As Joe points out in the comments, the string value above will break if there's a single quote in it. If you want to make this completely iron-clad, you'll have to replace all single quotes with escaped single quotes. The problem there is that all of the sudden slashes become an issue. For example, if your string is "foo \' bar
", and you replace the single quote, what will come out is "foo \\' bar
", and you're right back to the same problem. (This is the age old difficulty of chained encoding.) The best way to handle this is to treat backslashes and quotes as special and make sure they're all escaped:
@{
var safeStringValue = ViewBag.someStringValue
.Replace("\\", "\\\\")
.Replace("'", "\\'");
}
var someStringValue = '@(safeStringValue)';
A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.
You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.
If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.
String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());
Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join -
A left outer join will give all rows in A, plus any common rows in B.
Full outer join -
A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.
check this
I was having the same problem today.. and has been searching for answers.. I am on Ubuntu... however, I could not find the correct one that works on this thread.. after much research the following worked for me finally!! :)
First, after running
mongod dbpath
if appeared that mongodb was looking for the data/db directory.. which was missing in my installed mongodb app.. so I ran the following commands:
$ sudo mkdir -p /data/db
then run,
$ sudo chown -R $USER /data/db
chown - changes ownership of files/dirs. Ie. owner of the file/dir changes to the specified one, but it doesn't modify permissions. As detailed here: https://unix.stackexchange.com/questions/402062/how-are-chown-and-chmod-command-different-in-the-given-operation
Finally, run
`$ sudo systemctl enable mongod.service
It will give a message: Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service ? /lib/systemd/system/mongod.service and started the service.
To take first 5 elements better use expression like this one:
var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5);
or
var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5).OrderBy([ORDER EXPR]);
It will be faster than orderBy variant, because LINQ engine will not scan trough all list due to delayed execution, and will not sort all array.
class MyList : IEnumerable<int>
{
int maxCount = 0;
public int RequestCount
{
get;
private set;
}
public MyList(int maxCount)
{
this.maxCount = maxCount;
}
public void Reset()
{
RequestCount = 0;
}
#region IEnumerable<int> Members
public IEnumerator<int> GetEnumerator()
{
int i = 0;
while (i < maxCount)
{
RequestCount++;
yield return i++;
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
class Program
{
static void Main(string[] args)
{
var list = new MyList(15);
list.Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 5;
list.Reset();
list.OrderBy(q => q).Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 15;
list.Reset();
list.Where(q => (q & 1) == 0).Take(5).ToArray();
Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
list.Reset();
list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray();
Console.WriteLine(list.RequestCount); // 9; (first 5 odd)
}
}
Some of the comments mention this as well, but asp net core does all this work for you.
If you have a query string that matches the name it will be available in the controller.
https://myapi/some-endpoint/123?someQueryString=YayThisWorks
[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
{
Debug.WriteLine(someValue);
Debug.WriteLine(someQueryString);
return Ok();
}
Ouputs:
123
YayThisWorks
You basically have two choices:
1.Require an instance:
public Navigation(T t) { this("", "", t); }
2.Require a class instance:
public Navigation(Class<T> c) { this("", "", c.newInstance()); }
You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.
Use: Arrays.copyOf(yourArray,n);
With plt.scatter
, I can only think of one: to use a proxy artist:
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ccm=x.get_cmap()
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)]
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1)
And the result is:
Stack-based solution.
public static string Reverse(string text)
{
var stack = new Stack<char>(text);
var array = new char[stack.Count];
int i = 0;
while (stack.Count != 0)
{
array[i++] = stack.Pop();
}
return new string(array);
}
Or
public static string Reverse(string text)
{
var stack = new Stack<char>(text);
return string.Join("", stack);
}
In case you're using git, use the right email address you used for github registration and then your computer name. this worked for me.
Python version >= 2.7, do the below:
d = {i: True for i in [1,2,3]}
Python version < 2.7(RIP, 3 July 2010 - 31 December 2019), do the below:
d = dict((i,True) for i in [1,2,3])
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {_x000D_
var checked = false;_x000D_
if (document.querySelector('#opt1:checked')) {_x000D_
checked = true;_x000D_
}_x000D_
document.getElementById('msg').innerText = checked;_x000D_
}
_x000D_
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
_x000D_
Use ECMA2015. Arrow functions make "this" a lot more intuitive.
import React from 'react';
class TestApp extends React.Component {
getComponent(e, index) {
$(e.target).css({
'background-color': '#ccc'
});
}
render() {
return (
<div>
<ul>
<li onClick={(e) => this.getComponent(e, 1)}>Component 1</li>
<li onClick={(e) => this.getComponent(e, 2)}>Component 2</li>
<li onClick={(e) => this.getComponent(e, 3)}>Component 3</li>
</ul>
</div>
);
}
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));`
You can try the following:
gitk --all
You can tell gitk
what to display using anything that git rev-list
understands, so if you just want a few branches, you can do:
gitk master origin/master origin/experiment
... or more exotic things like:
gitk --simplify-by-decoration --all
ChronoUnit.between
Use instances of ChronoUnit
to calculate amount of time in different units (days,months, seconds).
For Example:
ChronoUnit.DAYS.between(startDate,endDate)
Some of the other answers here are about adding HTML5 capabilities to IE8 and other browsers. These are called Polyfills and my favourite place for finding those is here.
You can add property to your model as follows:
public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }
and then your view will be simpler and will contain no logic at all:
<div class="details @Model.DetailsClass"/>
This will work even with many classes and will not render class if it is null:
<div class="@Model.Class1 @Model.Class2"/>
with 2 not null properties will render:
<div class="class1 class2"/>
if class1 is null
<div class=" class2"/>
import re
s = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/'''
g = re.findall(r'(text\d+)',s)
print ('list',g)
for i in g:
print (i)
Out
list ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
text1
text2
text3
text4
text5
text6 ?
This solution is deprecated
failure|fail|error() is deprecated and will be removed in 2.1, please use promise-style instead.
so you have to use
Project.update(
// Set Attribute values
{
title: 'a very different title now'
},
// Where clause / criteria
{
_id: 1
}
).then(function() {
console.log("Project with id =1 updated successfully!");
}).catch(function(e) {
console.log("Project update failed !");
})
And you can use
.complete()
as well
Regards
As FLAG_FULLSCREEN is deprecated from android R. You can use below code to hide status bar.
@Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}
The correct way to set the column width is by using the line as posted by Jahmic, however it is important to note that additionally, you have to apply styling after adding the data, and not before, otherwise on some configurations, the column width is not applied
Replace [^a-zA-Z0-9 -]
with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.
In the Java context, we first need to make a distinction between "copying a value" and "copying an object".
int a = 1;
int b = a; // copying a value
int[] s = new int[]{42};
int[] t = s; // copying a value (the object reference for the array above)
StringBuffer sb = new StringBuffer("Hi mom");
// copying an object.
StringBuffer sb2 = new StringBuffer(sb);
In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new
, either explicitly or under the hood.
Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:
public class Example {
public int foo;
public int[] bar;
public Example() { };
public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}
Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ...
The normal interpretation is that a "shallow" copy of eg1
would be a new Example
object whose foo
equals 1 and whose bar
field refers to the same array as in the original; e.g.
Example eg2 = new Example(eg1.foo, eg1.bar);
The normal interpretation of a "deep" copy of eg1
would be a new Example
object whose foo
equals 1 and whose bar
field refers to a copy of the original array; e.g.
Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));
(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)
Two more questions / areas of uncertainty exist:
How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?
What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?
Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:
The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).
In fact, the specification does not even specifically state that clone produces a new object.
Here's what the javadoc says:
"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression
x.clone() != x
will be true, and that the expressionx.clone().getClass() == x.getClass()
will be true, but these are not absolute requirements. While it is typically the case thatx.clone().equals(x)
will be true, this is not an absolute requirement."
Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.
In short, clone potentially means something different for every Java class.
Some people argue (as @supercat does in comments) that the Java clone()
method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.
To create sets you can use a varargs factory method instead of double-brace initialisation:
public static Set<T> setOf(T ... elements) {
return new HashSet<T>(Arrays.asList(elements));
}
The Google Collections library has lots of convenience methods like this, as well as loads of other useful functionality.
As for the idiom's obscurity, I encounter it and use it in production code all the time. I'd be more concerned about programmers who get confused by the idiom being allowed to write production code.
It's probably because you are directly or indirectly through a library call accessing a NULL pointer. In this particular case, it looks like you've jumped to a NULL address, which is a b bit hairier.
In my experience, the easiest way to track these down are to run it with a debugger, and dump a stack trace.
Alternatively, you can do it "by hand" and add lots of logging until you can track down exactly which function (and possibly LOC) this violation occurred in.
Take a look at Stack Tracer, which might help you improve your debugging.
You are not interested in a lot of "solutions" to your problem. I do not think there really is a good way to do what you want to do. Anything you insert using :after
and content
has exactly the same syntactic and semantic validity it would have done if you had just written it in there yourself.
The tools CSS provide work. You should just float the li
s and then clear: left
when you want to start a new line, as you have mentioned:
See an example: http://jsfiddle.net/marcuswhybrow/YMN7U/5/
As seen here,
$ git remote rm origin
$ git remote add origin [email protected]:aplikacjainfo/proj1.git
$ git config master.remote origin
$ git config master.merge refs/heads/master
An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ?
to any type:
var name: String? = "Bertie"
Optionals (along with Generics) are one of the most difficult Swift concepts to understand. Because of how they are written and used, it's easy to get a wrong idea of what they are. Compare the optional above to creating a normal String:
var name: String = "Bertie" // No "?" after String
From the syntax it looks like an optional String is very similar to an ordinary String. It's not. An optional String is not a String with some "optional" setting turned on. It's not a special variety of String. A String and an optional String are completely different types.
Here's the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int. Think of an optional as a kind of parcel. Before you open it (or "unwrap" in the language of optionals) you won't know if it contains something or nothing.
You can see how optionals are implemented in the Swift Standard Library by typing "Optional" into any Swift file and ?-clicking on it. Here's the important part of the definition:
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
Optional is just an enum
which can be one of two cases: .none
or .some
. If it's .some
, there's an associated value which, in the example above, would be the String
"Hello". An optional uses Generics to give a type to the associated value. The type of an optional String isn't String
, it's Optional
, or more precisely Optional<String>
.
Everything Swift does with optionals is magic to make reading and writing code more fluent. Unfortunately this obscures the way it actually works. I'll go through some of the tricks later.
Note: I'll be talking about optional variables a lot, but it's fine to create optional constants too. I mark all variables with their type to make it easier to understand type types being created, but you don't have to in your own code.
To create an optional, append a ?
after the type you wish to wrap. Any type can be optional, even your own custom types. You can't have a space between the type and the ?
.
var name: String? = "Bob" // Create an optional String that contains "Bob"
var peter: Person? = Person() // An optional "Person" (custom type)
// A class with a String and an optional String property
class Car {
var modelName: String // must exist
var internalName: String? // may or may not exist
}
You can compare an optional to nil
to see if it has a value:
var name: String? = "Bob"
name = nil // Set name to nil, the absence of a value
if name != nil {
print("There is a name")
}
if name == nil { // Could also use an "else"
print("Name has no value")
}
This is a little confusing. It implies that an optional is either one thing or another. It's either nil or it's "Bob". This is not true, the optional doesn't transform into something else. Comparing it to nil is a trick to make easier-to-read code. If an optional equals nil, this just means that the enum is currently set to .none
.
If you try to set a non-optional variable to nil, you'll get an error.
var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'
Another way of looking at optionals is as a complement to normal Swift variables. They are a counterpart to a variable which is guaranteed to have a value. Swift is a careful language that hates ambiguity. Most variables are define as non-optionals, but sometimes this isn't possible. For example, imagine a view controller which loads an image either from a cache or from the network. It may or may not have that image at the time the view controller is created. There's no way to guarantee the value for the image variable. In this case you would have to make it optional. It starts as nil
and when the image is retrieved, the optional gets a value.
Using an optional reveals the programmers intent. Compared to Objective-C, where any object could be nil, Swift needs you to be clear about when a value can be missing and when it's guaranteed to exist.
An optional String
cannot be used in place of an actual String
. To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a !
after the optional name. This is called "force unwrapping". It returns the value inside the optional (as the original type) but if the optional is nil
, it causes a runtime crash. Before unwrapping you should be sure there's a value.
var name: String? = "Bob"
let unwrappedName: String = name!
print("Unwrapped name: \(unwrappedName)")
name = nil
let nilName: String = name! // Runtime crash. Unexpected nil.
Because you should always check for nil before unwrapping and using an optional, this is a common pattern:
var mealPreference: String? = "Vegetarian"
if mealPreference != nil {
let unwrappedMealPreference: String = mealPreference!
print("Meal: \(unwrappedMealPreference)") // or do something useful
}
In this pattern you check that a value is present, then when you are sure it is, you force unwrap it into a temporary constant to use. Because this is such a common thing to do, Swift offers a shortcut using "if let". This is called "optional binding".
var mealPreference: String? = "Vegetarian"
if let unwrappedMealPreference: String = mealPreference {
print("Meal: \(unwrappedMealPreference)")
}
This creates a temporary constant (or variable if you replace let
with var
) whose scope is only within the if's braces. Because having to use a name like "unwrappedMealPreference" or "realMealPreference" is a burden, Swift allows you to reuse the original variable name, creating a temporary one within the bracket scope
var mealPreference: String? = "Vegetarian"
if let mealPreference: String = mealPreference {
print("Meal: \(mealPreference)") // separate from the other mealPreference
}
Here's some code to demonstrate that a different variable is used:
var mealPreference: String? = "Vegetarian"
if var mealPreference: String = mealPreference {
print("Meal: \(mealPreference)") // mealPreference is a String, not a String?
mealPreference = "Beef" // No effect on original
}
// This is the original mealPreference
print("Meal: \(mealPreference)") // Prints "Meal: Optional("Vegetarian")"
Optional binding works by checking to see if the optional equals nil. If it doesn't, it unwraps the optional into the provided constant and executes the block. In Xcode 8.3 and later (Swift 3.1), trying to print an optional like this will cause a useless warning. Use the optional's debugDescription
to silence it:
print("\(mealPreference.debugDescription)")
Optionals have two use cases:
Some concrete examples:
middleName
or spouse
in a Person
classweak
properties in classes. The thing they point to can be set to nil
at any timeBoolean
Optionals don't exist in Objective-C but there is an equivalent concept, returning nil. Methods that can return an object can return nil instead. This is taken to mean "the absence of a valid object" and is often used to say that something went wrong. It only works with Objective-C objects, not with primitives or basic C-types (enums, structs). Objective-C often had specialized types to represent the absence of these values (NSNotFound
which is really NSIntegerMax
, kCLLocationCoordinate2DInvalid
to represent an invalid coordinate, -1
or some negative value are also used). The coder has to know about these special values so they must be documented and learned for each case. If a method can't take nil
as a parameter, this has to be documented. In Objective-C, nil
was a pointer just as all objects were defined as pointers, but nil
pointed to a specific (zero) address. In Swift, nil
is a literal which means the absence of a certain type.
nil
You used to be able to use any optional as a Boolean
:
let leatherTrim: CarExtras? = nil
if leatherTrim {
price = price + 1000
}
In more recent versions of Swift you have to use leatherTrim != nil
. Why is this? The problem is that a Boolean
can be wrapped in an optional. If you have Boolean
like this:
var ambiguous: Boolean? = false
it has two kinds of "false", one where there is no value and one where it has a value but the value is false
. Swift hates ambiguity so now you must always check an optional against nil
.
You might wonder what the point of an optional Boolean
is? As with other optionals the .none
state could indicate that the value is as-yet unknown. There might be something on the other end of a network call which takes some time to poll. Optional Booleans are also called "Three-Value Booleans"
Swift uses some tricks to allow optionals to work. Consider these three lines of ordinary looking optional code;
var religiousAffiliation: String? = "Rastafarian"
religiousAffiliation = nil
if religiousAffiliation != nil { ... }
None of these lines should compile.
String
the types are differentI'll go through some of the implementation details of optionals that allow these lines to work.
Using ?
to create an optional is syntactic sugar, enabled by the Swift compiler. If you want to do it the long way, you can create an optional like this:
var name: Optional<String> = Optional("Bob")
This calls Optional
's first initializer, public init(_ some: Wrapped)
, which infers the optional's associated type from the type used within the parentheses.
The even longer way of creating and setting an optional:
var serialNumber:String? = Optional.none
serialNumber = Optional.some("1234")
print("\(serialNumber.debugDescription)")
nil
You can create an optional with no initial value, or create one with the initial value of nil
(both have the same outcome).
var name: String?
var name: String? = nil
Allowing optionals to equal nil
is enabled by the protocol ExpressibleByNilLiteral
(previously named NilLiteralConvertible
). The optional is created with Optional
's second initializer, public init(nilLiteral: ())
. The docs say that you shouldn't use ExpressibleByNilLiteral
for anything except optionals, since that would change the meaning of nil in your code, but it's possible to do it:
class Clint: ExpressibleByNilLiteral {
var name: String?
required init(nilLiteral: ()) {
name = "The Man with No Name"
}
}
let clint: Clint = nil // Would normally give an error
print("\(clint.name)")
The same protocol allows you to set an already-created optional to nil
. Although it's not recommended, you can use the nil literal initializer directly:
var name: Optional<String> = Optional(nilLiteral: ())
nil
Optionals define two special "==" and "!=" operators, which you can see in the Optional
definition. The first ==
allows you to check if any optional is equal to nil. Two different optionals which are set to .none will always be equal if the associated types are the same. When you compare to nil, behind the scenes Swift creates an optional of the same associated type, set to .none then uses that for the comparison.
// How Swift actually compares to nil
var tuxedoRequired: String? = nil
let temp: Optional<String> = Optional.none
if tuxedoRequired == temp { // equivalent to if tuxedoRequired == nil
print("tuxedoRequired is nil")
}
The second ==
operator allows you to compare two optionals. Both have to be the same type and that type needs to conform to Equatable
(the protocol which allows comparing things with the regular "==" operator). Swift (presumably) unwraps the two values and compares them directly. It also handles the case where one or both of the optionals are .none
. Note the distinction between comparing to the nil
literal.
Furthermore, it allows you to compare any Equatable
type to an optional wrapping that type:
let numberToFind: Int = 23
let numberFromString: Int? = Int("23") // Optional(23)
if numberToFind == numberFromString {
print("It's a match!") // Prints "It's a match!"
}
Behind the scenes, Swift wraps the non-optional as an optional before the comparison. It works with literals too (if 23 == numberFromString {
)
I said there are two ==
operators, but there's actually a third which allow you to put nil
on the left-hand side of the comparison
if nil == name { ... }
There is no Swift convention for naming optional types differently from non-optional types. People avoid adding something to the name to show that it's an optional (like "optionalMiddleName", or "possibleNumberAsString") and let the declaration show that it's an optional type. This gets difficult when you want to name something to hold the value from an optional. The name "middleName" implies that it's a String type, so when you extract the String value from it, you can often end up with names like "actualMiddleName" or "unwrappedMiddleName" or "realMiddleName". Use optional binding and reuse the variable name to get around this.
From "The Basics" in the Swift Programming Language:
Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.
Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.
To finish, here's a poem from 1899 about optionals:
Yesterday upon the stair
I met a man who wasn’t there
He wasn’t there again today
I wish, I wish he’d go away
Antigonish
i solved the query this way
SELECT
ca.ID, ca.[Name]
FROM [Emp2]
CROSS APPLY (
Values
('ID' , cast(ID as varchar)),
('[Name]' , Name)
) as CA (ID, Name)
ID Name
------ --------------------------------------------------
ID 1
[Name] Joy
ID 2
[Name] jean
ID 4
[Name] paul
Here is the arguments parser. You can mix any string arguments (kept untouched) or escaped options (single or option/value pairs). To test it uncomment last 2 statements and run as:
getargs anystr1 anystr2 /test$1 /test$2=123 /test$3 str anystr3
Escape char is defined as "_SEP_=/"
, redefine if needed.
@echo off
REM Command line argument parser. Format (both "=" and "space" separators are supported):
REM anystring1 anystring2 /param1 /param2=value2 /param3 value3 [...] anystring3 anystring4
REM Returns enviroment variables as:
REM param1=1
REM param2=value2
REM param3=value3
REM Leading and traling strings are preserved as %1, %2, %3 ... %9 parameters
REM but maximum total number of strings is 9 and max number of leading strings is 8
REM Number of parameters is not limited!
set _CNT_=1
set _SEP_=/
:PARSE
if %_CNT_%==1 set _PARAM1_=%1 & set _PARAM2_=%2
if %_CNT_%==2 set _PARAM1_=%2 & set _PARAM2_=%3
if %_CNT_%==3 set _PARAM1_=%3 & set _PARAM2_=%4
if %_CNT_%==4 set _PARAM1_=%4 & set _PARAM2_=%5
if %_CNT_%==5 set _PARAM1_=%5 & set _PARAM2_=%6
if %_CNT_%==6 set _PARAM1_=%6 & set _PARAM2_=%7
if %_CNT_%==7 set _PARAM1_=%7 & set _PARAM2_=%8
if %_CNT_%==8 set _PARAM1_=%8 & set _PARAM2_=%9
if "%_PARAM2_%"=="" set _PARAM2_=1
if "%_PARAM1_:~0,1%"=="%_SEP_%" (
if "%_PARAM2_:~0,1%"=="%_SEP_%" (
set %_PARAM1_:~1,-1%=1
shift /%_CNT_%
) else (
set %_PARAM1_:~1,-1%=%_PARAM2_%
shift /%_CNT_%
shift /%_CNT_%
)
) else (
set /a _CNT_+=1
)
if /i %_CNT_% LSS 9 goto :PARSE
set _PARAM1_=
set _PARAM2_=
set _CNT_=
rem getargs anystr1 anystr2 /test$1 /test$2=123 /test$3 str anystr3
rem set | find "test$"
rem echo %1 %2 %3 %4 %5 %6 %7 %8 %9
:EXIT
just select '0' as the value for the desired column
If using Visual Studio 2010 you can right-click on the project for the service, and select properties
. Then select the Web
tab. Under the Servers
section you can configure the URL. There is also a button to create the virtual directory.
In addition to the above, I would like to point out that client-side validation (HTML code, javascript, etc.) is never enough. Also check the length server-side, or just don't check at all (if it's not so important that people can be allowed to get around it, then it's not important enough to really warrant any steps to prevent that, either).
Also, fellows, he (or she) said HTML, not XHTML. ;)
Execute in command line on OS-X El Captain:
kill -kill `lsof -t -i tcp:3000`
Terse option of lsof returns just the PID.
I like the top-voted answer by Dan McNevin. I ended up doing the sequence of git commands too many times and decided to make a script. So here it is:
#!/bin/bash
# Usage
usage() {
echo "Usage: ${0} -m [ master-branch-directory ] -r [ remote-branch-directory ] [ project-name ]"
exit 1
}
# Defaults
defaults() {
masterdir="${HOME}/Dropbox/git"
remotedir="${PWD}"
gitignorefile="# OS generated files #\n\n.DS_Store\n.DS_Store?\n.Spotlight-V100\n.Trashes\nehthumbs.db\nThumbs.db"
}
# Check if no arguments
if [ ${#} -eq 0 ] ; then
echo "Error: No arguments specified"
usage
fi
#Set defaults
defaults
# Parse arguments
while [ ${#} -ge 1 ]; do
case "${1}" in
'-h' | '--help' ) usage ;;
'-m' )
shift
masterdir="${1}"
;;
'-r' )
shift
remotedir="${1}"
;;
* )
projectname="${1##*/}"
projectname="${projectname%.git}.git"
;;
esac
shift
done
# check if specified directories and project name exists
if [ -z "${projectname}" ]; then
echo "Error: Project name not specified"
usage
fi
if [ ! -d "${remotedir}" ]; then
echo "Error: Remote directory ${remotedir} does not exist"
usage
fi
if [ ! -d "${masterdir}" ]; then
echo "Error: Master directory ${masterdir} does not exist"
usage
fi
#absolute paths
remotedir="`( cd \"${remotedir}\" && pwd )`"
masterdir="`( cd \"${masterdir}\" && pwd )`"
#Make master git repository
cd "${masterdir}"
git init --bare "${projectname}"
#make local repository and push to master
cd "${remotedir}"
echo -e "${gitignorefile}" > .gitignore # default .gitignore file
git init
git add .
git commit -m "first commit"
git remote add origin "${masterdir}/${projectname}"
git push -u origin master
#done
echo "----- Locations -----"
echo "Remote branch location: ${remotedir}"
echo "Master branch location: ${masterdir}"
echo "Project Name: ${projectname}"
The script only requires a project name. It will generate a git repository in ~/Dropbox/git/
under the specified name and will push the entire contents of the current directory to the newly created origin master branch. If more than one project name is given, the right-most project name argument will be used.
Optionally, the -r command argument specifies the remote branch that will push to the origin master. The location of the project origin master can also be specified with the -m argument. A default .gitignore file is also placed in the remote branch directory. The directory and .gitignore file defaults are specified in the script.
You could also have problems if the string has <
, >
or &
chars in it, etc. Pass it to cgi.escape()
to deal with those.
http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape
body
{
width:80%;
margin-left:auto;
margin-right:auto;
}
This will work on most browsers, including IE.
Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:
condition && (answer if true) || (answer if false)
So in example, something like this would work:
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>
UPDATE: Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).
x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.
x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
Do you need to do it from mgmt studio? Here's how we do it from cmd line:
"C:\Program Files\Microsoft SQL Server\MSSQL\Binn\TEXTCOPY.exe" /S < Server> /D < DataBase> /T mytable /C mypictureblob /F "C:\picture.png" /W"where RecId=" /I
I had a similar situation where I needed to execute a controller function after the view was loaded and also after a particular 3rd-party component within the view was loaded, initialized, and had placed a reference to itself on $scope. What ended up working for me was to setup a watch on this scope property and firing my function only after it was initialized.
// $scope.myGrid property will be created by the grid itself
// The grid will have a loadedRows property once initialized
$scope.$watch('myGrid', function(newValue, oldValue) {
if (newValue && newValue.loadedRows && !oldValue) {
initializeAllTheGridThings();
}
});
The watcher is called a couple of times with undefined values. Then when the grid is created and has the expected property, the initialization function may be safely called. The first time the watcher is called with a non-undefined newValue, oldValue will still be undefined.
typeof
is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType
is called on an object at runtime. In both cases the result is an object of the type System.Type
containing meta-information on a type.
Example where compile-time and run-time types are equal
string s = "hello";
Type t1 = typeof(string);
Type t2 = s.GetType();
t1 == t2 ==> true
Example where compile-time and run-time types are different
object obj = "hello";
Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType(); // ==> string!
t1 == t2 ==> false
i.e., the compile time type (static type) of the variable obj
is not the same as the runtime type of the object referenced by obj
.
Testing types
If, however, you only want to know whether mycontrol
is a TextBox
then you can simply test
if (mycontrol is TextBox)
Note that this is not completely equivalent to
if (mycontrol.GetType() == typeof(TextBox))
because mycontrol
could have a type that is derived from TextBox
. In that case the first comparison yields true
and the second false
! The first and easier variant is OK in most cases, since a control derived from TextBox
inherits everything that TextBox
has, probably adds more to it and is therefore assignment compatible to TextBox
.
public class MySpecializedTextBox : TextBox
{
}
MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox) ==> true
if (specialized.GetType() == typeof(TextBox)) ==> false
Casting
If you have the following test followed by a cast and T is nullable ...
if (obj is T) {
T x = (T)obj; // The casting tests, whether obj is T again!
...
}
... you can change it to ...
T x = obj as T;
if (x != null) {
...
}
Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as
operator followed by a test for null
is more performing.
Starting with C# 7.0 you can simplify the code by using pattern matching:
if (obj is T t) {
// t is a variable of type T having a non-null value.
...
}
Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:
if (o is int? ni) ===> does NOT compile!
This is because either the value is null
or it is an int
. This works for int? o
as well as for object o = new Nullable<int>(x);
:
if (o is int i) ===> OK!
I like it, because it eliminates the need to access the Nullable<T>.Value
property.
I would like to quote an answer given by Microsoft support engineer at here:-
Hi Henny, MSVCR110.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2011. The dll letters spell this out. MS = Microsoft, V = Visual, C = C++, R = Redistributable For Winroy to get started, this file is probably needed. This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. The redistributable can easily be downloaded on the Microsoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Refer the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679# Please let us know if the issue persists. We will be happy to assist you further. Thanks, Yaqub Khan - Microsoft Support Engineer
After I plotted all the lines, I was able to set the transparency of all of them as follows:
for l in fig_field.gca().lines:
l.set_alpha(.7)
EDIT: please see Joe's answer in the comments.
If you want to merge changes in SubBranch to MainBranch
git checkout MainBranch
git merge SubBranch
I use a tool called Android Icon Set in the Eclipse for standard icons like Launcher, ActionBar, Tab icons and notification icons. You can launch it from File --> New --> Other.. --> Android --> Android Icon Set. The best part is that you can choose any file from your computer and it will automatically place all the images of standard sizes into your project directory.
I was able to use the workspace setting that other people on this page have been asking for.
In Preferences, ?+P, search for python.pythonPath
in the search bar.
You should see something like:
// Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
"python.pythonPath": "python"
Then click on the WORKSPACE SETTINGS tab on the right side of the window. This will make it so the setting is only applicable to the workspace you're in.
Afterwards, click on the pencil icon next to "python.pythonPath". This should copy the setting over the workspace settings.
Change the value to something like:
"python.pythonPath": "${workspaceFolder}/venv"
Decompile with CMD:
If those didn't work try this:
cmd /K g++ "$(FULL_CURRENT_PATH)" -o "$(FULL_CURRENT_PATH).exe
It should save where you got the file (Example: If I got file from Desktop, it will be saved as .exe on the Desktop)
I don't know if it works on 64 bits though so you can try it!
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:
$('#exampleBtn').click(function() {
function();
});
For others in my situation, the solution was:
qmake -qt=qt5
This was on Ubuntu 14.04 after install qt5-qmake. qmake was a symlink to qtchooser which takes the -qt argument.
I was facing exact same error
Computed property "callRingtatus" was assigned to but it has no setter
here is a sample code according to my scenario
computed: {
callRingtatus(){
return this.$store.getters['chat/callState']===2
}
}
I change the above code into the following way
computed: {
callRingtatus(){
return this.$store.state.chat.callState===2
}
}
fetch values from vuex store state instead of getters inside the computed hook
Use the shell globbing syntax:
grep pattern -r --include=\*.{cpp,h} rootdir
The syntax for --exclude
is identical.
Note that the star is escaped with a backslash to prevent it from being expanded by the shell (quoting it, such as --include="*.{cpp,h}"
, would work just as well). Otherwise, if you had any files in the current working directory that matched the pattern, the command line would expand to something like grep pattern -r --include=foo.cpp --include=bar.h rootdir
, which would only search files named foo.cpp
and bar.h
, which is quite likely not what you wanted.
Put your image in a container div then use the following CSS (changing the dimensions to suit your image.
.imageContainer{
position: absolute;
width: 100px; /*the image width*/
height: 100px; /*the image height*/
left: 50%;
top: 50%;
margin-left: -50px; /*half the image width*/
margin-top: -50px; /*half the image height*/
}
If you are looking for the solution in Android Studio :
If you're feeling adventurous, take a look at JScience. It has a Rational
class that represents fractions.
As far as the actual loading image, check out this site for a bunch of options.
As far as displaying a DIV with this image when a request begins, you have a few choices:
A) Manually show and hide the image:
$('#form').submit(function() {
$('#wait').show();
$.post('/whatever.php', function() {
$('#wait').hide();
});
return false;
});
B) Use ajaxStart and ajaxComplete:
$('#wait').ajaxStart(function() {
$(this).show();
}).ajaxComplete(function() {
$(this).hide();
});
Using this the element will show/hide for any request. Could be good or bad, depending on the need.
C) Use individual callbacks for a particular request:
$('#form').submit(function() {
$.ajax({
url: '/whatever.php',
beforeSend: function() { $('#wait').show(); },
complete: function() { $('#wait').hide(); }
});
return false;
});
You can also use this:
private boolean doesUserHavePermission()
{
int result = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
You need to concatenate the selector and pseudo selector. You'll also need a style element to contain your styles. Most people use an external stylesheet, for lots of benefits (caching for one).
<a class="hover">click</a>
<style type="text/css">
a.hover:hover {
text-decoration: underline;
}
</style>
Just a note: the hover class is not necessary, unless you are defining only certain links to have this behavior (which may be the case)
Unlike C/C++ Long in Python have unlimited precision. Refer the section Numeric Types in python for more information.To determine the max value of integer you can just refer sys.maxint
. You can get more details from the documentation of sys.
If you don't mind the slashes being switched, you could [ab]use Uri
:
Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
Uri folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}
Try:
String path1 = "path1";
String path2 = "path2";
String joinedPath = new File(path1, path2).toString();
This looks like an old thread but there is one more variant of how we can set an environment variable in the Gradle task.
task runSomeRandomTask(type: NpmTask, dependsOn: [npmInstall]) {
environment = [ 'NODE_ENV': 'development', BASE_URL: '3000' ]
args = ['run']
}
The above Gradle task integrates the Gradle and npm tasks.
This way we can pass multiple environment variables. Hope this helps to broaden the understanding which the answers above have already provided. Cheers!!
Try this solution:
.home p:first-of-type {_x000D_
border:5px solid red;_x000D_
width:100%;_x000D_
display:block;_x000D_
}
_x000D_
<div class="home">_x000D_
<span>blah</span>_x000D_
<p class="red">first</p>_x000D_
<p class="red">second</p>_x000D_
<p class="red">third</p>_x000D_
<p class="red">fourth</p>_x000D_
</div>
_x000D_
use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";
You can try one of the following:
Method 1:
MyProject
go build
./MyProject
You can do both steps at once by typing go build && ./MyProject
. Go files of the package main
are compiled to an executable.
Method 2:
go run *.go
. It won't create any executable but it runs.As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.
This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...
function changeBGColor() {
var cols = document.getElementsByClassName('col1');
for(i = 0; i < cols.length; i++) {
cols[i].style.backgroundColor = 'blue';
}
}
For example:
String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);
This will let you use Enter as a delimiter.
Thus, if you input:
Hello world (ENTER)
it will print 'Hello World'.
Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):
CREATE TABLE "dbo"."TableName"
(
id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
name varchar(20),
);
the insert statement should list all columns except the id column (it will be filled with autoincremented value):
INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');
and the result of
SELECT id, name FROM "dbo"."TableName";
will be
id name
--------------------------
1 alpha
2 beta
A simple call back program. Hope it answers your question.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"
typedef void (*call_back) (S32, S32);
void test_call_back(S32 a, S32 b)
{
printf("In call back function, a:%d \t b:%d \n", a, b);
}
void call_callback_func(call_back back)
{
S32 a = 5;
S32 b = 7;
back(a, b);
}
S32 main(S32 argc, S8 *argv[])
{
S32 ret = SUCCESS;
call_back back;
back = test_call_back;
call_callback_func(back);
return ret;
}
Update 2019 - Bootstrap 4
You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.
.card-columns {
@include media-breakpoint-only(xl) {
column-count: 5;
}
@include media-breakpoint-only(lg) {
column-count: 4;
}
@include media-breakpoint-only(md) {
column-count: 3;
}
@include media-breakpoint-only(sm) {
column-count: 2;
}
}
SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX
Or, CSS only like this...
@media (min-width: 576px) {
.card-columns {
column-count: 2;
}
}
@media (min-width: 768px) {
.card-columns {
column-count: 3;
}
}
@media (min-width: 992px) {
.card-columns {
column-count: 4;
}
}
@media (min-width: 1200px) {
.card-columns {
column-count: 5;
}
}
CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ
The finally block is always run after the try block ends, whether try ends normally or abnormally due to an exception, er, throwable.
If an exception is thrown by any of the code within the try block, then the current method simply re-throws (or continues to throw) the same exception (after running the finally block).
If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.
Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.
E.g. -
r = new LeakyThing();
try { useResource( r); }
finally { r.release(); } // close, destroy, etc
"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:
catch ( Exception e) ... // doesn't really catch *all*, eh?
do this instead:
catch ( Throwable t) ...
The pattern is group by keys => do something to each group e.g. reduce => return to dataframe
I thought the Dataframe abstraction is a bit cumbersome in this case so I used RDD functionality
val rdd: RDD[Row] = originalDf
.rdd
.groupBy(row => row.getAs[String]("grouping_row"))
.map(iterableTuple => {
iterableTuple._2.reduce(reduceFunction)
})
val productDf = sqlContext.createDataFrame(rdd, originalDf.schema)
C++20 introduced a guarantee that time_since_epoch
is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
Using C++17 or earlier, time()
is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
To convert it to a single dictionary with some decided keys value, you can use the code below.
data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
ListOfDictAsDict[PrecedingText + str(i)] = data[i]
Collection is a interface which is used to represent group of individual object as a single entity.
Collections is an utility class present in java.util. package to define several utility method (like sorting,searching ) for collection object.
Adding this since this was not mentioned.
SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');
Because that's what actually works for me. Adding date() function on both comparison values.
If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.
In order to change date format in the views.py and then assign it to template.
# get the object details
home = Home.objects.get(home_id=homeid)
# get the start date
_startDate = home.home_startdate.strftime('%m/%d/%Y')
# assign it to template
return render_to_response('showme.html'
{'home_startdate':_startDate},
context_instance=RequestContext(request) )
Just use com.google.common.io.Resources class. Example:
URL url = Resources.getResource("file name")
After that you have methods like: .getContent(), .getFile(), .getPath() etc
I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.
double time_seconds = time_milliseconds / 1000.0; // add the decimal
System.out.println(time_milliseconds); // Now this should give you the right value.
Try this:
select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2
The number in the having should match the amount of people. If you also need the Status to be Complete
use this where
clause instead of the previous one:
where personName in ('Ryan', 'Holly') and status = 'Complete'
I usually lose track of all of my -20001
-type error codes, so I try to consolidate all my application errors into a nice package like such:
SET SERVEROUTPUT ON
CREATE OR REPLACE PACKAGE errors AS
invalid_foo_err EXCEPTION;
invalid_foo_num NUMBER := -20123;
invalid_foo_msg VARCHAR2(32767) := 'Invalid Foo!';
PRAGMA EXCEPTION_INIT(invalid_foo_err, -20123); -- can't use var >:O
illegal_bar_err EXCEPTION;
illegal_bar_num NUMBER := -20156;
illegal_bar_msg VARCHAR2(32767) := 'Illegal Bar!';
PRAGMA EXCEPTION_INIT(illegal_bar_err, -20156); -- can't use var >:O
PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL);
END;
/
CREATE OR REPLACE PACKAGE BODY errors AS
unknown_err EXCEPTION;
unknown_num NUMBER := -20001;
unknown_msg VARCHAR2(32767) := 'Unknown Error Specified!';
PROCEDURE raise_err(p_err NUMBER, p_msg VARCHAR2 DEFAULT NULL) AS
v_msg VARCHAR2(32767);
BEGIN
IF p_err = unknown_num THEN
v_msg := unknown_msg;
ELSIF p_err = invalid_foo_num THEN
v_msg := invalid_foo_msg;
ELSIF p_err = illegal_bar_num THEN
v_msg := illegal_bar_msg;
ELSE
raise_err(unknown_num, 'USR' || p_err || ': ' || p_msg);
END IF;
IF p_msg IS NOT NULL THEN
v_msg := v_msg || ' - '||p_msg;
END IF;
RAISE_APPLICATION_ERROR(p_err, v_msg);
END;
END;
/
Then call errors.raise_err(errors.invalid_foo_num, 'optional extra text')
to use it, like such:
BEGIN
BEGIN
errors.raise_err(errors.invalid_foo_num, 'Insufficient Foo-age!');
EXCEPTION
WHEN errors.invalid_foo_err THEN
dbms_output.put_line(SQLERRM);
END;
BEGIN
errors.raise_err(errors.illegal_bar_num, 'Insufficient Bar-age!');
EXCEPTION
WHEN errors.illegal_bar_err THEN
dbms_output.put_line(SQLERRM);
END;
BEGIN
errors.raise_err(-10000, 'This Doesn''t Exist!!');
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(SQLERRM);
END;
END;
/
produces this output:
ORA-20123: Invalid Foo! - Insufficient Foo-age!
ORA-20156: Illegal Bar! - Insufficient Bar-age!
ORA-20001: Unknown Error Specified! - USR-10000: This Doesn't Exist!!
IF EXISTS(SELECT TOP 1 1 FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'[dbo].[ChannelPlayerSkins]') AND name = 'FK_ChannelPlayerSkins_Channels')
BEGIN
DROP CONSTRAINT FK_ChannelPlayerSkins_Channels
END
GO
I was able to achieve this by using set -x
in the main script (which makes the script print out every command that is executed) and writing a wrapper script which just shows the last line of output generated by set -x
.
This is the main script:
#!/bin/bash
set -x
echo some command here
echo last command
And this is the wrapper script:
#!/bin/sh
./test.sh 2>&1 | grep '^\+' | tail -n 1 | sed -e 's/^\+ //'
Running the wrapper script produces this as output:
echo last command
I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input
event.
$('input').on('input', function() {
$(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});
Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.
$('input').on('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
In javascript there are no block-level scopes
only function-level scopes
:
Read this article about javaScript Scoping and Hoisting.
var deferred = $q.defer();
deferred.count = i;
console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects
// some code
.success(function(data){
console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
deferred.resolve(data);
})
var deferred= $q.defer();
inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop
.closure scope
even after functions are executed.angular.forEach
:Here is a demo plunker: http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview
UploadService.uploadQuestion = function(questions){
var promises = [];
angular.forEach(questions , function(question) {
var promise = $http({
url : 'upload/question',
method: 'POST',
data : question
});
promises.push(promise);
});
return $q.all(promises);
}
Array#map
:Here is a demo plunker: http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview
UploadService.uploadQuestion = function(questions){
var promises = questions.map(function(question) {
return $http({
url : 'upload/question',
method: 'POST',
data : question
});
});
return $q.all(promises);
}
In my case (the same problem) helped to add -NoProfile in task action command arguments and check checkbox "Run with highest privileges", because on my server UAC is on (active).
More info about it enter link description here
That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.
The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.
But, I'll take a stab. The original sentence is this:
All told, a monad in X is just a monoid in the category of endofunctors of X, with product Ă— replaced by composition of endofunctors and unit set by the identity endofunctor.
X here is a category. Endofunctors are functors from a category to itself (which is usually all Functor
s as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.
And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:
* -> *
with a Functor
instance)join
in Haskell)return
in Haskell)With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.
I found a list of Java class file versions on the Wikipedia page that describes the class file format:
http://en.wikipedia.org/wiki/Java_class_file#General_layout
Under byte offset 6 & 7, the versions are listed with which Java VM they correspond to.
import React, { useState } from 'react';
function App() {
const [apes , setap] = useState('yo');
const handleClick = () =>{
setap(document.getElementById('name').value)
};
return (
<div>
<input id='name' />
<h2> {apes} </h2>
<button onClick={handleClick} />
</div>
);
}
export default App;
Ensure you record your work in a reproducible script. From time-to-time, reopen R, then source()
your script. You'll clean out anything you're no longer using, and as an added benefit will have tested your code.
This code will help you, and it's fairly self-explanatory:
#include <stdio.h> /* Standard Library of Input and Output */
#include <complex.h> /* Standard Library of Complex Numbers */
int main() {
double complex z1 = 1.0 + 3.0 * I;
double complex z2 = 1.0 - 4.0 * I;
printf("Working with complex numbers:\n\v");
printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));
double complex sum = z1 + z2;
printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));
double complex difference = z1 - z2;
printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));
double complex product = z1 * z2;
printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));
double complex quotient = z1 / z2;
printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));
double complex conjugate = conj(z1);
printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));
return 0;
}
with:
creal(z1)
: get the real part (for float crealf(z1)
, for long double creall(z1)
)
cimag(z1)
: get the imaginary part (for float cimagf(z1)
, for long double cimagl(z1)
)
Another important point to remember when working with complex numbers is that functions like cos()
, exp()
and sqrt()
must be replaced with their complex forms, e.g. ccos()
, cexp()
, csqrt()
.
File >> New Project >> Java Project With Existing Source>Next >> Project Name(add a name for your project) >> Next>>Add Folder >> select your existing project source code from your Directory>>Next >> Finish
Java Project With Existing Source
I am facing small trouble in returning a value from callback function in Node.js
This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.
Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
// call the function that needs the value
callback(finalData);
// we are done
return;
});
}
Line callback(finalData);
is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)
I had a similar problem, and the solution for me was quite different from what the other users posted.
The problem with me was related to the project I was working last year, which required a certain proxy on maven settings (located at <path to maven folder>\maven\conf\settings.xml
and C:\Users\<my user>\.m2\settings.xml
). The proxy was blocking the download of required external packages.
The solution was to put back the original file (settings.xml
) on those places. Once things were restored, I was able to download the packages and everything worked.
The registry/configurationSettings/XML argument still seems very active. I've used them all, as the technology has progressed, but my favourite is based on Threed's system combined with Isolated Storage.
The following sample allows storage of an objects named properties to a file in isolated storage. Such as:
AppSettings.Save(myobject, "Prop1,Prop2", "myFile.jsn");
Properties may be recovered using:
AppSettings.Load(myobject, "myFile.jsn");
It is just a sample, not suggestive of best practices.
internal static class AppSettings
{
internal static void Save(object src, string targ, string fileName)
{
Dictionary<string, object> items = new Dictionary<string, object>();
Type type = src.GetType();
string[] paramList = targ.Split(new char[] { ',' });
foreach (string paramName in paramList)
items.Add(paramName, type.GetProperty(paramName.Trim()).GetValue(src, null));
try
{
// GetUserStoreForApplication doesn't work - can't identify.
// application unless published by ClickOnce or Silverlight
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write((new JavaScriptSerializer()).Serialize(items));
}
}
catch (Exception) { } // If fails - just don't use preferences
}
internal static void Load(object tar, string fileName)
{
Dictionary<string, object> items = new Dictionary<string, object>();
Type type = tar.GetType();
try
{
// GetUserStoreForApplication doesn't work - can't identify
// application unless published by ClickOnce or Silverlight
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
using (StreamReader reader = new StreamReader(stream))
{
items = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
}
}
catch (Exception) { return; } // If fails - just don't use preferences.
foreach (KeyValuePair<string, object> obj in items)
{
try
{
tar.GetType().GetProperty(obj.Key).SetValue(tar, obj.Value, null);
}
catch (Exception) { }
}
}
}
The simple way I use is
app.controller("Back2Square1Controller", function($scope, $location) {
window.location.assign(basePath + "/index.html");
});
You have to use RegExp
:
str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));
When I'm concatenating strings, all slashes are gone.
If you have a backslash in your pattern to escape a special regex character, (like \(
), you have to use two backslashes in the string (because \
is the escape character in a string): new RegExp('\\(')
would be the same as /\(/
.
So your patterns have to become:
var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}
If you want to get an index about the similarity of the two pictures, I suggest you from the metrics the SSIM index. It is more consistent with the human eye. Here is an article about it: Structural Similarity Index
It is implemented in OpenCV too, and it can be accelerated with GPU: OpenCV SSIM with GPU
If you ever need to send GET
request to an IP
as well as a Domain
(Other answers did not mention you can specify a port
variable), you can make use of this function:
function getCode(host, port, path, queryString) {
console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")
// Construct url and query string
const requestUrl = url.parse(url.format({
protocol: 'http',
hostname: host,
pathname: path,
port: port,
query: queryString
}));
console.log("(" + host + path + ")" + "Sending GET request")
// Send request
console.log(url.format(requestUrl))
http.get(url.format(requestUrl), (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
console.log("GET chunk: " + chunk);
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log("GET end of response: " + data);
});
}).on("error", (err) => {
console.log("GET Error: " + err);
});
}
Don't miss requiring modules at the top of your file:
http = require("http");
url = require('url')
Also bare in mind that you may use https
module for communicating over secured network.
Have you tried just going: git commit -m "Message here"
So in your case:
git commit -m "Form validation added"
After you've added your files of course.
For API 16+, use
finishAffinity();
For lower, use
ActivityCompat.finishAffinity(YourActivity.this)
You could pass the CSS through javascript and replace all instances of COLOUR1 with a certain color (basically regex it) and provide a backup stylesheet incase the end user has JS turned off
I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.
user_input = input("Enter multiple values separated by comma > ")
def add_numbers(num_list):
addition_result = 0
for i in num_list:
addition_result = addition_result + i
print(addition_result)
add_numbers(user_input)
Your problem is that log4j has not been initialized. It does not affect the outcome of you application in any way, so it's safe to ignore or just initialize Log4J, see: How to initialize log4j properly?
The below actually works very well.
private void networkInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
var _open = false;
FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
if (frm.Name == "FormBrowseNetworkInformation")
{
_open = true;
frm.Select();
break;
}
}
if (_open == false)
{
var formBrowseNetworkInformation = new FormBrowseNetworkInformation();
formBrowseNetworkInformation.Show();
}
}
Update: The GSOC project and the code there isn't active, but this is: https://github.com/hierynomus/sshj
hierynomus took over as maintainer since early 2015. Here is the older, no longer maintained, Github link:
https://github.com/shikhar/sshj
There was a GSOC project:
http://code.google.com/p/commons-net-ssh/
Code quality seem to be better than JSch, which, while a complete and working implementation, lacks documentation. Project page spots an upcoming beta release, last commit to the repository was mid-august.
Compare the APIs:
http://code.google.com/p/commons-net-ssh/
SSHClient ssh = new SSHClient();
//ssh.useCompression();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
new SCPDownloadClient(ssh).copy("ten", "/tmp");
} finally {
ssh.disconnect();
}
Session session = null;
Channel channel = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(username, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
// exec 'scp -f rfile' remotely
String command = "scp -f " + remoteFilename;
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
while (true) {
int c = checkAck(in);
if (c != 'C') {
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize = 0L;
while (true) {
if (in.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ') {
break;
}
filesize = filesize * 10L + (long) (buf[0] - '0');
}
String file = null;
for (int i = 0;; i++) {
in.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
file = new String(buf, 0, i);
break;
}
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
// read a content of lfile
FileOutputStream fos = null;
fos = new FileOutputStream(localFilename);
int foo;
while (true) {
if (buf.length < filesize) {
foo = buf.length;
} else {
foo = (int) filesize;
}
foo = in.read(buf, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(buf, 0, foo);
filesize -= foo;
if (filesize == 0L) {
break;
}
}
fos.close();
fos = null;
if (checkAck(in) != 0) {
System.exit(0);
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
channel.disconnect();
session.disconnect();
}
} catch (JSchException jsche) {
System.err.println(jsche.getLocalizedMessage());
} catch (IOException ioe) {
System.err.println(ioe.getLocalizedMessage());
} finally {
channel.disconnect();
session.disconnect();
}
}
You can use x = func()[0]
to return the first value, x = func()[1]
to return the second, and so on.
If you want to get multiple values at a time, use something like x, y = func()[2:4]
.
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
function getMeta(url){
$("<img/>",{
load : function(){
alert(this.width+' '+this.height);
},
src : url
});
}
function getMeta(url){
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = url;
}
function getMeta(url){
var img = new Image();
img.addEventListener("load", function(){
alert( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = url;
}
Use the above simply as: getMeta( "http://example.com/img.jpg" );
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
Besides the correct answers offered as long term solutions, you can use git to remove all unnecessary files once for you with the git clean -f
command but use git clean --dry-run
first to ensure nothing unintended would happen.
This has the benefit of using tested built in functionality of Git over scripts specific to your OS/shell to remove the files.
I can't find a way to do this with code, but in stock Firefox 64, events are listed next to each HTML entity in the Developer Tools Inspector as noted on MDN's Examine Event Listeners page and as demonstrated in this image:
yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).
@Component({
...
host: {
'(document:keydown)': 'handleKeyboardEvents($event)'
}
})
export class MyComponent {
...
handleKeyboardEvents(event: KeyboardEvent) {
this.key = event.which || event.keyCode;
}
}
See also an earlier version of this answer on another rotate question with some more details about what asm gcc/clang produce for x86.
The most compiler-friendly way to express a rotate in C and C++ that avoids any Undefined Behaviour seems to be John Regehr's implementation. I've adapted it to rotate by the width of the type (using fixed-width types like uint32_t
).
#include <stdint.h> // for uint32_t
#include <limits.h> // for CHAR_BIT
// #define NDEBUG
#include <assert.h>
static inline uint32_t rotl32 (uint32_t n, unsigned int c)
{
const unsigned int mask = (CHAR_BIT*sizeof(n) - 1); // assumes width is a power of 2.
// assert ( (c<=mask) &&"rotate by type width or more");
c &= mask;
return (n<<c) | (n>>( (-c)&mask ));
}
static inline uint32_t rotr32 (uint32_t n, unsigned int c)
{
const unsigned int mask = (CHAR_BIT*sizeof(n) - 1);
// assert ( (c<=mask) &&"rotate by type width or more");
c &= mask;
return (n>>c) | (n<<( (-c)&mask ));
}
Works for any unsigned integer type, not just uint32_t
, so you could make versions for other sizes.
See also a C++11 template version with lots of safety checks (including a static_assert
that the type width is a power of 2), which isn't the case on some 24-bit DSPs or 36-bit mainframes, for example.
I'd recommend only using the template as a back-end for wrappers with names that include the rotate width explicitly. Integer-promotion rules mean that rotl_template(u16 & 0x11UL, 7)
would do a 32 or 64-bit rotate, not 16 (depending on the width of unsigned long
). Even uint16_t & uint16_t
is promoted to signed int
by C++'s integer-promotion rules, except on platforms where int
is no wider than uint16_t
.
On x86, this version inlines to a single rol r32, cl
(or rol r32, imm8
) with compilers that grok it, because the compiler knows that x86 rotate and shift instructions mask the shift-count the same way the C source does.
Compiler support for this UB-avoiding idiom on x86, for uint32_t x
and unsigned int n
for variable-count shifts:
ror
or rol
instruction for variable counts.shld edi,edi,7
which is slower and takes more bytes than rol edi,7
on some CPUs (especially AMD, but also some Intel), when BMI2 isn't available for rorx eax,edi,25
to save a MOV._rotl
/ _rotr
intrinsics from <intrin.h>
on x86 (including x86-64).gcc for ARM uses an and r1, r1, #31
for variable-count rotates, but still does the actual rotate with a single instruction: ror r0, r0, r1
. So gcc doesn't realize that rotate-counts are inherently modular. As the ARM docs say, "ROR with shift length, n
, more than 32 is the same as ROR with shift length n-32
". I think gcc gets confused here because left/right shifts on ARM saturate the count, so a shift by 32 or more will clear the register. (Unlike x86, where shifts mask the count the same as rotates). It probably decides it needs an AND instruction before recognizing the rotate idiom, because of how non-circular shifts work on that target.
Current x86 compilers still use an extra instruction to mask a variable count for 8 and 16-bit rotates, probably for the same reason they don't avoid the AND on ARM. This is a missed optimization, because performance doesn't depend on the rotate count on any x86-64 CPU. (Masking of counts was introduced with 286 for performance reasons because it handled shifts iteratively, not with constant-latency like modern CPUs.)
BTW, prefer rotate-right for variable-count rotates, to avoid making the compiler do 32-n
to implement a left rotate on architectures like ARM and MIPS that only provide a rotate-right. (This optimizes away with compile-time-constant counts.)
Fun fact: ARM doesn't really have dedicated shift/rotate instructions, it's just MOV with the source operand going through the barrel-shifter in ROR mode: mov r0, r0, ror r1
. So a rotate can fold into a register-source operand for an EOR instruction or something.
Make sure you use unsigned types for n
and the return value, or else it won't be a rotate. (gcc for x86 targets does arithmetic right shifts, shifting in copies of the sign-bit rather than zeroes, leading to a problem when you OR
the two shifted values together. Right-shifts of negative signed integers is implementation-defined behaviour in C.)
Also, make sure the shift count is an unsigned type, because (-n)&31
with a signed type could be one's complement or sign/magnitude, and not the same as the modular 2^n you get with unsigned or two's complement. (See comments on Regehr's blog post). unsigned int
does well on every compiler I've looked at, for every width of x
. Some other types actually defeat the idiom-recognition for some compilers, so don't just use the same type as x
.
Some compilers provide intrinsics for rotates, which is far better than inline-asm if the portable version doesn't generate good code on the compiler you're targeting. There aren't cross-platform intrinsics for any compilers that I know of. These are some of the x86 options:
<immintrin.h>
provides _rotl
and _rotl64
intrinsics, and same for right shift. MSVC requires <intrin.h>
, while gcc require <x86intrin.h>
. An #ifdef
takes care of gcc vs. icc, but clang doesn't seem to provide them anywhere, except in MSVC compatibility mode with -fms-extensions -fms-compatibility -fms-compatibility-version=17.00
. And the asm it emits for them sucks (extra masking and a CMOV)._rotr8
and _rotr16
.<x86intrin.h>
also provides __rolb
/__rorb
for 8-bit rotate left/right, __rolw
/__rorw
(16-bit), __rold
/__rord
(32-bit), __rolq
/__rorq
(64-bit, only defined for 64-bit targets). For narrow rotates, the implementation uses __builtin_ia32_rolhi
or ...qi
, but the 32 and 64-bit rotates are defined using shift/or (with no protection against UB, because the code in ia32intrin.h
only has to work on gcc for x86). GNU C appears not to have any cross-platform __builtin_rotate
functions the way it does for __builtin_popcount
(which expands to whatever's optimal on the target platform, even if it's not a single instruction). Most of the time you get good code from idiom-recognition.// For real use, probably use a rotate intrinsic for MSVC, or this idiom for other compilers. This pattern of #ifdefs may be helpful
#if defined(__x86_64__) || defined(__i386__)
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h> // Not just <immintrin.h> for compilers other than icc
#endif
uint32_t rotl32_x86_intrinsic(rotwidth_t x, unsigned n) {
//return __builtin_ia32_rorhi(x, 7); // 16-bit rotate, GNU C
return _rotl(x, n); // gcc, icc, msvc. Intel-defined.
//return __rold(x, n); // gcc, icc.
// can't find anything for clang
}
#endif
Presumably some non-x86 compilers have intrinsics, too, but let's not expand this community-wiki answer to include them all. (Maybe do that in the existing answer about intrinsics).
(The old version of this answer suggested MSVC-specific inline asm (which only works for 32bit x86 code), or http://www.devx.com/tips/Tip/14043 for a C version. The comments are replying to that.)
Inline asm defeats many optimizations, especially MSVC-style because it forces inputs to be stored/reloaded. A carefully-written GNU C inline-asm rotate would allow the count to be an immediate operand for compile-time-constant shift counts, but it still couldn't optimize away entirely if the value to be shifted is also a compile-time constant after inlining. https://gcc.gnu.org/wiki/DontUseInlineAsm.
Try this:
If [ $a -lt 4 ] || [ $a -gt 64 ] ; then \n
Something something \n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then \n
Something something \n
else \n
Yes it works for me :) \n
Vb.net library has a simple solution using interaction class for this:
void MsgPopup(string text, string title, int secs = 3)
{
dynamic intr = Microsoft.VisualBasic.Interaction.CreateObject("WScript.Shell");
intr.Popup(text, secs, title);
}
bool MsgPopupYesNo(string text, string title, int secs = 3)
{
dynamic intr = Microsoft.VisualBasic.Interaction.CreateObject("WScript.Shell");
int answer = intr.Popup(text, secs, title, (int)Microsoft.VisualBasic.Constants.vbYesNo + (int)Microsoft.VisualBasic.Constants.vbQuestion);
return (answer == 6);
}
There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.
I can't figure out exactly what's there, yet ...
edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.
A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.
If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od
command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.
You have to declare the array variable as an array:
Dim test(10) As Variant
I would like to suggest you this amazing class. This worked very well for me.
http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php.html/
I am publishing the code I used with the copyright notice of original author. You can get latest code from the link above.
<?php
/**
* File: Browser.php
* Author: Chris Schuld (http://chrisschuld.com/)
*
* Copyright (C) 2008-2010 Chris Schuld ([email protected])
*
* Typical Usage:
*
* $browser = new Browser();
* if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) {
* echo 'You have FireFox version 2 or greater';
* }
*
*/
class Browser {
private $_agent = '';
private $_browser_name = '';
private $_version = '';
private $_platform = '';
private $_os = '';
private $_is_aol = false;
private $_is_mobile = false;
private $_is_robot = false;
private $_aol_version = '';
const BROWSER_UNKNOWN = 'unknown';
const VERSION_UNKNOWN = 'unknown';
const BROWSER_OPERA = 'Opera';
const BROWSER_OPERA_MINI = 'Opera Mini';
const BROWSER_WEBTV = 'WebTV';
const BROWSER_IE = 'Internet Explorer';
const BROWSER_POCKET_IE = 'Pocket Internet Explorer';
const BROWSER_KONQUEROR = 'Konqueror';
const BROWSER_ICAB = 'iCab';
const BROWSER_OMNIWEB = 'OmniWeb';
const BROWSER_FIREBIRD = 'Firebird';
const BROWSER_FIREFOX = 'Firefox';
const BROWSER_ICEWEASEL = 'Iceweasel';
const BROWSER_SHIRETOKO = 'Shiretoko';
const BROWSER_MOZILLA = 'Mozilla';
const BROWSER_AMAYA = 'Amaya';
const BROWSER_LYNX = 'Lynx';
const BROWSER_SAFARI = 'Safari';
const BROWSER_IPHONE = 'iPhone';
const BROWSER_IPOD = 'iPod';
const BROWSER_IPAD = 'iPad';
const BROWSER_CHROME = 'Chrome';
const BROWSER_ANDROID = 'Android';
const BROWSER_GOOGLEBOT = 'GoogleBot';
const BROWSER_SLURP = 'Yahoo! Slurp';
const BROWSER_W3CVALIDATOR = 'W3C Validator';
const BROWSER_BLACKBERRY = 'BlackBerry';
const BROWSER_ICECAT = 'IceCat';
const BROWSER_NOKIA_S60 = 'Nokia S60 OSS Browser';
const BROWSER_NOKIA = 'Nokia Browser';
const BROWSER_MSN = 'MSN Browser';
const BROWSER_MSNBOT = 'MSN Bot';
const BROWSER_NETSCAPE_NAVIGATOR = 'Netscape Navigator';
const BROWSER_GALEON = 'Galeon';
const BROWSER_NETPOSITIVE = 'NetPositive';
const BROWSER_PHOENIX = 'Phoenix';
const PLATFORM_UNKNOWN = 'unknown';
const PLATFORM_WINDOWS = 'Windows';
const PLATFORM_WINDOWS_CE = 'Windows CE';
const PLATFORM_APPLE = 'Apple';
const PLATFORM_LINUX = 'Linux';
const PLATFORM_OS2 = 'OS/2';
const PLATFORM_BEOS = 'BeOS';
const PLATFORM_IPHONE = 'iPhone';
const PLATFORM_IPOD = 'iPod';
const PLATFORM_IPAD = 'iPad';
const PLATFORM_BLACKBERRY = 'BlackBerry';
const PLATFORM_NOKIA = 'Nokia';
const PLATFORM_FREEBSD = 'FreeBSD';
const PLATFORM_OPENBSD = 'OpenBSD';
const PLATFORM_NETBSD = 'NetBSD';
const PLATFORM_SUNOS = 'SunOS';
const PLATFORM_OPENSOLARIS = 'OpenSolaris';
const PLATFORM_ANDROID = 'Android';
const OPERATING_SYSTEM_UNKNOWN = 'unknown';
public function Browser($useragent="") {
$this->reset();
if( $useragent != "" ) {
$this->setUserAgent($useragent);
}
else {
$this->determine();
}
}
/**
* Reset all properties
*/
public function reset() {
$this->_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
$this->_browser_name = self::BROWSER_UNKNOWN;
$this->_version = self::VERSION_UNKNOWN;
$this->_platform = self::PLATFORM_UNKNOWN;
$this->_os = self::OPERATING_SYSTEM_UNKNOWN;
$this->_is_aol = false;
$this->_is_mobile = false;
$this->_is_robot = false;
$this->_aol_version = self::VERSION_UNKNOWN;
}
/**
* Check to see if the specific browser is valid
* @param string $browserName
* @return boolean
*/
function isBrowser($browserName) { return( 0 == strcasecmp($this->_browser_name, trim($browserName))); }
/**
* The name of the browser. All return types are from the class contants
* @return string Name of the browser
*/
public function getBrowser() { return $this->_browser_name; }
/**
* Set the name of the browser
* @param $browser The name of the Browser
*/
public function setBrowser($browser) { return $this->_browser_name = $browser; }
/**
* The name of the platform. All return types are from the class contants
* @return string Name of the browser
*/
public function getPlatform() { return $this->_platform; }
/**
* Set the name of the platform
* @param $platform The name of the Platform
*/
public function setPlatform($platform) { return $this->_platform = $platform; }
/**
* The version of the browser.
* @return string Version of the browser (will only contain alpha-numeric characters and a period)
*/
public function getVersion() { return $this->_version; }
/**
* Set the version of the browser
* @param $version The version of the Browser
*/
public function setVersion($version) { $this->_version = preg_replace('/[^0-9,.,a-z,A-Z-]/','',$version); }
/**
* The version of AOL.
* @return string Version of AOL (will only contain alpha-numeric characters and a period)
*/
public function getAolVersion() { return $this->_aol_version; }
/**
* Set the version of AOL
* @param $version The version of AOL
*/
public function setAolVersion($version) { $this->_aol_version = preg_replace('/[^0-9,.,a-z,A-Z]/','',$version); }
/**
* Is the browser from AOL?
* @return boolean
*/
public function isAol() { return $this->_is_aol; }
/**
* Is the browser from a mobile device?
* @return boolean
*/
public function isMobile() { return $this->_is_mobile; }
/**
* Is the browser from a robot (ex Slurp,GoogleBot)?
* @return boolean
*/
public function isRobot() { return $this->_is_robot; }
/**
* Set the browser to be from AOL
* @param $isAol
*/
public function setAol($isAol) { $this->_is_aol = $isAol; }
/**
* Set the Browser to be mobile
* @param boolean
*/
protected function setMobile($value=true) { $this->_is_mobile = $value; }
/**
* Set the Browser to be a robot
* @param boolean
*/
protected function setRobot($value=true) { $this->_is_robot = $value; }
/**
* Get the user agent value in use to determine the browser
* @return string The user agent from the HTTP header
*/
public function getUserAgent() { return $this->_agent; }
/**
* Set the user agent value (the construction will use the HTTP header value - this will overwrite it)
* @param $agent_string The value for the User Agent
*/
public function setUserAgent($agent_string) {
$this->reset();
$this->_agent = $agent_string;
$this->determine();
}
/**
* Used to determine if the browser is actually "chromeframe"
* @return boolean
*/
public function isChromeFrame() {
return( strpos($this->_agent,"chromeframe") !== false );
}
/**
* Returns a formatted string with a summary of the details of the browser.
* @return string formatted string with a summary of the browser
*/
public function __toString() {
return "<strong>Browser Name:</strong>{$this->getBrowser()}<br/>\n" .
"<strong>Browser Version:</strong>{$this->getVersion()}<br/>\n" .
"<strong>Browser User Agent String:</strong>{$this->getUserAgent()}<br/>\n" .
"<strong>Platform:</strong>{$this->getPlatform()}<br/>";
}
/**
* Protected routine to calculate and determine what the browser is in use (including platform)
*/
protected function determine() {
$this->checkPlatform();
$this->checkBrowsers();
$this->checkForAol();
}
/**
* Protected routine to determine the browser type
* @return boolean
*/
protected function checkBrowsers() {
return (
$this->checkBrowserWebTv() ||
$this->checkBrowserInternetExplorer() ||
$this->checkBrowserOpera() ||
$this->checkBrowserGaleon() ||
$this->checkBrowserNetscapeNavigator9Plus() ||
$this->checkBrowserFirefox() ||
$this->checkBrowserChrome() ||
$this->checkBrowserOmniWeb() ||
// common mobile
$this->checkBrowserAndroid() ||
$this->checkBrowseriPad() ||
$this->checkBrowseriPod() ||
$this->checkBrowseriPhone() ||
$this->checkBrowserBlackBerry() ||
$this->checkBrowserNokia() ||
// common bots
$this->checkBrowserGoogleBot() ||
$this->checkBrowserMSNBot() ||
$this->checkBrowserSlurp() ||
// WebKit base check (post mobile and others)
$this->checkBrowserSafari() ||
// everyone else
$this->checkBrowserNetPositive() ||
$this->checkBrowserFirebird() ||
$this->checkBrowserKonqueror() ||
$this->checkBrowserIcab() ||
$this->checkBrowserPhoenix() ||
$this->checkBrowserAmaya() ||
$this->checkBrowserLynx() ||
$this->checkBrowserShiretoko() ||
$this->checkBrowserIceCat() ||
$this->checkBrowserW3CValidator() ||
$this->checkBrowserMozilla() /* Mozilla is such an open standard that you must check it last */
);
}
protected function checkBrowserBlackBerry() {
if( stripos($this->_agent,'blackberry') !== false ) {
$aresult = explode("/",stristr($this->_agent,"BlackBerry"));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_BLACKBERRY;
$this->setMobile(true);
return true;
}
return false;
}
protected function checkForAol() {
$this->setAol(false);
$this->setAolVersion(self::VERSION_UNKNOWN);
if( stripos($this->_agent,'aol') !== false ) {
$aversion = explode(' ',stristr($this->_agent, 'AOL'));
$this->setAol(true);
$this->setAolVersion(preg_replace('/[^0-9\.a-z]/i', '', $aversion[1]));
return true;
}
return false;
}
protected function checkBrowserGoogleBot() {
if( stripos($this->_agent,'googlebot') !== false ) {
$aresult = explode('/',stristr($this->_agent,'googlebot'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion(str_replace(';','',$aversion[0]));
$this->_browser_name = self::BROWSER_GOOGLEBOT;
$this->setRobot(true);
return true;
}
return false;
}
protected function checkBrowserMSNBot() {
if( stripos($this->_agent,"msnbot") !== false ) {
$aresult = explode("/",stristr($this->_agent,"msnbot"));
$aversion = explode(" ",$aresult[1]);
$this->setVersion(str_replace(";","",$aversion[0]));
$this->_browser_name = self::BROWSER_MSNBOT;
$this->setRobot(true);
return true;
}
return false;
}
protected function checkBrowserW3CValidator() {
if( stripos($this->_agent,'W3C-checklink') !== false ) {
$aresult = explode('/',stristr($this->_agent,'W3C-checklink'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_W3CVALIDATOR;
return true;
}
else if( stripos($this->_agent,'W3C_Validator') !== false ) {
// Some of the Validator versions do not delineate w/ a slash - add it back in
$ua = str_replace("W3C_Validator ", "W3C_Validator/", $this->_agent);
$aresult = explode('/',stristr($ua,'W3C_Validator'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_W3CVALIDATOR;
return true;
}
return false;
}
protected function checkBrowserSlurp() {
if( stripos($this->_agent,'slurp') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Slurp'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->_browser_name = self::BROWSER_SLURP;
$this->setRobot(true);
$this->setMobile(false);
return true;
}
return false;
}
protected function checkBrowserInternetExplorer() {
// Test for v1 - v1.5 IE
if( stripos($this->_agent,'microsoft internet explorer') !== false ) {
$this->setBrowser(self::BROWSER_IE);
$this->setVersion('1.0');
$aresult = stristr($this->_agent, '/');
if( preg_match('/308|425|426|474|0b1/i', $aresult) ) {
$this->setVersion('1.5');
}
return true;
}
// Test for versions > 1.5
else if( stripos($this->_agent,'msie') !== false && stripos($this->_agent,'opera') === false ) {
// See if the browser is the odd MSN Explorer
if( stripos($this->_agent,'msnb') !== false ) {
$aresult = explode(' ',stristr(str_replace(';','; ',$this->_agent),'MSN'));
$this->setBrowser( self::BROWSER_MSN );
$this->setVersion(str_replace(array('(',')',';'),'',$aresult[1]));
return true;
}
$aresult = explode(' ',stristr(str_replace(';','; ',$this->_agent),'msie'));
$this->setBrowser( self::BROWSER_IE );
$this->setVersion(str_replace(array('(',')',';'),'',$aresult[1]));
return true;
}
// Test for Pocket IE
else if( stripos($this->_agent,'mspie') !== false || stripos($this->_agent,'pocket') !== false ) {
$aresult = explode(' ',stristr($this->_agent,'mspie'));
$this->setPlatform( self::PLATFORM_WINDOWS_CE );
$this->setBrowser( self::BROWSER_POCKET_IE );
$this->setMobile(true);
if( stripos($this->_agent,'mspie') !== false ) {
$this->setVersion($aresult[1]);
}
else {
$aversion = explode('/',$this->_agent);
$this->setVersion($aversion[1]);
}
return true;
}
return false;
}
protected function checkBrowserOpera() {
if( stripos($this->_agent,'opera mini') !== false ) {
$resultant = stristr($this->_agent, 'opera mini');
if( preg_match('/\//',$resultant) ) {
$aresult = explode('/',$resultant);
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
}
else {
$aversion = explode(' ',stristr($resultant,'opera mini'));
$this->setVersion($aversion[1]);
}
$this->_browser_name = self::BROWSER_OPERA_MINI;
$this->setMobile(true);
return true;
}
else if( stripos($this->_agent,'opera') !== false ) {
$resultant = stristr($this->_agent, 'opera');
if( preg_match('/Version\/(10.*)$/',$resultant,$matches) ) {
$this->setVersion($matches[1]);
}
else if( preg_match('/\//',$resultant) ) {
$aresult = explode('/',str_replace("("," ",$resultant));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
}
else {
$aversion = explode(' ',stristr($resultant,'opera'));
$this->setVersion(isset($aversion[1])?$aversion[1]:"");
}
$this->_browser_name = self::BROWSER_OPERA;
return true;
}
return false;
}
protected function checkBrowserChrome() {
if( stripos($this->_agent,'Chrome') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Chrome'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_CHROME);
return true;
}
return false;
}
protected function checkBrowserWebTv() {
if( stripos($this->_agent,'webtv') !== false ) {
$aresult = explode('/',stristr($this->_agent,'webtv'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_WEBTV);
return true;
}
return false;
}
protected function checkBrowserNetPositive() {
if( stripos($this->_agent,'NetPositive') !== false ) {
$aresult = explode('/',stristr($this->_agent,'NetPositive'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion(str_replace(array('(',')',';'),'',$aversion[0]));
$this->setBrowser(self::BROWSER_NETPOSITIVE);
return true;
}
return false;
}
protected function checkBrowserGaleon() {
if( stripos($this->_agent,'galeon') !== false ) {
$aresult = explode(' ',stristr($this->_agent,'galeon'));
$aversion = explode('/',$aresult[0]);
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_GALEON);
return true;
}
return false;
}
protected function checkBrowserKonqueror() {
if( stripos($this->_agent,'Konqueror') !== false ) {
$aresult = explode(' ',stristr($this->_agent,'Konqueror'));
$aversion = explode('/',$aresult[0]);
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_KONQUEROR);
return true;
}
return false;
}
protected function checkBrowserIcab() {
if( stripos($this->_agent,'icab') !== false ) {
$aversion = explode(' ',stristr(str_replace('/',' ',$this->_agent),'icab'));
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_ICAB);
return true;
}
return false;
}
protected function checkBrowserOmniWeb() {
if( stripos($this->_agent,'omniweb') !== false ) {
$aresult = explode('/',stristr($this->_agent,'omniweb'));
$aversion = explode(' ',isset($aresult[1])?$aresult[1]:"");
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_OMNIWEB);
return true;
}
return false;
}
protected function checkBrowserPhoenix() {
if( stripos($this->_agent,'Phoenix') !== false ) {
$aversion = explode('/',stristr($this->_agent,'Phoenix'));
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_PHOENIX);
return true;
}
return false;
}
protected function checkBrowserFirebird() {
if( stripos($this->_agent,'Firebird') !== false ) {
$aversion = explode('/',stristr($this->_agent,'Firebird'));
$this->setVersion($aversion[1]);
$this->setBrowser(self::BROWSER_FIREBIRD);
return true;
}
return false;
}
protected function checkBrowserNetscapeNavigator9Plus() {
if( stripos($this->_agent,'Firefox') !== false && preg_match('/Navigator\/([^ ]*)/i',$this->_agent,$matches) ) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
return true;
}
else if( stripos($this->_agent,'Firefox') === false && preg_match('/Netscape6?\/([^ ]*)/i',$this->_agent,$matches) ) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
return true;
}
return false;
}
protected function checkBrowserShiretoko() {
if( stripos($this->_agent,'Mozilla') !== false && preg_match('/Shiretoko\/([^ ]*)/i',$this->_agent,$matches) ) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_SHIRETOKO);
return true;
}
return false;
}
protected function checkBrowserIceCat() {
if( stripos($this->_agent,'Mozilla') !== false && preg_match('/IceCat\/([^ ]*)/i',$this->_agent,$matches) ) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_ICECAT);
return true;
}
return false;
}
protected function checkBrowserNokia() {
if( preg_match("/Nokia([^\/]+)\/([^ SP]+)/i",$this->_agent,$matches) ) {
$this->setVersion($matches[2]);
if( stripos($this->_agent,'Series60') !== false || strpos($this->_agent,'S60') !== false ) {
$this->setBrowser(self::BROWSER_NOKIA_S60);
}
else {
$this->setBrowser( self::BROWSER_NOKIA );
}
$this->setMobile(true);
return true;
}
return false;
}
protected function checkBrowserFirefox() {
if( stripos($this->_agent,'safari') === false ) {
if( preg_match("/Firefox[\/ \(]([^ ;\)]+)/i",$this->_agent,$matches) ) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_FIREFOX);
return true;
}
else if( preg_match("/Firefox$/i",$this->_agent,$matches) ) {
$this->setVersion("");
$this->setBrowser(self::BROWSER_FIREFOX);
return true;
}
}
return false;
}
protected function checkBrowserIceweasel() {
if( stripos($this->_agent,'Iceweasel') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Iceweasel'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_ICEWEASEL);
return true;
}
return false;
}
protected function checkBrowserMozilla() {
if( stripos($this->_agent,'mozilla') !== false && preg_match('/rv:[0-9].[0-9][a-b]?/i',$this->_agent) && stripos($this->_agent,'netscape') === false) {
$aversion = explode(' ',stristr($this->_agent,'rv:'));
preg_match('/rv:[0-9].[0-9][a-b]?/i',$this->_agent,$aversion);
$this->setVersion(str_replace('rv:','',$aversion[0]));
$this->setBrowser(self::BROWSER_MOZILLA);
return true;
}
else if( stripos($this->_agent,'mozilla') !== false && preg_match('/rv:[0-9]\.[0-9]/i',$this->_agent) && stripos($this->_agent,'netscape') === false ) {
$aversion = explode('',stristr($this->_agent,'rv:'));
$this->setVersion(str_replace('rv:','',$aversion[0]));
$this->setBrowser(self::BROWSER_MOZILLA);
return true;
}
else if( stripos($this->_agent,'mozilla') !== false && preg_match('/mozilla\/([^ ]*)/i',$this->_agent,$matches) && stripos($this->_agent,'netscape') === false ) {
$this->setVersion($matches[1]);
$this->setBrowser(self::BROWSER_MOZILLA);
return true;
}
return false;
}
protected function checkBrowserLynx() {
if( stripos($this->_agent,'lynx') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Lynx'));
$aversion = explode(' ',(isset($aresult[1])?$aresult[1]:""));
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_LYNX);
return true;
}
return false;
}
protected function checkBrowserAmaya() {
if( stripos($this->_agent,'amaya') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Amaya'));
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
$this->setBrowser(self::BROWSER_AMAYA);
return true;
}
return false;
}
protected function checkBrowserSafari() {
if( stripos($this->_agent,'Safari') !== false && stripos($this->_agent,'iPhone') === false && stripos($this->_agent,'iPod') === false ) {
$aresult = explode('/',stristr($this->_agent,'Version'));
if( isset($aresult[1]) ) {
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
}
else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setBrowser(self::BROWSER_SAFARI);
return true;
}
return false;
}
protected function checkBrowseriPhone() {
if( stripos($this->_agent,'iPhone') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Version'));
if( isset($aresult[1]) ) {
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
}
else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setMobile(true);
$this->setBrowser(self::BROWSER_IPHONE);
return true;
}
return false;
}
protected function checkBrowseriPad() {
if( stripos($this->_agent,'iPad') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Version'));
if( isset($aresult[1]) ) {
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
}
else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setMobile(true);
$this->setBrowser(self::BROWSER_IPAD);
return true;
}
return false;
}
protected function checkBrowseriPod() {
if( stripos($this->_agent,'iPod') !== false ) {
$aresult = explode('/',stristr($this->_agent,'Version'));
if( isset($aresult[1]) ) {
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
}
else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setMobile(true);
$this->setBrowser(self::BROWSER_IPOD);
return true;
}
return false;
}
protected function checkBrowserAndroid() {
if( stripos($this->_agent,'Android') !== false ) {
$aresult = explode(' ',stristr($this->_agent,'Android'));
if( isset($aresult[1]) ) {
$aversion = explode(' ',$aresult[1]);
$this->setVersion($aversion[0]);
}
else {
$this->setVersion(self::VERSION_UNKNOWN);
}
$this->setMobile(true);
$this->setBrowser(self::BROWSER_ANDROID);
return true;
}
return false;
}
/**
* Determine the user's platform
*/
protected function checkPlatform() {
if( stripos($this->_agent, 'windows') !== false ) {
$this->_platform = self::PLATFORM_WINDOWS;
}
else if( stripos($this->_agent, 'iPad') !== false ) {
$this->_platform = self::PLATFORM_IPAD;
}
else if( stripos($this->_agent, 'iPod') !== false ) {
$this->_platform = self::PLATFORM_IPOD;
}
else if( stripos($this->_agent, 'iPhone') !== false ) {
$this->_platform = self::PLATFORM_IPHONE;
}
elseif( stripos($this->_agent, 'mac') !== false ) {
$this->_platform = self::PLATFORM_APPLE;
}
elseif( stripos($this->_agent, 'android') !== false ) {
$this->_platform = self::PLATFORM_ANDROID;
}
elseif( stripos($this->_agent, 'linux') !== false ) {
$this->_platform = self::PLATFORM_LINUX;
}
else if( stripos($this->_agent, 'Nokia') !== false ) {
$this->_platform = self::PLATFORM_NOKIA;
}
else if( stripos($this->_agent, 'BlackBerry') !== false ) {
$this->_platform = self::PLATFORM_BLACKBERRY;
}
elseif( stripos($this->_agent,'FreeBSD') !== false ) {
$this->_platform = self::PLATFORM_FREEBSD;
}
elseif( stripos($this->_agent,'OpenBSD') !== false ) {
$this->_platform = self::PLATFORM_OPENBSD;
}
elseif( stripos($this->_agent,'NetBSD') !== false ) {
$this->_platform = self::PLATFORM_NETBSD;
}
elseif( stripos($this->_agent, 'OpenSolaris') !== false ) {
$this->_platform = self::PLATFORM_OPENSOLARIS;
}
elseif( stripos($this->_agent, 'SunOS') !== false ) {
$this->_platform = self::PLATFORM_SUNOS;
}
elseif( stripos($this->_agent, 'OS\/2') !== false ) {
$this->_platform = self::PLATFORM_OS2;
}
elseif( stripos($this->_agent, 'BeOS') !== false ) {
$this->_platform = self::PLATFORM_BEOS;
}
elseif( stripos($this->_agent, 'win') !== false ) {
$this->_platform = self::PLATFORM_WINDOWS;
}
}
}
?>
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
Copy this method into your class
public int getArrayIndex(int[] arr,int value) {
int k=0;
for(int i=0;i<arr.length;i++){
if(arr[i]==value){
k=i;
break;
}
}
return k;
}
Call this method with pass two perameters Array and value and store its return value in a integer variable.
int indexNum = getArrayIndex(array,value);
Thank you
If you don't really need the button element, just move the classes to a regular link:
<div class="btn-group">
<a href="/save/1" class="btn btn-primary active">
<i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
</a>
<a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>
Conversely, you can also change a button to appear like a link:
<button type="button" class="btn btn-link">Link</button>
For Radio Buttons and CheckBoxes there is nothing that comes built in.
You can implement Checkboxes easily yourself. You can set an uncheckedImage for your button for UIControlStateNormal and a checkedImage for your UIControlStateSelected. Now on tap, the button will change its image and alternate between checked and unchecked image.
To use radio buttons, you have to keep an Array
for all the buttons that you want to behave as radio buttons. Whenever a button is pressed, you need to uncheck all other buttons in the array.
For radio buttons you can use SSRadioButtonsController You can create a controller object and add buttons array to it like
var radioButtonController = SSRadioButtonsController()
radioButtonController.setButtonsArray([button1!,button2!,button3!])
The main principle is something like this here.
I know that question is a bit old but
pipenv --venv
/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
Just create a style in values/styles.xml
.
<style name="ProgressBarStyle">
<item name="colorAccent">@color/greenLight</item>
</style>
Then set this style as your ProgressBar
theme.
<ProgressBar
android:theme="@style/ProgressBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
and doesn't matter your progress bar is horizontal or circular. That's all.
In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:
print([i for i,x in enumerate(list) if len(x) != 560])
In my case, the length reference was 560.
Dim MyString As String = "Hello World"
Dim YourString As String = "Hello World"
Console.WriteLine(String.Equals(MyString, YourString))
returns a bool True. This comparison is case-sensitive.
So in your example,
if String.Equals(string1, string2) and String.Equals(string3, string4) then
' do something
else
' do something else
end if
Use the put method: https://developer.android.com/reference/org/json/JSONObject.html
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
According to this document, add the following code to onCreate
getWindow().getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION |
SYSTEM_UI_FLAG_LAYOUT_STABLE | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
Your UITableViewDelegate
should implement tableView:heightForRowAtIndexPath:
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 20;
}
Swift 5
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.row * 20
}
You will probably want to use NSString
's sizeWithFont:constrainedToSize:lineBreakMode:
method to calculate your row height rather than just performing some silly math on the indexPath :)
Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handler
argument. Observe:
func someHandler(alert: UIAlertAction!) {
// Do something...
}
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: someHandler))
I suggest to use jQuery:
$('#mydiv')
.css('cursor', 'pointer')
.click(
function(){
alert('Click event is fired');
}
)
.hover(
function(){
$(this).css('background', '#ff00ff');
},
function(){
$(this).css('background', '');
}
);
Whoa whoa whoa. Is there a specific reason you're using floating-point for currency, or would things be better off with an arbitrary-precision, fixed-point number format? I have no idea what the specific problem that you're trying to solve is, but you should think about whether or not half a cent is really something you want to work with, or if it's just an artifact of using an imprecise number format.
into ~/.bash_profile add:
export ANDROID_HOME="/path/to/android-sdk-macosx"
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"
and then execute it in terminal to take effect immediately;
into /etc/sudoers add: (you can use console: sudo visudo
)
Defaults env_keep += "ANDROID_HOME"
since the building process has to start with sudo
and Node's process.env
get the respective variables.
If you don't want to use the first option (in case the field is hidden or something) then the following jQuery code is enough:
$(document).ready(function(){_x000D_
$('#but').click(function(){_x000D_
$('#baba').val(false);_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<select id="baba">_x000D_
<option>select something</option>_x000D_
<option value="1">something 1</option>_x000D_
<option value=2">something 2</option>_x000D_
</select>_x000D_
_x000D_
<input type="button" id="but" value="click">
_x000D_
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
You could create a user form:
When you only need to check for equality, you can also simply use the in
operator to do a membership test in a sequence of accepted elements:
if message.value[0] in ('/', '\\'):
do_stuff()
As an addendum to Don's answer, not only does groovy add a .toInteger()
method to String
s, it also adds toBigDecimal()
, toBigInteger()
, toBoolean()
, toCharacter()
, toDouble()
, toFloat()
, toList()
, and toLong()
.
In the same vein, groovy also adds is*
eqivalents to all of those that return true
if the String
in question can be parsed into the format in question.
The relevant GDK page is here.
If you have used:
from datetime import datetime
Then simply write the code as:
date = datetime(int(year), int(month), 1)
But if you have used:
import datetime
then only you can write:
date = datetime.datetime(int(2005), int(5), 1)
if (row.Columns.Contains("US_OTHERFRIEND"))
as.vector(unlist(aframe['a2']))
To answer the first part of your question:
LPCSTR
is a pointer to a const string (LP means Long Pointer)
LPCTSTR
is a pointer to a const TCHAR
string, (TCHAR
being either a wide char or char depending on whether UNICODE is defined in your project)
LPTSTR
is a pointer to a (non-const) TCHAR
string
In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.
This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)
You only need a minimal change; single-quote the here-document delimiter after <<
.
cat <<'EOF' >> brightup.sh
or equivalently backslash-escape it:
cat <<\EOF >>brightup.sh
Without quoting, the here document will undergo variable substitution, backticks will be evaluated, etc, like you discovered.
If you need to expand some, but not all, values, you need to individually escape the ones you want to prevent.
cat <<EOF >>brightup.sh
#!/bin/sh
# Created on $(date # : <<-- this will be evaluated before cat;)
echo "\$HOME will not be evaluated because it is backslash-escaped"
EOF
will produce
#!/bin/sh
# Created on Fri Feb 16 11:00:18 UTC 2018
echo "$HOME will not be evaluated because it is backslash-escaped"
As suggested by @fedorqui, here is the relevant section from man bash
:
Here Documents
This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.
The format of here-documents is:
<<[-]word here-document delimiter
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence
\<newline>
is ignored, and\
must be used to quote the characters\
,$
, and`
.
"Egg" is a single-file importable distribution format for Python-related projects.
"The Quick Guide to Python Eggs" notes that "Eggs are to Pythons as Jars are to Java..."
Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.
dependencies {
compile 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.android.gms:play-services-auth:11.8.0'
compile 'com.google.android.gms:play-services-ads:11.8.0'
compile 'com.google.firebase:firebase-storage:11.8.0'
}
apply plugin: 'com.google.gms.google-services'
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.google.gms:google-services:3.1.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
there is a function called isNaN
it return true if it's (Not-a-number) , so u can check for a number this way
if(!isNaN(miscCharge))
{
//do some thing if it's a number
}else{
//do some thing if it's NOT a number
}
hope it works
mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP
They are both data formats for hierarchical data, so while the syntax is quite different, the structure is similar. Example:
JSON:
{
"persons": [
{
"name": "Ford Prefect",
"gender": "male"
},
{
"name": "Arthur Dent",
"gender": "male"
},
{
"name": "Tricia McMillan",
"gender": "female"
}
]
}
XML:
<persons>
<person>
<name>Ford Prefect</name>
<gender>male</gender>
</person>
<person>
<name>Arthur Dent</name>
<gender>male</gender>
</person>
<person>
<name>Tricia McMillan</name>
<gender>female</gender>
</person>
</persons>
The XML format is more advanced than shown by the example, though. You can for example add attributes to each element, and you can use namespaces to partition elements. There are also standards for defining the format of an XML file, the XPATH language to query XML data, and XSLT for transforming XML into presentation data.
The XML format has been around for some time, so there is a lot of software developed for it. The JSON format is quite new, so there is a lot less support for it.
While XML was developed as an independent data format, JSON was developed specifically for use with Javascript and AJAX, so the format is exactly the same as a Javascript literal object (that is, it's a subset of the Javascript code, as it for example can't contain expressions to determine values).
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
You can use the new Bootstrap cards:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Link: Click here
regards,
There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH
(260) characters.
line-height
is how you vertically align text. It is pretty standard and I don't consider it a "hack". Just add line-height: 100px
to your ul.catBlock li
and it will be fine.
In this case you may have to add it to ul.catBlock li a
instead since all of the text inside the li
is also inside of an a
. I have seen some weird things happen when you do this, so try both and see which one works.
If you want a HTML only solution, we can just use the pre
tag. It defines "preformatted text" which means that it does not format word-wrapping. Here is a quick example to explain:
div {
width: 200px;
height: 200px;
padding: 20px;
background: #adf;
}
pre {
width: 200px;
height: 200px;
padding: 20px;
font: inherit;
background: #fda;
}
_x000D_
<div>Look at this, this text is very neat, isn't it? But it's not quite what we want, though, is it? This text shouldn't be here! It should be all the way over there! What can we do?</div>
<pre>The pre tag has come to the rescue! Yay! However, we apologise in advance for any horizontal scrollbars that may be caused. If you need support, please raise a support ticket.</pre>
_x000D_
update: Just saw the reference to call_user_func_array
in your post. that's different. use getattr
to get the function object and then call it with your arguments
class A(object):
def method1(self, a, b, c):
# foo
method = A.method1
method
is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1
with one of the two decorators discussed below, pass it an instance of A
as the first argument or access the method on an instance of A
.
a = A()
method = a.method1
method(1, 2)
You have three options for doing this
A
to call method1
(using two possible forms)classmethod
decorator to method1
: you will no longer be able to reference self
in method1
but you will get passed a cls
instance in it's place which is A
in this case.staticmethod
decorator to method1
: you will no longer be able to reference self
, or cls
in staticmethod1
but you can hardcode references to A
into it, though obviously, these references will be inherited by all subclasses of A
unless they specifically override method1
and do not call super
.Some examples:
class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
def method1(self, a, b):
return a + b
@staticmethod
def method2(a, b):
return a + b
@classmethod
def method3(cls, a, b):
return cls.method2(a, b)
t = Test1() # same as doing it in another class
Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2) # form two (the common one) essentially reduces to form one
Test1.method2(1, 2) #the static method can be called with just arguments
t.method2(1, 2) # on an instance or the class
Test1.method3(1, 2) # ditto for the class method. It will have access to the class
t.method3(1, 2) # that it's called on (the subclass if called on a subclass)
# but will not have access to the instance it's called on
# (if it is called on an instance)
Note that in the same way that the name of the self
variable is entirely up to you, so is the name of the cls
variable but those are the customary values.
Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
Use !empty
instead of isset
.
isset return true for $_POST
because $_POST
array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.
All you need to do is annotate a method that returns a DataSource with @Bean. A complete working example follows.
@Bean
public DataSource dataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url(dbUrl);
dataSourceBuilder.username(username);
dataSourceBuilder.password(password);
return dataSourceBuilder.build();
}
If you don't want to use JavaCV this works for me...
Download OpenCV Android SDK from http://opencv.org/downloads.html
Copy libopencv_info.so & libopencv_java.so from
OpenCV-2.?.?-android-sdk -> sdk -> native -> libs -> armeabi-v7a
to
Project Root -> Your Project -> lib - > armeabi-v7a
Zip the lib folder up and rename that zip to whatever-v7a.jar.
Copy this .jar file and place it in here in your project
Project Root -> Your Project -> libs
Add this line to your projects build.gradle in the dependencies section
compile files('libs/whatever-v7a.jar')
When you compile now you will probably see your .apk is about 4mb bigger.
(Repeat for "armeabi" if you want to support ARMv6 too, likely not needed anymore.)
Copy the java folder from here
OpenCV-2.?.?-android-sdk -> sdk
to
Project Root -> Your Project -> libs
(Same place as your .jar file);
(You can rename the 'java' folder name to 'OpenCV')
In this freshly copied folder add a typical build.gradle file; I used this:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
apply plugin: 'android-library'
repositories {
mavenCentral();
}
android {
compileSdkVersion 19
buildToolsVersion "19"
defaultConfig {
minSdkVersion 15
targetSdkVersion 19
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
}
In your Project Root settings.gradle file change it too look something like this:
include ':Project Name:libs:OpenCV', ':Project Name'
In your Project Root -> Project Name -> build.gradle file in the dependencies section add this line:
compile project(':Project Name:libs:OpenCV')
Rebuild and you should be able to import and start using OpenCV in your project.
import org.opencv.android.OpenCVLoader;
...
if (!OpenCVLoader.initDebug()) {}
I know this if a bit of hack but I figured I would post it anyway.
If you got nothing when inputted fastboot devices
, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-').
Then you can see you devices via fastboot devices
and continue to flash your devices.
note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.
char* data;
std::string myString(data);
In case it helps, I've ran into this problem when passing null
into a parameter for a generic TValue
, to get around this you have to cast your null values:
(string)null
(int)null
etc.
Use-
<span ng-bind-html="myContent"></span>
You need to tell angular to not escape it.
Using
generates a try / finally around the object being allocated and calls Dispose()
for you.
It saves you the hassle of manually creating the try / finally block and calling Dispose()
For those of you who are setting up MSYS Git on Windows using PuTTY via the standard command prompt, the way to add a host to PuTTY's cache is to run
> plink.exe <host>
For example:
> plink.exe codebasehq.com
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 2e:db:b6:22:f7:bd:48:f6:da:72:bf:59:d7:75:d7:4e
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)
Just answer y
, and then Ctrl+C the rest.
Do check the fingerprint though. This warning is there for a good reason. Fingerprints for some git services (please edit to add more):
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
For those using NHibernate, this is a port of [ram]'s code
public static string GenerateSQL(ICriteria criteria)
{
NHibernate.Impl.CriteriaImpl criteriaImpl = (NHibernate.Impl.CriteriaImpl)criteria;
NHibernate.Engine.ISessionImplementor session = criteriaImpl.Session;
NHibernate.Engine.ISessionFactoryImplementor factory = session.Factory;
NHibernate.Loader.Criteria.CriteriaQueryTranslator translator =
new NHibernate.Loader.Criteria.CriteriaQueryTranslator(
factory,
criteriaImpl,
criteriaImpl.EntityOrClassName,
NHibernate.Loader.Criteria.CriteriaQueryTranslator.RootSqlAlias);
String[] implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName);
NHibernate.Loader.Criteria.CriteriaJoinWalker walker = new NHibernate.Loader.Criteria.CriteriaJoinWalker(
(NHibernate.Persister.Entity.IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]),
translator,
factory,
criteriaImpl,
criteriaImpl.EntityOrClassName,
session.EnabledFilters);
return walker.SqlString.ToString();
}
Please try running
brew install docker
This will install the Docker engine, which will require Docker-Machine (+ VirtualBox) to run on the Mac.
If you want to install the newer Docker for Mac, which does not require virtualbox, you can install that through Homebrew's Cask:
brew install --cask docker
open /Applications/Docker.app
This one is dirty but works :)
I will be calling main()
function from my script. Previously I just put calls to main at the end of script. However I did add some other functions and exported them from script (to use functions in some other parts of code) - but I dont want to execute main() function every time I import other functions in other scripts.
So I did this, in my script i removed call to main(), and instead at the end of script I put this check:
if (process.argv.includes('main')) {
main();
}
So when I want to call that function in CLI: node src/myScript.js main
Using iTextSharp.dll
protected void Page_Load(object sender, EventArgs e)
{
String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
}
}
Response.Write("Success");
document.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
You can use a TextBox
and set multiline
to true
and canEdit
to false
.
In my case adding this code to CSS
ul {
list-style-type: '- ';
}
was enough. Simple as it is.
try adding
<meta http-equiv="X-UA-Compatible" content="IE=edge">
right after the opening head tag
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public class MyGallery extends Activity {
private GridView gridView;
private String _location;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
private AdView mAdView;
private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
public static String[] imageFileList;
TextView gallerytxt;
public static ImageAdapter imageAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mygallery);
/*if (MenuClass.mInterstitialAd.isLoaded()) {
MenuClass.mInterstitialAd.show();
}*/
gallerytxt = (TextView) findViewById(R.id.gallerytxt);
/*gallerytxt.setTextSize(20);
int[] color = {Color.YELLOW,Color.WHITE};
float[] position = {0, 1};
Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
Shader shader_gradient0 = lin_grad0;
gallerytxt.getPaint().setShader(shader_gradient0);*/
ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MyGallery.this.finish();
}
});
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
gridView = (GridView) findViewById(R.id.gridView);
new MyGalleryAsy().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(MyGallery.this, ImageDetail.class);
intent.putExtra("ImgUrl", imageFileList[pos]);
//Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
if (ImageDetail.deleted) {
photo = new ArrayList<Bitmap>();
new MyGalleryAsy().execute();
ImageDetail.deleted = false;
}
}
public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
Bitmap mBitmap;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
dialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
readImage();
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
DisplayMetrics displayMatrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
int screenWidth = displayMatrics.widthPixels / 3;
if (photo.size() > 0) {
imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
gridView.setAdapter(imageAdapter);
}
}
}
private void readImage() {
// TODO Auto-generated method stub
try {
if (isSdPresent()) {
_location = extStorageDirectory + newFolder;
} else
_location = getFilesDir() + newFolder;
File file1 = new File(_location);
if (file1.isDirectory()) { // sdCard == true
imageFileList = file1.list();
if (imageFileList != null) {
for (int i = 0; i < imageFileList.length; i++) {
try {
photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
} catch (Exception e) {
// TODO: handle exception
//Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private int width;
private int mGalleryItemBackground;
public ImageAdapter(Context c) {
context = c;
}
public ImageAdapter(Context c, int width) {
context = c;
this.width = width;
}
public int getCount() {
return photo.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.galleryadapter, null);
RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);
ImageView imageView = new ImageView(context);
layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
imageView.setImageBitmap(photo.get(position));
return v;
}
public void updateItemList(ArrayList<Bitmap> newItemList) {
photo = newItemList;
notifyDataSetChanged();
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@color/colorPrimary"
android:minHeight="?attr/actionBarSize">
<TextView
android:id="@+id/gallerytxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:fontFamily="@string/font_fontFamily_medium"
android:text="My Gallery"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/black"
android:textStyle="bold" />
<ImageButton
android:id="@+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="@drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center|bottom"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_id" />
<GridView
android:id="@+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/adView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/relativeLayout"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:smoothScrollbar="true"
android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="@+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]
public class ImageDetail extends Activity implements OnClickListener {
public static InterstitialAd mInterstitialAd;
private ImageView mainImageView;
private LinearLayout menuTop;
private TableLayout menuBottom;
private Boolean onOff = true;
private ImageView delButton, mailButton, shareButton;
private String imgUrl = null;
private AdView mAdView;
TextView titletxt;
private String newFolder = "/IslamicGif/";
private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
public static boolean deleted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.image_detail);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
mainImageView = (ImageView) findViewById(R.id.mainImageView);
menuTop = (LinearLayout) findViewById(R.id.menuTop);
menuBottom = (TableLayout) findViewById(R.id.menuBottom);
titletxt = (TextView) findViewById(R.id.titletxt);
titletxt.setTextSize(22);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
delButton = (ImageView) findViewById(R.id.delButton);
mailButton = (ImageView) findViewById(R.id.mailButton);
shareButton = (ImageView) findViewById(R.id.shareButton);
Bundle exBundle = getIntent().getExtras();
if (exBundle != null) {
imgUrl = exBundle.getString("ImgUrl");
}
if (isSdPresent()) {
imgUrl = extStorageDirectory + newFolder + imgUrl;
} else
imgUrl = getFilesDir() + newFolder + imgUrl;
if (imgUrl != null) {
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
Glide.with(this).load(imgUrl).into(imageViewTarget);
}
delButton.setOnClickListener(this);
mailButton.setOnClickListener(this);
shareButton.setOnClickListener(this);
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.shareButton:
Image_Link();
break;
case R.id.delButton:
deleted();
break;
case R.id.mailButton:
sendemail();
break;
default:
break;
}
}
private void sendemail() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"[email protected]", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void Image_Link() {
try {
File photo = new File(imgUrl);
Uri imageuri = Uri.fromFile(photo);
String url = Constant.AppUrl;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Face Placer App Available here..Play Link");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
String[] recipients2 = new String[]{"[email protected]", "",};
emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
emailIntent2.setType("text/html");
emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
emailIntent2.setType("image/JPEG");
startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private void deleted() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
builder.setTitle(getString(R.string.removeoption));
builder.setMessage(getString(R.string.deleteimage));
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
File fileDel = new File(imgUrl);
boolean isCheck1 = fileDel.delete();
if (isCheck1) {
deleted = true;
finish();
MyGallery.imageAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
dialog.cancel();
}
});
Dialog dialog = builder.create();
dialog.show();
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
mInterstitialAd.loadAd(adRequest);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
android:orientation="vertical">
<ImageView
android:id="@+id/mainImageView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:contentDescription="@string/app_name"
android:focusable="true"
android:focusableInTouchMode="true" />
<LinearLayout
android:id="@+id/adlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:visibility="gone"></LinearLayout>
<LinearLayout
android:id="@+id/menuTop"
android:layout_width="fill_parent"
android:layout_height="56dp"
android:layout_alignWithParentIfMissing="true"
android:layout_below="@+id/adlayout"
android:background="@color/colorPrimary"
android:orientation="vertical"
android:padding="10.0dip"
android:visibility="visible">
<TextView
android:id="@+id/titletxt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Islamic Gifs"
android:textColor="#000000"
android:textSize="22sp"
android:textStyle="bold" />
</LinearLayout>
<TableLayout
android:id="@+id/menuBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"
android:padding="10.0dip"
android:stretchColumns="*"
android:visibility="visible">
<TableRow>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/mailButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="@drawable/selector_shareimage"
android:contentDescription="@string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/shareButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="@drawable/selector_shareimage_small"
android:contentDescription="@string/app_name" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/delButton"
android:layout_width="52dp"
android:layout_height="52dp"
android:background="@drawable/selector_delete"
android:contentDescription="@string/app_name" />
</LinearLayout>
</TableRow>
</TableLayout>
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/menuTop"
android:layout_centerHorizontal="true"
android:visibility="gone"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_id"></com.google.android.gms.ads.AdView>
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="@drawable/result_bt_mail_s"/>
Dont forget to add in application tag for sdk version 29 and 30 to add this line
android:requestLegacyExternalStorage="true"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
native ES6 solution:
const pos = data.findIndex(el => el.id === ID_TO_REMOVE);
if (pos >= 0)
data.splice(pos, 1);
if you know that the element is in the array for sure:
data.splice(data.findIndex(el => el.id === ID_TO_REMOVE), 1);
prototype:
Array.prototype.removeByProp = function(prop,val) {
const pos = this.findIndex(x => x[prop] === val);
if (pos >= 0)
return this.splice(pos, 1);
};
// usage:
ar.removeByProp('id', ID_TO_REMOVE);
http://jsfiddle.net/oriadam/72kgprw5/
note: this removes the item in-place. if you need a new array use filter
as mentioned in previous answers.