To format code in-line within your text, use the '`' character to surround your code. Usually located to the left of the '1' key on your keyboard.
Example:
`printf("Hello World");`
Same delimiter as Stack Exchange!
I was trying to achieve the exact opposite when I bumped on this thread. I know it's quite old, but here's my solution nonetheless. You can use blocks, see here. In this case, compile the following code (with the right imports):
> String s = "äêìóblah";
> Pattern p = Pattern.compile("[\\p{InLatin-1Supplement}]+"); // this regex uses a block
> Matcher m = p.matcher(s);
> System.out.println(m.find());
> System.out.println(s.replaceAll(p.pattern(), "#"));
You should see the following output:
true
#blah
Best,
use arrayOf, arrayOfNulls, emptyArray
var colors_1: Array<String> = arrayOf("green", "red", "blue")
var colors_2: Array<String?> = arrayOfNulls(3)
var colors_3: Array<String> = emptyArray()
jQuery's attr
method returns the value of the attribute:
The
.attr()
method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's.each()
or.map()
method.
All you need is:
$('html').attr('lang') == 'fr-FR'
However, you might want to do a case-insensitive match:
$('html').attr('lang').toLowerCase() === 'fr-fr'
jQuery's val
method returns the value of a form element.
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case of<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option; if no option is selected, it returnsnull
.
I added $(inherited) but my project was still not compiling. For me problem was flag "Build for active Architecture only", I had to set it to YES.
This is caused by IPV6. Here is how you make MYSQL not use it. (so, without disabling IPV6)
edit mysql file 'my.ini'
under [wampmysqld]
or [mysqld]
add the following:
bind-address = ::
Save file and restart mysql service
enjoy!
On PostgreSQL (and many other RDBMS), you can do it with regular ALTER TABLE
statement:
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
I solved it myself for the time being. The original value has only 2 sub-properties. I reformed a new object with the properties from a
and then assigned it to b
. Now my event handler updates only b
, and my original a
stays as it is.
var a = { key1: 'value1', key2: 'value2' },
b = a;
$('#revert').on('click', function(e){
//FAIL!
b = a;
//WIN
b = { key1: a.key1, key2: a.key2 };
});
This works fine. I have not changed a single line anywhere in my code except for the above, and it works just how I wanted it to. So, trust me, nothing else was updating a
.
The simplest way I found was to override default_msec_format:
formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'
This solution allows you to add space in-between the images as well. It combines the best parts of all the existing solutions and doesn't add any ugly table borders.
<p align="center">
<img alt="Light" src="https://...light.png" width="45%">
<img alt="Dark" src="https://...dark.png" width="45%">
</p>
The key is adding the
non-breaking space HTML entities, which you can add and remove in order to customize the spacing.
You can see this example live on GitHub here.
you can easily do it with parseInt with format parameter.
Integer.parseInt("-FF", 16) ; // returns -255
I had files with the same name in different folders which caused this error.
So left div style depends on the presence of right div. I can't think of a CSS selector allowing that kind of behavior yet.
Thus it seems to me that you'll need to programmatically add a class server side (or in JS) on parent div or left div to do that.
<div id="parent twocols">
<div class="left"></div>
<div class="right"></div>
</div>
or
<div id="parent">
<div class="left"></div>
</div>
So right style is always :
.right {
float: right;
width: 200px; /* or whatever value you need */
/* margin and padding at your discretion */
}
and left style is :
.parent.twocols .left {
margin-right: 200px; /* according to right div width + margin + padding*/
}
SQLDeveloper can do this.
The __doPostBack()
method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.
var button = document.getElementById(/* button client id */);
button.click();
The simplest answer is what Paul H said:
d = []
for p in game.players.passing():
d.append(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
pd.DataFrame(d)
But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do it.
d = pd.DataFrame()
for p in game.players.passing():
temp = pd.DataFrame(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
d = pd.concat([d, temp])
I had the same problem and my problem had nothing to do with paths. One of my dll-s was written in c++ and it turnes out that if your visual studio doesn't know how to open a dll file it will say that it did not find it. What i did was locate which dll it did not find, than searched for that dll in my directories and opened it in a separate visual studio window. When trying to navigate through Solution explorer of that project, visual studio said that it cannot show what is inside and that i need some extra extensions, so that it can open those files. Surely enough, after installing the recomended extension (in my case something to do with c++) the
"This application has failed to start because xxx.dll was not found."
error miraculously dissapeared.
Generetic Action Sheet working for Swift 4, 4.2, 5
If you like a generic version that you can call from every ViewController
and in every project try this one:
class Alerts {
static func showActionsheet(viewController: UIViewController, title: String, message: String, actions: [(String, UIAlertActionStyle)], completion: @escaping (_ index: Int) -> Void) {
let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for (index, (title, style)) in actions.enumerated() {
let alertAction = UIAlertAction(title: title, style: style) { (_) in
completion(index)
}
alertViewController.addAction(alertAction)
}
viewController.present(alertViewController, animated: true, completion: nil)
}
}
Call like this in your ViewController.
var actions: [(String, UIAlertActionStyle)] = []
actions.append(("Action 1", UIAlertActionStyle.default))
actions.append(("Action 2", UIAlertActionStyle.destructive))
actions.append(("Action 3", UIAlertActionStyle.cancel))
//self = ViewController
Alerts.showActionsheet(viewController: self, title: "D_My ActionTitle", message: "General Message in Action Sheet", actions: actions) { (index) in
print("call action \(index)")
/*
results
call action 0
call action 1
call action 2
*/
}
Attention: Maybe you're wondering why I add Action 1/2/3
but got results like 0,1,2. In the line for (index, (title, style)) in actions.enumerated()
I get the index of actions. Arrays always begin with the index 0. So the completion is 0,1,2.
If you like to set a enum, an id or another identifier I would recommend to hand over an object in parameter actions
.
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
You must also have the following imports in order to import the DLL
using System.Runtime.InteropServices;
using System.Diagnostics;
Resolved this warning by setting attribute android:contentDescription
for my ImageView
android:contentDescription="@string/desc"
Android Lint support in ADT 16 throws this warning to ensure that image widgets provide a contentDescription.
This defines text that briefly describes content of the view. This property is used primarily for accessibility. Since some views do not have textual representation this attribute can be used for providing such.
Non-textual widgets like ImageViews and ImageButtons should use the contentDescription attribute to specify a textual description of the widget such that screen readers and other accessibility tools can adequately describe the user interface.
For IE: window.close();
and self.close();
should work fine.
If you want just open the IE browser and type
javascript:self.close()
and hit enter, it should ask you for a prompt.
Note: this method doesn't work for Chrome or Firefox.
In my case, for some reason(s) I need to check all the network involved information in each container. So the following commands must be valid in a container...
ip
route
netstat
ps
...
I checked through all these answers, none were helpful for me. I’ve searched information in other websites. I won’t add a super link here, since it’s not written in English. So I just put up this post with a summary solution for people who have the same requirements as me.
Say you have one running container named light-test. Follow the steps below.
docker inspect light-test -f {{.NetworkSettings.SandboxKey}}
. This command will get reply like /var/run/docker/netns/xxxx
.ln -s /var/run/docker/netns/xxxx /var/run/netns/xxxx
. The directory may not exist, do mkdir /var/run/netns
first.ip netns exec xxxx ip addr show
to explore network world in container. PS. xxxx
is always the same value received from the first command. And of course, any other commands are valid, i.e. ip netns exec xxxx netstat -antp|grep 8080
.
I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.
So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd
sample - with complete error checking of every runtime API call:
// (... prepare host-side buffers here ...)
auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);
cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);
// (... prepare a launch configuration here... )
cuda::launch(vectorAdd, launch_config,
d_A.get(), d_B.get(), d_C.get(), numElements
);
cuda::memory::copy(h_C.get(), d_C.get(), size);
// (... verify results here...)
Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none()
command).
The code above uses my
Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)
Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.
A few links to how CUDA errors are automagically checked with these wrappers:
Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.
This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input:
N = n_neurons * ( n_inputs + 1)
.
I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.
According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.
According to their documentation, here's what you would send:
http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>
And here's what you would receive back:
<?xml version="1.0"?>
<CityStateLookupResponse>
<ZipCode ID="0">
<Zip5>90210</Zip5>
<City>BEVERLY HILLS</City>
<State>CA</State>
</ZipCode>
</CityStateLookupResponse>
USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.
Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here
This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:
GET http://ziptasticapi.com/48867
And they will return a JSON object along the lines of:
{"country": "US", "state": "MI", "city": "OWOSSO"}
Indeed, it works. You can test this from a command line by doing something like:
curl http://ziptasticapi.com/48867
If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):
# 1) Get back to the main body page
driver.switch_to.default_content()
# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js:
# 3) Read the jquery from a file
jquery = jquery_js.read()
# 4) Load jquery lib
driver.execute_script(jquery)
# 5) Execute your command
driver.execute_script('$("#myId").click()')
I had to be logged into Ubuntu as root in order to access Mariadb as root. It may have something to do with that "Harden ..." that it prompts you to do when you first install. So:
$ sudo su
[sudo] password for user: yourubunturootpassword
# mysql -r root -p
Enter password: yourmariadbrootpassword
and you're in.
Starting
start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)
Stopping
stop-dfs.sh
stop-mapred.sh
I wasn't completely happy by the --allow-file-access-from-files
solution, because I'm using Chrome as my primary browser, and wasn't really happy with this breach I was opening.
Now I'm using Canary ( the chrome beta version ) for my development with the flag on. And the mere Chrome version for my real blogging : the two browser don't share the flag !
According to size_t description on en.cppreference.com size_t
is defined in the following headers :
std::size_t
...
Defined in header <cstddef>
Defined in header <cstdio>
Defined in header <cstring>
Defined in header <ctime>
Defined in header <cwchar>
Use a seperate column to indicate the join condition
SELECT t.importid,
case
when t.importid = g.home
then 'home'
else 'away'
end as join_condition,
g.network,
g.date_start
FROM game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC
LIMIT 7
The other answers are right. Assuming your examples reflect the full range of possibilities what you want is DECIMAL(3, 1)
. Or, DECIMAL(14, 1)
will allow a total of 14 digits. It's your job to think about what's enough.
I'd just make a small change to @NoDisplayName's answer and use QUOTENAME()
on the TABLE_NAME
column and also include the TABLE_SCHEMA
column encase the tables aren't in the dbo
schema.
DECLARE @sql nvarchar(max) = '';
SELECT @sql += 'DROP TABLE ' + QUOTENAME([TABLE_SCHEMA]) + '.' + QUOTENAME([TABLE_NAME]) + ';'
FROM [INFORMATION_SCHEMA].[TABLES]
WHERE [TABLE_TYPE] = 'BASE TABLE';
EXEC SP_EXECUTESQL @sql;
Or using sys
schema views (as per @swasheck's comment):
DECLARE @sql nvarchar(max) = '';
SELECT @sql += 'DROP TABLE ' + QUOTENAME([S].[name]) + '.' + QUOTENAME([T].[name]) + ';'
FROM [sys].[tables] AS [T]
INNER JOIN [sys].[schemas] AS [S] ON ([T].[schema_id] = [S].[schema_id])
WHERE [T].[type] = 'U' AND [T].[is_ms_shipped] = 0;
EXEC SP_EXECUTESQL @sql;
If you have the GitHub for Windows application, you can delete a file in 5 easy steps:
Better and clean example using JS only
Reference: TheDeveloperBlog.com
Step 1 - Create your java script and place it in your HTML page.
<script type="text/javascript">
function ShowLoading(e) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = 'loading_bar.GIF';
div.innerHTML = "Loading...<br />";
div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
div.appendChild(img);
document.body.appendChild(div);
return true;
// These 2 lines cancel form submission, so only use if needed.
//window.event.cancelBubble = true;
//e.stopPropagation();
}
</script>
in your form call the java script function on submit event.
<form runat="server" onsubmit="ShowLoading()">
</form>
Soon after you submit the form, it will show you the loading image.
I found the solutions here when the Stream is created of list or array (and you know the size). But what if Stream is with unknown size? In this case try this variant:
public class WithIndex<T> {
private int index;
private T value;
WithIndex(int index, T value) {
this.index = index;
this.value = value;
}
public int index() {
return index;
}
public T value() {
return value;
}
@Override
public String toString() {
return value + "(" + index + ")";
}
public static <T> Function<T, WithIndex<T>> indexed() {
return new Function<T, WithIndex<T>>() {
int index = 0;
@Override
public WithIndex<T> apply(T t) {
return new WithIndex<>(index++, t);
}
};
}
}
Usage:
public static void main(String[] args) {
Stream<String> stream = Stream.of("a", "b", "c", "d", "e");
stream.map(WithIndex.indexed()).forEachOrdered(e -> {
System.out.println(e.index() + " -> " + e.value());
});
}
Upgrade your Gradle Plugin
com.android.tools.build:gradle:3.1.4
Upgrade gradle wraperpropeties
distributionUrl=https://services.gradle.org/distributions/gradle-4.4-all.zip
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.
var data=[{'com':'something'},{'com':'some other thing'}];
$.each(data, function() {
$.each(this, function(key, val){
alert(val);//here data
alert (key); //here key
});
});
Nothing worked for me until I finally found the answer here: http://ptspts.blogspot.co.il/2011/10/how-to-fix-adb-no-permissions-error-on.html
I'm copying the text here in case it disappears in the future.
Create a file named /tmp/android.rules with the following contents (hex vendor numbers were taken from the vendor list page):
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0e79", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0502", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0b05", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="413c", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0489", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="091e", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="12d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="24e3", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2116", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0482", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="17ef", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1004", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="22b8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0409", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2080", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0955", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2257", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="10a9", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1d4d", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0471", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04da", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="05c6", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1f53", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04e8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04dd", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0fce", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0930", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="19d2", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1bbb", MODE="0666"
Run the following commands:
sudo cp /tmp/android.rules /etc/udev/rules.d/51-android.rules
sudo chmod 644 /etc/udev/rules.d/51-android.rules
sudo chown root. /etc/udev/rules.d/51-android.rules
sudo service udev restart
sudo killall adb
Disconnect the USB cable between the phone and the computer.
Reconnect the phone.
Run adb devices
to confirm that now it has permission to access the phone.
Please note that it's possible to use , USER="$LOGINNAME"
instead of , MODE="0666"
in the .rules
file, substituting $LOGINNAME
for your login name, i.e. what id -nu
prints.
In some cases it can be necessary to give the udev rules file a name that sorts close to the end, such as z51-android.rules
.
Try creating a symlink, make sure you have openssl installed in /usr/local/include
first.
ln -s /usr/local/Cellar/openssl/{version}/include/openssl /usr/local/include/openssl
More info at Openssl with El Capitan.
In your father component <Father />
, you could create an initial state where you track each child (using and id for instance), assigning a boolean value, which means render or not:
getInitialState() {
let state = {};
React.Children.forEach(this.props.children, (child, index) => {
state[index] = false;
});
return state;
}
Then, when the component is mounted, you start your timers to change the state:
componentDidMount() {
this.timeouts = React.Children.forEach(this.props.children, (child, index) => {
return setTimeout(() => {
this.setState({ index: true; });
}, child.props.delay);
});
}
When you render your children, you do it by recreating them, assigning as a prop the state for the matching child that says if the component must be rendered or not.
let children = React.Children.map(this.props.children, (child, index) => {
return React.cloneElement(child, {doRender: this.state[index]});
});
So in your <Child />
component
render() {
if (!this.props.render) return null;
// Render method here
}
When the timeout is fired, the state is changed and the father component is rerendered. The children props are updated, and if doRender
is true
, they will render themselves.
For those who wonder why you want to use an EditoFor if you don`t want it to be editable, I have an example.
I have this in my Model.
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
public DateTime issueDate { get; set; }
and when you want to display that format, the only way it works is with an EditorFor, but I have a jquery datepicker for that "input" so it has to be readonly to avoid the users of writting down wrong dates.
To make it work the way I want I put this in the View...
@Html.EditorFor(m => m.issueDate, new{ @class="inp", @style="width:200px", @MaxLength = "200"})
and this in my ready function...
$('#issueDate').prop('readOnly', true);
I hope this would be helpful for someone out there. Sorry for my English
You can try
$sudo service network-manager restart
Worked for me.
To keep this question current it is worth highlighting that AssemblyInformationalVersion
is used by NuGet and reflects the package version including any pre-release suffix.
For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli
dotnet pack --version-suffix ci-7 src/MyProject
Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:
CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);
0..($letters.count-1) | foreach { "Value: {0}, Index: {1}" -f $letters[$_],$_}
Thought I would add an answer to this one, since my problem was simple but hard to notice. In particular I had copy/pasted an existing meta-data element when creating my com.google.firebase.messaging.default_notification_icon
, which used an android:value
tag to specify its value. This will not work for the notification icon, and once I changed it to android:resource
everything worked as expected.
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");
in our use we have to capture with host x.x.x.x. or (vlan and host x.x.x.x)
anything less will not capture? I am not sure why but that is the way it works!
I would like to suggest yet another alternative that I find the cleanest, but it requires react-redux
or something simular - also I'm using a few other fancy features along the way:
// actions.js
export const someAction = (items) => ({
type: 'SOME_ACTION',
payload: {items},
});
// Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction}) => (<div
onClick={boundSomeAction}
/>);
const mapState = ({otherReducer: {items}}) => ({
items,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => mappedDispatches.someAction(mappedState.items),
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
// (with other mapped state or dispatches) Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction, otherAction, otherMappedState}) => (<div
onClick={boundSomeAction}
onSomeOtherEvent={otherAction}
>
{JSON.stringify(otherMappedState)}
</div>);
const mapState = ({otherReducer: {items}, otherMappedState}) => ({
items,
otherMappedState,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
otherAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
const {items, ...remainingMappedState} = mappedState;
const {someAction, ...remainingMappedDispatch} = mappedDispatch;
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => someAction(items),
...remainingMappedState,
...remainingMappedDispatch,
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
If you want to reuse this you'll have to extract the specific mapState
, mapDispatch
and mergeProps
into functions to reuse elsewhere, but this makes dependencies perfectly clear.
On Windows/Linux press Alt+F3.
This worked for me on Ubuntu. I changed it in my "Key-Bindings:User" to something that I liked better though.
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
I've found none of the suggestions to really work. Here's a more robust one that normalizes spacing when finding classes.
//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
function normalize(str) {
if (!str) return '';
str = String(str).replace(/\s*([>~+])\s*/g, ' $1 '); //Normalize symbol spacing.
return str.replace(/(\s+)/g, ' ').trim(); //Normalize whitespace
}
function split(str, on) { //Split, Trim, and remove empty elements
return str.split(on).map(x => x.trim()).filter(x => x);
}
function containsAny(selText, ors) {
return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
}
return function (selector) {
const logicalORs = split(normalize(selector), ',');
const sheets = Array.from(window.document.styleSheets);
const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
};
})();
Here's it in action from the Chrome console.
If you need the component to remain loaded but hidden you can set the opacity to 0. (I needed this for expo camera for instance)
//in constructor
this.state = {opacity: 100}
/in component
style = {{opacity: this.state.opacity}}
//when you want to hide
this.setState({opacity: 0})
This function worked perfectly for me. It detects Edge as well.
Originally from this Codepen:
https://codepen.io/gapcode/pen/vEJNZN
/**
* detect IE
* returns version of IE or false, if browser is not Internet Explorer
*/
function detectIE() {
var ua = window.navigator.userAgent;
// Test values; Uncomment to check result …
// IE 10
// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11
// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// Edge 12 (Spartan)
// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
// Edge 13
// ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
Then you can use if (detectIE()) { /* do IE stuff */ }
in your code.
In this code, you pass a text to Form2. Form2 shows that text in textBox1. User types new text into textBox1 and presses the submit button. Form1 grabs that text and shows it in a textbox on Form1.
public class Form2 : Form
{
private string oldText;
public Form2(string newText):this()
{
oldText = newText;
btnSubmit.DialogResult = DialogResult.OK;
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = oldText;
}
public string getText()
{
return textBox1.Text;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
}
And this is Form1 code:
public class Form1:Form
{
using (Form2 dialogForm = new Form2("old text to show in Form2"))
{
DialogResult dr = dialogForm.ShowDialog(this);
if (dr == DialogResult.OK)
{
tbSubmittedText = dialogForm.getText();
}
dialogForm.Close();
}
}
This is a feature, not a bug.
See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.
None of the above worked for me, the only one working was
insert into tableName
select 11, 'BALOO' from sysibm.sysdummy1 union all
select 22, nullif('','') AS nullColumn from sysibm.sysdummy1
The nullif is used since it is not possible to pass null in the select statement otherwise.
Met this problem when I created a branch based on branch A by
git checkout -b a
and then I set the up stream of branch a to origin branch B by
git branch -u origin/B
Then I got the error message above.
One way to solve this problem for me was,
git checkout -b b origin/B
If you are passing data to a DOM element from the server, you should set the data on the element:
<a id="foo" data-foo="bar" href="#">foo!</a>
The data can then be accessed using .data()
in jQuery:
console.log( $('#foo').data('foo') );
//outputs "bar"
However when you store data on a DOM node in jQuery using data, the variables are stored on the node object. This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.
Continuing my example from above:$('#foo').data('foo', 'baz');
console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the attribute was never changed
console.log( $('#foo').data('foo') );
//outputs "baz" as the value has been updated on the object
Also, the naming convention for data attributes has a bit of a hidden "gotcha":
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
The hyphenated key will still work:
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('foo-bar-baz') );
//still outputs "fizz-buzz"
However the object returned by .data()
will not have the hyphenated key set:
$('#bar').data().fooBarBaz; //works
$('#bar').data()['fooBarBaz']; //works
$('#bar').data()['foo-bar-baz']; //does not work
It's for this reason I suggest avoiding the hyphenated key in javascript.
For HTML, keep using the hyphenated form. HTML attributes are supposed to get ASCII-lowercased automatically, so <div data-foobar></div>
, <DIV DATA-FOOBAR></DIV>
, and <dIv DaTa-FoObAr></DiV>
are supposed to be treated as identical, but for the best compatibility the lower case form should be preferred.
The .data()
method will also perform some basic auto-casting if the value matches a recognized pattern:
<a id="foo"
href="#"
data-str="bar"
data-bool="true"
data-num="15"
data-json='{"fizz":["buzz"]}'>foo!</a>
JS:
$('#foo').data('str'); //`"bar"`
$('#foo').data('bool'); //`true`
$('#foo').data('num'); //`15`
$('#foo').data('json'); //`{fizz:['buzz']}`
This auto-casting ability is very convenient for instantiating widgets & plugins:
$('.widget').each(function () {
$(this).widget($(this).data());
//-or-
$(this).widget($(this).data('widget'));
});
If you absolutely must have the original value as a string, then you'll need to use .attr()
:
<a id="foo" href="#" data-color="ABC123"></a>
<a id="bar" href="#" data-color="654321"></a>
JS:
$('#foo').data('color').length; //6
$('#bar').data('color').length; //undefined, length isn't a property of numbers
$('#foo').attr('data-color').length; //6
$('#bar').attr('data-color').length; //6
This was a contrived example. For storing color values, I used to use numeric hex notation (i.e. 0xABC123), but it's worth noting that hex was parsed incorrectly in jQuery versions before 1.7.2, and is no longer parsed into a Number
as of jQuery 1.8 rc 1.
jQuery 1.8 rc 1 changed the behavior of auto-casting. Before, any format that was a valid representation of a Number
would be cast to Number
. Now, values that are numeric are only auto-cast if their representation stays the same. This is best illustrated with an example.
<a id="foo"
href="#"
data-int="1000"
data-decimal="1000.00"
data-scientific="1e3"
data-hex="0x03e8">foo!</a>
JS:
// pre 1.8 post 1.8
$('#foo').data('int'); // 1000 1000
$('#foo').data('decimal'); // 1000 "1000.00"
$('#foo').data('scientific'); // 1000 "1e3"
$('#foo').data('hex'); // 1000 "0x03e8"
If you plan on using alternative numeric syntaxes to access numeric values, be sure to cast the value to a Number
first, such as with a unary +
operator.
+$('#foo').data('hex'); // 1000
Step-by-step:
[newline]ab
ab
[backspace]si
asi
[carriage-return]ha
hai
Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.
By declaring it global
inside the function that accesses it:
g_c = 0
class TestClass():
def run(self):
global g_c
for i in range(10):
g_c = 1
print(g_c)
The Python documentation says this, about the global
statement:
The global statement is a declaration which holds for the entire current code block.
As mentioned above several times, it's not possible to catch a StackOverflowException that was raised by the System due to corrupted process-state. But there's a way to notice the exception as an event:
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspxStarting with the .NET Framework version 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.
Nevertheless your application will terminate after exiting the event-function (a VERY dirty workaround, was to restart the app within this event haha, havn't done so and never will do). But it's good enough for logging!
In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads.
Sorry I know this is an old one but still felt like helping out ^_^
Maybe it's the way I read this but assuming the excel sheet 1 is called "London" and has this information; B5="Marleybone" B6="Paddington" B7="Victoria" B8="Hammersmith". And the excel sheet 2 is called "Nottingham" and has this information; C5="Alverton" C6="Annesley" C7="Arnold" C8="Askham". Then I think this code below would work. ^_^
$xlCellTypeLastCell = 11
$startRow = 5
$excel = new-object -com excel.application
$wb = $excel.workbooks.open("C:\users\administrator\my_test.xls")
for ($i = 1; $i -le $wb.sheets.count; $i++)
{
$sh = $wb.Sheets.Item($i)
$endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$col = $col + $i - 1
$city = $wb.Sheets.Item($i).name
$rangeAddress = $sh.Cells.Item($startRow, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
$sh.Range($rangeAddress).Value2 | foreach{
New-Object PSObject -Property @{City = $city; Area=$_}
}
}
$excel.Workbooks.Close()
This should be the output (without the commas):
City, Area
---- ----
London, Marleybone
London, Paddington
London, Victoria
London, Hammersmith
Nottingham, Alverton
Nottingham, Annesley
Nottingham, Arnold
Nottingham, Askham
As your query string is a literal, and assuming your dates are properly stored as DATE
you should use date literals:
SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'
If you want to use TO_DATE
(because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:
SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
'NLS_DATE_LANGUAGE = American');
before you send the email you can press <ESC> f
(Escape followed by f) to change the From:
Address.
Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!
Ideally insertAfter
should work similar to insertBefore. The code below will perform the following:
Node
is appendedNode
, the new Node
is appendedNode
after the reference Node
, the new Node
is appendedNode
has a sibling after, then the new Node
is inserted before that siblingNode
Extending Node
Node.prototype.insertAfter = function(node, referenceNode) {
if (node)
this.insertBefore(node, referenceNode && referenceNode.nextSibling);
return node;
};
One common example
node.parentNode.insertAfter(newNode, node);
See the code running
// First extend_x000D_
Node.prototype.insertAfter = function(node, referenceNode) {_x000D_
_x000D_
if (node)_x000D_
this.insertBefore(node, referenceNode && referenceNode.nextSibling);_x000D_
_x000D_
return node;_x000D_
};_x000D_
_x000D_
var referenceNode,_x000D_
newNode;_x000D_
_x000D_
newNode = document.createElement('li')_x000D_
newNode.innerText = 'First new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
document.getElementById('no-children').insertAfter(newNode);_x000D_
_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Second new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
document.getElementById('no-reference-node').insertAfter(newNode);_x000D_
_x000D_
referenceNode = document.getElementById('no-sibling-after');_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Third new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
referenceNode.parentNode.insertAfter(newNode, referenceNode);_x000D_
_x000D_
referenceNode = document.getElementById('sibling-after');_x000D_
newNode = document.createElement('li');_x000D_
newNode.innerText = 'Fourth new item';_x000D_
newNode.style.color = '#FF0000';_x000D_
_x000D_
referenceNode.parentNode.insertAfter(newNode, referenceNode);
_x000D_
<h5>No children</h5>_x000D_
<ul id="no-children"></ul>_x000D_
_x000D_
<h5>No reference node</h5>_x000D_
<ul id="no-reference-node">_x000D_
<li>First item</li>_x000D_
</ul>_x000D_
_x000D_
<h5>No sibling after</h5>_x000D_
<ul>_x000D_
<li id="no-sibling-after">First item</li>_x000D_
</ul>_x000D_
_x000D_
<h5>Sibling after</h5>_x000D_
<ul>_x000D_
<li id="sibling-after">First item</li>_x000D_
<li>Third item</li>_x000D_
</ul>
_x000D_
Here's a more flexible way to make a sequence unique with a custom matching function.
extension Sequence where Iterator.Element: Hashable {
func unique(matching: (Iterator.Element, Iterator.Element) -> Bool) -> [Iterator.Element] {
var uniqueArray: [Iterator.Element] = []
forEach { element in
let isUnique = uniqueArray.reduce(true, { (result, item) -> Bool in
return result && matching(element, item)
})
if isUnique {
uniqueArray.append(element)
}
}
return uniqueArray
}
}
I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B
and /C
options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1
@S.Lott
The following code processes lines one at a time and produces a result that isn't memory eager:
filename = 'english names.txt'
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in)
lines = (line for line in lines if line)
the_strange_sum = 0
for l in lines:
the_strange_sum += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(l[0])
print the_strange_sum
So the generator (line.rstrip() for line in f_in) is quite the same acceptable than the nonblank_lines() function.
Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:
If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.
In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.
AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.
If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.
Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.
Another option:
$("<p>").html(myContent).text();
Use FastImage - it'll grab the minimum required data from the URL to determine if it's an image, what type of image and what size.
In my limited experience with the following details.throws is a declaration that declares multiple exceptions that may occur but do not necessarily occur, throw is an action that can throw only one exception, typically a non-runtime exception, try catch is a block that catches exceptions that can be handled when an exception occurs in a method,this exception can be thrown.An exception can be understood as a responsibility that should be taken care of by the behavior that caused the exception, rather than by its upper callers. I hope my answer will help you
I had the same problem in Pre Lollipop devices. To solve that I did as follows. Meantime I was using multiDex in the project.
1. add this for build.gradle in module: app
multiDexEnabled = true
dexOptions {
javaMaxHeapSize "4g"
}
2. add this dependancy
compile 'com.android.support:multidex:1.0.1'
3.Then in the MainApplication
public class MainApplication extends MultiDexApplication {
private static MainApplication mainApplication;
@Override
public void onCreate() {
super.onCreate();
mainApplication = this;
}
@Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
public static synchronized MainApplication getInstance() {
return mainApplication;
}
}
4.In the manifests file
<application
android:allowBackup="true"
android:name="android.support.multidex.MultiDexApplication"
This works for me. Hope this Helps you too :)
ps ax | grep tmux
17685 pts/22 S+ 0:00 tmux a -t 13g2
17920 pts/11 S+ 0:00 tmux a -t 13g2
18065 pts/19 S+ 0:00 grep tmux
kill the other one.
Edit:
Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs
See the working example: http://jsfiddle.net/U6aKT/
<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>
As I can see, you are comparing the message with the empty string using ==.
Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.
I hope, it will help you. If any problem, then please revert.
Nikhil Pahariya
I faced the same problem. There are two types of permissions in Android:
Normal permissions are automatically approved by Android while dangerous permissions need to be approved by Android users.
Here is the strategy to get dangerous permissions in Android 6.0
Here is my case: I need to write to external storage.
First, I check if I have the permission:
...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(parentActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
Then check the user's approval:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
You can read more about the new permission model here: https://developer.android.com/training/permissions/requesting.html
This error was caused, for me, by different circumstances. A downloaded project tutorial had a default setting of [Project]>Targets>Build Settings>Architectures>Build Active Architecture Only>Release = "Yes." I wasn't intending to build a release, so the solution was to set Release (which presumably requires not just a developer profile but distribution profile) to "No."
select count(*) from
(
SELECT distinct column1,column2,column3,column4 FROM abcd
) T
This will give count of distinct group of columns.
Css is going to work in same manner i assume.
You can center the content with something like this :
.center{
text-align:center;
}
Update
To adjust the width in proper manner, modify your DOM as below :
<div class="item-input-inset">
<label class="item-input-wrapper"> Date
<input type="text" placeholder="Text Area" />
</label>
</div>
<div class="item-input-inset">
<label class="item-input-wrapper"> Suburb
<input type="text" placeholder="Text Area" />
</label>
</div>
CSS
label {
display:inline-block;
border:1px solid red;
width:100%;
font-weight:bold;
}
input{
float:right; /* shift to right for alignment*/
width:80% /* set a width, you can use max-width to limit this as well*/
}
final update
If you don't plan to modify existing HTML (one in your question originally), below css would make me your best friend!! :)
html, body, .con {
height:100%;
margin:0;
padding:0;
}
.item-input-inset {
display:inline-block;
width:100%;
font-weight:bold;
}
.item-input-inset > h4 {
float:left;
margin-top:0;/* important alignment */
width:15%;
}
.item-input-wrapper {
display:block;
float:right;
width:85%;
}
input {
width:100%;
}
You can use a heredoc to do this e.g.
ftp -n $Server <<End-Of-Session
# -n option disables auto-logon
user anonymous "$Password"
binary
cd $Directory
put "$Filename.lsm"
put "$Filename.tar.gz"
bye
End-Of-Session
so the ftp process is fed on stdin with everything up to End-Of-Session
. A useful tip for spawning any process, not just ftp! Note that this saves spawning a separate process (echo, cat etc.). Not a major resource saving, but worth bearing in mind.
from within the git bash shell type:
>cd /bin
>ls -l
You will then see a long listing of all the unix-like commands available. There are lots of goodies in there.
File | Settings | Editor --> Use soft wraps in editor
: to turn them on for all files by default.
File | Settings | Code Style | General --> Wrap when typing reaches right margin
.. but that's different (it will make new line).
If the datetime is in field (not a formula) then you can format it:
If the datetime is in a formula:
ToText({MyDate}, "dd-MMM-yyyy")
//Displays 31-Jan-2010
or
ToText({MyDate}, "dd-MM-yyyy")
//Displays 31-01-2010
or
ToText({MyDate}, "dd-MM-yy")
//Displays 31-01-10
etc...
Nowadays, we could use some flexbox to align those divs.
.container {_x000D_
display: flex;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>_x000D_
<span>source list</span>_x000D_
<select size="10">_x000D_
<option />_x000D_
<option />_x000D_
<option />_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<span>destination list</span>_x000D_
<select size="10">_x000D_
<option />_x000D_
<option />_x000D_
<option />_x000D_
</select>_x000D_
</div>_x000D_
</div>
_x000D_
If it is Rails 5, because of new hash notation:
params.permit(:name, groundtruth: [:type, coordinates:[]])
will work fine.
double RoundTo2Decimals(double val) {
DecimalFormat df2 = new DecimalFormat("###.##");
return Double.valueOf(df2.format(val));
}
To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:
1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686
3) System variable create: C:\program files (x86)\java\jre6\bin\
4) Anywhere you type java -version
it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.
Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent()
. Example:
list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());
Your data
variable contains an object, not an array, and objects do not have the push
function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
Try using download manager, which can help you download everything you want and save you time.
Check those to options:
Option 1 ->
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Option 2 ->
if(mWebview.getUrl().contains(".mp3") {
Request request = new Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
// You can change the name of the downloads, by changing "download" to everything you want, such as the mWebview title...
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
For eclipse users: solution is simple just change the nature of project Spring Tools->add spring project nature
done.
The fix for me was to set property HorizontalAlignment="Stretch"
on ItemsPresenter
inside ScrollViewe
r..
Hope this helps someone...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<ScrollViewer x:Name="ScrollViewer" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Padding="{TemplateBinding Padding}" HorizontalAlignment="Stretch">
<ItemsPresenter Height="252" HorizontalAlignment="Stretch"/>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
Use pivot tables, it will definitely save you time. If you are using excel 2007+ use tables (structured references) to keep your table dynamic. However if you insist on using functions, go with Smandoli's suggestion. Again, if you are on 2007+ use SUMIFS, it's faster compared to SUMIF.
Use os.path.join to combine the path to the Documents
directory with the completeName
(filename?) supplied by the user.
import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
toFile = raw_input("Write what you want into the field")
file1.write(toFile)
If you want the Documents
directory to be relative to the user's home directory, you could use something like:
os.path.join(os.path.expanduser('~'),'Documents',completeName)
Others have proposed using os.path.abspath
. Note that os.path.abspath
does not resolve '~'
to the user's home directory:
In [10]: cd /tmp
/tmp
In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'
May be answer would depend on what problem you have with using iterator? may be use
i = 100
while i:
print i
i-=1
or
def loop(N, doSomething):
if not N:
return
print doSomething(N)
loop(N-1, doSomething)
loop(100, lambda a:a)
but frankly i see no point in using such approaches
As previous answers, there is no standard API in Java for this.
You can add groovy jar files to your path and groovy.util.Eval.me("4*5") gets your job done.
In case anyone finds this useful, I was getting this issue chronically, although not constantly, and it was because I had git directory within Dropbox, removed it from Dropbox and all was fine.
The default name for a configuration file is [yourexe].exe.config. So notepad.exe will have a configuration file named notepad.exe.config, in the same folder as the program. This is a general configuration file for all aspects of the CLR and Framework, but it can contain your own settings under an <appSettings>
node.
The <appSettings>
element creates a collection of name-value pairs which can be accessed as System.Configuration.ConfigurationSettings.AppSettings
. There is no way to save changes back to the configuration file, however.
It is also possible to add your own custom elements to a configuration file - for example, to define a structured setting - by creating a class that implements IConfigurationSectionHandler
and adding it to the <configSections>
element of the configuration file. You can then access it by calling ConfigurationSettings.GetConfig
.
.NET 2.0 adds a new class, System.Configuration.ConfigurationManager
, which supports multiple files, with per-user overrides of per-system data. It also supports saving modified configurations back to settings files.
Visual Studio creates a file called App.config
, which it copies to the EXE folder, with the correct name, when the project is built.
It allocates space on the heap equal to an integer array of size N, and returns a pointer to it, which is assigned to int* type pointer called "array"
It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.
Try to use this composed of two steps command:
rm -rf bar && cp -r foo bar
The accepted solution fails if @forums
is empty. To workaround this I had to do
Topic.find(:all, :conditions => ['forum_id not in (?)', (@forums.empty? ? '' : @forums.map(&:id))])
Or, if using Rails 3+:
Topic.where( 'forum_id not in (?)', (@forums.empty? ? '' : @forums.map(&:id)) ).all
How about this?
class name(str):
def __init__(self, name):
print (name)
# ------
person1 = name("jean")
person2 = name("dean")
print('===')
print(person1)
print(person2)
Output:
jean
dean
===
jean
dean
(x > 0 for x in list)
in that function call creates a generator expression eg.
>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
print x
True
True
False
True
False
Which any
uses, and shortcircuits on encountering the first object that evaluates True
I am following the same tuturial and I had this issue and how I solved is just download the
from this link then install it then the command worked just fine!
/*
It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"[email protected]","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"[email protected]"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"[email protected]"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"[email protected]"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
//use the add method from the list and returns it.
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
According to the man page the -P flag is:
-P prefix --directory-prefix=prefix Set directory prefix to prefix. The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree. The default is . (the current directory).
This mean that it only specifies the destination but where to save the directory tree. It does not flatten the tree into just one directory. As mentioned before the -nd flag actually does that.
@Jon in the future it would be beneficial to describe what the flag does so we understand how something works.
C# just does a shallow copy when it passes by value unless the object in question executes ICloneable
(which apparently the List
class does not).
What this means is that it copies the List
itself, but the references to the objects inside the list remain the same; that is, the pointers continue to reference the same objects as the original List
.
If you change the values of the things your new List
references, you change the original List
also (since it is referencing the same objects). However, you then change what myList
references entirely, to a new List
, and now only the original List
is referencing those integers.
Read the Passing Reference-Type Parameters section from this MSDN article on "Passing Parameters" for more information.
"How do I Clone a Generic List in C#" from StackOverflow talks about how to make a deep copy of a List.
Considering Natalie's response, it seemed very good, but I had problems with a possible footer area, which could be hacked a little using clear: both
.
Of course, a better solution would be to use flexbox or grid nowadays.
You can check this codepen if you want.
.section {
width: 500px;
margin: auto;
overflow: hidden;
padding: 0;
}
div {
padding: 1rem;
}
.header {
background: lightblue;
}
.sidebar {
background: lightgreen;
width: calc(25% - 1rem);
}
.sidebar-left {
float: left;
padding-bottom: 500rem;
margin-bottom: -500rem;
}
.main {
background: pink;
width: calc(50% - 4rem);
float: left;
padding-bottom: 500rem;
margin-bottom: -500rem;
}
.sidebar-right {
float: right;
padding-bottom: 500rem;
margin-bottom: -500rem;
}
.footer {
background: black;
color: white;
float: left;
clear: both;
margin-top: 1rem;
width: calc(100% - 2rem);
}
_x000D_
<div class="section">
<div class="header">
This is the header
</div>
<div class="sidebar sidebar-left">
This sidebar could have a menu or something like that. It may not have the same length as the other
</div>
<div class="main">
This is the main area. It should have the same length as the sidebars
</div>
<div class="sidebar sidebar-right">
This is the other sidebar, it could have some ads
</div>
<div class="footer">
Footer area
</div>
</div>
_x000D_
After a half of the day of investigating why Analyzing Dependencies
takes forever, I found out that I was installing the latest Firebase
pod (7.1.0), which relies on GoogleAppMeasurement
version 7.1.0, and there was another pod, which is an ad mediation framework, which includes Google-Mobile-Ads-SDK
. This SDK was relying on a much lower version of GoogleAppMeasurement
~ 6.0.
I was able to install the pods by commenting out the conflicting pod from the ad mediation.
Something like this:
# Ad network framework
pod 'SomeMediationNetwork/Core'
# pod 'SomeMediationNetwork/GoogleMobileAds' # - the conflicting pod
pod 'SomeMediationNetwork/Facebook'
pod 'SomeMediationNetwork/SmartAdServer'
pod 'SomeMediationNetwork/Mopub'
I had to contact the ad mediation library publisher to fix this issue, most probably by updating to the latest Google-Mobile-Ads-SDK
pod and releasing a new version.
I hope this one helps some other folks who are banging their head
ln -s /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk'
might help you. It fixed my problem.
Here is a working example of creating select options for a DDL:
var resman = ViewModelResources.TimeFrame.ResourceManager;
ViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame
in Enum.GetValues(typeof(MapOverlayTimeFrames))
select new SelectListItem
{
Value = timeFrame.ToString(),
Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()
};
In simple words:
This is how I use OUTPUT INSERTED, when inserting to a table that uses ID as identity column in SQL Server:
'myConn is the ADO connection, RS a recordset and ID an integer
Set RS=myConn.Execute("INSERT INTO M2_VOTELIST(PRODUCER_ID,TITLE,TIMEU) OUTPUT INSERTED.ID VALUES ('Gator','Test',GETDATE())")
ID=RS(0)
Thanks to the solution provided by @yogihosting I was able to achieve similar result from schemaless columns of mysql with codes shown below:
// @params - will be bound to named query parameters
$criteria = [];
$criteria['latitude'] = '9.0285183';
$criteria['longitude'] = '7.4869546';
$criteria['distance'] = 500;
$criteria['skill'] = 'software developer';
// Get doctrine connection
$conn = $this->getEntityManager()->getConnection();
$sql = '
SELECT DISTINCT m.uuid AS phone, (((acos(sin((:latitude*pi()/180)) * sin((JSON_EXTRACT(m.location, "$.latitude")*pi()/180))+cos((:latitude*pi()/180)) *
cos((JSON_EXTRACT(m.location, "$.latitude")*pi()/180)) *
cos(((:longitude - JSON_EXTRACT(m.location, "$.longitude"))*pi()/180))))*180/pi())*60*1.1515*1.609344) AS distance FROM member_profile AS m
INNER JOIN member_card_subscription mcs ON mcs.primary_identity = m.uuid
WHERE mcs.end > now() AND JSON_SEARCH(m.skill_logic, "one", :skill) IS NOT NULL AND (((acos(sin((:latitude*pi()/180)) * sin((JSON_EXTRACT(m.location, "$.latitude")*pi()/180))+cos((:latitude*pi()/180)) *
cos((JSON_EXTRACT(m.location, "$.latitude")*pi()/180)) *
cos(((:longitude - JSON_EXTRACT(m.location, "$.longitude"))*pi()/180))))*180/pi())*60*1.1515*1.609344) <= :distance ORDER BY distance
';
$stmt = $conn->prepare($sql);
$stmt->execute(['latitude'=>$criteria['latitude'], 'longitude'=>$criteria['longitude'], 'skill'=>$criteria['skill'], 'distance'=>$criteria['distance']]);
var_dump($stmt->fetchAll());
Please note the above code snippet is using doctrine DB connection and PHP
So far the answers didn't help me as I have a button and a textInput field (side by side) below the textView which kept getting hidden by the keyboard, but this has solved my issue:
android:windowSoftInputMode="adjustResize"
There is a misunderstanding here with respect to what a "fork" is. A fork is in fact nothing more than a set of per-user branches. When you push to a fork you actually do push to the original repository, because that is the ONLY repository.
You can try this out by pushing to a fork, noting the commit and then going to the original repository and using the commit ID, you'll see that the commit is "in" the original repository.
This makes a lot of sense, but it is far from obvious (I only discovered this accidentally recently).
When John forks repository SuperProject what seems to actually happen is that all branches in the source repository are replicated with a name like "John.master", "John.new_gui_project", etc.
GitHub "hides" the "John." from us and gives us the illusion we have our own "copy" of the repository on GitHub, but we don't and nor is one even needed.
So my fork's branch "master" is actually named "Korporal.master", but the GitHub UI never reveals this, showing me only "master".
This is pretty much what I think goes on under the hood anyway based on stuff I've been doing recently and when you ponder it, is very good design.
For this reason I think it would be very easy for Microsoft to implement Git forks in their Visual Studio Team Services offering.
using and import REACTIVE_FORM_DIRECTIVES:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
Well, its not technically managing conflicts with submodules (ie: keep this but not that), but I found a way to continue working...and all I had to do was pay attention to my git status
output and reset the submodules:
git reset HEAD subby
git commit
That would reset the submodule to the pre-pull commit. Which in this case is exactly what I wanted. And in other cases where I need the changes applied to the submodule, I'll handle those with the standard submodule workflows (checkout master, pull down the desired tag, etc).
What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.
The one solution that worked on Win 10 flawlessly.
import matplotlib.pyplot as plt
plt.plot(x_data, y_data)
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.show()
Shortly: gene_name[x]
is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.
Further explanation:
Mutable objects are objects which value can be changed.
For example, list
is a mutable object, since you can append to it. int
is an immutable object, because you can't change it. When you do:
a = 5;
a = 3;
You don't change the value of a
, you create a new object and make a
point to its value.
Mutable objects cannot be hashed. See this answer.
To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple
, string
, int
.
I need some extra operation based on the result of aggregate function. Finally I've found some solution for aggregate function and the operation based on the result in MongoDB. I've a collection Request
with field request, source, status, requestDate
.
Single Field Group By & Count:
db.Request.aggregate([
{"$group" : {_id:"$source", count:{$sum:1}}}
])
Multiple Fields Group By & Count:
db.Request.aggregate([
{"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}}
])
Multiple Fields Group By & Count with Sort using Field:
db.Request.aggregate([
{"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
{$sort:{"_id.source":1}}
])
Multiple Fields Group By & Count with Sort using Count:
db.Request.aggregate([
{"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
{$sort:{"count":-1}}
])
A version that works on both Linux and Mac OS X (by adding the -e
switch to sed
):
export LC_CTYPE=C LANG=C
find . -name '*.txt' -print0 | xargs -0 sed -i -e 's/this/that/g'
I use a function that can check variables and objects. very convenient to work with jQuery
function _isset (variable) {
if(typeof(variable) == "undefined" || variable == null)
return false;
else
if(typeof(variable) == "object" && !variable.length)
return false;
else
return true;
};
In case you missed it, there's a chapter in the excellent Joshua Bloch's book "Effective Java, 2nd edition".
Just the conclusion :
A minor disadvantage of the use of interfaces to emulate extensible enums is those implementations cannot be inherited from one enum type to another. In the case of our Operation example, the logic to store and retrieve the symbol associated with an operation is duplicated in BasicOperation and ExtendedOperation. In this case, it doesn’t matter because very little code is duplicated. If there were a a larger amount of shared functionality, you could encapsulate it in a helper class or a static helper method to eliminate the code duplication.
In summary, while you cannot write an extensible enum type, you can emulate it by writing an interface to go with a basic enum type that implements the interface. This allows clients to write their own enums that implement the interface. These enums can then be used wherever the basic enum type can be used, assuming APIs are written in terms of the interface.
Using ES8 Object.entries() should be a more compact way to achieve this.
Object.entries(validation_messages).map(([key,object]) => {
alert(`Looping through key : ${key}`);
Object.entries(object).map(([token, value]) => {
alert(`${token} : ${value}`);
});
});
I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:
//store the element
var $cache = $('.my-sticky-element');
//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= vTop) {
// if so, ad the fixed class
$cache.addClass('stuck');
} else {
// otherwise remove it
$cache.removeClass('stuck');
}
});
.my-sticky-element.stuck {
position:fixed;
top:0;
box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}
Use ng-switch with expression and ng-switch-when
for matching expression value:
<div ng-switch="data.id">
<div ng-switch-when="5">...</div>
<div ng-switch-default>...</div>
</div>
This will drop existing connections except for yours:
Query pg_stat_activity
and get the pid values you want to kill, then issue SELECT pg_terminate_backend(pid int)
to them.
PostgreSQL 9.2 and above:
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'TARGET_DB' -- ? change this to your DB
AND pid <> pg_backend_pid();
PostgreSQL 9.1 and below:
SELECT pg_terminate_backend(pg_stat_activity.procpid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'TARGET_DB' -- ? change this to your DB
AND procpid <> pg_backend_pid();
Once you disconnect everyone you will have to disconnect and issue the DROP DATABASE command from a connection from another database aka not the one your trying to drop.
Note the renaming of the procpid
column to pid
. See this mailing list thread.
The previous remarks about deleting or removing a connection are absolutely a possibility. But you can also get this error when you attempt to invoke a package that uses project level connections (instead of package level connections).
If you are using project level connections and still want to use dtexec, never fear there is a way. I would not recommend converting them to package level connections (assuming you created them as project level connections for a good reason).
You will need to deploy your SSIS project. Your SSIS server will need to have a catalog created (https://msdn.microsoft.com/en-us/library/gg471509.aspx). Once you have the catalog, in your SSIS project select Project->Deploy and follow the wizard. The result will be a *.ispac file generated in your SSIS solution folder/bin/Development
Now for the money command, instead of invoking your package with a simple: dtexec.exe /f "package.dtsx"
instead call it this way: dtexec.exe /project "<...>/project.ispac" /package "<...>/package.dtsx"
The ispac file has the project level connection info that is needed to execute your package and you should be set!
I am using the below commands for this:
set lines=50 " For increasing the height to 50 lines (vertical)
set columns=200 " For increasing the width to 200 columns (horizontal)
You want grepl
:
> chars <- "test"
> value <- "es"
> grepl(value, chars)
[1] TRUE
> chars <- "test"
> value <- "et"
> grepl(value, chars)
[1] FALSE
SET ANSI_NULLS ON
IT Returns all values including null values in the table
SET ANSI_NULLS off
it Ends when columns contains null values
You can try.
SELECT * FROM
(
SELECT EMPLOYEE, LAST_NAME, SALARY,
RANK() OVER (ORDER BY SALARY DESC) EMPRANK
FROM emp
)
WHERE emprank <= 3;
This will give correct output even if there are two employees with same maximun salary
My solution..
(function(global){
const SECOND = 1;
const MINUTE = 60;
const HOUR = 3600;
const DAY = 86400;
const MONTH = 2629746;
const YEAR = 31556952;
const DECADE = 315569520;
global.timeAgo = function(date){
var now = new Date();
var diff = Math.round(( now - date ) / 1000);
var unit = '';
var num = 0;
var plural = false;
switch(true){
case diff <= 0:
return 'just now';
break;
case diff < MINUTE:
num = Math.round(diff / SECOND);
unit = 'sec';
plural = num > 1;
break;
case diff < HOUR:
num = Math.round(diff / MINUTE);
unit = 'min';
plural = num > 1;
break;
case diff < DAY:
num = Math.round(diff / HOUR);
unit = 'hour';
plural = num > 1;
break;
case diff < MONTH:
num = Math.round(diff / DAY);
unit = 'day';
plural = num > 1;
break;
case diff < YEAR:
num = Math.round(diff / MONTH);
unit = 'month';
plural = num > 1;
break;
case diff < DECADE:
num = Math.round(diff / YEAR);
unit = 'year';
plural = num > 1;
break;
default:
num = Math.round(diff / YEAR);
unit = 'year';
plural = num > 1;
}
var str = '';
if(num){
str += `${num} `;
}
str += `${unit}`;
if(plural){
str += 's';
}
str += ' ago';
return str;
}
})(window);
console.log(timeAgo(new Date()));
console.log(timeAgo(new Date('Jun 03 2018 15:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('Jun 03 2018 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2018 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2017 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2000 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('Sep 10 1994 13:12:19 GMT+0300 (FLE Daylight Time)')));
According to W3:
Partial URLs are interpreted relative to the source of the style sheet, not relative to the document
Therefore, in answer to your question, it will be relative to /stylesheets/
.
If you think about this, this makes sense, since the CSS file could be added to pages in different directories, so standardising it to the CSS file means that the URLs will work wherever the stylesheets are linked.
I found slightly different problem running R on through mac terminal, but connecting remotely to an Ubuntu server, which prevented me from successfully installing a library.
The solution I have was finding out what "LANG" variable is used in Ubuntu terminal
Ubuntu > echo $LANG
en_US.TUF-8
I got "en_US.TUF-8" reply from Ubuntu.
In R session, however, I got "UTF-8" as the default value and it complained that LC_TYPEC Setting LC_CTYPE failed, using "C"
R> Sys.getenv("LANG")
"UTF-8"
So, I tried to change this variable in R. It worked.
R> Sys.setenv(LANG="en_US.UTF-8")
I have got the same issue and I found that variable name and method were missing. Double check the layout file or look for build error that says DATABINDINGISSUE, or invalidate and restart android studio. It should work.
This also works specially if you are looping over an object.
unset($object[$key])
Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array
as mentioned by @CXJ . In that case you can use brackets instead
unset($object->{$key})
I've had a same problem with react-redux types. The simplest solution was add to tsconfig.json:
"noImplicitAny": false
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"noImplicitAny": false,
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}
Since Python 3.3, you can use the class ExitStack
from the contextlib
module.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
The canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
Here is a generic example:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(stack._exit_callbacks)
nums = [stack.enter_context(x) for x in xs]
print(stack._exit_callbacks)
print(stack._exit_callbacks)
print(nums)
Output:
deque([])
enter X1
enter X2
enter X3
deque([<function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86158>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f861e0>, <function ExitStack._push_cm_exit.<locals>._exit_wrapper at 0x7f5c95f86268>])
exit X3
exit X2
exit X1
deque([])
[1, 2, 3]
When incrementing time you should convert back to UTC and then add or subtract. Use the local time only for display.
This way you will be able to walk through any periods where hours or minutes happen twice.
If you converted to UTC, add each second, and convert to local time for display. You would go through 11:54:08 p.m. LMT - 11:59:59 p.m. LMT and then 11:54:08 p.m. CST - 11:59:59 p.m. CST.
My take on it...obviously, you've got to do something with the data you read in. If it involves writing it to the sheet, that'll be deadly slow with a normal For Loop. I came up with the following based upon a rehash of some of the items there, plus some help from the Chip Pearson website.
Reading in the text file (assuming you don't know the length of the range it will create, so only the startingCell is given):
Public Sub ReadInPlainText(startCell As Range, Optional textfilename As Variant)
If IsMissing(textfilename) Then textfilename = Application.GetOpenFilename("All Files (*.*), *.*", , "Select Text File to Read")
If textfilename = "" Then Exit Sub
Dim filelength As Long
Dim filenumber As Integer
filenumber = FreeFile
filelength = filelen(textfilename)
Dim text As String
Dim textlines As Variant
Open textfilename For Binary Access Read As filenumber
text = Space(filelength)
Get #filenumber, , text
'split the file with vbcrlf
textlines = Split(text, vbCrLf)
'output to range
Dim outputRange As Range
Set outputRange = startCell
Set outputRange = outputRange.Resize(UBound(textlines), 1)
outputRange.Value = Application.Transpose(textlines)
Close filenumber
End Sub
Conversely, if you need to write out a range to a text file, this does it quickly in one print statement (note: the file 'Open' type here is in text mode, not binary..unlike the read routine above).
Public Sub WriteRangeAsPlainText(ExportRange As Range, Optional textfilename As Variant)
If IsMissing(textfilename) Then textfilename = Application.GetSaveAsFilename(FileFilter:="Text Files (*.txt), *.txt")
If textfilename = "" Then Exit Sub
Dim filenumber As Integer
filenumber = FreeFile
Open textfilename For Output As filenumber
Dim textlines() As Variant, outputvar As Variant
textlines = Application.Transpose(ExportRange.Value)
outputvar = Join(textlines, vbCrLf)
Print #filenumber, outputvar
Close filenumber
End Sub
UPDATE
The bookmarklet hack below is broken due to XHR issues and API changes.
Thankfully Github now has "A Whole New Code Search" which does the job superbly.
Checkout this voodoo: Github code search userscript.
Follow the directions there, or if you hate bloating your browser with scripts and extensions, use my bookmarkified bundle of the userscript:
javascript:(function(){var s='https://raw.githubusercontent.com/skratchdot/github-enhancement-suite/master/build/github-enhancement-suite.user.js',t='text/javascript',d=document,n=navigator,e;(e=d.createElement('script')).src=s;e.type=t;d.getElementsByTagName('head')[0].appendChild(e)})();doIt('');void('');
Save the source above as the URL of a new bookmark. Browse to any Github repo, click the bookmark, and bam: in-page, ajaxified code search.
CAVEAT Github must index a repo before you can search it.
Abracadabra...
Here's a sample search from the annotated ECMAScript 5.1 specification repository:
Try this:
var script = "<script type='text/javascript'> content </script>";
//using jquery next
$('body').append(script);//incorporates and executes inmediatelly
Personally, I didn't test it but seems to work.
Try this, jQuery how to get multiple checkbox's value
$(document).ready(function() {_x000D_
$(".btn_click").click(function(){_x000D_
var test = new Array();_x000D_
$("input[name='programming']:checked").each(function() {_x000D_
test.push($(this).val());_x000D_
});_x000D_
_x000D_
alert("My favourite programming languages are: " + test);_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Get Values of Selected Checboxes</title>_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
</head>_x000D_
<body>_x000D_
<form>_x000D_
<h3>Select your favorite Programming Languages :</h3>_x000D_
<label><input type="checkbox" value="PHP" name="programming"> PHP</label>_x000D_
<label><input type="checkbox" value="Java" name="programming"> Java</label>_x000D_
<label><input type="checkbox" value="Ruby" name="programming"> Ruby</label>_x000D_
<label><input type="checkbox" value="Python" name="programming"> Python</label>_x000D_
<label><input type="checkbox" value="JavaScript" name="programming"> JavaScript</label>_x000D_
<label><input type="checkbox" value="Rust" name="programming">Rust</label>_x000D_
<label><input type="checkbox" value="C" name="programming"> C</label>_x000D_
<br>_x000D_
<button type="button" class="btn_click" style="margin-top: 10px;">Click here to Get Values</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
Thank you @Gorge Reith. Working off the solution provided by @George Reith, here is a function that furthers (1) separates out the individual 'hrefs' links (because they might be useful), (2) uses attributes as keys (since attributes are more descriptive), and (3) it's usable within Node.js without needing Chrome by using the 'jsdom' package:
const jsdom = require('jsdom') // npm install jsdom provides in-built Window.js without needing Chrome
// Function to map HTML DOM attributes to inner text and hrefs
function mapDOM(html_string, json) {
treeObject = {}
// IMPT: use jsdom because of in-built Window.js
// DOMParser() does not provide client-side window for element access if coding in Nodejs
dom = new jsdom.JSDOM(html_string)
document = dom.window.document
element = document.firstChild
// Recursively loop through DOM elements and assign attributes to inner text object
// Why attributes instead of elements? 1. attributes more descriptive, 2. usually important and lesser
function treeHTML(element, object) {
var nodeList = element.childNodes;
if (nodeList != null) {
if (nodeList.length) {
object[element.nodeName] = [] // IMPT: empty [] array for non-text recursivable elements (see below)
for (var i = 0; i < nodeList.length; i++) {
// if final text
if (nodeList[i].nodeType == 3) {
if (element.attributes != null) {
for (var j = 0; j < element.attributes.length; j++) {
if (element.attributes[j].nodeValue !== '' &&
nodeList[i].nodeValue !== '') {
if (element.attributes[j].name === 'href') { // separate href
object[element.attributes[j].name] = element.attributes[j].nodeValue;
} else {
object[element.attributes[j].nodeValue] = nodeList[i].nodeValue;
}
}
}
}
// else if non-text then recurse on recursivable elements
} else {
object[element.nodeName].push({}); // if non-text push {} into empty [] array
treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length -1]);
}
}
}
}
}
treeHTML(element, treeObject);
return (json) ? JSON.stringify(treeObject) : treeObject;
}
As others have said, usually you want to use hg backout
or git revert
. However, sometimes you really want to get rid of a commit.
First, you'll want to go to your repository's settings. Click on the Strip commits
link.
Enter the changeset ID for the changeset you want to destroy, and click Preview strip
. That will let you see what kind of damage you're about to do before you do it. Then just click Confirm
and your commit is no longer history. Make sure you tell all your collaborators what you've done, so they don't accidentally push the offending commit back.
This should not affect everyone, but one of the semi-hidden reasons of the repository size being large could be Git submodules.
You might have added one or more submodules, but stopped using it at some time, and some files remained in .git/modules
directory. To make redundant submodule files gone away, see this question.
However, just like the main repository, the other way is to navigate to the submodule directory in .git/modules
, and do a, for example, git gc --aggressive --prune
.
These should have a good impact in the repository size, but as long as you use Git submodules, e.g. especially with large libraries, your repository size should not change drastically.
Using dict.popitem() in straightforward nested-list-like recursion:
def flatten(d):
if d == {}:
return d
else:
k,v = d.popitem()
if (dict != type(v)):
return {k:v, **flatten(d)}
else:
flat_kv = flatten(v)
for k1 in list(flat_kv.keys()):
flat_kv[k + '_' + k1] = flat_kv[k1]
del flat_kv[k1]
return {**flat_kv, **flatten(d)}
I have a span. I want to take the value of attribute data-txt-lang, which is used defined.
$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});
You might want to take a look at Standard Compression Scheme for Unicode.
SQL Server 2008 R2 use it internally and can achieve up to 50% compression.
Rather than allocating a massive array, could you try utilizing an iterator? These are delay-executed, meaning values are generated only as they're requested in an foreach statement; you shouldn't run out of memory this way:
private static IEnumerable<double> MakeRandomNumbers(int numberOfRandomNumbers)
{
for (int i = 0; i < numberOfRandomNumbers; i++)
{
yield return randomGenerator.GetAnotherRandomNumber();
}
}
...
// Hooray, we won't run out of memory!
foreach(var number in MakeRandomNumbers(int.MaxValue))
{
Console.WriteLine(number);
}
The above will generate as many random numbers as you wish, but only generate them as they're asked for via a foreach statement. You won't run out of memory that way.
Alternately, If you must have them all in one place, store them in a file rather than in memory.
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementHow do I convert a list of dictionaries to a pandas DataFrame?
The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.
DataFrame()
, DataFrame.from_records()
, and .from_dict()
Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.
Consider a very contrived example.
np.random.seed(0)
data = pd.DataFrame(
np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')
print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
This list consists of "records" with every keys present. This is the simplest case you could encounter.
# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
orient='index'
/'columns'
Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".
orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.
For example, data
above is in the "columns" orient.
data_c = [
{'A': 5, 'B': 0, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'C': 3, 'D': 5},
{'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
Note: If you are using pd.DataFrame.from_records
, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.
orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict
.
data_i ={
0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
This case is not considered in the OP, but is still useful to know.
If you need a custom index on the resultant DataFrame, you can set it using the index=...
argument.
pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])
A B C D
a 5 0 3 3
b 7 9 3 5
c 2 4 7 6
This is not supported by pd.DataFrame.from_dict
.
All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,
data2 = [
{'A': 5, 'C': 3, 'D': 3},
{'A': 7, 'B': 9, 'F': 5},
{'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)
A B C D E F
0 5.0 NaN 3.0 3.0 NaN NaN
1 7.0 9.0 NaN NaN NaN 5.0
2 NaN 4.0 7.0 NaN 6.0 NaN
"What if I don't want to read in every single column"? You can easily specify this using the columns=...
parameter.
For example, from the example dictionary of data2
above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:
pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])
A D F
0 5.0 3.0 NaN
1 7.0 NaN 5.0
2 NaN NaN NaN
This is not supported by pd.DataFrame.from_dict
with the default orient "columns".
pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'
Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2
above, you can use:
rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
if i not in rows_to_select:
del data2[i]
pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)
A B C D E
0 5.0 NaN 3 3.0 NaN
1 NaN 4.0 7 NaN 6.0
json_normalize
for Nested DataA strong, robust alternative to the methods outlined above is the json_normalize
function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.
pd.json_normalize(data)
A B C D
0 5 0 3 3
1 7 9 3 5
2 2 4 7 6
pd.json_normalize(data2)
A B C D E
0 5.0 NaN 3 3.0 NaN
1 NaN 4.0 7 NaN 6.0
Again, keep in mind that the data passed to json_normalize
needs to be in the list-of-dictionaries (records) format.
As mentioned, json_normalize
can also handle nested dictionaries. Here's an example taken from the documentation.
data_nested = [
{'counties': [{'name': 'Dade', 'population': 12345},
{'name': 'Broward', 'population': 40000},
{'name': 'Palm Beach', 'population': 60000}],
'info': {'governor': 'Rick Scott'},
'shortname': 'FL',
'state': 'Florida'},
{'counties': [{'name': 'Summit', 'population': 1234},
{'name': 'Cuyahoga', 'population': 1337}],
'info': {'governor': 'John Kasich'},
'shortname': 'OH',
'state': 'Ohio'}
]
pd.json_normalize(data_nested,
record_path='counties',
meta=['state', 'shortname', ['info', 'governor']])
name population state shortname info.governor
0 Dade 12345 Florida FL Rick Scott
1 Broward 40000 Florida FL Rick Scott
2 Palm Beach 60000 Florida FL Rick Scott
3 Summit 1234 Ohio OH John Kasich
4 Cuyahoga 1337 Ohio OH John Kasich
For more information on the meta
and record_path
arguments, check out the documentation.
Here's a table of all the methods discussed above, along with supported features/functionality.
* Use orient='columns'
and then transpose to get the same effect as orient='index'
.
2020 : Similar Issue
If your content is a set of buttons that you want to center on a page, then wrap them in a row and use justify-content-center.
Sample code below:
<div class="row justify-content-center">
<button>Action A</button>
<button>Action B</button>
<button>Action C</button>
</div>
Use git add -A
, this will include the deleted files.
Note: use git rm
for certain files.
I really like this method as well, less clutter:
count=$[count+1]
I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:
http://github.com/mastermind202/GoogleVoice
I hope others find it useful. Feedback and suggestions welcome.
Just To mention, in CSS 3
:after
should be used like this
::after
From https://developer.mozilla.org/de/docs/Web/CSS/::after :
The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.
So it should be:
li { display: inline; list-style-type: none; }
li::after { content: ", "; }
li:last-child::before { content: "and "; }
li:last-child::after { content: "."; }
LogisticRegression
is not for regression but classification !
The Y
variable must be the classification class,
(for example 0
or 1
)
And not a continuous
variable,
that would be a regression problem.
For the numeric wrapper types.
e.g Double.POSITVE_INFINITY
Hope this might help you.
This example worked for me. Both encryption and decryption work without any issue.
package com.test.encodedecode;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class ThreeDesHandler {
public static void main(String[] args) {
String encodetext = null;
String decodetext = null;
ThreeDesHandler handler = new ThreeDesHandler();
String key = "secret key";//Need to change with your value
String plaintxt = "String for encode";//Need to change with your value
encodetext = handler.encode3Des(key, plaintxt);
System.out.println(encodetext);
decodetext = handler.decode3Des(key, encodetext);
System.out.println(decodetext);
}
public String encode3Des(String key, String plaintxt) {
try {
byte[] seed_key = (new String(key)).getBytes();
SecretKeySpec keySpec = new SecretKeySpec(seed_key, "TripleDES");
Cipher nCipher = Cipher.getInstance("TripleDES");
nCipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] cipherbyte = nCipher.doFinal(plaintxt.getBytes());
String encodeTxt = new String(Base64.encodeBase64(cipherbyte));
return encodeTxt;
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String decode3Des(String key, String desStr) {
try {
Base64 base64 = new Base64();
byte[] seed_key = (new String(key)).getBytes();
SecretKeySpec keySpec = new SecretKeySpec(seed_key, "TripleDES");
Cipher nCipher = Cipher.getInstance("TripleDES");
nCipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] src = base64.decode(desStr);
String returnstring = new String(nCipher.doFinal(src));
return returnstring;
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
OK, just change your code to something like this:
<script>
function submit() {
return confirm('Do you really want to submit the form?');
}
</script>
<form onsubmit="return submit(this);">
<input type="image" src="xxx" border="0" name="submit" onclick="show_alert();"
alt="PayPal - The safer, easier way to pay online!" value="Submit">
</form>
Also this is the code in run, just I make it easier to see how it works, just run the code below to see the result:
function submitForm() {_x000D_
return confirm('Do you really want to submit the form?');_x000D_
}
_x000D_
<form onsubmit="return submitForm(this);">_x000D_
<input type="text" border="0" name="submit" />_x000D_
<button value="submit">submit</button>_x000D_
</form>
_x000D_
I am using anaconda for the same.
I installed graphviz using conda install graphviz
in anaconda prompt.
and then installed pip install graphviz
in the same command prompt. It worked for me.
Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE
I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:
$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});
Another would be to load the content of your external link into the dialog container using ajax.
$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});
Both works fine but depends on the external content.
For completeness these are the cmap choices I encountered so far:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spring, spring_r, summer, summer_r, tab10, tab10_r, tab20, tab20_r, tab20b, tab20b_r, tab20c, tab20c_r, terrain, terrain_r, twilight, twilight_r, twilight_shifted, twilight_shifted_r, viridis, viridis_r, winter, winter_r
In pure Ruby you could extend the string class using code lifted from Rails .camelize
class String
def camelize(uppercase_first_letter = true)
string = self
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
else
string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
end
string.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.gsub("/", "::")
end
end
In my case problem went away simply by using HttpContext.Current.Session
instead of Session
As Luiggi mentioned you need to change your main to:
import java.util.Arrays;
public class trial1{
public static void main(String[] args){
int[] A = numbers();
System.out.println(Arrays.toString(A)); //Might require import of util.Arrays
}
public static int[] numbers(){
int[] A = {1,2,3};
return A;
}
}
If you wanted to avoid the @interface
block at the top you could always put the private declarations in another file MyClassPrivate.h
not ideal but its not cluttering up the implementation.
MyClass.h
interface MyClass : NSObject {
@private
BOOL publicIvar_;
BOOL privateIvar_;
}
@property (nonatomic, assign) BOOL publicIvar;
//any other public methods. etc
@end
MyClassPrivate.h
@interface MyClass ()
@property (nonatomic, assign) BOOL privateIvar;
//any other private methods etc.
@end
MyClass.m
#import "MyClass.h"
#import "MyClassPrivate.h"
@implementation MyClass
@synthesize privateIvar = privateIvar_;
@synthesize publicIvar = publicIvar_;
@end
In SQL 2k5+, you can do something like:
;with cte as (
select CName, AddressLine,
rank() over (partition by CName order by AddressLine) as [r]
from MyTable
)
select CName, AddressLine
from cte
where [r] = 1
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
The sample you provided is not valid PHP and has a few issues:
public scoreTest() {
...
}
is not a proper function declaration -- you need to declare functions with the 'function' keyword.
The syntax should rather be:
public function scoreTest() {
...
}
Second, wrapping the bigTest() and smallTest() functions in public function() {} does not make them private — you should use the private keyword on both of these individually:
class test () {
public function newTest(){
$this->bigTest();
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public function scoreTest(){
//Scoring code here;
}
}
Also, it is convention to capitalize class names in class declarations ('Test').
Hope that helps.
You can try this too, If you don't want to do this by your method.
Arrays.sort(arr);
System.out.println("Min value "+arr[0]);
System.out.println("Max value "+arr[arr.length-1]);
If you know how many lines you want, create an array of String with that many members (e.g. myStringArray). Then use myListBox.Lines = myStringArray;
None of the suggested solutions worked for me.
I had run tomcat restart
before completing the deployment which messed up my web app.
EC2 ran tomcat automatically and tomcat was stuck trying to connect to a database connection which was not configured properly.
I just needed to remove my customized context in server.xml, restart tomcat and add the context back in.
Excel has a very powerful feature providing for a dropdown select list in a cell, reflecting data from a named region. It'a a very easy configuration, once you have done it before. Two steps are to follow:
Create a named region,
Setup the dropdown in a cell.
There is a detailed explanation of the process HERE.
For whatever reason I've never liked the clearing approaches, I rely on floats and percentage widths for things like this.
Here's something that works in simple cases:
#content {
overflow:auto;
width: 600px;
background: gray;
}
#left, #right {
width: 40%;
margin:5px;
padding: 1em;
background: white;
}
#left { float:left; }
#right { float:right; }
If you put some content in you'll see that it works:
<div id="content">
<div id="left">
<div id="object1">some stuff</div>
<div id="object2">some more stuff</div>
</div>
<div id="right">
<div id="object3">unas cosas</div>
<div id="object4">mas cosas para ti</div>
</div>
</div>
You can see it here: http://cssdesk.com/d64uy
Useful sns.heatmap
api is here. Check out the parameters, there are a good number of them. Example:
import seaborn as sns
%matplotlib inline
idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)
# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
It's all in the tutorial how to do that:
ContentValues args = new ContentValues();
args.put(columnName, newValue);
db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
Use ContentValues
to set the updated columns and than the update()
method in which you have to specifiy, the table and a criteria to only update the rows you want to update.
I also had similar problem where redirects were giving 404 or 405 randomly on my development server. It was an issue with gunicorn instances.
Turns out that I had not properly shut down the gunicorn instance before starting a new one for testing.
Somehow both of the processes were running simultaneously, listening to the same port 8080 and interfering with each other.
Strangely enough they continued running in background after I had killed all my terminals.
Had to kill them manually using fuser -k 8080/tcp
using $(this) improves performance, as the class/whatever attr u are using to search, need not be searched for multiple times in the entire webpage content.
I will share one misused concept that I fell into one day:
var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};
var startingWith_M = names.Where(x => x.StartsWith("m"));
var startingWith_F = names.Where(x => x.StartsWith("f"));
// updating existing list
names[0] = "ford";
// Guess what should be printed before continuing
print( startingWith_M.ToList() );
print( startingWith_F.ToList() );
// I was expecting
print( startingWith_M.ToList() ); // mercedes, mazda
print( startingWith_F.ToList() ); // fiat, ferrari
// what printed actualy
print( startingWith_M.ToList() ); // mazda
print( startingWith_F.ToList() ); // ford, fiat, ferrari
As per other answers, the evaluation of the result was deferred until calling ToList
or similar invocation methods for example ToArray
.
So I can rewrite the code in this case as:
var names = new List<string> {"mercedes", "mazda", "bmw", "fiat", "ferrari"};
// updating existing list
names[0] = "ford";
// before calling ToList directly
var startingWith_M = names.Where(x => x.StartsWith("m"));
var startingWith_F = names.Where(x => x.StartsWith("f"));
print( startingWith_M.ToList() );
print( startingWith_F.ToList() );
To remove an element from an array, just do:
array.splice(index, 1);
In your case:
removePeople(e) {
var array = [...this.state.people]; // make a separate copy of the array
var index = array.indexOf(e.target.value)
if (index !== -1) {
array.splice(index, 1);
this.setState({people: array});
}
},
Not for blanks in the middle of a range, but this works for a complex chart from a start date until infinity (ie no need to adjust the chart's data source each time informatiom is added), without showing any lines for dates that have not yet been entered. As you add dates and data to the spreadsheet, the chart expands. Without it, the chart has a brain hemorrhage.
So, to count a complex range of conditions over an extended period of time but only if the date of the events is not blank :
=IF($B6<>"",(COUNTIF($O6:$O6,Q$5)),"") returns “#N/A” if there is no date in column B.
In other words, "count apples or oranges or whatever in column O (as determined by what is in Q5) but only if column B (the dates) is not blank". By returning “#N/A”, the chart will skip the "blank" rows (blank as in a zero value or rather "#N/A").
From that table of returned values you can make a chart from a date in the past to infinity
Although dated, not one answer on this thread can be used universally. Using rgba to create transparent color masks - that doesn't exactly explain how to do so with background images.
My solution works for background images or color backgrounds.
#parent {_x000D_
font-family: 'Open Sans Condensed', sans-serif;_x000D_
font-size: 19px;_x000D_
text-transform: uppercase;_x000D_
border-radius: 50%;_x000D_
margin: 20px auto;_x000D_
width: 125px;_x000D_
height: 125px;_x000D_
background-color: #476172;_x000D_
background-image: url('https://unsplash.it/200/300/?random');_x000D_
line-height: 29px;_x000D_
text-align:center;_x000D_
}_x000D_
_x000D_
#content {_x000D_
color: white;_x000D_
height: 125px !important;_x000D_
width: 125px !important;_x000D_
display: table-cell;_x000D_
border-radius: 50%;_x000D_
vertical-align: middle;_x000D_
background: rgba(0,0,0, .3);_x000D_
}
_x000D_
<h1 id="parent"><a href="" id="content" title="content" rel="home">Example</a></h1>
_x000D_
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
Another option is to use an array, e.g.
void method(SomeClass[] v) { v[0] = ...; }
but 1) the array must be initialized before method invoked, 2) still one cannot implement e.g. swap method in this way...
This way is used in JDK, e.g. in java.util.concurrent.atomic.AtomicMarkableReference.get(boolean[])
.
As far as I can tell this will only work on newer versions of Android, so you will probably have to figure out a different way to do it. This solution works for me on 4.4, but not on 4.0 or 2.3.3, so this will not be a useful way to go about sharing content for an app that's meant to run on any Android device.
In manifest.xml:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.myapp.SharingActivity"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Take careful note of how you specify the authorities. You must specify the activity from which you will create the URI and launch the share intent, in this case the activity is called SharingActivity. This requirement is not obvious from Google's docs!
file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="just_a_name" path=""/>
</paths>
Be careful how you specify the path. The above defaults to the root of your private internal storage.
In SharingActivity.java:
Uri contentUri = FileProvider.getUriForFile(getActivity(),
"com.mydomain.myapp.SharingActivity", myFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg");
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share with"));
In this example we are sharing a JPEG image.
Finally it is probably a good idea to assure yourself that you have saved the file properly and that you can access it with something like this:
File myFile = getActivity().getFileStreamPath("mySavedImage.jpeg");
if(myFile != null){
Log.d(TAG, "File found, file description: "+myFile.toString());
}else{
Log.w(TAG, "File not found!");
}
Have you tried using the official JQueryUI implementation (not jQuery only) : ?