I hit this problem with the latest version (August 2020) (after not using Maven on this machine for ages) and was scratching my head as to why it could still be an issue after reading these answers.
Turns out I had an old settings.xml
sitting in the .m2/
folder in my home directory with some customisations from years ago.
However, even deleting that file didn't fix it for me. I ended up deleting the entire .m2
folder.
I don't think there was anything else in it except for downloaded resources. Maybe just deleting folders like repository/org/apache/maven/archetype
would have been sufficient.
This is what worked for me in IntelliJIdea:
Go to File -> Build, Execution, Deployment -> Build Tools -> Maven -> Repositories
Check that there are two repositories:
https://repo.maven.apache.org/maven2 (Remote)
C:/Users/_user_/.m2/repository (Local)
And then click on Update for both repos. The update of remote repository will take a while, but in the end click on OK and that's all.
ymptom: After configuring Nexus to serve SSL maven builds fail with "peer not authenticated" or "PKIX path building failed".
This is usually caused by using a self signed SSL certificate on Nexus. Java does not consider these to be a valid certificates, and will not allow connecting to server's running them by default.
You have a few choices here to fix this:
For option 1 you can use the keytool command and follow the steps in the below article.
Explicitly Trusting a Self-Signed or Private Certificate in a Java Based Client
For option 3, invoke Maven with "-Dmaven.wagon.http.ssl.insecure=true". If the host name configured in the certificate doesn't match the host name Nexus is running on you may also need to add "-Dmaven.wagon.http.ssl.allowall=true".
Note: These additional parameters are initialized in static initializers, so they have to be passed in via the MAVEN_OPTS environment variable. Passing them on the command line to Maven will not work.
See here for more information:
I had put a not encrypted password in the settings.xml .
I tested the call with curl
curl -u username:password http://url/artifactory/libs-snapshot-local/com/myproject/api/1.0-SNAPSHOT/api-1.0-20160128.114425-1.jar --request PUT --data target/api-1.0-SNAPSHOT.jar
and I got the error:
{
"errors" : [ {
"status" : 401,
"message" : "Artifactory configured to accept only encrypted passwords but received a clear text password."
} ]
}
I retrieved my encrypted password clicking on my artifactory profile and unlocking it.
As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml
if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven
This error occurs if some unit test cases are failing.
In my application, certain unit tests were not compatible with Java 8 so they were failing. My error was resolved after changing jdk1.8.0_92
to jdk1.7.0_80
.
The build would succeed with mvn clean install -DskipTests
but this will skip the unit tests. So just ensure that you run then separately after the build is complete.
I found these two links very helpful while I was trying to learn socket.io:
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
I would use tel:
(as recommended). But to have a better fallback/not display error pages I would use something like this (using jquery):
// enhance tel-links
$("a[href^='tel:']").each(function() {
var target = "call-" + this.href.replace(/[^a-z0-9]*/gi, "");
var link = this;
// load in iframe to supress potential errors when protocol is not available
$("body").append("<iframe name=\"" + target + "\" style=\"display: none\"></iframe>");
link.target = target;
// replace tel with callto on desktop browsers for skype fallback
if (!navigator.userAgent.match(/(mobile)/gi)) {
link.href = link.href.replace(/^tel:/, "callto:");
}
});
The assumption is, that mobile browsers that have a mobile stamp in the userAgent-string have support for the tel:
protocol. For the rest we replace the link with the callto:
protocol to have a fallback to Skype where available.
To suppress error-pages for the unsupported protocol(s), the link is targeted to a new hidden iframe.
Unfortunately it does not seem to be possible to check, if the url has been loaded successfully in the iframe. It's seems that no error events are fired.
I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.
By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.
As of PowerShell 2, simple:
$recipients = $addresses -split "; "
Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit
to force case-sensitivity. See about_Split for more details.
Dashes don't need to be removed from HTTP request as you can see in URL of this thread. But if you want to prepare well-formed URL without dependency on data you should use URLEncoder.encode( String data, String encoding ) instead of changing standard form of you data. For UUID string representation dashes is normal.
Resizing images in a canvas element is generally bad idea since it uses the cheapest box interpolation. The resulting image noticeable degrades in quality. I'd recommend using http://nodeca.github.io/pica/demo/ which can perform Lanczos transformation instead. The demo page above shows difference between canvas and Lanczos approaches.
It also uses web workers for resizing images in parallel. There is also WEBGL implementation.
There are some online image resizers that use pica for doing the job, like https://myimageresizer.com
Assuming the column is set to support NULL as a value:
UPDATE YOUR_TABLE
SET column = NULL
Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:
UPDATE YOUR_TABLE
SET column = CAST(NULL AS DATETIME)
...assuming column
is a DATETIME data type in the example above.
I created my markup to insert as a string since it's less code and easier to read than working with the fancy dom stuff.
Then I made it innerHTML of a temporary element just so I could take the one and only child of that element and attach to the body.
var html = '<div>';
html += 'Hello div!';
html += '</div>';
var tempElement = document.createElement('div');
tempElement.innerHTML = html;
document.getElementsByTagName('body')[0].appendChild(tempElement.firstChild);
Have you tried setting the spacing to zero?
/*alternating row*/
table, tr, td, th {margin:0;border:0;padding:0;spacing:0;}
tr.rowhighlight {background-color:#f0f8ff;margin:0;border:0;padding:0;spacing:0;}
For Dense Layers:
output_size * (input_size + 1) == number_parameters
For Conv Layers:
output_channels * (input_channels * window_size + 1) == number_parameters
Consider following example,
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
Conv2D(128, (3, 3), activation='relu'),
Dense(num_classes, activation='softmax')
])
model.summary()
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 222, 222, 32) 896
_________________________________________________________________
conv2d_2 (Conv2D) (None, 220, 220, 64) 18496
_________________________________________________________________
conv2d_3 (Conv2D) (None, 218, 218, 128) 73856
_________________________________________________________________
dense_9 (Dense) (None, 218, 218, 10) 1290
=================================================================
Calculating params,
assert 32 * (3 * (3*3) + 1) == 896
assert 64 * (32 * (3*3) + 1) == 18496
assert 128 * (64 * (3*3) + 1) == 73856
assert num_classes * (128 + 1) == 1290
if you want pressed image button then image should be change from normal to pressed
But I best way will be to customize the RadioButton and use them in a group. I have see an example of that. Sorry I did not remember that link.
but if you want to avoid that. You need to add this to your selector.xml
Once Done. Just got to your code and add this
public void onClick ( View v ) {
myImageButton.setSelected ( true ) ;
}
You will see the result. But you have to mange the states which button was recently press. So that you can set
myOLDImageButton.setSelected ( false ) ;
I suggest you to put all button reference in a array.
From now I use http://marxi.co/. Marxi.co has online and offline version.
I'm sure you have enough to go on by now, but I can't help but suggest using the k-means clustering method. k-means is an unsupervised clustering algorithm which will take you data (in any number of dimensions - I happen to do this in 3D) and arrange it into k clusters with distinct boundaries. It's nice here because you know exactly how many toes these canines (should) have.
Additionally, it's implemented in Scipy which is really nice (http://docs.scipy.org/doc/scipy/reference/cluster.vq.html).
Here's an example of what it can do to spatially resolve 3D clusters:
What you want to do is a bit different (2D and includes pressure values), but I still think you could give it a shot.
I think that main difference is whether you frequently need to insert or remove stuff from the top of the list.
With an array, if you remove something from the top of list than the complexity is o(n) because all of the indices of the array elements will have to shift.
With a linked list, it is o(1) because you need only create the node, reassign the head and assign the reference to next as the previous head.
When frequently inserting or removing at the end of the list, arrays are preferable because the complexity will be o(1), no reindexing is required, but for a linked list it will be o(n) because you need to go from the head to the last node.
I think that searching in both linked list and arrays will be o(log n) because you will be probably be using a binary search.
This react & redux example is based off Mohamed Mellouki's example. But validates using prettify and linting rules. Note that we define our props and dispatch methods using PropTypes so that our compiler doesn't scream at us. This example also included some lines of code that had been missing in Mohamed's example. To use connect you will need to import it from react-redux. This example also binds the method filterItems this will prevent scope problems in the component. This source code has been auto formatted using JavaScript Prettify.
import React, { Component } from 'react-native';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
class ItemsContainer extends Component {
constructor(props) {
super(props);
const { items, filters } = props;
this.state = {
items,
filteredItems: filterItems(items, filters),
};
this.filterItems = this.filterItems.bind(this);
}
componentWillReceiveProps(nextProps) {
const { itmes } = this.state;
const { filters } = nextProps;
this.setState({ filteredItems: filterItems(items, filters) });
}
filterItems = (items, filters) => {
/* return filtered list */
};
render() {
return <View>/*display the filtered items */</View>;
}
}
/*
define dispatch methods in propTypes so that they are validated.
*/
ItemsContainer.propTypes = {
items: PropTypes.array.isRequired,
filters: PropTypes.array.isRequired,
onMyAction: PropTypes.func.isRequired,
};
/*
map state to props
*/
const mapStateToProps = state => ({
items: state.App.Items.List,
filters: state.App.Items.Filters,
});
/*
connect dispatch to props so that you can call the methods from the active props scope.
The defined method `onMyAction` can be called in the scope of the componets props.
*/
const mapDispatchToProps = dispatch => ({
onMyAction: value => {
dispatch(() => console.log(`${value}`));
},
});
/* clean way of setting up the connect. */
export default connect(mapStateToProps, mapDispatchToProps)(ItemsContainer);
This example code is a good template for a starting place for your component.
This is the main difference between use git reset --hard and git reset --soft:
--soft
Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
--hard
Resets the index and working tree. Any changes to tracked files in the working tree since are discarded.
its very easy. Use the bellow code, Its works for me. Here I have used fontawesome icon but you can use anything as image or any other Icon's code.
$(document).ready(function(){
$('.slider').slick({
autoplay:true,
arrows: true,
prevArrow:"<button type='button' class='slick-prev pull-left'><i class='fa fa-angle-left' aria-hidden='true'></i></button>",
nextArrow:"<button type='button' class='slick-next pull-right'><i class='fa fa-angle-right' aria-hidden='true'></i></button>"
});
});
Why not:
tar czvf backup.tar.gz *
Sure it's clever to use find and then xargs, but you're doing it the hard way.
Update: Porges has commented with a find-option that I think is a better answer than my answer, or the other one: find -print0 ... | xargs -0 ....
I had issue with the solutions mentioned above as specifying the string key would give me javax.el.PropertyNotFoundException. The code shown below worked for me. In this I used status to count the index of for each loop and displayed the value of index I am interested on
<c:forEach items="${requestScope.key}" var="map" varStatus="status" >
<c:if test="${status.index eq 1}">
<option><c:out value=${map.value}/></option>
</c:if>
</c:forEach>
Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following
if (!empty($var) && is_null($var))
Note the PHP manual
variable is considered empty if it does not exist or if its value equals FALSE
As opposed to being null which is handy here!
Base on @Mark answer, I add the constructor to directive and it work with me.
I share a sample to whom concern.
constructor(private el: ElementRef, private renderer: Renderer) {
}
TS file
@Directive({ selector: '[accordion]' })
export class AccordionDirective {
constructor(private el: ElementRef, private renderer: Renderer) {
}
@HostListener('click', ['$event']) onClick($event) {
console.info($event);
this.el.nativeElement.classList.toggle('is-open');
var content = this.el.nativeElement.nextElementSibling;
if (content.style.maxHeight) {
// accordion is currently open, so close it
content.style.maxHeight = null;
} else {
// accordion is currently closed, so open it
content.style.maxHeight = content.scrollHeight + "px";
}
}
}
HTML
<button accordion class="accordion">Accordian #1</button>
<div class="accordion-content">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
</p>
</div>
Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts
Or get the number of unique values for each column:
df.nunique()
dID 3
hID 5
mID 3
uID 5
dtype: int64
New in pandas 0.20.0
pd.DataFrame.agg
df.agg(['count', 'size', 'nunique'])
dID hID mID uID
count 8 8 8 8
size 8 8 8 8
nunique 3 5 3 5
You've always been able to do an agg
within a groupby
. I used stack
at the end because I like the presentation better.
df.groupby('mID').agg(['count', 'size', 'nunique']).stack()
dID hID uID
mID
A count 5 5 5
size 5 5 5
nunique 3 5 5
B count 2 2 2
size 2 2 2
nunique 2 2 2
C count 1 1 1
size 1 1 1
nunique 1 1 1
Create a new layout in drawable folder and name it custom_radiobutton (You can rename also)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false"
android:drawable="@drawable/your_radio_off_image_name" />
<item android:state_checked="true"
android:drawable="@drawable/your_radio_on_image_name" />
</selector>
Use this in your layout activity
<RadioButton
android:id="@+id/radiobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/custom_radiobutton"/>
I know this is old, but came across it looking for a simpler way, and this is how i do it, just create a new list of the same object and add it to the one you want to use e.g.
Subject[] subjectsList = {new Subject1{....}, new Subject2{....}, new Subject3{....}}
univStudent.subjects = subjectsList ;
with BytesIO() as output:
from PIL import Image
with Image.open(filename) as img:
img.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
I just use this for add a image to clipboard in windows.
I believe the best solution will be using head()
Considering your example:
+---+---+
| A| B|
+---+---+
|1.0|4.0|
|2.0|5.0|
|3.0|6.0|
+---+---+
Using agg and max method of python we can get the value as following :
from pyspark.sql.functions import max
df.agg(max(df.A)).head()[0]
This will return:
3.0
Make sure you have the correct import:
from pyspark.sql.functions import max
The max function we use here is the pySPark sql library function, not the default max function of python.
the problem here is that by using the apostrophes you are setting the value being passed to be a string, when in fact, as @Shijo stated from the documentation, the function is expecting a label or list, but not a string! If the list contains each of the name of the columns beings passed for both the left and right dataframe, then each column-name must individually be within apostrophes. With what has been stated, we can understand why this is inccorect:
new_df = pd.merge(A_df, B_df, how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')
And this is the correct way of using the function:
new_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])
UPDATE
Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.
This should work independent of the types and values:
$scope.$watch('[age,name]', function () { ... }, true);
You have to set the third parameter to true in this case.
The string concatenation 'age + name'
will fail in a case like this:
<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>
Before the user clicks the button the watched value would be 42foo
(42
+ foo
) and after the click 42foo
(4
+ 2foo
). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" />
<script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script>
<script>
angular.module('demo', []).controller('MainCtrl', function ($scope) {
$scope.firstWatchFunctionCounter = 0;
$scope.secondWatchFunctionCounter = 0;
$scope.$watch('[age, name]', function () { $scope.firstWatchFunctionCounter++; }, true);
$scope.$watch('age + name', function () { $scope.secondWatchFunctionCounter++; });
});
describe('Demo module', function () {
beforeEach(module('demo'));
describe('MainCtrl', function () {
it('watch function should increment a counter', inject(function ($controller, $rootScope) {
var scope = $rootScope.$new();
scope.age = 42;
scope.name = 'foo';
var ctrl = $controller('MainCtrl', { '$scope': scope });
scope.$digest();
expect(scope.firstWatchFunctionCounter).toBe(1);
expect(scope.secondWatchFunctionCounter).toBe(1);
scope.age = 4;
scope.name = '2foo';
scope.$digest();
expect(scope.firstWatchFunctionCounter).toBe(2);
expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail!
}));
});
});
(function () {
var jasmineEnv = jasmine.getEnv();
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body></body>
</html>
http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview
PS:
As stated by @reblace in a comment, it is of course possible to access the values:
$scope.$watch('[age,name]', function (newValue, oldValue) {
var newAge = newValue[0];
var newName = newValue[1];
var oldAge = oldValue[0];
var oldName = oldValue[1];
}, true);
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Here's a solution that uses more modern syntax and is less verbose than the ones already provided:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const video = document.querySelector("video");
video.addEventListener('play', () => {
function step() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
requestAnimationFrame(step)
}
requestAnimationFrame(step);
})
Some useful links:
yes, simply use colspan.
I've recently battled with this problem as well, and I've learned two things about the above suggestions.
The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.
Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.
OOP and the GoF patterns deal with states. OOP models reality to keep the code base as near as possible to the given requirements of reality. GoF design patterns are patterns that were identified to solve atomic real world problems. They handle the problem of state in a semantic way.
As in real functional programming no state exists, it does not make sense to apply the GoF patterns. There are not functional design patterns in the same way there are GoF design patterns. Every functional design pattern is artifical in contrast to reality as functions are constructs of math and not reality.
Functions lack the concept of time as they are always return the same value whatever the current time is unless time is part of the function parameters what makes it really hard to prrocess "future requests". Hybrid languages mix those concepts make the languages not real functional programming languages.
Functional languages are rising only because of one thing: the current natural restrictions of physics. Todays processors are limited in their speed of processing instructions due to physical laws. You see a stagnation in clock frequency but an expansion in processing cores. That's why parallelism of instructions becomes more and more important to increase speed of modern applications. As functional programming by definition has no state and therefore has no side effects it is safe to process functions safely in parallel.
GoF patterns are not obsolete. They are at least necessary to model the real world requirements. But if you use a functional programming language you have to transform them into their hybrid equivalents. Finally you have no chance to make only functional programs if you use persistence. For the hybrid elements of your program there remains the necessity to use GoF patterns. For any other element that is purely functional there is no necessity to use GoF patterns because there is no state.
Because the GoF patterns are not necessary for real functional programming, it doesn't mean that the SOLID principles should not be applied. The SOLID principles are beyond any language paradigm.
Convert Dictionary to Data Frame
col_dict_df = pd.Series(col_dict).to_frame('new_col').reset_index()
Give new name to Column
col_dict_df.columns = ['col1', 'col2']
byte * matToBytes(Mat image)
{
int size = image.total() * image.elemSize();
byte * bytes = new byte[size]; //delete[] later
std::memcpy(bytes,image.data,size * sizeof(byte));
}
Wrap the label and the input within a bootstraps div
<div class ="row">
<div class="col-md-4">Name:</div>
<div class="col-md-8"><input type="text"></div>
</div>
Here is code to set default radio button set to true
@Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = "checked", id = "rdGender", name = "rbGender" })
This will work with "org.bouncycastle.util.encoders.Hex" following package
return new String(Hex.encode(digest));
Its in bouncycastle jar.
That's easy to do in Interface Builder:
1) make UILabel Attributed in Attributes Inspector
2) select part of phrase you want to make bold
3) change its font (or bold typeface of the same font) in font selector
That's all!
The source code looks like -
package com.bluestone.pms.app.boot;
import org.springframework.boot.Banner;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.your.pkg"})
public class BootApplication extends SpringBootServletInitializer {
/**
* @param args Arguments
*/
public static void main(String[] args) {
SpringApplication application = new SpringApplication(BootApplication.class);
/* Setting Boot banner off default value is true */
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
/**
* @param builder a builder for the application context
* @return the application builder
* @see SpringApplicationBuilder
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
builder) {
return super.configure(builder);
}
}
very fast way , this method works very quickly:
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
Use this Format as per your requirements:
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay"
"arrayOneName" : [
{
"Id" : 1,
"Employee" : "EmpOne",
"Deptartment" : "HR"
},
{
"Id" : 2,
"Employee" : "EmpTwo",
"Deptartment" : "IT"
},
{
"Id" : 3,
"Employee" : "EmpThree",
"Deptartment" : "Sales"
}
],
"arrayTwoName": [
{
"Product": "3",
"Price": "6790"
}
],
"arrayThreeName" : [
"name1", "name2", "name3", "name4" // For Strings
],
"arrayFourName" : [
1, 2, 3, 4 // For Numbers
]
}
Remember to use this in POST with proper endpoint. Also, RAW selected and JSON(application/json) in Body Tab.
Like THIS:
Update 1:
I don't think multiple @RequestBody is allowed or possible.
@RequestBody parameter must have the entire body of the request and bind that to only one object.
You have to use something like Wrapper Object for this to work.
In Place of using this
MsgBox(json.SelectToken("Venue").SelectToken("ID"))
You can also use
MsgBox(json.SelectToken("Venue.ID"))
Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle foreign keys, indexes, triggers, or any other clever stuff. It works on SQLServer 2000, 2005 and 2008.
declare @schema varchar(100), @table varchar(100)
set @schema = 'dbo' -- set schema name here
set @table = 'MyTable' -- set table name here
declare @sql table(s varchar(1000), id int identity)
-- create statement
insert into @sql(s) values ('create table [' + @table + '] (')
-- column list
insert into @sql(s)
select
' ['+column_name+'] ' +
data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=@table
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(@table) as varchar) + ',' +
cast(ident_incr(@table) as varchar) + ')'
else ''
end + ' ' +
( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','
from INFORMATION_SCHEMA.COLUMNS where table_name = @table AND table_schema = @schema
order by ordinal_position
-- primary key
declare @pkname varchar(100)
select @pkname = constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where table_name = @table and constraint_type='PRIMARY KEY'
if ( @pkname is not null ) begin
insert into @sql(s) values(' PRIMARY KEY (')
insert into @sql(s)
select ' ['+COLUMN_NAME+'],' from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
where constraint_name = @pkname
order by ordinal_position
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
insert into @sql(s) values (' )')
end
else begin
-- remove trailing comma
update @sql set s=left(s,len(s)-1) where id=@@identity
end
-- closing bracket
insert into @sql(s) values( ')' )
-- result!
select s from @sql order by id
I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.
The solution is however straight forward:
Regex isn't needed, nor is plugins
if (isNaN($('#Field').val() / 1) == false) {
your code here
}
I wrote my own index-of function, inspired by strpos() in PHP.
<xsl:function name="fn:strpos">
<xsl:param name="haystack"/>
<xsl:param name="needle"/>
<xsl:value-of select="fn:_strpos($haystack, $needle, 1, string-length($haystack) - string-length($needle))"/>
</xsl:function>
<xsl:function name="fn:_strpos">
<xsl:param name="haystack"/>
<xsl:param name="needle"/>
<xsl:param name="pos"/>
<xsl:param name="count"/>
<xsl:choose>
<xsl:when test="$count < 0">
<!-- Not found. Most common is to return -1 here (or maybe 0 in XSL?). -->
<!-- But this way, the result can be used with substring() without checking. -->
<xsl:value-of select="string-length($haystack) + 1"/>
</xsl:when>
<xsl:when test="starts-with(substring($haystack, $pos), $needle)">
<xsl:value-of select="$pos"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="fn:_strpos($haystack, $needle, $pos + 1, $count - 1)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:function>
Try this explanation on...
TypeSafe means that variables are statically checked for appropriate assignment at compile time. For example, consder a string or an integer. These two different data types cannot be cross-assigned (ie, you can't assign an integer to a string nor can you assign a string to an integer).
For non-typesafe behavior, consider this:
object x = 89;
int y;
if you attempt to do this:
y = x;
the compiler throws an error that says it can't convert a System.Object to an Integer. You need to do that explicitly. One way would be:
y = Convert.ToInt32( x );
The assignment above is not typesafe. A typesafe assignement is where the types can directly be assigned to each other.
Non typesafe collections abound in ASP.NET (eg, the application, session, and viewstate collections). The good news about these collections is that (minimizing multiple server state management considerations) you can put pretty much any data type in any of the three collections. The bad news: because these collections aren't typesafe, you'll need to cast the values appropriately when you fetch them back out.
For example:
Session[ "x" ] = 34;
works fine. But to assign the integer value back, you'll need to:
int i = Convert.ToInt32( Session[ "x" ] );
Read about generics for ways that facility helps you easily implement typesafe collections.
C# is a typesafe language but watch for articles about C# 4.0; interesting dynamic possibilities loom (is it a good thing that C# is essentially getting Option Strict: Off... we'll see).
Step 1: Start button -> Computer menu item -> Properties on right click menu item -> Advanced System Settings button on left panel -> Advanced tab in System Properties dialog -> Environment Variables button -> System variables table
Step 2: Add MAVEN_HOME variable
Step 3: Update PATH variable
Step 4: Make sure you have JAVA_HOME variable correctly
step 5: open console and check below command
mvn -v
When they say List<T>
is "optimized" I think they want to mean that it doesn't have features like virtual methods which are bit more expensive. So the problem is that once you expose List<T>
in your public API, you loose ability to enforce business rules or customize its functionality later. But if you are using this inherited class as internal within your project (as opposed to potentially exposed to thousands of your customers/partners/other teams as API) then it may be OK if it saves your time and it is the functionality you want to duplicate. The advantage of inheriting from List<T>
is that you eliminate lot of dumb wrapper code that is just never going to be customized in foreseeable future. Also if you want your class to explicitly have exact same semantics as List<T>
for the life of your APIs then also it may be OK.
I often see lot of people doing tons of extra work just because of FxCop rule says so or someone's blog says it's a "bad" practice. Many times, this turns code in to design pattern palooza weirdness. As with lot of guideline, treat it as guideline that can have exceptions.
I'd go down the Ajax route as others suggested with something like:
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open("POST", "YourPageHere.asp", true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length);
self.xmlHttpReq.send("?YourQueryString=Value");
I would say that the consultant is right in the theory, and you are right in practice. As the saying goes:
In theory, theory and practice are the same. In practice, they are not.
The Java spec says that System.gc suggests to call garbage collection. In practice, it just spawns a thread and runs right away on the Sun JVM.
Although in theory you could be messing up some finely tuned JVM implementation of garbage collection, unless you are writing generic code intended to be deployed on any JVM out there, don't worry about it. If it works for you, do it.
stdbool.h was introduced in c99
You must just put the values into parentheses:
'%s in %s' % (unicode(self.author), unicode(self.publication))
Here, for the first %s
the unicode(self.author)
will be placed. And for the second %s
, the unicode(self.publication)
will be used.
Note: You should favor
string formatting
over the%
Notation. More info here
It is just this:
int count = 4;
string sub = mystring.Substring(mystring.Length - count, count);
git log path
should do what you want. From the git log
man:
[--] <path>…
Show only commits that affect any of the specified paths. To prevent confusion with
options and branch names, paths may need to be prefixed with "-- " to separate them
from options or refnames.
If you are using Sentry
check the logged in user with Sentry::getUser()->id
. The error you get is that the Auth::user()
returns NULL and it tries to get id from NULL hence the error trying to get a property from a non-object
.
This solution worked for me:
var rawBodySaver = function (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
}
app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));
When I use solution with req.on('data', function(chunk) { });
it not working on chunked request body.
I've solved this error by this way.
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;
Error still occurs, but I can handle response data in variable.
var classname=$('#div1').attr('class')
Android documents suggests to use getApplicationContext();
but it will not work instead of that use your current activity while instantiating AlertDialog.Builder or AlertDialog or Dialog...
Ex:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
or
AlertDialog.Builder builder = new AlertDialog.Builder((Your Activity).this);
There are two ways to do the redirect. Both apply to either subprocess.Popen
or subprocess.call
.
Set the keyword argument shell = True
or executable = /path/to/the/shell
and specify the command just as you have it there.
Since you're just redirecting the output to a file, set the keyword argument
stdout = an_open_writeable_file_object
where the object points to the output
file.
subprocess.Popen
is more general than subprocess.call
.
Popen
doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen
returns a Popen
object.
call
does block. While it supports all the same arguments as the Popen
constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call
returns a code representing the process' exit status.
returncode = call(*args, **kwargs)
is basically the same as calling
returncode = Popen(*args, **kwargs).wait()
call
is just a convenience function. It's implementation in CPython is in subprocess.py:
def call(*popenargs, timeout=None, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
As you can see, it's a thin wrapper around Popen
.
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
We do it this way...
String.prototype.getValueByKey = function (k) {
var p = new RegExp('\\b' + k + '\\b', 'gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};
You declare the variable as extern
in a common header:
//globals.h
extern int x;
And define it in an implementation file.
//globals.cpp
int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace
.
A span tag is only as wide as its contents, so there is no 'center' of a span tag. There is no extra space on either side of the content.
A div tag, however, is as wide as its containing element, so the content of that div can be centered using any extra space that the content doesn't take up.
So if your div is 100px width and your content only takes 50px, the browser will divide the remaining 50px by 2 and pad 25px on each side of your content to center it.
dummyElem.focus() where dummyElem is a hidden object (e.g. has negative zIndex)?
Do you want an incrementing integer column returned with your recordset? If so: -
--Check for existance
if exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1)
drop table dbo.t
go
--create dummy table and insert data
create table dbo.t(x char(1) not null primary key, y char(1) not null)
go
set nocount on
insert dbo.t (x,y) values ('A','B')
insert dbo.t (x,y) values ('C','D')
insert dbo.t (x,y) values ('E','F')
--create temp table to add an identity column
create table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null)
--populate the temporary table
insert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t
--return the data
select i,x,y from dbo.#TempWithIdentity
--clean up
drop table dbo.#TempWithIdentity
HTML
<table cellspacing="0">
<tr class="top bottom row">
<td>one one</td>
<td>one two</td>
</tr>
<tr class="top bottom row">
<td>two one</td>
<td>two two</td>
</tr>
<tr class="top bottom row">
<td>three one</td>
<td>three two</td>
</tr>
</table>?
CSS:
tr.top td { border-top: thin solid black; }
tr.bottom td { border-bottom: thin solid black; }
tr.row td:first-child { border-left: thin solid black; }
tr.row td:last-child { border-right: thin solid black; }?
as @MikeM pointed out.
select exists(select 1 from contact where id=12)
with index on contact, it can usually reduce time cost to 1 ms.
CREATE INDEX index_contact on contact(id);
memset
requires you to import the header string.h
file. So just add the following header
#include <string.h>
...
This should do it (bold as well);
label1.Font = new Font("Serif", 24,FontStyle.Bold);
The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.
import numpy as np
names = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 , 0.5678 , 0.9123 ])
ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats
np.savetxt('test.txt', ab, fmt="%10s %10.3f")
Update: This example also works properly in Python 3 by using the 'U6'
Unicode string dtype, when creating the ab
structured array, instead of the 'S6'
byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1'
in Python 3.
You can also do like this:
var mocha = require('mocha')
var describe = mocha.describe
var it = mocha.it
var assert = require('chai').assert
describe('#indexOf()', function() {
it('should return -1 when not present', function() {
assert.equal([1,2,3].indexOf(4), -1)
})
})
Reference: http://mochajs.org/#require
That's basically it. These are the methods I use to convert to and from Unix epoch time:
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return origin.AddSeconds(timestamp);
}
public static double ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan diff = date.ToUniversalTime() - origin;
return Math.Floor(diff.TotalSeconds);
}
Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch
.
The NuGet package Pdf2Png is available for free and is only protected by the MIT License, which is very open.
I've tested around a bit and this is the code to get it to convert a PDF file to an image (tt does save the image in the debug folder).
using cs_pdf_to_image;
using PdfToImage;
private void BtnConvert_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string PdfFile = openFileDialog1.FileName;
string PngFile = "Convert.png";
List<string> Conversion = cs_pdf_to_image.Pdf2Image.Convert(PdfFile, PngFile);
Bitmap Output = new Bitmap(PngFile);
PbConversion.Image = Output;
}
catch(Exception E)
{
MessageBox.Show(E.Message);
}
}
}
One time when an FK might cause you a problem is when you have historical data that references the key (in a lookup table) even though you no longer want the key available.
Obviously the solution is to design things better up front, but I am thinking of real world situations here where you don't always have control of the full solution.
For example: perhaps you have a look up table customer_type
that lists different types of customers - lets say you need to remove a certain customer type, but (due to business restraints) aren't able to update the client software, and nobody invisaged this situation when developing the software, the fact that it is a foreign key in some other table may prevent you from removing the row even though you know the historical data that references it is irrelevant.
After being burnt with this a few times you probably lean away from db enforcement of relationships.
(I'm not saying this is good - just giving a reason why you may decide to avoid FKs and db contraints in general)
Agree @Drixson Oseña: You should not write localhost/xampp/...., else write for e.g: localhost/mw-config/index.php
Check in Administration Tools\Services (or type services.msc in the console if you a service named SQL Server (SQLEXPRESS). If you do then it is installed.
From Visual Studio open Server Explorer (menu View\Server Explorer or CTRL + W, L). Right click Data Connections and choose Create New SQL Server Database. After that create tables and stuff...
If you want the Management Studio to manage the server you must download and install it from:
I have been looking for the same feature for Postgres (or SQL databases in general) for a while, but I found no tools to be suitable (simple and intuitive) enough. This is probably due to the binary nature of how data is stored. Klonio sounds ideal but looks dead. Noms DB looks interesting (and alive). Also take a look at Irmin (OCaml-based with Git-properties).
Though this doesn't answer the question in that it would work with Postgres, check out the Flur.ee database. It has a "time-travel" feature that allows you to query the data from an arbitrary point in time. I'm guessing it should be able to work with a "branching" model.
This database was recently being developed for blockchain-purposes. Due to the nature of blockchains, the data needs to be recorded in increments, which is exactly how git works. They are targeting an open-source release in Q2 2019.
Update: Also check out the Crux database, which can query across the time dimension of inserts, which you could see as 'versions'. Crux seems to be an open-source implementation of the highly appraised Datomic.
Crux is a bitemporal database that stores transaction time and valid time histories. While a [uni]temporal database enables "time travel" querying through the transactional sequence of database states from the moment of database creation to its current state, Crux also provides "time travel" querying for a discrete valid time axis without unnecessary design complexity or performance impact. This means a Crux user can populate the database with past and future information regardless of the order in which the information arrives, and make corrections to past recordings to build an ever-improving temporal model of a given domain.
Update II Check out Terminus DB: "Documentation for TerminusDB - an open-source graph database that stores data like git".
To change the font globally for ggplot2 plots.
theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))
What are -moz- and -webkit-?
CSS properties starting with -webkit-
, -moz-
, -ms-
or -o-
are called vendor prefixes.
Why do different browsers add different prefixes for the same effect?
A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:
Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.
Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.
Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds
-ms-grid
.The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.
UPDATE AS OF THE YEAR 2016
As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.
As mentioned in this glossary about Mozilla's view on Vendor Prefix
on May 3, 2016
,
Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.
For example, just a few years ago, to set a rounded corner on a box you had to write:
-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;
But now that browsers have come to fully support this feature, you really only need the standardized version:
border-radius: 10px 5px;
Finding the right rules for all browsers
As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.
You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.
Input:
a {
column-count: 3;
column-gap: 10px;
column-fill: auto;
}
Output:
a {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
-webkit-column-gap: 10px;
-moz-column-gap: 10px;
column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-fill: auto;
column-fill: auto;
}
If you need to do it manually, one time:
First, merge in a temporary table, with something like:
create table MERGED as select * from table 1 UNION select * from table 2
Then, identify the primary key constraints with something like
SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1
Where PK is the primary key field...
Solve the duplicates.
Rename the table.
[edited - removed brackets in the UNION query, which was causing the error in the comment below]
You are applying shapiro.test()
to a data.frame
instead of the column. Try the following:
shapiro.test(heisenberg$HWWIchg)
Use max-width
on the images too. Change:
.erb-image-wrapper img{
width:100% !important;
height:100% !important;
display:block;
}
to...
.erb-image-wrapper img{
max-width:100% !important;
max-height:100% !important;
display:block;
}
Two types of mongo dependencies -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Two types of repositories -
MongoRepository
ReactiveMongoRepository
Make sure you are using the right combination.
>>> dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
If they are not the same size, zip
will truncate the longer one.
XHTML solution:
<input type="radio" name="imgsel" value="" checked="checked" />
Please note, that the actual value of checked
attribute does not actually matter; it's just a convention to assign "checked"
. Most importantly, strings like "true"
or "false"
don't have any special meaning.
If you don't aim for XHTML conformance, you can simplify the code to:
<input type="radio" name="imgsel" value="" checked>
Note that, since git 1.8.3 (April, 22d 2013):
"
git count-objects
" learned "--human-readable
" aka "-H
" option to show various large numbers inKi
/Mi
/GiB
scaled as necessary.
That could be combined with the -v
option mentioned by Jack Morrison in his answer.
git gc
git count-objects -vH
(git gc
is important, as mentioned by A-B-B's answer)
Plus (still git 1.8.3), the output is more complete:
"
git count-objects -v
" learned to report leftover temporary packfiles and other garbage in the object store.
Insert in the lint.xml
file this:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
...
<issue
id="MissingTranslation"
severity="ignore" />
</lint>
For more details: Suppressing Lint Warnings.
Using ObjectMapper framework
if let path = Bundle(for: BPPView.self).path(forResource: jsonFileName, ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
self.levels = Mapper<Level>().mapArray(JSONArray: (json as! [[String : Any]]))!
print(levels.count)
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}
Before you should prepare the set of appropriate :Mappable objects to parse into
import UIKit
import ObjectMapper
class Level: Mappable {
var levelName = ""
var levelItems = [LevelItem]()
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
levelName <- map["levelName"]
levelItems <- map["levelItems"]
}
import UIKit
import ObjectMapper
class LevelItem: Mappable {
var frontBackSide = BPPFrontBack.Undefined
var fullImageName = ""
var fullImageSelectedName = ""
var bodyParts = [BodyPart]()
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
frontBackSide <- map["frontBackSide"]
fullImageName <- map["fullImageName"]
fullImageSelectedName <- map["fullImageSelectedName"]
bodyParts <- map["bodyParts"]
}}
I realize this is a very old question, and that the answers provided were adequate, since is active and I came across this by doing some research on fullscreen, I leave here one update to this topic:
There is a way to "simulate" the F11 key, but cannot be automated, the user actually needs to click a button for example, in order to trigger the full screen mode.
With this example, the user can switch to and from fullscreen mode by clicking a button:
HTML element to act as trigger:
<input type="button" value="click to toggle fullscreen" onclick="toggleFullScreen()">
JavaScript:
function toggleFullScreen() {
if ((document.fullScreenElement && document.fullScreenElement !== null) ||
(!document.mozFullScreen && !document.webkitIsFullScreen)) {
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
}
This example allows you to enable full screen mode without making alternation, ie you switch to full screen but to return to the normal screen will have to use the F11 key:
HTML element to act as trigger:
<input type="button" value="click to go fullscreen" onclick="requestFullScreen()">
JavaScript:
function requestFullScreen() {
var el = document.body;
// Supports most browsers and their versions.
var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen
|| el.mozRequestFullScreen || el.msRequestFullScreen;
if (requestMethod) {
// Native full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") {
// Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
How to make in Javascript full screen windows (stretching all over the screen)
How to make browser full screen using F11 key event through JavaScript
I just stumbled upon a usage of __call__()
in concert with __getattr__()
which I think is beautiful. It allows you to hide multiple levels of a JSON/HTTP/(however_serialized) API inside an object.
The __getattr__()
part takes care of iteratively returning a modified instance of the same class, filling in one more attribute at a time. Then, after all information has been exhausted, __call__()
takes over with whatever arguments you passed in.
Using this model, you can for example make a call like api.v2.volumes.ssd.update(size=20)
, which ends up in a PUT request to https://some.tld/api/v2/volumes/ssd/update
.
The particular code is a block storage driver for a certain volume backend in OpenStack, you can check it out here: https://github.com/openstack/cinder/blob/master/cinder/volume/drivers/nexenta/jsonrpc.py
EDIT: Updated the link to point to master revision.
You can change the tint, quite easily in code via:
imageView.setColorFilter(Color.argb(255, 255, 255, 255));
// White Tint
If you want color tint then
imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.MULTIPLY);
For Vector Drawable
imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.SRC_IN);
UPDATE:
@ADev has newer solution in his answer here, but his solution requires newer support library - 25.4.0 or above.
Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.
A:you need to configure the primeng tabulemodule in ngmodule
The chart control in the WPF Toolkit has a horrible bug: it never forgets any of the data points. So if you try to implement a floating chart you will get out of memory after round about 3000 DataPoint-objects. This bug has been reported to MS over a year ago but nobody seems to care...
java.io.NotSerializableException
can occur when you serialize an inner class instance because:
serializing such an inner class instance will result in serialization of its associated outer class instance as well
Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged
Here is the solution: - Go to build settings - Search SWIFT_COMPILATION_MODE - If this is "Whole Module" for Release configuration then change it to "Incremental". - Archive now.
When you change the setting to "Incremental" the process succeeds.
It's called designated initializer which is introduced in C99. It's used to initialize struct
or arrays, in this example, struct
.
Given
struct point {
int x, y;
};
the following initialization
struct point p = { .y = 2, .x = 1 };
is equivalent to the C89-style
struct point p = { 1, 2 };
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
You can also call any controller from JavaScript/jQuery. Say you have a controller returning 404 or some other usercontrol/page. Then, on some action, from your client code, you can call some address that will fire your controller and return the result in HTML format your client code can take this returned result and put it wherever you want in you your page...
When I ran mongod.exe from Windows Terminal I got a message Unrecognized option: mp
. There was an empty mp:
in the end of mongod.cfg
. Removing that solved the problem for me.
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console
class. you can not get Console instance from System.console()
when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
There are two types of measurements you can use for specifying widths, heights, margins etc: relative and fixed.
An example of a relative measurement is percentages, which you have used. Percentages are relevant to their containing element. If there is no containing element they are relative to the window.
<div style="width:100%">
<!-- This div will be the full width of the browser, whatever size it is -->
<div style="width:300px">
<!-- this div will be 300px, whatever size the browser is -->
<p style="width:50%">
This paragraph's width will be 50% of it's parent (150px).
</p>
</div>
</div>
Another relative measurement is ems which are relative to font size.
An example of a fixed measurement is pixels but a fixed measurement can also be pt (points), cm (centimetres) etc. Fixed (sometimes called absolute) measurements are always the same size. A pixel is always a pixel, a centimetre is always a centimetre.
If you were to use fixed measurements for your sizes the browser size wouldn't affect the layout.
This only covers a simple case:
a = ‘Quattro TT’
print tuple(a)
If you use only delimiter like ‘,’, then it could work.
I used a string from configparser
like so:
list_users = (‘test1’, ‘test2’, ‘test3’)
and the i get from file
tmp = config_ob.get(section_name, option_name)
>>>”(‘test1’, ‘test2’, ‘test3’)”
In this case the above solution does not work. However, this does work:
def fot_tuple(self, some_str):
# (‘test1’, ‘test2’, ‘test3’)
some_str = some_str.replace(‘(‘, ”)
# ‘test1’, ‘test2’, ‘test3’)
some_str = some_str.replace(‘)’, ”)
# ‘test1’, ‘test2’, ‘test3’
some_str = some_str.replace(“‘, ‘”, ‘,’)
# ‘test1,test2,test3’
some_str = some_str.replace(“‘”, ‘,’)
# test1,test2,test3
# and now i could convert to tuple
return tuple(item for item in some_str.split(‘,’) if item.strip())
Yes, you may use both ways. If you just want to separate the elements and show they in separated lines, a list is simpler:
set list=A B C D
A list of values separated by space may be easily processed by for
command:
(for %%a in (%list%) do (
echo %%a
echo/
)) > theFile.txt
You may also create an array this way:
setlocal EnableDelayedExpansion
set n=0
for %%a in (A B C D) do (
set vector[!n!]=%%a
set /A n+=1
)
and show the array elements this way:
(for /L %%i in (0,1,3) do (
echo !vector[%%i]!
echo/
)) > theFile.txt
For further details about array management in Batch files, see: Arrays, linked lists and other data structures in cmd.exe (batch) script
ATTENTION! You must know that all characters included in set
command are inserted in the variable name (at left of equal sign), or in the variable value. For example, this command:
set list = "A B C D"
create a variable called list
(list-space) with the value "A B C D"
(space, quote, A, etc). For this reason, it is a good idea to never insert spaces in set
commands. If you need to enclose the value in quotes, you must enclose both the variable name and its value:
set "list=A B C D"
PS - You should NOT use ECHO.
in order to left blank lines! An alternative is ECHO/
. For further details about this point, see: http://www.dostips.com/forum/viewtopic.php?f=3&t=774
I found this question looking to change the timezone in my Django project's settings.py
file to the United Kingdom.
Using the tz database in jfs' solution I found the answer:
TIME_ZONE = 'Europe/London'
Regarding number of days in month just use static switch command and check if (year % 4 == 0)
in which case February will have 29 days.
Minute, hour, day etc:
var someMillisecondValue = 511111222127;
var date = new Date(someMillisecondValue);
var minute = date.getMinutes();
var hour = date.getHours();
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
alert([minute, hour, day, month, year].join("\n"));
Check with "uname -a" and/or "lsb_release -a" to see which version of Linux you are actually running on your AWS instance. The default Amazon AMI image uses YUM for its package manager.
I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:
public static byte[] httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException {
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : postsData.entrySet()) {
if (postData.length() != 0) postData.append('&');
Object value = param.getValue();
String key = param.getKey();
if(value instanceof Object[] || value instanceof List<?>)
{
int size = value instanceof Object[] ? ((Object[])value).length : ((List<?>)value).size();
for(int i = 0; i < size; i++)
{
Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List<?>)value).get(i);
if(i>0) postData.append('&');
postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(val), "UTF-8"));
}
}
else
{
postData.append(URLEncoder.encode(key, "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
}
}
return postData.toString().getBytes("UTF-8");
}
The init(frame:)
version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:)
version will be called. Since Swift now requires an implementation of the required init?(coder:)
, I have updated the example below and changed the let
variable declarations to var
and optional. In this case, you would initialize them in awakeFromNib()
or at some later time.
class TestView : UIView {
var s: String?
var i: Int?
init(s: String, i: Int) {
self.s = s
self.i = i
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
Down-casting and up-casting was as follows:
Upcasting: When we want to cast a Sub class to Super class, we use Upcasting(or widening). It happens automatically, no need to do anything explicitly.
Downcasting : When we want to cast a Super class to Sub class, we use Downcasting(or narrowing), and Downcasting is not directly possible in Java, explicitly we have to do.
Dog d = new Dog();
Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting
d.callme();
a.callme(); // It calls Dog's method even though we use Animal reference.
((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly.
// Internally if it is not a Dog object it throws ClassCastException
None of these worked for me. I converted the first element to be part of a series (a single element series), and converted the second element also to be a series, and used append function.
l = ((pd.Series(<first element>)).append(pd.Series(<list of other elements>))).tolist()
Here's a method that works by transforming the querystring into JSON...
var link = $('a').attr('href');
if (link.indexOf("?") != -1) {
var query = link.split("?")[1];
eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");
if (query.page)
alert(unescape(query.page));
else
alert('No page parameter');
} else {
alert('No querystring');
}
I'd go with a library like the others suggest though... =)
Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch()
to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.
Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.
The pip's proxy parameter is, according to pip --help
, in the form scheme://[user:passwd@]proxy.server:port
You should use the following:
pip install --proxy http://user:password@proxyserver:port TwitterApi
Also, the HTTP_PROXY
env var should be respected.
Note that in earlier versions (couldn't track down the change in the code, sorry, but the doc was updated here), you had to leave the scheme://
part out for it to work, i.e. pip install --proxy user:password@proxyserver:port
You can check it by regular expression
public boolean isValid(String strEmail)
{
pattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
matcher = pattern.matcher(strEmail);
if (strEmail.isEmpty()) {
return false;
} else if (!matcher.matches()) {
return false;
}
else
{
return true;
}
}
Create your AlphaAnimation
Object that decides how much will be the fading effect of the button, then let it start in the onClickListener
of your buttons
For example :
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
// some code
public void onClick(View v) {
v.startAnimation(buttonClick);
}
of course this is just a way, not the most preferred one, it's just easier
One solution is to use subquery
DELETE FROM posts WHERE post_id in (SELECT post_id FROM posts p
INNER JOIN projects prj ON p.project_id = prj.project_id
INNER JOIN clients c on prj.client_id = c.client_id WHERE c.client_id = :client_id
);
The subquery returns the ID that need to be deleted; all three tables are connected using joins and only those records are deleted that meets the filter condition (in yours case i.e. client_id in the where clause).
An easy way to overcome this problem is to use 64 bit type
list = numpy.array(list, dtype=numpy.float64)
As @FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).
However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.
Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.
Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).
function getMonthDays(MonthYear) {
var months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
var Value=MonthYear.split(" ");
var month = (months.indexOf(Value[0]) + 1);
return new Date(Value[1], month, 0).getDate();
}
console.log(getMonthDays("March 2011"));
With the release of TypeScript 3.7, optional chaining (the ?
operator) is now officially available.
As such, you can simplify your expression to the following:
const data = change?.after?.data();
You may read more about it from that version's release notes, which cover other interesting features released on that version.
Run the following to install the latest stable release of TypeScript.
npm install typescript
That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null
or undefined
values
const data = change?.after?.data() ?? someOtherData();
An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.
CREATE VIEW xyz SELECT q.question, a.alternative
FROM tbl_question AS q, tbl_alternative AS a
WHERE q.categoryid = a.categoryid
AND q._id = a.questionid;
This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html
I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.
Except for the first time, each time a word is seen the if statement's test fails. If you are counting a large number of words, many will probably occur multiple times. In a situation where the initialization of a value is only going to occur once and the augmentation of that value will occur many times it is cheaper to use a try statement:
urls_d = {}
for url in list_of_urls:
try:
urls_d[url] += 1
except KeyError:
urls_d[url] = 1
you can read more about this: https://wiki.python.org/moin/PythonSpeed/PerformanceTips
controller name:
<%= controller.controller_name %>
return => 'users'
action name:
<%= controller.action_name %>
return => 'show'
id:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
return => '23'
There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.
The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.
Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.
Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:
why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.
Solution:
check write permissions on registers
a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it
b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log
c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"
d. run the following command netsh int ipv6 reset reset.log
and repeat step c)
unistall all not-working miniports
a. go to device managers (windows+x -> device manager)
b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)
c. unistall these not working devices
d. reboot your computer
e. Repeat steps a) - d) until you will not see any yellow mark on miniports
delete your vpn connection and create a new one.
that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)
references:
In Java 8+, you can create an IntStream
in the range of 0
to myArray.length
and check that all values are true
in the corresponding (primitive) array with something like,
return IntStream.range(0, myArray.length).allMatch(i -> myArray[i]);
Here is another solution using css transform (for performance purposes on mobiles, see answer of @mate64 ) without having to use animations and keyframes.
I created two versions to slide-in from either side.
$('#toggle').click(function() {_x000D_
$('.slide-in').toggleClass('show');_x000D_
});
_x000D_
.slide-in {_x000D_
z-index: 10; /* to position it in front of the other content */_x000D_
position: absolute;_x000D_
overflow: hidden; /* to prevent scrollbar appearing */_x000D_
}_x000D_
_x000D_
.slide-in.from-left {_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
.slide-in.from-right {_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
.slide-in-content {_x000D_
padding: 5px 20px;_x000D_
background: #eee;_x000D_
transition: transform .5s ease; /* our nice transition */_x000D_
}_x000D_
_x000D_
.slide-in.from-left .slide-in-content {_x000D_
transform: translateX(-100%);_x000D_
-webkit-transform: translateX(-100%);_x000D_
}_x000D_
_x000D_
.slide-in.from-right .slide-in-content {_x000D_
transform: translateX(100%);_x000D_
-webkit-transform: translateX(100%);_x000D_
}_x000D_
_x000D_
.slide-in.show .slide-in-content {_x000D_
transform: translateX(0);_x000D_
-webkit-transform: translateX(0);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="slide-in from-left">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="slide-in from-right">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>One</li>_x000D_
<li>Two</li>_x000D_
<li>Three</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
The common practice is to put scripts in a discrete folder, typically at the root of the site. So, if clock.js lived here:
/js/clock.js
then you could add this code to the top of any page in your site and it would just work:
<script src="/js/clock.js" type="text/javascript"></script>
Update 10/11/2020 to reflect the latest brew changes.
Brew
already provide a command to uninstall itself (this will remove everything you installed with Homebrew):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
If you failed to run this command due to permission (like run as second user), run again with sudo
Then you can install again:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
Here's the complete process in Kotlin:
the spinner adapter class:
class CustomSpinnerAdapter(
context: Context,
textViewResourceId: Int,
val list: List<User>
) : ArrayAdapter<User>(
context,
textViewResourceId,
list
) {
override fun getCount() = list.size
override fun getItem(position: Int) = list[position]
override fun getItemId(position: Int) = list[position].report.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return (super.getDropDownView(position, convertView, parent) as TextView).apply {
text = list[position].name
}
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return (super.getDropDownView(position, convertView, parent) as TextView).apply {
text = list[position].name
}
}
}
and use it in your activity/fragment like this:
spinner.adapter = CustomerSalesSpinnerAdapter(
context,
R.layout.cuser_spinner_item,
userList
)
There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.
And See this question too : Generating SQL using XML and XSLT
From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:
select * from table where length(RTRIM(fieldName))=10
UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:
select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890 ' as varchar(30)) ))
as tab(fieldName)
FIELDNAME LEN_ONLY LEN_RTRIM
------------------------------ ----------- -----------
1234567890 12 10
One can test this by using this term:
where length(fieldName)!=length(rtrim(fieldName))
select translate(description,'\\t','') from myTable;
Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)
Char/varchar support added as of Hive 0.14.0
Tested on Ubuntu:
sudo apt install git-extras
git-show-tree
This produces an effect similar to the 2 most upvoted answers here.
Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html
Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow
shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch
or manually via git branch --set-upstream-to=upstream_branch
).
git branch
you are on too!"If you're running into this error from a downloaded powershell script, you can unblock the script this way:
Right-click on the .ps1
file in question, and select Properties
Click Unblock in the file properties
Click OK
In your code if you use requestWindowFeature(Window.FEATURE_NO_TITLE);
be sure that it goes before dialog.setContentView();
otherwise it causes the application to crash.
Open the XAMMP php.ini file (the default path is C:\xammp\php\php.ini) and change the code (;extension=ldap) to extension=php_ldap.dll and save. Restart XAMMP and save.
php.ini
; Notes for Windows environments :
;
; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
; extension folders as well as the separate PECL DLL download (PHP 5+).
; Be sure to appropriately set the extension_dir directive.
;
extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
extension=php_ldap.dll
This is an old question but it can be summed up as easily as this if you're using django-registration.
In your Log In and Log Out link (lets say in your page header) add the next parameter to the link which will go to login or logout. Your link should look like this.
<li><a href="http://www.noobmovies.com/accounts/login/?next={{ request.path | urlencode }}">Log In</a></li>
<li><a href="http://www.noobmovies.com/accounts/logout/?next={{ request.path | urlencode }}">Log Out</a></li>
That's simply it, nothing else needs to be done, upon logout they will immediately be redirected to the page they are at, for log in, they will fill out the form and it will then redirect to the page that they were on. Even if they incorrectly try to log in it still works.
Check out the documentation for numpy.sum
, paying particular attention to the axis
parameter. To sum over columns:
>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])
Or, to sum over rows:
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
Other aggregate functions, like numpy.mean
, numpy.cumsum
and numpy.std
, e.g., also take the axis
parameter.
From the Tentative Numpy Tutorial:
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the
ndarray
class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying theaxis
parameter you can apply an operation along the specified axis of an array:
I faced the same issue. My code was a .NET dll (AutoCAD extension) running inside AutoCAD 2012. I am also using Oracle.DataAccess and my code was throwing the same exception during ExecuteNonQuery(). I luckily solved this problem by changing the .net version of the ODP I was using (that is, 2.x of Oracle.DataAccess)
The answer from @gunn is correct, target="_blank
makes the link open in a new tab.
But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer"
.
<a style={{display: "table-cell"}} href = "someLink" target = "_blank"
rel = "noopener noreferrer">text</a>
To do it in PHP: You have a couple of parameters to view your page, lets say action
and view-all
. You will (probably) access these already with $action = $_GET['action']
or whatever, maybe setting a default value.
Then you decide depending on that if you want to swich a variable like $viewAll = $viewAll == 'Yes' ? 'No' : 'Yes'
.
And in the end you just build the url with these values again like
$clickUrl = $_SERVER['PHP_SELF'] . '?action=' . $action . '&view-all=' . $viewAll;
And thats it.
So you depend on the page status and not the users url (because maybe you decide later that $viewAll is Yes as default or whatever).
If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:
function interval(date1, date2) {_x000D_
if (date1 > date2) { // swap_x000D_
var result = interval(date2, date1);_x000D_
result.years = -result.years;_x000D_
result.months = -result.months;_x000D_
result.days = -result.days;_x000D_
result.hours = -result.hours;_x000D_
return result;_x000D_
}_x000D_
result = {_x000D_
years: date2.getYear() - date1.getYear(),_x000D_
months: date2.getMonth() - date1.getMonth(),_x000D_
days: date2.getDate() - date1.getDate(),_x000D_
hours: date2.getHours() - date1.getHours()_x000D_
};_x000D_
if (result.hours < 0) {_x000D_
result.days--;_x000D_
result.hours += 24;_x000D_
}_x000D_
if (result.days < 0) {_x000D_
result.months--;_x000D_
// days = days left in date1's month, _x000D_
// plus days that have passed in date2's month_x000D_
var copy1 = new Date(date1.getTime());_x000D_
copy1.setDate(32);_x000D_
result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
}_x000D_
if (result.months < 0) {_x000D_
result.years--;_x000D_
result.months+=12;_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).
So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.
Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).
For me, I have to run
sudo dpkg --add-architecture i386
before running Mike Tang's answer. Otherwise, I can't install ia32-libs.
For mysqli you can use :
$db = ADONewConnection('mysqli');
... ...
$db->execute("set names 'utf8'");
How about doing this?
import string
def isAscii(s):
for c in s:
if c not in string.ascii_letters:
return False
return True
After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:
Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));
Please inform me if you have any difficulties implementing this solution so I can help.
const dismissKeyboard = require('dismissKeyboard');
dismissKeyboard(); //dismisses it
Approach No# 2;
Thanks to user @ricardo-stuven for pointing this out, there is another better way to dismiss the keyboard which you can see in the example in the react native docs.
Simple import Keyboard
and call it's method dismiss()
DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:
num_rows_deleted = db.session.query(Model).delete()
Also, don't forget that the deletion won't take effect until you commit, as in this snippet:
try:
num_rows_deleted = db.session.query(Model).delete()
db.session.commit()
except:
db.session.rollback()
It doesn't matter - they're both allowed inside each other.
You could use the Chr(int) function
i don't know of a simple css(2.1 standard)-only solution for circles, but for squares you can do easily:
.squared {
border: 2x solid black;
}
then, use the following html code:
<img src="…" alt="an image " class="squared" />
Swift version:
let navigationBarHeight: CGFloat = self.navigationController!.navigationBar.frame.height
I think in general, you'd want a web service for a blocking task (this tasks needs to be completed before we execute more code), and a message queue for a non-blocking task (could take quite a while, but we don't need to wait for it).
I can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.
Anyway, you shouldn't hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:
data: JSON.stringify({ name : "AA" }),
Now on the server also make sure that you have the proper view model expecting to receive this input:
public class UserViewModel
{
public string Name { get; set; }
}
and the corresponding action:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
}
Now there's one more thing. You have specified dataType: 'json'
. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
return Json(new { Foo = "bar" });
}
This being said, in most cases, usually you don't need to set the dataType
property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult
(such as a ViewResult
or a JsonResult
), the framework will automatically set the correct Content-Type
response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.
I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).
One more thing that I just noticed:
async: false,
Please, avoid setting this attribute to false. If you set this attribute to false
you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.
On Mac OS X, you can use Ctrl + Fn + F12 to rotate the Android emulator if you have have not configured your keyboard to "Use all F1, F2, etc. keys as standard function keys" (Check it on System Preferences - Keyboard).
If you have checked the option mentioned above, you will not need the Fn key and you should be able to rotate the emulator only with Ctrl + F12.
There are some cool answers here (errator esp.), but for something analogous to split in other languages -- which is what I took the original question to mean -- I settled on this:
IN="[email protected];[email protected]"
declare -a a="(${IN/;/ })";
Now ${a[0]}
, ${a[1]}
, etc, are as you would expect. Use ${#a[*]}
for number of terms. Or to iterate, of course:
for i in ${a[*]}; do echo $i; done
IMPORTANT NOTE:
This works in cases where there are no spaces to worry about, which solved my problem, but may not solve yours. Go with the $IFS
solution(s) in that case.
unicodestring = '\xa0'
decoded_str = unicodestring.decode("windows-1252")
encoded_str = decoded_str.encode('ascii', 'ignore')
Works for me
I would recommend having a look at this answer of mine, and see if it is relevant to what you are doing. If I understand your real problem, it's that your just not using your async action correctly and updating the redux "store", which will automatically update your component with it's new props.
This section of your code:
componentDidMount() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Should not be triggering in a component, it should be handled after executing your first request.
Have a look at this example from redux-thunk:
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
You don't necessarily have to use redux-thunk, but it will help you reason about scenarios like this and write code to match.
Guess You are running on Windows (To make @jowey's answer more straightforward).
$ npm install -g @angular/cli@latest
Next is to rearrange the PATHS toin System Environment Variables, the picture below shows the arrangement.
The best way to do this is using Google Tag Manager to fire your Google Analytics tags based on history listeners. These are built in to the GTM interface and easily allow tracking on client side HTML5 interactions .
Enable the built in History variables and create a trigger to fire an event based on history changes.
For me the problem was caused when I took my laptop home without restarting the emulator. From what I have read, when the emulator starts up it reads your PC's DNS settings and uses them. When I was on my home network, my work DNS settings were failing.
So yeah. Just restarting the emulator solved my problem.
SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.
What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:
backup.bat:
sqlcmd -i backup.sql
backup.sql:
backup database TeamCity to disk = 'c:\backups\MyBackup.bak'
Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.
The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE
queries instead.
If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.
It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:
How do I get started with the SQL Server Maintenance Solution on SQL Server Express?
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.
Download MaintenanceSolution.sql.
Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.
Create cmd files to execute the stored procedures; for example:
sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txtIn Windows Scheduled Tasks, create tasks to call the cmd files.
Schedule the tasks.
Start the tasks and verify that they are completing successfully.
In this case a loop will also do the job (and is usually sufficiently fast).
a <- array(0, dim=dim(X))
for (i in 1:ncol(X)) {a[,i] <- X[,i]}
If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.
I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.
What about:
//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));
A <context:component-scan/>
custom tag registers the same set of bean definitions as is done by , apart from its primary responsibility of scanning the java packages and registering bean definitions from the classpath.
If for some reason this registration of default bean definitions are to be avoided, the way to do that is to specify an additional "annotation-config" attribute in component-scan, this way:
<context:component-scan basePackages="" annotation-config="false"/>
Reference: http://www.java-allandsundry.com/2012/12/contextcomponent-scan-contextannotation.html
Does this work for you?
eval repo forall -c '....$variable'
CSS font-stretch is now supported in all major browsers (except iOS Safari and Opera Mini). It is not easy to find a common font-family that supports expanding fonts, but it is easy to find fonts that support condensing, for example:
font-stretch: condense;
font-family: sans-serif, "Helvetica Neue", "Lucida Grande", Arial;
May be helpful... :)
$(document).ready(function() {
$('#buutonId').on('click', function() {
$('#modalId').modal('open');
});
});
here is my solution
List<Country> list = CountryBO.GetCountries(0);
CountriesAdapter dataAdapter = new CountriesAdapter(this,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCountries.setAdapter(dataAdapter);
spnCountries.setSelection(dataAdapter.getItemIndexById(userProfile.GetCountryId()));
and getItemIndexById below
public int getItemIndexById(String id) {
for (Country item : this.items) {
if(item.GetId().toString().equals(id.toString())){
return this.items.indexOf(item);
}
}
return 0;
}
Hope this help!
If the variable you are checking would be in the global scope you could do:
array_key_exists('v', $GLOBALS)
you have forgotten width of parent
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
Just in case anyone comes looking a solution for this problem.
The Authentication problems can be alleviated by activating the google 2-step verification for the account in use and creating an app specific password. I had the same problem as the OP. Enabling 2-step worked.
You can use sessions to save $_POST
data, then retrieve that data and set it to $_POST
on the subsequent request.
User submits request to /dirty-submission-url.php
Do:
if (session_status()!==PHP_SESSION_ACTIVE)session_start();
$_SESSION['POST'] = $_POST;
}
header("Location: /clean-url");
exit;
Then the browser redirects to and requests /clean-submission-url
from your server. You will have some internal routing to figure out what to do with this.
At the beginning of the request, you will do:
if (session_status()!==PHP_SESSION_ACTIVE)session_start();
if (isset($_SESSION['POST'])){
$_POST = $_SESSION['POST'];
unset($_SESSION['POST']);
}
Now, through the rest of your request, you can access $_POST
as you could upon the first request.
alternatively in c or c++ after including stdio.h
char d=(char)(7);
printf("%c\n",d);
(char)7 is called the bell character.
You could use Clint:
from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:
render = () => null
This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render
function and this is the most concise form satisfying this requirement that I can think of.
I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router
documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.
In order to prevent 'Access Denied
' error:
Start
-> search 'Services
' -> right click -> Run as admistrator
Swift 4.0 Please use this code in "didFinishLaunchingWithOptions launchOptions:" Appdelegate class
UIApplication.shared.statusBarStyle = .lightContent let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView if statusBar.responds(to: #selector(setter: UIView.backgroundColor)){ statusBar.backgroundColor = UIColor.black }
iOS 13
var statusBarView: UIView = UIView()
if #available(iOS 13.0, *) {
let tag:UInt64 = 38482458385
if let statusBar = UIApplication.shared.keyWindow?.viewWithTag(Int(tag)) {
statusBar.backgroundColor = UIColor.red
statusBarView = statusBar
} else {
let statusBar = UIView(frame: UIApplication.shared.statusBarFrame)
statusBar.tag = Int(tag)
UIApplication.shared.keyWindow?.addSubview(statusBar)
statusBarView = statusBar
}
} else {
statusBarView = (UIApplication.shared.value(forKey: "statusBar") as? UIView)!
if statusBarView.responds(to: #selector(setter: UIView.backgroundColor)){
statusBarView.backgroundColor = UIColor.red
}
}
maybe you need to set your window-size dimension. just like:
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--window-size=1920x1080');
browser = webdriver.Chrome(options=options,executable_path = './chromedriver')
if also not working, try increase window-size dimension.
Firstly, you start Activities and Services with an intent, you start fragments with fragment transactions. Secondly, your transaction isnt doing anything. Change it to something like:
FragmentTransaction transaction = getFragmentManager();
transaction.beginTransaction()
.replace(R.layout.container, newFragment) //<---replace a view in your layout (id: container) with the newFragment
.commit();
I'm a bit new to Bibtex (and to Latex in general) and I'd like to revive this old post since I found it came up in many of my Google search inquiries about the ordering of a bibliography in Latex.
I'm providing a more verbose answer to this question in the hope that it might help some novices out there facing the same difficulties as me.
Here is an example of the main .tex file in which the bibliography is called:
\documentclass{article}
\begin{document}
So basically this is where the body of your document goes.
``FreeBSD is easy to install,'' said no one ever \cite{drugtrafficker88}.
``Yeah well at least I've got chicken,'' said Leeroy Jenkins \cite{goodenough04}.
\newpage
\bibliographystyle{ieeetr} % Use ieeetr to list refs in the order they're cited
\bibliography{references} % Or whatever your .bib file is called
\end{document}
...and an example of the .bib file itself:
@ARTICLE{ goodenough04,
AUTHOR = "G. D. Goodenough and others",
TITLE = "What it's like to have a sick-nasty last name",
JOURNAL = "IEEE Trans. Geosci. Rem. Sens.",
YEAR = "xxxx",
volume = "xx",
number = "xx",
pages = "xx--xx"
}
@BOOK{ drugtrafficker88,
AUTHOR = "G. Drugtrafficker",
TITLE = "What it's Like to Have a Misleading Last Name",
YEAR = "xxxx",
PUBLISHER = "Harcourt Brace Jovanovich, Inc."
ADDRESS = "The Florida Alps, FL, USA"
}
Note the references in the .bib file are listed in reverse order but the references are listed in the order they are cited in the paper.
More information on the formatting of your .bib file can be found here: http://en.wikibooks.org/wiki/LaTeX/Bibliography_Management
Your operating system probably provides facilities for encrypting data securely. For instance, on Windows there is DPAPI (data protection API). Why not ask the user for their credentials the first time you run then squirrel them away encrypted for subsequent runs?
ExiRe wrote:
Such behavior of ruby is really frustrating. I mean if you move to private section self.method then it is NOT private. But if you move it to class << self then it suddenly works. It is just disgusting.
Confusing it probably is, frustrating it may well be, but disgusting it is definitely not.
It makes perfect sense once you understand Ruby's object model and the corresponding method lookup flow, especially when taking into consideration that private
is NOT an access/visibility modifier, but actually a method call (with the class as its recipient) as discussed here... there's no such thing as "a private section" in Ruby.
To define private instance methods, you call private
on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private
on the class's class, ie. its metaclass.
Other mainstream, self-proclaimed OO languages may give you a less confusing syntax, but you definitely trade that off against a confusing and less consistent (inconsistent?) object model without the power of Ruby's metaprogramming facilities.
This is another late answer but i figured out a fairly simple way of placing the "bar" text in between the four squares. Here are the changes i made; In the bar section i wrapped the "bar" text within a center and div tags.
<header><center><div class="bar">bar</div></center></header>
And in the CSS section i created a "bar" class which is used in the div tag above. After adding this the bar text was centered between the four colored blocks.
.bar{
position: relative;
}
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
you can use..
<div style="width: 100%;">
<div style="float:left; width: 80%">
</div>
<div style="float:right;">
</div>
</div>
<div style="clear:both"></div>
now element below this will not be affected.
In short, []
operator is more efficient for updating values because it involves calling default constructor of the value type and then assigning it a new value, while insert()
is more efficient for adding values.
The quoted snippet from Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers, Item 24 might help.
template<typename MapType, typename KeyArgType, typename ValueArgType>
typename MapType::iterator
insertKeyAndValue(MapType& m, const KeyArgType&k, const ValueArgType& v)
{
typename MapType::iterator lb = m.lower_bound(k);
if (lb != m.end() && !(m.key_comp()(k, lb->first))) {
lb->second = v;
return lb;
} else {
typedef typename MapType::value_type MVT;
return m.insert(lb, MVT(k, v));
}
}
You may decide to choose a generic-programming-free version of this, but the point is that I find this paradigm (differentiating 'add' and 'update') extremely useful.
The only option that worked for me was to put this line in my ~/.vimrc file
set noundofile
The other options referring to backup files did not prevent the creation of the temp files ending in ~ (tilde)
The input.files
attribute is an HTML5 feature. That's why some browsers din't return anything.
Simply add a fallback to the plain old input.value
(string) if files
doesn't exist.
reference: http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-apis.html#dom-input-files
Clean Solution and Build again In my case, whatever the previous settings were blocking due to mismatch. I imported a new project and build it, tried changing versions and all. clean the solutions and build worked for me.
Its very late here but thought to share below code. If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below
public class ProductsController : Controller
{
// GET: Products
public async Task<ActionResult> Index()
{
string apiUrl = "http://localhost:58764/api/values";
using (HttpClient client=new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);
}
}
return View();
}
}
I was having the same problem ConcurrentAccessException and mysolution was to:
List<SomeBean> tempList = new ArrayList<>();
for (CartItem item : prodList) {
tempList.add(item);
}
prodList.clear();
prodList = new ArrayList<>(tempList);
So it works only one operation at the time and avoids the Exeption...
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.