Try
alter table company drop constraint Company_CountryID_FK
alter table company drop column CountryID
Your code isn't working, because the hidden attibute is not supported in versions of IE before v11
If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:
*[hidden] { display: none; }
npm-install-peers worked for me.
npm install -g npm-install-peers
Per the JQuery documentation, .get()
only takes the url
, data
(content), dataType
, and success
callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax()
, this is done with the beforeSend()
method. But since .get()
is a shortcut, it doesn't allow it.
It should be relatively easy to switch your .ajax()
calls to .get()
calls though. After all, .get()
is just a subset of .ajax()
, so you can probably use all the default values for .ajax()
(except, of course, for beforeSend()
).
Edit:
::Looks at Jivings' answer::
Oh yeah, forgot about the cache
parameter! While beforeSend()
is useful for adding other headers, the built-in cache
parameter is far simpler here.
If you don't want to use $(this).val()
, you can try:
var file_onchange = function () {
var input = this; // avoid using 'this' directly
if (input.files && input.files[0]) {
var type = input.files[0].type; // image/jpg, image/png, image/jpeg...
// allow jpg, png, jpeg, bmp, gif, ico
var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/;
if (type_reg.test(type)) {
// file is ready to upload
} else {
alert('This file type is unsupported.');
}
}
};
$('#file').on('change', file_onchange);
Hope this helps!
As @Darin Dimitrov said, if it is not an iframe on the same domain it is not posible, if it is, check that $("#frame1").contents()
returns all it should, and then check if the textbox is found:
$("#frame1").contents().find("#area1").length
should be 1.
Edit
If when your textarea is "empty" an empty string is returned and when it has some text entered that text is returned, then it is working perfect!! When the textarea is empty, an empty string is returned!
Edit 2 Ok. Here there is one way, it is not very pretty but it works:
Outside the iframe you will access the textarea like this:
window.textAreaInIframe
And inside the iframe (which I assume has jQuery) in the document ready put this code:
$("#area1").change(function() {
window.parent.textAreaInIframe = $(this).val();
}).trigger("change");
You have an array that is the "hash table".
In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.
In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
By default node will run on every IP address exposed by the host on which it runs. You don't need to do anything special. You already knew the server runs on a particular port. You can prove this, by using that IP address on a browser on that machine:
http://my-ip-address:port
If that didn't work, you might have your IP address wrong.
Another gotcha here wasted some of my time, so I thought I would pass along the tip. I had a hidden field I gave an id that had . and []
brackets in the name (due to use with struts2) and the selector $("#model.thefield[0]")
would not find my hidden field. Renaming the id to not use the periods and brackets caused the selector to begin working. So in the end I ended up with an id of model_the_field_0
instead and the selector worked fine.
It doesn't?
>>> "abc".__len__()
3
It is very simple: Use the command:
docker-compose restart worker
You can set the time to wait for stop before killing the container (in seconds)
docker-compose restart -t 30 worker
Note that this will restart the container but without rebuilding it. If you want to apply your changes and then restart, take a look at the other answers.
Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.
Best that works for me:
.left{
width:140px;
float:left;
height:100%;
}
.right{
margin-left:140px;
}
With Notepad++, you can show end-of-line characters. It shows CR and LF, instead of "\r" and "\n", but it gets the point across. However, it will still insert the line breaks. But you do get to see the line-ending characters.
To use Notepad++ for this, open the View menu, open the Show Symbols slide out, and select either "Show all characters" or "Show end-of-line characters".
/**
* Created by Ilya Gazman on 3/6/2016.
*/
public class ImageSaver {
private String directoryName = "images";
private String fileName = "image.png";
private Context context;
private boolean external;
public ImageSaver(Context context) {
this.context = context;
}
public ImageSaver setFileName(String fileName) {
this.fileName = fileName;
return this;
}
public ImageSaver setExternal(boolean external) {
this.external = external;
return this;
}
public ImageSaver setDirectoryName(String directoryName) {
this.directoryName = directoryName;
return this;
}
public void save(Bitmap bitmapImage) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(createFile());
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@NonNull
private File createFile() {
File directory;
if(external){
directory = getAlbumStorageDir(directoryName);
}
else {
directory = context.getDir(directoryName, Context.MODE_PRIVATE);
}
if(!directory.exists() && !directory.mkdirs()){
Log.e("ImageSaver","Error creating directory " + directory);
}
return new File(directory, fileName);
}
private File getAlbumStorageDir(String albumName) {
return new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
}
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
public Bitmap load() {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(createFile());
return BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
To save:
new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
save(bitmap);
To load:
Bitmap bitmap = new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
load();
Edit:
Added ImageSaver.setExternal(boolean)
to support saving to external storage based on googles example.
First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be
By default is private
. Unless they're nested, classes are internal
.
I got this error after overriding action bar style like this. Also i lost action bar in preview.
<style name="general_app_theme" parent="@style/Theme.AppCompat">
<!-- for API level 11 -->
<item name="android:actionBarStyle">@style/action_bar_style</item>
<!-- Support library compatibility -->
<item name="actionBarStyle">@style/action_bar_style</item>
</style>
<style name="action_bar_style" parent="@style/Widget.AppCompat.ActionBar">
<!-- for API level 11 -->
<item name="android:height">@dimen/action_bar_height</item>
<item name="android:background">@color/action_bar_color</item>
<item name="android:displayOptions">showTitle</item>
<!-- Support library compatibility -->
<item name="displayOptions">showTitle</item>
</style>
So, problem is overriding theme by my custom. this is the reason, why I've changed AppCompat (from "Project Themes") to general_app_theme (from "Manifest Themes"). Now I have no this error and action bar in preview come back.
One more thing, if you want to change the navigation bg color in UIPopover you need to set barStyle
to UIBarStyleBlack
if([UINavigationBar instancesRespondToSelector:@selector(barTintColor)]){ //iOS7
navigationController.navigationBar.barStyle = UIBarStyleBlack;
navigationController.navigationBar.barTintColor = [UIColor redColor];
}
Just wrap it around then.
<?php
if ( ($cart->count_product) > 0)
{
echo "<div class='my_class'>";
print $cart->count_product;
echo "</div>";
}
?>
Add xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads", This will solve your Issue.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.app.activities.Initializer" >
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-123456789/123456789"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
The way to do it would be with a boolean at a higher scope:
var hasBeenClicked = false;
jQuery('#id').click(function () {
hasBeenClicked = true;
});
if (hasBeenClicked) {
// The link has been clicked.
} else {
// The link has not been clicked.
}
HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
os.stat https://docs.python.org/2/library/stat.html#module-stat
edit: In newer code you should probably use os.path.getmtime() (thanks Christian Oudard)
but note that it returns a floating point value of time_t with fraction seconds (if your OS supports it)
You're close.
std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
std::cout << it->name;
}
Note that you can define it
inside the for
loop:
for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
std::cout << it->name;
}
And if you are using C++11 then you can use a range-based for
loop instead:
for (auto const& i : data) {
std::cout << i.name;
}
Here auto
automatically deduces the correct type. You could have written Student const& i
instead.
I know this post is getting outdated, but here's what they asked. In your style sheet:
.social {
width: 330px;
height: 75px;
float: right;
text-align: left;
padding: 10px 0;
border-bottom: dotted 1px #6d6d6d;
}
[class~="first"] {
padding-top:0;
}
[class~="last"] {
border:0;
}
But it may be a bad way to use selectors. Also, if you need multiple "first" extension, you'll have to be sure to set different name, or to refine your selector.
[class="social first"] {...}
I hope this will help someone, it can be pretty handy in some situation.
For exemple, if you have a tiny piece of css that has to be linked to many different components, and you don't want to write a hundred time the same code.
div.myClass1 {font-weight:bold;}
div.myClass2 {font-style:italic;}
...
div.myClassN {text-shadow:silver 1px 1px 1px;}
div.myClass1.red {color:red;}
div.myClass2.red {color:red;}
...
div.myClassN.red {color:red;}
Becomes:
div.myClass1 {font-weight:bold;}
div.myClass2 {font-style:italic;}
...
div.myClassN {text-shadow:silver 1px 1px 1px;}
[class~=red] {color:red;}
In javascript, there is no way, to make the code wait. I've had this problem and the way I did it was do a synchronous SJAX call to the server, and the server actually executes sleep or does some activity before returning and the whole time, the js waits.
Eg of Sync AJAX: http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX
Ant now comes with the skipNonTests
attribute which was designed to do exactly what you seem to be looking for. No need to change your base classes to abstract or add annotations to them.
The file you are trying to import is a zip file. Unzip the file and then try to import again.
For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.
Repository
public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
{
List<Order> orders = new List<Order>();
using (DatabaseContext db = new DatabaseContext())
{
orders = (from o in db.Orders
orderby o.Date descending //use orderby, otherwise Skip will throw an error
select o)
.Skip(itemsPerPage * page).Take(itemsPerPage)
.ToList();
totalCount = db.Orders.Count();//return the number of pages
}
return orders;//the query is now already executed, it is a subset of all the orders.
}
Controller
public ActionResult Index(int? page)
{
int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
int totalCount = 0;
List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
List<OrderViewModel> orderViews = new List<OrderViewModel>();
foreach(Order order in orders)//convert your models to some view models.
{
orderViews.Add(orderMan.GenerateOrderViewModel(order));
}
//create staticPageList, defining your viewModel, current page, page size and total number of pages.
IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
return View(pageOrders);
}
View
@using PagedList.Mvc;
@using PagedList;
@model IPagedList<Babywatcher.Core.Models.OrderViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="container-fluid">
<p>
@Html.ActionLink("Create New", "Create")
</p>
@if (Model.Count > 0)
{
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.First().orderId)
</th>
<!--rest of your stuff-->
</table>
}
else
{
<p>No Orders yet.</p>
}
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>
Do above first, then perhaps use this!
Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).
Repository
In your order repository (in my case), add a static method to convert a model:
public static OrderModel ConvertToModel(Order entity)
{
if (entity == null) return null;
OrderModel model = new OrderModel
{
ContactId = entity.contactId,
OrderId = entity.orderId,
}
return model;
}
Below your repository class, add this:
public static partial class Ex
{
public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
{
bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
return source.Select(x => new OrderModel
{
OrderId = x.orderId,
//example use ConvertToModel of some other repository
BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
//example use another extension of some other repository
Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
});
}
}
And then in your GetOrderPage
method:
public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
out int totalCount)
{
IQueryable<Order> query = DbContext.Orders; //get queryable from db
.....//do your filtering, sorting, paging (do not use .ToList() yet)
return queryOrders.SelectOrderModel().AsEnumerable();
//or, if you want to include relations
return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
//notice difference, first ToList(), then SelectOrderModel().
}
Let me explain:
The static ConvertToModel
method can be accessed by any other repository, as used above, I use ConvertToModel
from some AddressRepository
.
The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.
Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel()
extension, includeRelations
inside the extension will be true because the source
is NOT a database query type (not an linq-to-sql IQueryable
). When this is true, the extension can call other methods/extensions throughout your application for converting models.
Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList()
yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations
will be false so that it doesn't call other c# methods that SQL doesn't understand.
It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include()
extra will load the relations.
As stated by many here, I am writing the same thing but with an additional point!
At first we need to make sure that our R Studio has these two packages installed:
In order to load a package in R you can use the below function:
install.packages("readxl/XLConnect")
library(XLConnect)
search()
search will display the list of current packages being available in your R Studio.
Now another catch, even though you might have these two packages but still you may encounter problem while reading "xlsx" file and the error could be like "error: more columns than column name"
To solve this issue you can simply resave your excel sheet "xlsx" in to
"CSV (Comma delimited)"
and your life will be super easy....
Have fun!!
This d = t.getElementsByTagName("tr")
and this r = d.getElementsByTagName("td")
are both arrays
. The getElementsByTagName
returns an collection of elements even if there's just one found on your match.
So you have to use like this:
var t = document.getElementById("table"), // This have to be the ID of your table, not the tag
d = t.getElementsByTagName("tr")[0],
r = d.getElementsByTagName("td")[0];
Place the index of the array as you want to access the objects.
Note that getElementById
as the name says just get the element with matched id, so your table have to be like <table id='table'>
and getElementsByTagName
gets by the tag.
EDIT:
Well, continuing this post, I think you can do this:
var t = document.getElementById("table");
var trs = t.getElementsByTagName("tr");
var tds = null;
for (var i=0; i<trs.length; i++)
{
tds = trs[i].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
tds[n].onclick=function() { alert(this.innerHTML); }
}
}
Try it!
The isConnected
method won't help, it will return true
even if the remote side has closed the socket. Try this:
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException
(broken pipe) will be thrown) on the associated Input/OutputStreams.
I actually ended up building my own Component. <Redirect>
It takes info from the react-router
element so I can keep it in my routes. Such as:
<Route
path="/privacy-policy"
component={ Redirect }
loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
/>
Here is my component incase-anyone is curious:
import React, { Component } from "react";
export class Redirect extends Component {
constructor( props ){
super();
this.state = { ...props };
}
componentWillMount(){
window.location = this.state.route.loc;
}
render(){
return (<section>Redirecting...</section>);
}
}
export default Redirect;
EDIT -- NOTE:
This is with react-router: 3.0.5
, it is not so simple in 4.x
Icon creation wizard
none of these solutions worked for me.
I have a terms and conditions modal that i wanted to force people to review before continuing...the defaults "static" and "keyboard" as per the options made it impossible to scroll down the page as the terms and conditions are a few pages log, static was not the answer for me.
So instead i went to unbind the the click method on the modal, with the following i was able to get the desired effect.
$('.modal').off('click');
A Spring Boot with Thymeleaf solution could look like:
Lets say my context-path is /app/
In Thymeleaf you can get it via:
<script th:inline="javascript">
/*<![CDATA[*/
let contextPath = /*[[@{/}]]*/
/*]]>*/
</script>
Just add "D".
int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D
Use https://updates.jenkins-ci.org/download/plugins/. Download it from this central update repository for Jenkins.
EMs are the ONLY thing that scales for media queries that handle +/- scaling, which people do all the time, not just blind people. Here's another very well written professional demonstration of why this matters.
By the way, this is why Zurb Foundation uses ems, while the inferior Bootstrap 3 still uses pixels.
This is an old question, but here's another way to do it.
You can modify the R code itself instead of the chunk options, by wrapping the source
call in suppressPackageStartupMessages()
, suppressMessages()
, and/or suppressWarnings()
. E.g:
```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```
You can also put those functions around your library()
calls inside the "source.R"
script.
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
I had the same problem and I fixed it by using the
There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.
To create a unique token:
string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
Basic example of creating a unique token containing a time stamp:
byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());
To decode the token to get the creation time:
byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
// too old
}
Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.
As long as checker
is not null
, you may use !checker
as posted. This is possible since Java 5, because this Boolean
variable will be autoboxed to the primivite boolean
value.
All the validation from model are skipped when we use validate: false
user = User.new(....)
user.save(validate: false)
Most answers here are from 2008. It looks that things have changed over the time. My latest benchmarks made with JMH shows that on Java 8 +
is around two times faster than concat
.
My benchmark:
@Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
public class StringConcatenation {
@org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State2 {
public String a = "abc";
public String b = "xyz";
}
@org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State3 {
public String a = "abc";
public String b = "xyz";
public String c = "123";
}
@org.openjdk.jmh.annotations.State(Scope.Thread)
public static class State4 {
public String a = "abc";
public String b = "xyz";
public String c = "123";
public String d = "!@#";
}
@Benchmark
public void plus_2(State2 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b);
}
@Benchmark
public void plus_3(State3 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b+state.c);
}
@Benchmark
public void plus_4(State4 state, Blackhole blackhole) {
blackhole.consume(state.a+state.b+state.c+state.d);
}
@Benchmark
public void stringbuilder_2(State2 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).toString());
}
@Benchmark
public void stringbuilder_3(State3 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).toString());
}
@Benchmark
public void stringbuilder_4(State4 state, Blackhole blackhole) {
blackhole.consume(new StringBuilder().append(state.a).append(state.b).append(state.c).append(state.d).toString());
}
@Benchmark
public void concat_2(State2 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b));
}
@Benchmark
public void concat_3(State3 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b.concat(state.c)));
}
@Benchmark
public void concat_4(State4 state, Blackhole blackhole) {
blackhole.consume(state.a.concat(state.b.concat(state.c.concat(state.d))));
}
}
Results:
Benchmark Mode Cnt Score Error Units
StringConcatenation.concat_2 thrpt 50 24908871.258 ± 1011269.986 ops/s
StringConcatenation.concat_3 thrpt 50 14228193.918 ± 466892.616 ops/s
StringConcatenation.concat_4 thrpt 50 9845069.776 ± 350532.591 ops/s
StringConcatenation.plus_2 thrpt 50 38999662.292 ± 8107397.316 ops/s
StringConcatenation.plus_3 thrpt 50 34985722.222 ± 5442660.250 ops/s
StringConcatenation.plus_4 thrpt 50 31910376.337 ± 2861001.162 ops/s
StringConcatenation.stringbuilder_2 thrpt 50 40472888.230 ± 9011210.632 ops/s
StringConcatenation.stringbuilder_3 thrpt 50 33902151.616 ± 5449026.680 ops/s
StringConcatenation.stringbuilder_4 thrpt 50 29220479.267 ± 3435315.681 ops/s
Use javascript
But it depends on what you are trying to do. If you just want to change the height and width, I suggest this:
{
document.getElementById('sample_id').style.height = '150px';
document.getElementById('sample_id').style.width = '150px';
}
TO totally remove it, remove the style, and then re-set the color:
getElementById('sample_id').removeAttribute("style");
document.getElementById('sample_id').style.color = 'red';
Of course, no the only question that remains is on which event you want this to happen.
The conflict message:
CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD
means that res/layout/dialog_item.xml
was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).
So you have to decide whether
git rm res/layout/dialog_item.xml
"or
git add res/layout/dialog_item.xml
"Then you finalize merge with "git commit
".
Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.
If the hour is important, I used str_to_date(date, '%d/%m/%Y %T' )
, the %T
shows the hour in the format hh:mm:ss
.
It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.
Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j;
int b=0;
for (i=2;i<=100;i++){
for (j=2;j<=i;j++){
if (i%j==0){
break;
}
}
if (i==j)
print f("\n%d",j);
}
getch ();
}
Here's full list of black dotlikes from unicode
● - ●
- Black Circle
⏺ - ⏺
- Black Circle for Record
⚫ - ⚫
- Medium Black Circle
⬤ - ⬤
- Black Large Circle
⧭ - ⧭
- Black Circle with Down Arrow
🞄 - 🞄
- Black Slightly Small Circle
• - •
- Bullet (also - •
- Message Waiting)
∙ - ∙
- Bullet Operator
⋅ - ⋅
- Dot Operator (also · - ·
- Middle Dot)
🌑 - 🌑
- New Moon Symbol
They refer to the same element, the difference is that when you say document.body
you are passing the element directly to jQuery. Alternatively, when you pass the string 'body'
, the jQuery selector engine has to interpret the string to figure out what element(s) it refers to.
In practice either will get the job done.
If you are interested, there is more information in the documentation for the jQuery function.
Explicitly specifying the max_iter
resolves the warning as the default max_iter
is 100. [For Logistic Regression].
logreg = LogisticRegression(max_iter=1000)
There are two options, really:
E.g.,
int[] ints = {11367, 11358, 11421, 11530, 11491, 11218, 11789};
Arrays.sort(ints);
System.out.println(Arrays.asList(ints));
That of course assumes that you already have your integers as an array. If you need to parse those first, look for String.split and Integer.parseInt.
You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).
This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
{
$theData = fgets($fh);
$i++
}
fclose($fh);
echo $theData;
?>
If you are looking for a generic way of doing this via MySQL, you could simply use a SELECT
statement, and add the WHERE
clause to it.
This will grab all fields for all rows, where the date stored in field "date" is before "now".
SELECT * FROM table WHERE UNIX_TIMESTAMP(`date`) < UNIX_TIMESTAMP()
Personally, I found this method to be more gentle on newbies in MySQL, since it uses the standard SELECT statement with WHERE to fetch the results. Obviously, you could grab only the fields relevant if you wanted to, by listing them instead of using a wildcard (*).
Try this ---
https://www.facebook.com/help/community/question/?id=589302607826562
1 - Click Apps and then select your app.
2 - Click the Settings button on the left side of the screen.
3 - In the Basic settings, click the Add Platform button below the settings configuration.
4 - Select Website in the platform dialog.
5 - Enter your URL (localhost works here).
6 - In the App Domains text input, add your domain that matches the one in the URL.
7 - Save your settings.
I also experienced that for example:
This code doesnt work and get the intended block error.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
However, when i press tab before typing return self.title statement, the code works.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
Hope, this will help others.
A good question. Should tell you it took some time to crack this one. Here is my result.
DECLARE @TABLE TABLE
(
ID INT,
USERS VARCHAR(10),
ACTIVITY VARCHAR(10),
PAGEURL VARCHAR(10)
)
INSERT INTO @TABLE
VALUES (1, 'Me', 'act1', 'ab'),
(2, 'Me', 'act1', 'cd'),
(3, 'You', 'act2', 'xy'),
(4, 'You', 'act2', 'st')
SELECT T1.USERS, T1.ACTIVITY,
STUFF(
(
SELECT ',' + T2.PAGEURL
FROM @TABLE T2
WHERE T1.USERS = T2.USERS
FOR XML PATH ('')
),1,1,'')
FROM @TABLE T1
GROUP BY T1.USERS, T1.ACTIVITY
I found the generated set of drop statements useful, and recommend these tweaks:
SELECT concat('DROP TABLE IF EXISTS `', table_name, '`;')
FROM information_schema.tables
WHERE table_schema = 'MyDatabaseName';
Note 1: This does not execute the DROP statements, it just gives you a list of them. You will need to cut and paste the output into your SQL engine to execute them.
Note 2: If you have VIEWs, you'll have to correct each DROP TABLE `VIEW_NAME`
statement to DROP VIEW `VIEW_NAME`
manually.
"RESTRICT and CASCADE are permitted to make porting easier. In MySQL 5.5, they do nothing."
Therefore, in order for the drop statements to work if you need:
SET FOREIGN_KEY_CHECKS = 0
This will disable referential integrity checks - so when you are done performing the drops you need, you will want to reset key checking with
SET FOREIGN_KEY_CHECKS = 1
SET FOREIGN_KEY_CHECKS = 0;
-- Your semicolon separated list of DROP statements here
SET FOREIGN_KEY_CHECKS = 1;
NB: to use output of SELECT easier, mysql -B option can help.
If you are using Windows CMD then go to the terminal Properties/Colors (CMD top left) and then redefine the RGB value of the offensive color. In my case I believe it's the fifth color square from the left, which I changed to (222,222,222). It does not matter if the currently selected radio button shows Screen Text or Screen Background as you just redefine that specific "system" color. Once you changed the color don't forget to select back the preferred color for the background or text before clicking OK.
After the change all these reddish messages from Node (Ember in my case) are clearly visible.
When you get frustrated trying this:
CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END
Try this one instead:
CASE LEN(ISNULL(last_Name,''))
WHEN 0 THEN ''
ELSE ' ' + last_name
END AS newlastName
LEN(ISNULL(last_Name,''))
measures the number of characters in that column, which will be zero whether it's empty, or NULL, therefore WHEN 0 THEN
will evaluate to true and return the '' as expected.
I hope this is a helpful alternative.
I have included this test case for sql server 2008 and above:
DECLARE @last_Name varchar(50) = NULL
SELECT
CASE LEN(ISNULL(@last_Name,''))
WHEN 0 THEN ''
ELSE 'A ' + @last_name
END AS newlastName
SET @last_Name = 'LastName'
SELECT
CASE LEN(ISNULL(@last_Name,''))
WHEN 0 THEN ''
ELSE 'A ' + @last_name
END AS newlastName
(In an attempt to give a succinct yet complete derivation.)
Every input byte has 8 bits, so for n input bytes we get:
n × 8 input bits
Every 6 bits is an output byte, so:
ceil(n × 8 / 6) = ceil(n × 4 / 3) output bytes
This is without padding.
With padding, we round that up to multiple-of-four output bytes:
ceil(ceil(n × 4 / 3) / 4) × 4 = ceil(n × 4 / 3 / 4) × 4 = ceil(n / 3) × 4 output bytes
See Nested Divisions (Wikipedia) for the first equivalence.
Using integer arithmetics, ceil(n / m) can be calculated as (n + m – 1) div m, hence we get:
(n * 4 + 2) div 3 without padding
(n + 2) div 3 * 4 with padding
For illustration:
n with padding (n + 2) div 3 * 4 without padding (n * 4 + 2) div 3
------------------------------------------------------------------------------
0 0 0
1 AA== 4 AA 2
2 AAA= 4 AAA 3
3 AAAA 4 AAAA 4
4 AAAAAA== 8 AAAAAA 6
5 AAAAAAA= 8 AAAAAAA 7
6 AAAAAAAA 8 AAAAAAAA 8
7 AAAAAAAAAA== 12 AAAAAAAAAA 10
8 AAAAAAAAAAA= 12 AAAAAAAAAAA 11
9 AAAAAAAAAAAA 12 AAAAAAAAAAAA 12
10 AAAAAAAAAAAAAA== 16 AAAAAAAAAAAAAA 14
11 AAAAAAAAAAAAAAA= 16 AAAAAAAAAAAAAAA 15
12 AAAAAAAAAAAAAAAA 16 AAAAAAAAAAAAAAAA 16
Finally, in the case of MIME Base64 encoding, two additional bytes (CR LF) are needed per every 76 output bytes, rounded up or down depending on whether a terminating newline is required.
In most cases a screen -RRx $username/
will suffice :)
If you still want to list all screens then put the following script in your path and call it screen or whatever you like:
#!/bin/bash
if [[ "$1" != "-ls-all" ]]; then
exec /usr/bin/screen "$@"
else
shopt -s nullglob
screens=(/var/run/screen/S-*/*)
if (( ${#screens[@]} == 0 )); then
echo "no screen session found in /var/run/screen"
else
echo "${screens[@]#*S-}"
fi
fi
It will behave exactly like screen except for showing all screen sessions, when giving the option -ls-all as first parameter.
Try this EDITED:
(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)
UNION ALL
(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)
This is how we do it.
fun Fragment.emptyDatabase() {
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
withContext(Dispatchers.IO) {
Database.getInstance(requireActivity()).clearAllTables()
}
}
}
Here is an updated answer which works in Access 2010 VBA using Data Access Objects (DAO). The table's name is held in TableDef.Name. The collection of all table definitions is held in TableDefs. Here is a quick example of looping through the table names:
Dim db as Database
Dim td as TableDef
Set db = CurrentDb()
For Each td In db.TableDefs
YourSubTakingTableName(td.Name)
Next td
Just pass your string to following method:
+(BOOL)isEmpty:(NSString *)str
{
if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
return YES;
}
return NO;
}
With EasyGui:
import easygui
print(easygui.fileopenbox())
To install:
pip install easygui
Demo:
import easygui
easygui.egdemo()
I received the exact same error message. Except that my error message said "Could not load file or assembly 'EntityFramework, Version=6.0.0.0...", because I installed EF 6.1.1. Here's what I did to resolve the problem.
1) I started NuGet Manager Console by clicking on Tools > NuGet Package Manager > Package Manager Console 2) I uninstalled the installed EntityFramework 6.1.1 by typing the following command:
Uninstall-package EntityFramework
3) Once I received confirmation that the package has been uninstalled successfully, I installed the 5.0.0 version by typing the following command:
Install-Package EntityFramework -version 5.0.0
The problem is resolved.
scp will do the job, but there is one wrinkle: the connection to the second remote destination will use the configuration on the first remote destination, so if you use .ssh/config on the local environment, and you expect rsa and dsa keys to work, you have to forward your agent to the first remote host.
Can a modulus be negative?
%
can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.
// a % b
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
The modulo OP wanted is a classic Euclidean modulo, not %
.
I was expecting a positive result every time.
To perform a Euclidean modulo that is well defined whenever a/b
is defined, a,b
are of any sign and the result is never negative:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
modulo_Euclidean( 7, 3) --> 1
modulo_Euclidean( 7, -3) --> 1
modulo_Euclidean(-7, 3) --> 2
modulo_Euclidean(-7, -3) --> 2
the best and fast way to obtain last index of a list is using -1
for number of index ,
for example:
my_list = [0, 1, 'test', 2, 'hi']
print(my_list[-1])
out put is : 'hi'
.
index -1
in show you last index or first index of the end.
You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)
DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
SET @StartDate = NULL
SET @EndDate = NULL
IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL)
BEGIN
print 'yoyoyo'
END
IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2)
BEGIN
print 'Oh hey there'
END
In flutter 1.5 and Dart 2.3 for visibility gone, You can set the visibility by using an if statement within the collection without having to make use of containers.
e.g
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('This is text one'),
if (_isVisible) Text('can be hidden or shown'), // no dummy container/ternary needed
Text('This is another text'),
RaisedButton(child: Text('show/hide'), onPressed: (){
setState(() {
_isVisible = !_isVisible;
});
},)
],
)
For Markdown Extra you can use custom attributes:
# Example text {style=text-align:center}
This works for headers and blockquotes, but not for paragraphs, inline elements and code blocks.
A shorter version (but not supported in HTML 5):
# Example text {align=center}
You can use while(in.available() != 0)
instead of while(true)
.
If you are using VB, you need to drop the semicolon:
<% Response.Redirect("new.aspx", true) %>
This prints in an easy to read format -
import datetime
time_now = datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S')
print(time_now)
Output: 02_03_2021_22_44_50
Use this following code:
let intVal=56
let floatval:Double=56.897898
let doubleValue=89.0
let explicitDaouble:Double=89.56
let stringValue:"Hello"
let stringValue="String:\(stringValue) Integer:\(intVal) Float:\(floatval) Double:\(doubleValue) ExplicitDouble:\(explicitDaouble) "
This is the simplest wat to get the File object to which a certain URL object is pointing at:
File file=new File(url.toURI());
Now, for your concrete questions:
- finding all resources in the META-INF "directory":
You can indeed get the File object pointing to this URL
Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
URL metaInf=en.nextElement();
File fileMetaInf=new File(metaInf.toURI());
File[] files=fileMetaInf.listFiles();
//or
String[] filenames=fileMetaInf.list();
}
- all resources named bla.xml (recursivly)
In this case, you'll have to do some custom code. Here is a dummy example:
final List<File> foundFiles=new ArrayList<File>();
FileFilter customFilter=new FileFilter() {
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory()) {
pathname.listFiles(this);
}
if(pathname.getName().endsWith("bla.xml")) {
foundFiles.add(pathname);
return true;
}
return false;
}
};
//rootFolder here represents a File Object pointing the root forlder of your search
rootFolder.listFiles(customFilter);
When the code is run, you'll get all the found ocurrences at the foundFiles
List.
Try this it might solve your problem.
Css:
.item{padding-top:1px;}
.jobs .item:hover {
background: #e1e1e1;
border-top: 1px solid #d0d0d0;
padding-top:0;
}
HTML:
<div class="jobs">
<div class="item">
content goes here
</div>
</div>
See fiddle for output: http://jsfiddle.net/dLDNA/
You can turn off/change a particular rule for a file by putting the configurations at the top of the file.
/* eslint no-use-before-define: 0 */ // --> OFF
or
/* eslint no-use-before-define: 2 */ // --> ON
you can also add comment by pressing Ctrl+shift+/ and shift+ / for one line.
PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:
import sip
sip.setapi('QString', 2)
With this API, QtCore.QString
class is no longer available and self.ui.comboBox.currentText()
will return a Python string or unicode object.
See Selecting Incompatible APIs from the doc.
You can simply check whether the element length is undefined or not just by using
var theHref = $(obj.mainImg_select).attr('href');
if (theHref){
//get the length here if the element is not undefined
elementLength = theHref.length
// do stuff
} else {
// do other stuff
}
I developed these 3 useful functions:
def loadModule(moduleName):
module = None
try:
import sys
del sys.modules[moduleName]
except BaseException as err:
pass
try:
import importlib
module = importlib.import_module(moduleName)
except BaseException as err:
serr = str(err)
print("Error to load the module '" + moduleName + "': " + serr)
return module
def reloadModule(moduleName):
module = loadModule(moduleName)
moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
if (modulePath.endswith(".pyc")):
import os
os.remove(modulePath)
module = loadModule(moduleName)
return module
def getInstance(moduleName, param1, param2, param3):
module = reloadModule(moduleName)
instance = eval("module." + moduleName + "(param1, param2, param3)")
return instance
And everytime I want to reload a new instance I just have to call getInstance() like this:
myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)
Finally I can call all the functions inside the new Instance:
myInstance.aFunction()
The only specificity here is to customize the params list (param1, param2, param3) of your instance.
What does the
if __name__ == "__main__":
do?
To outline the basics:
The global variable, __name__
, in the module that is the entry point to your program, is '__main__'
. Otherwise, it's the name you import the module by.
So, code under the if
block will only run if the module is the entry point to your program.
It allows the code in the module to be importable by other modules, without executing the code block beneath on import.
Why do we need this?
Say you're writing a Python script designed to be used as a module:
def do_important():
"""This function does something very important"""
You could test the module by adding this call of the function to the bottom:
do_important()
and running it (on a command prompt) with something like:
~$ python important.py
However, if you want to import the module to another script:
import important
On import, the do_important
function would be called, so you'd probably comment out your function call, do_important()
, at the bottom.
# do_important() # I must remember to uncomment to execute this!
And then you'll have to remember whether or not you've commented out your test function call. And this extra complexity would mean you're likely to forget, making your development process more troublesome.
The __name__
variable points to the namespace wherever the Python interpreter happens to be at the moment.
Inside an imported module, it's the name of that module.
But inside the primary module (or an interactive Python session, i.e. the interpreter's Read, Eval, Print Loop, or REPL) you are running everything from its "__main__"
.
So if you check before executing:
if __name__ == "__main__":
do_important()
With the above, your code will only execute when you're running it as the primary module (or intentionally call it from another script).
There's a Pythonic way to improve on this, though.
What if we want to run this business process from outside the module?
If we put the code we want to exercise as we develop and test in a function like this and then do our check for '__main__'
immediately after:
def main():
"""business logic for when running this module as the primary one!"""
setup()
foo = do_important()
bar = do_even_more_important(foo)
for baz in bar:
do_super_important(baz)
teardown()
# Here's our payoff idiom!
if __name__ == '__main__':
main()
We now have a final function for the end of our module that will run if we run the module as the primary module.
It will allow the module and its functions and classes to be imported into other scripts without running the main
function, and will also allow the module (and its functions and classes) to be called when running from a different '__main__'
module, i.e.
import important
important.main()
This idiom can also be found in the Python documentation in an explanation of the __main__
module. That text states:
This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:
if __name__ == '__main__': main()
I'd suggest <a href='page1.jsp'>Refresh</a>
.
If you have installed git on your machine, you can open a git terminal and just use the Linux diff
command as normal.
Some special characters give this type of error, so use
$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";
With Java 8
DateTime
/LocalDateTime
:
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
ValueRange range = date.range(ChronoField.DAY_OF_MONTH);
Long max = range.getMaximum();
LocalDate newDate = date.withDayOfMonth(max.intValue());
System.out.println(newDate);
OR
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
LocalDate newDate = date.withDayOfMonth(date.getMonth().length(date.isLeapYear()));
System.out.println(newDate);
Output:
2012-01-31
LocalDateTime
should be used instead ofLocalDate
if you have time information in your date string . I.E.2015/07/22 16:49
This will ensure you get a two-digit day and month.
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
Or terser:
function formattedDate(d = new Date) {
return [d.getDate(), d.getMonth()+1, d.getFullYear()]
.map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}
Normality tests don't do what most think they do. Shapiro's test, Anderson Darling, and others are null hypothesis tests AGAINST the the assumption of normality. These should not be used to determine whether to use normal theory statistical procedures. In fact they are of virtually no value to the data analyst. Under what conditions are we interested in rejecting the null hypothesis that the data are normally distributed? I have never come across a situation where a normal test is the right thing to do. When the sample size is small, even big departures from normality are not detected, and when your sample size is large, even the smallest deviation from normality will lead to a rejected null.
For example:
> set.seed(100)
> x <- rbinom(15,5,.6)
> shapiro.test(x)
Shapiro-Wilk normality test
data: x
W = 0.8816, p-value = 0.0502
> x <- rlnorm(20,0,.4)
> shapiro.test(x)
Shapiro-Wilk normality test
data: x
W = 0.9405, p-value = 0.2453
So, in both these cases (binomial and lognormal variates) the p-value is > 0.05 causing a failure to reject the null (that the data are normal). Does this mean we are to conclude that the data are normal? (hint: the answer is no). Failure to reject is not the same thing as accepting. This is hypothesis testing 101.
But what about larger sample sizes? Let's take the case where there the distribution is very nearly normal.
> library(nortest)
> x <- rt(500000,200)
> ad.test(x)
Anderson-Darling normality test
data: x
A = 1.1003, p-value = 0.006975
> qqnorm(x)
Here we are using a t-distribution with 200 degrees of freedom. The qq-plot shows the distribution is closer to normal than any distribution you are likely to see in the real world, but the test rejects normality with a very high degree of confidence.
Does the significant test against normality mean that we should not use normal theory statistics in this case? (another hint: the answer is no :) )
Lets say you wanted the maximum allowed value to be 1000 - either typed or with the spinner.
You restrict the spinner values using:
type="number" min="0" max="1000"
and restrict what is typed by the keyboard with javascript:
onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }
"
<input type="number" min="0" max="1000" onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }">
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable
whereas
PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments
However, there are pros and cons to both and one should choose as per their specific use case.
I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.
Make sure to download these from here:
Also create PATH
enviroment variable on you computer like this (if it doesn't exist already):
PATH
variable doesn't exist among "User variables" click New
(Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin;
<-- please check out the right version, this may differ as Oracle keeps updating Java). ;
in the end enables assignment of multiple values to PATH
variable.To be sure that everything works, open CMD Prompt and type: java -version
to check for Java version and javac
to be sure that compiler responds.
I hope this helps. Good luck!
When I installed Python 3.6.1 on Windows 7 recently, it also installed the Python Launcher for Windows, which is supposed to handle the shebang line. However, I found that the Python Launcher did not do this: the shebang line was ignored and Python 2.7.13 was always used (unless I executed the script using py -3).
To fix this, I had to edit the Windows registry key HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.File\shell\open\command
. This still had the value
"C:\Python27\python.exe" "%1" %*
from my earlier Python 2.7 installation. I modified this registry key value to
"C:\Windows\py.exe" "%1" %*
and the Python Launcher shebang line processing worked as described above.
find the position of the nth occurrence of str2 in str1(same order of parameters as Oracle SQL INSTR), returns 0 if not found
instr <- function(str1,str2,startpos=1,n=1){
aa=unlist(strsplit(substring(str1,startpos),str2))
if(length(aa) < n+1 ) return(0);
return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) )
}
instr('xxabcdefabdddfabx','ab')
[1] 3
instr('xxabcdefabdddfabx','ab',1,3)
[1] 15
instr('xxabcdefabdddfabx','xx',2,1)
[1] 0
Even this helps me while trying to solve someone's problem,
Split the contents inside curly braces (
{}
) having a pattern like,{'day': 1, 'count': 100}
.
For example:
#include <iostream>
#include <regex>
#include<string>
using namespace std;
int main()
{
//string to be searched
string s = "{'day': 1, 'count': 100}, {'day': 2, 'count': 100}";
// regex expression for pattern to be searched
regex e ("\\{[a-z':, 0-9]+\\}");
regex_token_iterator<string::iterator> rend;
regex_token_iterator<string::iterator> a ( s.begin(), s.end(), e );
while (a!=rend) cout << " [" << *a++ << "]";
cout << endl;
return 0;
}
Output:
[{'day': 1, 'count': 100}] [{'day': 2, 'count': 100}]
There are 3 possibilities on the MS KB
When I see stuff like this: I always think hotfix, engine, server errors etc.
Edit: It's on MS Connect too
gradlew
is a wrapper(w - character) that uses gradle
.
Under the hood gradlew
performs three main things:
gradle
versiongradle
taskUsing Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.
To create a wrapper run:
gradle wrapper
This command generate:
gradle-wrapper.properties
will contain the information about the Gradle distribution
*./
Is used on Unix to specify the current directory
I couldn't synchronize and change the speed my setIntervals too and I was about to post a question. But I think I've found a way. It should certainly be improved because I'm a beginner. So, I'd gladly read your comments/remarks about this.
<body onload="foo()">
<div id="count1">0</div>
<div id="count2">2nd counter is stopped</div>
<button onclick="speed0()">pause</button>
<button onclick="speedx(1)">normal speed</button>
<button onclick="speedx(2)">speed x2</button>
<button onclick="speedx(4)">speed x4</button>
<button onclick="startTimer2()">Start second timer</button>
</body>
<script>
var count1 = 0,
count2 = 0,
greenlight = new Boolean(0), //blocks 2nd counter
speed = 1000, //1second
countingSpeed;
function foo(){
countingSpeed = setInterval(function(){
counter1();
counter2();
},speed);
}
function counter1(){
count1++;
document.getElementById("count1").innerHTML=count1;
}
function counter2(){
if (greenlight != false) {
count2++;
document.getElementById("count2").innerHTML=count2;
}
}
function startTimer2(){
//while the button hasn't been clicked, greenlight boolean is false
//thus, the 2nd timer is blocked
greenlight = true;
counter2();
//counter2() is greenlighted
}
//these functions modify the speed of the counters
function speed0(){
clearInterval(countingSpeed);
}
function speedx(a){
clearInterval(countingSpeed);
speed=1000/a;
foo();
}
</script>
If you want the counters to begin to increase once the page is loaded, put counter1()
and counter2()
in foo()
before countingSpeed
is called. Otherwise, it takes speed
milliseconds before execution.
EDIT : Shorter answer.
Seems like nobody was able to answer the question so far :)
I use EclipseLink's MOXy to dynamically generate binding classes and then recursively go through the bound types. It is somewhat heavy, but it allows XPath value injection once the object tree is instantiated:
InputStream in = new FileInputStream(PATH_TO_XSD);
DynamicJAXBContext jaxbContext =
DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);
DynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);
DynamicEntity root = rootType.newDynamicEntity();
traverseProps(jaxbContext, root, rootType, 0);
TraverseProps is pretty simple recursive method:
private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{
if (t!=null) {
logger.info(indent(level) + "type [" + t.getName() + "] of class [" + t.getClassName() + "] has " + t.getNumberOfProperties() + " props");
for (String pName:t.getPropertiesNames()){
Class<?> clazz = t.getPropertyType(pName);
logger.info(indent(level) + "prop [" + pName + "] in type: " + clazz);
//logger.info("prop [" + pName + "] in entity: " + e.get(pName));
if (clazz==null){
// need to create an instance of object
String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);
logger.info(indent(level) + "Creating new type instance for " + pName + " using following class name: " + updatedClassName );
DynamicType child = c.getDynamicType("generated." + updatedClassName);
DynamicEntity childEntity = child.newDynamicEntity();
e.set(pName, childEntity);
traverseProps(c, childEntity, child, level+1);
} else {
// just set empty value
e.set(pName, clazz.newInstance());
}
}
} else {
logger.warn("type is null");
}
}
Converting everything to XML is pretty easy:
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
@media (max-width: 767px) {
footer .text-right,
footer .text-left {
text-align: center;
}
}
I updated @loddn's answer, making two changes
max-width
of xs
screens in bootstrap is 767px (768px is the start of sm
screens)footer
instead of col-*
so that if the column widths change, the CSS doesn't need to be updated.Use this:
word = raw_input("Please enter a single word : ")
while True:
if " " in word:
word = raw_input("Please enter a single word : ")
else:
print "Thanks"
break
You don't have to add a .
in getElementsByClassName
, i.e.
var multibutton = angular.element(element.getElementsByClassName("multi-files"));
However, when using angular.element
, you do have to use jquery style selectors:
angular.element('.multi-files');
should do the trick.
Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""
alter table your_table
alter column LoginDate datetime;
use
require_once(__DIR__.'/_path/_of/_filename.php');
This will also help in importing files in from different folders.
Try extends
method to inherit the classes in that file and reuse the functions
Browser scrollbars don't work at all on iPhone/iPad. At work we are using custom JavaScript scrollbars like jScrollPane to provide a consistent cross-browser UI: http://jscrollpane.kelvinluck.com/
It works very well for me - you can make some really beautiful custom scrollbars that fit the design of your site.
The scripting runtime dictionary seems to have a bug that can ruin your design at advanced stages.
If the dictionary value is an array, you cannot update values of elements contained in the array through a reference to the dictionary.
Using importlib
the only thing you've got to add is
from importlib import import_module
from pathlib import Path
__all__ = [
import_module(f".{f.stem}", __package__)
for f in Path(__file__).parent.glob("*.py")
if "__" not in f.stem
]
del import_module, Path
There is another error with the forwars=d slash.
if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']
SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.
MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.
The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.
So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?
You're trying to cherry pick fd9f578
, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m
option. For example, git cherry-pick -m 1 fd9f578
to use parent 1 as the base.
I can't say for sure for your particular situation, but using git merge
instead of git cherry-pick
is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
This tip shows how to use Logger in any java application. Logger needs to configure Formatter and Handler. There are many types of handlers and formatters present. In this example FileHandler is used to store all the log messages in a log file. And Simple formatter is used to format the log messages in human readable form.
package MyProject;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class MyLogger {
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("c:\\MyLogFile.log", true);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.log(Level.WARNING,"My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
some more examples you can find here https://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html
If you need to save multiple objects, you can simply put them in a single list, or tuple, for instance:
import pickle
# obj0, obj1, obj2 are created here...
# Saving the objects:
with open('objs.pkl', 'w') as f: # Python 3: open(..., 'wb')
pickle.dump([obj0, obj1, obj2], f)
# Getting back the objects:
with open('objs.pkl') as f: # Python 3: open(..., 'rb')
obj0, obj1, obj2 = pickle.load(f)
If you have a lot of data, you can reduce the file size by passing protocol=-1
to dump()
; pickle
will then use the best available protocol instead of the default historical (and more backward-compatible) protocol. In this case, the file must be opened in binary mode (wb
and rb
, respectively).
The binary mode should also be used with Python 3, as its default protocol produces binary (i.e. non-text) data (writing mode 'wb'
and reading mode 'rb'
).
Open a PL/SQL object in the Editor.
Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.
Compile the object on the database.
Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor
Following answer can help in this and other similar situations like synchronous AJAX call -
Working example
waitForMe().then(function(intentsArr){
console.log('Finally, I can execute!!!');
},
function(err){
console.log('This is error message.');
})
function waitForMe(){
// Returns promise
console.log('Inside waitForMe');
return new Promise(function(resolve, reject){
if(true){ // Try changing to 'false'
setTimeout(function(){
console.log('waitForMe\'s function succeeded');
resolve();
}, 2500);
}
else{
setTimeout(function(){
console.log('waitForMe\'s else block failed');
resolve();
}, 2500);
}
});
}
// this is a dirty hack - but should be ok for a unittest.
private void setNewEnvironmentHack(Map<String, String> newenv) throws Exception
{
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.clear();
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.clear();
cienv.putAll(newenv);
}
Just had the similar error when installing java 8 (jdk & jre) on a system already running Java 7.
Error: Registry key 'Software\JavaSoft\Java Runtime
Environment'\CurrentVersion' has value '1.8', but '1.7' is required.
Error: could not find java.dll Error: Could not find Java SE Runtime Environment.
My environment was set up correctly (Path & java_home correctly defined), but the problem arises from the way pre-8 Java installers worked, which is that they used to copy the three executables (java.exe, javaw.exe & javaws.exe) to the Windows system directory. These remain unless overwritten by a new pre-8 installation.
However the Java 8 installer instead creates symbolic links in a new directory, C:\ProgramData\Oracle\Java\javapath, pointing to the actual JRE 8 location.
This means that you'll actually run the old 7 exes but use the new 8 DLLs.
So, the solution is simply to delete the 3 Java exes, as above, from the windows system directory.
If you are running 32-bit Java on a 64-bit Windows, the exes would be in Windows\SysWOW64, otherwise in Windows\System32.
You change default value in MySQL configuration file (option connect_timeout in mysqld section) -
[mysqld]
connect_timeout=100
If this file is not accessible for you, then you can set this value using this statement -
SET GLOBAL connect_timeout=100;
Regex if you want to ensure URL starts with HTTP/HTTPS:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
If you do not require HTTP protocol:
[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.
Example JavaScript implementation:
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;_x000D_
var regex = new RegExp(expression);_x000D_
var t = 'www.google.com';_x000D_
_x000D_
if (t.match(regex)) {_x000D_
alert("Successful match");_x000D_
} else {_x000D_
alert("No match");_x000D_
}
_x000D_
With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:
let a = `something something`;
and to make multiline strings just press enter to create a new line, with no special characters:
let a = `something
something`;
The results are exactly the same as you write in the string.
I am fine with regular expressions, lazy and averse to installs, so I created a batch file that creates the directory and copies with vanilla DOS commands. Seems laborious but quicker for me than working out robocopy.
(.*)
replace string "\1"
, and click replace all(.*)
replace string md qqq\1\nxcopy \1 qqq\1\n
and click replace all\\([^\\^"]+)"\n
replace \\"\n
A:\src
and B:\dest
). Turn OFF regular expressions, search qqq"A:\src\
replace B:\dest\
and click replace all.md will create nested directories. copy would probably behave identically to xcopy in this example. You might want to add /Y to xcopy to suppress overwrite confirms. You end up with a batch file like so:
md "B:\dest\a\b\c\"
xcopy "C:\src\a\b\c\e.xyz" "B:\dest\a\b\c\e.xyz"
repeated for every file in your original list. Tested on Win7.
I had same problem when upgrading to Yosemite.
I just had to modify ~/.bashrc
to source /usr/local/etc/bash_completion.d/git-prompt.sh
instead of the old path.
then re-source your . ~/.bashrc
to get the effect.
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
You could try using AJAX calls with jQuery. Like how youtube adds your comment without refreshing. This would remove the problem with refreshing overal.
You'd need to send the info necessary trough the ajax call.
I'll use the youtube comment as example.
$.ajax({
type: 'POST',
url: 'ajax/comment-on-video.php',
data: {
comment: $('#idOfInputField').val();
},
success: function(obj) {
if(obj === 'true') {
//Some code that recreates the inserted comment on the page.
}
}
});
You can now create the file comment-on-video.php
and create something like this:
<?php
session_start();
if(isset($_POST['comment'])) {
$comment = mysqli_real_escape_string($db, $_POST['comment']);
//Given you are logged in and store the user id in the session.
$user = $_SESSION['user_id'];
$query = "INSERT INTO `comments` (`comment_text`, `user_id`) VALUES ($comment, $user);";
$result = mysqli_query($db, $query);
if($result) {
echo true;
exit();
}
}
echo false;
exit();
?>
Simply call test2
from test1
like:
EXEC test2 @newId, @prod, @desc;
Make sure to get @id
using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT @newId = SCOPE_IDENTITY()
When I tried Continue For
it Failed, I got a compiler error. While doing this, I discovered 'Resume':
For Each I As Item In Items
If I = x Then
'Move to next item
Resume Next
End If
'Do something
Next
Note: I am using VBA here.
We can increase maximum upload file size for WordPress media uploads in 3 different ways.
That's are
For .htaccess way, add following code,
php_value upload_max_filesize 1024M
php_value post_max_size 1024M
php_value max_execution_time 1000
php_value max_input_time 1000
for PHP.INI file method, add following code,
upload_max_filesize = 1024M
post_max_size = 1024M
max_execution_time = 1000
for Theme’s Functions.php File, add following code,
@ini_set( ‘upload_max_size’ , ’1024M’ );
@ini_set( ‘post_max_size’, ’1024M’);
@ini_set( ‘max_execution_time’, ’1000' );
You can use one of the following.
$!
is the PID of the last backgrounded process.kill -0 $PID
checks whether it's still running.$$
is the PID of the current shell.LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'
I think you're missing a )
on both of the trims. Some SQL versions support just TRIM which does both L and R trims...
Simple Trick with jQuery and CSS Like so:
JQuery:
$('input[value=""]').addClass('empty');
$('input').keyup(function(){
if( $(this).val() == ""){
$(this).addClass("empty");
}else{
$(this).removeClass("empty");
}
});
CSS:
input.empty:valid{
box-shadow: none;
background-image: none;
border: 1px solid #000;
}
input:invalid,
input:required {
box-shadow: 3px 1px 5px rgba(200, 0, 0, 0.85);
border: 1px solid rgb(200,0,0);
}
input:valid{
box-shadow: none;
border: 1px solid #0f0;
}
You can try:
top -bn1 | grep "Cpu(s)" | \
sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
awk '{print 100 - $1"%"}'
For rails 5, it better to add
protect_from_forgery prepend: true
than to skip the verify_authentication_token
On Mac:
Eclipse toolbar Eclipse ? Preferences OR Command + , (comma)
General ? Appearance ? Colors and Fonts ? Basic ? Text Font
Apply
Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too
So use this instead of script tags:
<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
public static void openWebPage(String url) {
try {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(new URI(url));
}
throw new NullPointerException();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, url, "", JOptionPane.PLAIN_MESSAGE);
}
}
In my case artifactory was down. npm install command is throwing below error.
npm ERR! registry error parsing json
In my case I had folder name Newtonsoft.Json.6.0.7
but .csproj
file had path though folder ...\Newtonsoft.Json.6.0.5\...
Changing .csproj
file to have 6.0.7 fixed the problem.
let array = [267, 306, 108]
let longest = Math.max(...array);
Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.
It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.
Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:
export function forceCast<T>(input: any): T {
// ... do runtime checks here
// @ts-ignore <-- forces TS compiler to compile this as-is
return input;
}
Then you can use it to force cast objects to a certain type:
import { forceCast } from './forceCast';
const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);
Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts
interface files into JSON schemas and using ajv
to validate in runtime.
You probably want to change the condition to if ($(this).hasClass('active'))
Also, hasClass
and addClass
take classnames, not selectors.
Therefore, you shouldn't include a .
.
Just use a normal Javascript expression, no {}
or anything necessary:
@click="addToCount(item.contactID)"
if you also need the event object:
@click="addToCount(item.contactID, $event)"
In Joomla Yootheme works for me:
a:not([class]) {
color: #fff !important;
}
Is the file really a symbolic link? If not, the usual test for existence is -r
or -e
.
See man test
.
If you tried the above options and no success, also you're using IIS (iisnode) to host your node app, putting this code on web.config resolved the problem for me:
Here is the reference: https://www.inflectra.com/support/knowledgebase/kb306.aspx
Also, you can chagne the length allowed because now I think its 2GB. Modify it by your needs.
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
This version is for German language but you can modifiy the $CHARSETS and the $TESTCHARS
class CharsetDetector
{
private static $CHARSETS = array(
"ISO_8859-1",
"ISO_8859-15",
"CP850"
);
private static $TESTCHARS = array(
"€",
"ä",
"Ä",
"ö",
"Ö",
"ü",
"Ü",
"ß"
);
public static function convert($string)
{
return self::__iconv($string, self::getCharset($string));
}
public static function getCharset($string)
{
$normalized = self::__normalize($string);
if(!strlen($normalized))return "UTF-8";
$best = "UTF-8";
$charcountbest = 0;
foreach (self::$CHARSETS as $charset) {
$str = self::__iconv($normalized, $charset);
$charcount = 0;
$stop = mb_strlen( $str, "UTF-8");
for( $idx = 0; $idx < $stop; $idx++)
{
$char = mb_substr( $str, $idx, 1, "UTF-8");
foreach (self::$TESTCHARS as $testchar) {
if($char == $testchar)
{
$charcount++;
break;
}
}
}
if($charcount>$charcountbest)
{
$charcountbest=$charcount;
$best=$charset;
}
//echo $text."<br />";
}
return $best;
}
private static function __normalize($str)
{
$len = strlen($str);
$ret = "";
for($i = 0; $i < $len; $i++){
$c = ord($str[$i]);
if ($c > 128) {
if (($c > 247)) $ret .=$str[$i];
elseif ($c > 239) $bytes = 4;
elseif ($c > 223) $bytes = 3;
elseif ($c > 191) $bytes = 2;
else $ret .=$str[$i];
if (($i + $bytes) > $len) $ret .=$str[$i];
$ret2=$str[$i];
while ($bytes > 1) {
$i++;
$b = ord($str[$i]);
if ($b < 128 || $b > 191) {$ret .=$ret2; $ret2=""; $i+=$bytes-1;$bytes=1; break;}
else $ret2.=$str[$i];
$bytes--;
}
}
}
return $ret;
}
private static function __iconv($string, $charset)
{
return iconv ( $charset, "UTF-8" , $string );
}
}
If you have two columns with the same name. One simple way is to manually rename the columns like this:-
df.columns = ['column1', 'column2', 'column3']
Then you can drop via column index as you requested, like this:-
df.drop(df.columns[1], axis=1, inplace=True)
df.column[1]
will drop index 1.
Remember axis 1 = columns and axis 0 = rows.
I find the quickest and easiest way to work with a PHP array in Javascript is to do this:
PHP:
$php_arr = array('a','b','c','d');
Javascript:
//this gives me a JSON object
js_arr = '<?php echo JSON_encode($php_arr);?>';
//Depending on what I use it for I sometimes parse the json so I can work with a straight forward array:
js_arr = JSON.parse('<?php echo JSON_encode($php_arr);?>');
**write this before adding view to dialog.**
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
I agree with pjco. The best way is the official method explained in Support Library Setup in the tutorial at developer.android.com.
Then, in the Eclipse "package explorer", expand your main project and delete android-support-v4.jar from the "libs" folder (as Pratik Butani suggested).
This worked for me.
Just be sure you have used double apostrophe ('')
String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);
Edit:
Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. ...
Any unmatched quote is treated as closed at the end of the given pattern. For example, pattern string "'{0}" is treated as pattern "'{0}'".
Source http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html
Setting window full height for empty divs
1st solution with absolute positioning - FIDDLE
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 0;
width: 75%;
}
2nd solution with static (also can be used a relative) positioning & jQuery - FIDDLE
.div1 {
float: left;
width: 25%;
}
.div2 {
float: left;
width: 75%;
}
$(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
$(window).resize(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
});
});
From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.
Here are the links where I found this information:
http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/
If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:
In your CSS use (for example)
div.centered{
width: 100px;
height: 50px;
position:fixed;
top: calc(50% - 25px); // half of width
left: calc(50% - 50px); // half of height
}
No JS required.
I had a similar issue using the Chrome driver (v2.23) / running the tests thru TeamCity. I was able to fix the issue by adding the "no-sandbox" flag to the Chrome options:
var options = new ChromeOptions();
options.AddArgument("no-sandbox");
I'm not sure if there is a similar option for the FF driver. From what I understand the issue has something to do with TeamCity running Selenium under the SYSTEM account.
What do you think of this?
if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
$scheme = 'https';
else
$scheme = 'http';
@Paul Cavacas, I had the same issue and I solved by setting the Input()
decorator above the getter.
@Input('allowDays')
get in(): any {
return this._allowDays;
}
//@Input('allowDays')
// not working
set in(val) {
console.log('allowDays = '+val);
this._allowDays = val;
}
See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview
To see just the Python releases, do conda search --full-name python
.
To extend the expression chain syntax answer by Clever Human:
If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:
var dealerInfo = DealerContact.Join(Dealer,
dc => dc.DealerId,
d => d.DealerId,
(dc, d) => new { DealerContact = dc, Dealer = d })
.Where(dc_d => dc_d.Dealer.FirstName == "Glenn"
&& dc_d.DealerContact.City == "Chicago")
.Select(dc_d => new {
dc_d.Dealer.DealerID,
dc_d.Dealer.FirstName,
dc_d.Dealer.LastName,
dc_d.DealerContact.City,
dc_d.DealerContact.State });
The interesting part is the lambda expression in line 4 of that example:
(dc, d) => new { DealerContact = dc, Dealer = d }
...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.
We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d
as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.
Run these commands:
sudo apt-get update
sudo apt-get install build-essential libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
source ~/.profile
nvm ls-remote
nvm install v9.10.1
nvm use v9.10.1
node -v
The screenshot was very helpful - the following code will do the job (assuming data is located in column A starting A1):
Sub RemoveRows()
Dim i As Long
i = 1
Do While i <= ThisWorkbook.ActiveSheet.Range("A1").CurrentRegion.Rows.Count
If InStr(1, ThisWorkbook.ActiveSheet.Cells(i, 1).Text, "-", vbTextCompare) > 0 Then
ThisWorkbook.ActiveSheet.Cells(i, 1).EntireRow.Delete
Else
i = i + 1
End If
Loop
End Sub
Sample file is shared: https://www.dropbox.com/s/2vhq6vw7ov7ssya/RemoweDashRows.xlsm
You can use below query to update or create comment on already created table.
SYNTAX:
COMMENT ON COLUMN TableName.ColumnName IS 'comment text';
Example:
COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';
In order to be independent of the language and locale settings, you should use the ISO 8601 YYYYMMDD
format - this will work on any SQL Server system with any language and regional setting in effect:
SELECT
CAST(
CAST(year AS VARCHAR(4)) +
RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
RIGHT('0' + CAST(day AS VARCHAR(2)), 2)
AS DATETIME)
well it depends if all you want is to position a div and then nothing else, you don't need to use java script for that. You can achieve this by CSS only. What matters is relative to what container you want to position your div, if you want to position it relative to document body then your div must be positioned absolute and its container must not be positioned relatively or absolutely, in that case your div will be positioned relative to the container.
Otherwise with Jquery if you want to position an element relative to document you can use offset() method.
$(".mydiv").offset({ top: 10, left: 30 });
if relative to offset parent position the parent relative or absolute. then use following...
var pos = $('.parent').offset();
var top = pos.top + 'no of pixel you want to give the mydiv from top relative to parent';
var left = pos.left + 'no of pixel you want to give the mydiv from left relative to parent';
$('.mydiv').css({
position:'absolute',
top:top,
left:left
});
As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
If you got a lot configurations the output might be pretty lengthy. To just show dependencies for the runtime configuration, run
gradle dependencies --configuration runtime
No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).
But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.
For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.
Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.
You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.
Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.
It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
Try this.Vals.replace(/("|')/g, "")
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
If none of the above work, quotation marks around the stash itself might work for you:
git stash pop "stash@{0}"
I fixed this by checking Delete all existing files prior to publish
in Visual Studio:
Now to answer the question that perhaps you should have asked, like "I'm getting 100 floats form somewhere; do I need to put them in an array or list before I find the minimum?"
Answer: No, if somewhere
is a iterable, instead of doing this:
temp = []
for x in somewhere:
temp.append(x)
answer = min(temp)
you can do this:
answer = min(somewhere)
Example:
answer = min(float(line) for line in open('floats.txt'))
If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.
I wrote a quick console app to run your code and parse the file and it works fine for me.
Here is an awesome and precise explanation I found.
TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.
TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.
TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.
TIMESTAMP is 4 bytes and DATETIME is 8 bytes.
TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'
Also...
You just need to pass --recursive & --include "*"
aws --region "${BUCKET_REGION}" s3 cp s3://${BUCKET}${BUCKET_PATH}/ ${LOCAL_PATH}/tmp --recursive --include "*" 2>&1
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
Well I agree with Ryan Conrad on how to do it in eclipse, have you ensured you have changed your manifest.xml?
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K
and V
.
Also bear in mind that std::sort
requires a strict weak ordeing comparison, and <=
does not satisfy that. You would need, for example, a less-than comparison <
for K
and V
. With that in place, all you need is
std::vector<pair<K,V>> items;
std::sort(items.begin(), items.end());
If you really need to provide your own comparison function, then you need something along the lines of
template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
return lhs.first < rhs.first;
}
This simple code will also work, to remove for example double quote from a string surrounded with double quote:
var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"(.+)"/g, '$1'));
Just use:
mail
d 1-15
quit
Which will delete all messages between number 1 and 15. to delete all, use the d *
.
I just used this myself on ubuntu 12.04.4, and it worked like a charm.
For example:
eric@dev ~ $ mail
Heirloom Mail version 12.4 7/29/08. Type ? for help.
"/var/spool/mail/eric": 2 messages 2 new
>N 1 Cron Daemon Tue Jul 29 17:43 23/1016 "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
N 2 Cron Daemon Tue Jul 29 17:44 23/1016 "Cron <eric@ip-10-0-1-51> /usr/bin/php /var/www/sandbox/eric/c"
& d *
& quit
Then check your mail again:
eric@dev ~ $ mail
No mail for eric
eric@dev ~ $
What is tripping you up is you are using x
or exit
to quit which rolls back the changes during that session.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date_x000D_
var milliseconds = date.getTime(); _x000D_
// This will return you the number of milliseconds_x000D_
// elapsed from January 1, 1970 _x000D_
// if your date is less than that date, the value will be negative_x000D_
_x000D_
console.log(milliseconds);
_x000D_
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date
object
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var result = myDate.getTime();_x000D_
console.log(result);
_x000D_
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");_x000D_
var offset = myDate.getTimezoneOffset() * 60 * 1000;_x000D_
_x000D_
var withOffset = myDate.getTime();_x000D_
var withoutOffset = withOffset - offset;_x000D_
console.log(withOffset);_x000D_
console.log(withoutOffset);
_x000D_
Seems working. As far as problems with converting ISO string into the Date
object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
I have solved this as follows:
Window > Customize Perspective... (you will see Android and AVD Manager are disabled)
Command Groups Availability > Android and AVD Manager > check
Tool Bar Visibility > Android and AVD Manager > check
The following may not be the best method--it is O(n^2). However, it should serve to get the job done (eventually).
count_of_elements_so_far = 0;
for (each element in linked list)
{
search for current element in first <count_of_elements_so_far>
if found, then you have a loop
else,count_of_elements_so_far++;
}
First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?
You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.
I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.
But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.
javascript function for client side validation (using jQuery)...
function CheckBoxRequired_ClientValidate(sender, e)
{
e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
}
code-behind for server side validation...
protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = MyCheckBox.Checked;
}
ASP.Net code for the checkbox & validator...
<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
OnServerValidate="CheckBoxRequired_ServerValidate"
ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>
and finally, in your postback - whether from a button or whatever...
if (Page.IsValid)
{
// your code here...
}
I had these choices:
-----------------------------------------------
* 1 /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
+ 2 /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
3 /home/ec2-user/local/java/jre1.7.0_25/bin/java
When I chose 3, it didn't work. When I chose 2, it did work.
var str = " \n this is a string \n \n \n"_x000D_
_x000D_
console.log(str);_x000D_
console.log(str.trim());
_x000D_
String.trim()
removes whitespace from the beginning and end of strings... including newlines.
const myString = " \n \n\n Hey! \n I'm a string!!! \n\n";
const trimmedString = myString.trim();
console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"
Here's an example fiddle: http://jsfiddle.net/BLs8u/
NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.
Array to string conversion
in latest versions of php 7.x is error, rather than notice, and prevents further code execution.
Using print
, echo
on array is not an option anymore.
Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.
Use var_dump
,print_r
, iterate through input value using foreach
or for
to output input data for names that are declared as input arrays ('name[]
')
Most common practice to catch errors is using try/catch
blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try
block.
try{ //wrap around possible cause of error or notice
if(!empty($_POST['C'])){
echo $_POST['C'];
}
}catch(Exception $e){
//handle the error message $e->getMessage();
}