I've read this whole thread, and I just want to point out what seems like an inconsistency to me.
The compiler prevents you from doing the assignment with Lists:
List<Tiger> myTigersList = new List<Tiger>() { new Tiger(), new Tiger(), new Tiger() };
List<Animal> myAnimalsList = myTigersList; // Compiler error
But the compiler is perfectly fine with arrays:
Tiger[] myTigersArray = new Tiger[3] { new Tiger(), new Tiger(), new Tiger() };
Animal[] myAnimalsArray = myTigersArray; // No problem
The argument about whether the assignment is known to be safe falls apart here. The assignment I did with the array is not safe. To prove that, if I follow that up with this:
myAnimalsArray[1] = new Giraffe();
I get a runtime exception "ArrayTypeMismatchException". How does one explain this? If the compiler really wants to prevent me from doing something stupid, it should have prevented me from doing the array assignment.
Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:
Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)
or like this:
Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)
Use the query below to find out pending transaction.
If it returns a value, it means there is a pending transaction.
Here is the query:
select dbms_transaction.step_id from dual
;
References:
http://www.acehints.com/2011/07/how-to-check-pending-transaction-in.html
http://www.acehints.com/p/site-map.html
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.
Apache Commons validator can be used as mentioned in the other answers.
pom.xml:
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.4.1</version>
</dependency>
build.gradle:
compile 'commons-validator:commons-validator:1.4.1'
The import:
import org.apache.commons.validator.routines.EmailValidator;
The code:
String email = "[email protected]";
boolean valid = EmailValidator.getInstance().isValid(email);
and to allow local addresses
boolean allowLocal = true;
boolean valid = EmailValidator.getInstance(allowLocal).isValid(email);
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));
//Output : C
items.forEach(item->{
System.out.println(item);
System.out.println(item.toLowerCase());
}
});
Question
How to get an actual file path from a URI
Answer
To my knowledge, we don't need to get the file path from a URI because for most of the cases we can directly use the URI to get our work done (like 1. getting bitmap 2. Sending a file to the server, etc.)
1. Sending to the server
We can directly send the file to the server using just the URI.
Using the URI we can get InputStream, which we can directly send to the server using MultiPartEntity.
Example
/**
* Used to form Multi Entity for a URI (URI pointing to some file, which we got from other application).
*
* @param uri URI.
* @param context Context.
* @return Multi Part Entity.
*/
public MultipartEntity formMultiPartEntityForUri(final Uri uri, final Context context) {
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));
try {
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
if (inputStream != null) {
ContentBody contentBody = new InputStreamBody(inputStream, getFileNameFromUri(uri, context));
multipartEntity.addPart("[YOUR_KEY]", contentBody);
}
}
catch (Exception exp) {
Log.e("TAG", exp.getMessage());
}
return multipartEntity;
}
/**
* Used to get a file name from a URI.
*
* @param uri URI.
* @param context Context.
* @return File name from URI.
*/
public String getFileNameFromUri(final Uri uri, final Context context) {
String fileName = null;
if (uri != null) {
// Get file name.
// File Scheme.
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
File file = new File(uri.getPath());
fileName = file.getName();
}
// Content Scheme.
else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Cursor returnCursor =
context.getContentResolver().query(uri, null, null, null, null);
if (returnCursor != null && returnCursor.moveToFirst()) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
fileName = returnCursor.getString(nameIndex);
returnCursor.close();
}
}
}
return fileName;
}
2. Getting a BitMap from a URI
If the URI is pointing to image then we will get bitmap, else null:
/**
* Used to create bitmap for the given URI.
* <p>
* 1. Convert the given URI to bitmap.
* 2. Calculate ratio (depending on bitmap size) on how much we need to subSample the original bitmap.
* 3. Create bitmap bitmap depending on the ration from URI.
* 4. Reference - http://stackoverflow.com/questions/3879992/how-to-get-bitmap-from-an-uri
*
* @param context Context.
* @param uri URI to the file.
* @param bitmapSize Bitmap size required in PX.
* @return Bitmap bitmap created for the given URI.
* @throws IOException
*/
public static Bitmap createBitmapFromUri(final Context context, Uri uri, final int bitmapSize) throws IOException {
// 1. Convert the given URI to bitmap.
InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
return null;
}
// 2. Calculate ratio.
int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
double ratio = (originalSize > bitmapSize) ? (originalSize / bitmapSize) : 1.0;
// 3. Create bitmap.
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
bitmapOptions.inDither = true;//optional
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
input = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
input.close();
return bitmap;
}
/**
* For Bitmap option inSampleSize - We need to give value in power of two.
*
* @param ratio Ratio to be rounded of to power of two.
* @return Ratio rounded of to nearest power of two.
*/
private static int getPowerOfTwoForSampleRatio(final double ratio) {
int k = Integer.highestOneBit((int) Math.floor(ratio));
if (k == 0) return 1;
else return k;
}
Comments
Reference
I have written an incredibly simple (5 lines of code) plugin for exactly this functionality:
http://byrichardpowell.github.com/jquery-or/
It allows you to effectively say "get this element, or if that element doesnt exist, use this element". For example:
$( '#doesntExist' ).or( '#exists' );
Whilst the accepted answer provides similar functionality to this, if both selectors (before & after the comma) exist, both selectors will be returned.
I hope it proves helpful to anyone who might land on this page via google.
You can use innerHTML
(then parse text from HTML) or use innerText
.
let textContentWithHTMLTags = document.querySelector('div').innerHTML;
let textContent = document.querySelector('div').innerText;
console.log(textContentWithHTMLTags, textContent);
innerHTML
and innerText
is supported by all browser(except FireFox < 44) including IE6.
Would like to add:
After update, such as
ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;
If you get
ERROR 1138 (22004): Invalid use of NULL value
Make sure you update the table first to have values in the related column (so it's not null)
the bast way i use i bind the textblock and combobox to same property and this property should support notifyPropertyChanged.
i used relativeresource to bind to parent view datacontext which is usercontrol to go up datagrid level in binding because in this case the datagrid will search in object that you used in datagrid.itemsource
<DataGridTemplateColumn Header="your_columnName">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.SelectedUnit.Name, Mode=TwoWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox DisplayMemberPath="Name"
IsEditable="True"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.UnitLookupCollection}"
SelectedItem="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.SelectedUnit, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding UnitId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Id" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
jQuery was written using JavaScript, and is a library to be used by JavaScript. You cannot learn jQuery without learning JavaScript.
Likely, you'll want to learn and use both of them. go through following breif diffrence http://www.slideshare.net/umarali1981/difference-between-java-script-and-jquery
del /s /q c:\where ever the file is\*
rmdir /s /q c:\where ever the file is\
mkdir c:\where ever the file is\
Here I have a solution that avoid multiple requests, for loops and old document removal.
You can easily create a new idea manually using something like:_id:ObjectId()
But knowing Mongo will automatically assign an _id if missing, you can use aggregate to create a $project
containing all the fields of your document, but omit the field _id. You can then save it with $out
So if your document is:
{
"_id":ObjectId("5b5ed345cfbce6787588e480"),
"title": "foo",
"description": "bar"
}
Then your query will be:
db.getCollection('myCollection').aggregate([
{$match:
{_id: ObjectId("5b5ed345cfbce6787588e480")}
}
{$project:
{
title: '$title',
description: '$description'
}
},
{$out: 'myCollection'}
])
Replace
import { Router, Route, Link, browserHistory } from 'react-router';
With
import { BrowserRouter as Router, Route } from 'react-router-dom';
It will start working. It is because react-router-dom exports BrowserRouter
I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
The two key elements of a recursive algorithm are:
n == 0
factorial(n - 1)
There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.
And then you can copy for example the file "test.txt" from a remote host to the local host
scp [email protected]:test.txt /local/dir
@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.
In UNIX, absolute paths must start with '/'.
Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.
Server side Comments:
Razor .cshtml
@* Comment goes here *@
.aspx
For those looking for the older .aspx
view (and Asp.Net WebForms) server side comment syntax:
<%-- Comment goes here --%>
Client Side Comments
HTML Comment
<!-- Comment goes here -->
Javascript Comment
// One line Comment goes Here
/* Multiline comment
goes here */
As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).
You could either use a negative look-ahead or look-behind:
^(?!.*?bar).*
^(.(?<!bar))*?$
Or use just basics:
^(?:[^b]+|b(?:$|[^a]|a(?:$|[^r])))*$
These all match anything that does not contain bar
.
I found the best solution was to use the base tag. Add the following to the head of the page in the iframe:
<base target="_parent">
This will load all links on the page in the parent window. If you want your links to load in a new window, use:
<base target="_blank">
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
The Python approach to "main" is almost unique to the language(*).
The semantics are a bit subtle. The __name__
identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__
is set to "__main__"
(the literal string: __main__
).
This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:
#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
pass
def some_function(*args,**kwargs):
pass
if __name__ == '__main__':
print("This only executes when %s is executed rather than imported" % __file__)
Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.
It's important to understand that all of the code above the if __name__
line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print
statement before the if __name__
line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).
I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.
Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__"
to isolate a block of code which calls a suite of unit tests that apply to this module.
(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).
Summary: if __name__ == '__main__':
has two primary use cases:
It's fairly common to def main(*args)
and have if __name__ == '__main__':
simply call main(*sys.argv[1:])
if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module()
and calling test_module()
in your if __name__ == '__main__:'
suite.
if __file__ == $0
).To get an array as result from a json string you should set second param as boolean true.
$result = json_decode($json_string, true);
$context = $result['context'];
Otherwise $result will be an std object. but you can access values as object.
$result = json_decode($json_string);
$context = $result->context;
In case you want to hide and show an element, depending on whether it is already visible or not, you can use
toggle instead of .hide()
and .show()
$('elem').toggle();
You get the value of the textarea, use it :
$('.type').keyup(function() {
var v = $('.type').val(); // you'd better use this.value here
if (v.indexOf('> <')!=-1) {
console.log('contains > <');
}
});
The default is: no prompt.
You can enable it with -Confirm
or disable it with -Confirm:$false
However, it will still prompt, when the target:
-Recurse
parameter is not specified.-Force
is required to also remove hidden and read-only items etc.
To sum it up:
Remove-Item -Recurse -Force -Confirm:$false
...should cover all scenarios.
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
Both setInterval and setTimeout return a timer id that you can use to cancel the execution, that is, before the timeouts are triggered. To cancel you call either clearInterval or clearTimeout like this:
var timeoutId = setTimeout(someFunction, 1000);
clearTimeout(timeoutId);
var intervalId = setInterval(someFunction, 1000),
clearInterval(intervalId);
Also, the timeouts are automatically cancelled when you leave the page or close the browser window.
Use element.innerHTML="some \\\\n some";
.
My fix was as simple as making sure the correct connection string was in ALL appsettings.json files, not just the default one.
Well, there's a much easier way of doing this. When you grab embed link for youtube video, scroll down a bit and you will see some options: iFrame Embed, Use old embed, related videos etc. There, select Use old embed link. This solves the issue.
Set setHasMenuOptions(true)
works if application has a theme with Actionbar
such as Theme.MaterialComponents.DayNight.DarkActionBar
or Activity has it's own Toolbar, otherwise onCreateOptionsMenu
in fragment does not get called.
If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with
(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)
which lets your fragment onCreateOptionsMenu to be called.
Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU)
and item listener with
toolbar.setOnMenuItemClickListener {
// do something
true
}
If you already have initialized the modal window, then you may want to reset the options with $('#myModal').removeData("modal").modal({backdrop: 'static', keyboard: false})
to make sure it will apply the new options.
you can do it on terminal, either:
apachectl -M
apache2ctl -M
taken from 2daygeek
You can use cat > filename
to use standart input to write to the file. At the end you have to put EOF CTRL+D
.
For me the problems occurs because I have my old username/password settings saved for gitlab, so that I need to remove those credentials. I run the following command on my mac:
sudo su
git config --system --unset credential.helper
and do the clone again, enter the username and password. And everything is fine.
Matt Ball answered it correctly. I would say about it with examples.
Consider running a program compiled in Turbo-Borland C/C++ (version 3.1 from the year 1991) compiler and let it run under a 32-bit version of windows like Win 98/2000 etc.
It's a 16-bit compiler. And you will see all your programs have 16-bit pointers. Why is it so when your OS is 32bit? Because your compiler has set up the execution environment of 16 bit and the 32-bit version of OS supported it.
What is commonly called as JRE (Java Runtime Environment) provides a Java program with all the resources it may need to execute.
Actually, runtime environment is brain product of idea of Virtual Machines. A virtual machine implements the raw interface between hardware and what a program may need to execute. The runtime environment adopts these interfaces and presents them for the use of the programmer. A compiler developer would need these facilities to provide an execution environment for its programs.
In Java 8, you can use the new forEachRemaining
method that's been added to the Iterator
interface:
List<Element> list = new ArrayList<>();
iterator.forEachRemaining(list::add);
Another option is to create a exclude list, this is particulary usefull when you have a long list of things to exclude.
vi /root/scripts/exclude_list.txt
Now add what you would like to exclude
Nopaging the limit is
keyword to remove is
Now use grep to remove lines from your file log file and view information not excluded.
grep -v -f /root/scripts/exclude_list.txt /var/log/admin.log
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
10 * * * Sun
Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday.
Hashes can not be decrypted check this out.
If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).
But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php
For Blowfish by crypt()
function -
crypt('String', '$2a$07$twentytwocharactersalt$');
password_hash
will be introduced in PHP 5.5.
$options = [
'cost' => 7,
'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.
This is what I use to have VB
wait for process to complete before continuing.
I did not write this and do not take credit.
It was offered in some other open forum and works very well for me:
The following declarations are needed for the RunShell
subroutine:
Option Explicit
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Const PROCESS_QUERY_INFORMATION = &H400
Private Const STATUS_PENDING = &H103&
'then in your subroutine where you need to shell:
RunShell (path and filename or command, as quoted text)
This official doc - talks about how to turn off forgery protection for api properly http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html
awk 'NF' file-with-blank-lines > file-with-no-blank-lines
You can do like
HTML in PHP :
<?php
echo "<table>";
echo "<tr>";
echo "<td>Name</td>";
echo "<td>".$name."</td>";
echo "</tr>";
echo "</table>";
?>
Or You can write like.
PHP in HTML :
<?php /*Do some PHP calculation or something*/ ?>
<table>
<tr>
<td>Name</td>
<td><?php echo $name;?></td>
</tr>
</table>
<?php /*Do some PHP calculation or something*/ ?>
Means:
You can open a PHP tag with <?php
, now add your PHP code, then close the tag with ?>
and then write your html code. When needed to add more PHP, just open another PHP tag with <?php
.
You should avoid using global vars, and prefer using .data()
So, you'd do:
jQuery('#id').click(function(){
$(this).data('clicked', true);
});
Then, to check if it was clicked and perform an action:
if(jQuery('#id').data('clicked')) {
//clicked element, do-some-stuff
} else {
//run function2
}
Hope this helps. Cheers
Regardless the compiled code, They are semantically different thing. <cond>?<true expr>:<false expr>
is an expression and if..else..
is a statement.
Although the syntax of conditional expression seems awkward, it is a good thing. You are forced to provide a <false expr>
and the two expressions are type checked.
The equivalent to if..else..
in expression-based, functional language like Lisp, Haskell is ? :
in C++, instead of if..else..
statement.
LITTLE JAVASCRIPT + SCSS SOLUTION
I usually use a quite different point of view and a (very) little javascript. The thing is:
what we really want is change height
The height is the sum of all list items inside the submenu
We usually know the height of a list item, since we're styling it
So my solution applies to 'normal' submenus where items names have only 1 row. Anyway, with a little more js one could accomodate even more than 1 row names.
Basically, what I do is simply count the submenus items and apply specific classes accordingly. Then pass the ball to (s)css. So, for example:
var main_menu = $('.main-menu');
var submenus = $('.main-menu').find('.submenu');
submenus.each(function(index,item){
var i = $(item);
i.addClass('has-' + i.find('li').length + '-children');
});
You can use any class/selector, obviously. At this point we have submenus like this:
<ul class="submenu has-3-children">
<li></li>
<li></li>
<li></li>
</ul>
And our css like this:
.submenu{
//your styles [...]
height:0;
overflow:hidden;
transition: all 200ms ease-in-out; //assume Autoprefixer is used
}
We will also have some scss variables like these (arbitrary example):
$sub_item_height:30px;
$sub_item_border:2px;
At this point, assumed that opened main menu items will get a class like 'opened' or the like (your implemetations..), we can do something like this:
//use a number of children reasonably high so it won't be overcomed by real buttons
.main-menu .opened .submenu{
&.has-1-children{ height: $sub_item_height*1 + $sub_item_border*1; }
&.has-2-children{ height: $sub_item_height*2 + $sub_item_border*2; }
&.has-3-children{ height: $sub_item_height*3 + $sub_item_border*3; }
//and so on....
}
Or, to shorten up:
.main-menu .opened .submenu{
@for $i from 1 through 12{//12 is totally arbitrary
&.has-#{$i}-children { height: $menu_item_height * $i + $menu_item_border * $i; }
}
}
For most of the times, this will do the job. Hope it helps!
If you want to animate each character you might need to wrap it in span element;
var $demoText = $("#demo-text");
$demoText.html( $demoText.html().replace(/./g, "<span>$&</span>").replace(/\s/g, " "));
I think this is the best way to do it, then process the spans. ( for example with TweenMax)
TweenMax.staggerFromTo( $demoText.find("span"), 0.2, {autoAlpha:0}, {autoAlpha:1}, 0.1 );
As there is no proper wheel file in http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv?
Try this:(Worked in Anaconda Prompt or Pycharm)
pip install opencv-contrib-python
pip install opencv-python
The gap between the (bootstrap) input field and jquery-ui autocompleter seem to occur only in jQuery versions >= 3.2
When using jQuery version 3.1.1 it seem to not happen.
Possible reason is the notable update in v3.2.0 related to a bug fix on .width()
and .height()
. Check out the jQuery release notes for further details: v3.2.0 / v3.1.1
Bootstrap version 3.4.1 and jquery-ui version 1.12.0 used
(PartlyStolen from ServerFault)
I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.
Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.
This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):
Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.
The Memcache module also provides a session handler (memcache).
More information about memcached can be found at » http://www.danga.com/memcached/.
The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:
memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).
Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.
Ok, you should be using a servlet not a JSP but if you really need to... add this directive at the top of your page:
<%@ page trimDirectiveWhitespaces="true" %>
Or in the jsp-config section your web.xml
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>
</jsp-config>
Also flush
/close
the OutputStream
and return when done.
dataOutput.flush();
dataOutput.close();
return;
you would have to do something like this:
objArray.sort(function(a, b) {
var textA = a.DepartmentName.toUpperCase();
var textB = b.DepartmentName.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
note: changing the case (to upper or lower) ensures a case insensitive sort.
Use the native PHP $_SERVER['HTTP_USER_AGENT']
variable instead.
I found this snippet to work well when switching between X and no-X environments.
import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
import matplotlib.pyplot as plt
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
Two example works for me, for your reference.
Bitmap bitmap = Utils.decodeBase64(base64);
try {
File file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
LOG.i(null, "Save file error!");
return false;
}
and this one
Bitmap savePic = Utils.decodeBase64(base64);
File file = new File(filePath);
File path = new File(file.getParent());
if (savePic != null) {
try {
// build directory
if (file.getParent() != null && !path.isDirectory()) {
path.mkdirs();
}
// output image to file
FileOutputStream fos = new FileOutputStream(filePath);
savePic.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
ret = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
LOG.i(TAG, "savePicture image parsing error");
}
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
I combined some of Flavio's answer to this small solution.
.hidden-ul-bullets li {
list-style: none;
}
.hidden-ul-bullets ul {
margin-left: 0.25em; // for my purpose, a little indentation is wished
}
The decision about bullets is made at an enclosing element, typically a div
. The drawback (or todo) of my solution is that the liststyle removal also applies to ordered lists.
From the HTTP core module docs:
Example from the documentation:
location = / {
# matches the query / only.
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
location /documents/ {
# matches any query beginning with /documents/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
[ configuration C ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration D.
[ configuration E ]
}
If it's still confusing, here's a longer explanation.
For result find: Click Here
Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. There is a scrollback history buffer for each virtual terminal and a copy-and-paste mechanism that allows the user to move text regions between windows.
Please try
sudo a2enmod rewrite
or use correct apache restart command
sudo /etc/init.d/apache2 restart
Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()
is working for me
SIMPLIEST WAY TO HANDLE TIMEOUT LOOP
function myFunc (terminator = false) {
if(terminator) {
clearTimeout(timeOutVar);
} else {
// do something
timeOutVar = setTimeout(function(){myFunc();}, 1000);
}
}
myFunc(true); // -> start loop
myFunc(false); // -> end loop
This means, it couldn't find any class which can be executed as jersey RESTful web service.
Check:
com.sun.jersey.config.property.packages
' is missing in your
web.xml. com.sun.jersey.config.property.packages
'
param is missing or invalid (the mentioned package doesn't exists). It should be a package where you have put your POJO classes which runs as jersey services.@Path
attribute.use this function.
its the same convention you wanted. using the simple abs feature of python.
also - sometimes the answers are so simple we miss them, its okay :)
>>> def distance(x,y):
return abs(x-y)
Also, while not a pure Python solution, if you're using IPython (as you probably should anyway), you can do:
%run /path/to/filename.py
Which is equally easy.
Also to maintain accessibility, you should use this to determine your keycode:
c = e.which ? e.which : e.keyCode;
if (c == 13) ...
I had the same problem. I decided in a very unexpected way. Just opened the command line as an administrator. And then typed:
pip install numpy
I also had the same issue. I also wanted so users could take photos easily while picking photos from the gallery. Couldn't find a native way of doing this therefore I decided to make an opensource project. It is much like MultipleImagePick but just better way of implementing it.
https://github.com/giljulio/android-multiple-image-picker
private static final RESULT_CODE_PICKER_IMAGES = 9000;
Intent intent = new Intent(this, SmartImagePicker.class);
startActivityForResult(intent, RESULT_CODE_PICKER_IMAGES);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case RESULT_CODE_PICKER_IMAGES:
if(resultCode == Activity.RESULT_OK){
Parcelable[] parcelableUris = data.getParcelableArrayExtra(ImagePickerActivity.TAG_IMAGE_URI);
//Java doesn't allow array casting, this is a little hack
Uri[] uris = new Uri[parcelableUris.length];
System.arraycopy(parcelableUris, 0, uris, 0, parcelableUris.length);
//Do something with the uris array
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
There's no direct way to do it with Python's datetime.
Check out the relativedelta type at python-dateutil. It allows you to specify a time delta in months.
Use either a simple blank *
or [:blank:]*
to remove all possible spaces at the end of the line:
sed 's/ *$//' file
Using the [:blank:]
class you are removing spaces and tabs:
sed 's/[[:blank:]]*$//' file
Note this is POSIX, hence compatible in both GNU sed and BSD.
For just GNU sed you can use the GNU extension \s*
to match spaces and tabs, as described in BaBL86's answer. See POSIX specifications on Basic Regular Expressions.
Let's test it with a simple file consisting on just lines, two with just spaces and the last one also with tabs:
$ cat -vet file
hello $
bye $
ha^I $ # there is a tab here
Remove just spaces:
$ sed 's/ *$//' file | cat -vet -
hello$
bye$
ha^I$ # tab is still here!
Remove spaces and tabs:
$ sed 's/[[:blank:]]*$//' file | cat -vet -
hello$
bye$
ha$ # tab was removed!
May be you need Decimal
>>> from decimal import Decimal
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')
maybe the unbind method will work for you
$("#myimage").unbind("click");
This can also be done as follows for a list of dataframes df_list
:
df = df_list[0]
for df_ in df_list[1:]:
df = df.merge(df_, on='join_col_name')
or if the dataframes are in a generator object (e.g. to reduce memory consumption):
df = next(df_list)
for df_ in df_list:
df = df.merge(df_, on='join_col_name')
The setInterval
method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
If you looking for a simple way of datetime
to string conversion and can omit the format. You can convert datetime
object to str
and then use array slicing.
In [1]: from datetime import datetime
In [2]: now = datetime.now()
In [3]: str(now)
Out[3]: '2019-04-26 18:03:50.941332'
In [5]: str(now)[:10]
Out[5]: '2019-04-26'
In [6]: str(now)[:19]
Out[6]: '2019-04-26 18:03:50'
But note the following thing. If other solutions will rise an AttributeError
when the variable is None
in this case you will receive a 'None'
string.
In [9]: str(None)[:19]
Out[9]: 'None'
Change
$data[$parts[0]] = $parts[1];
to
if ( ! isset($parts[1])) {
$parts[1] = null;
}
$data[$parts[0]] = $parts[1];
or simply:
$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;
Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.
According to php.net possible return values from explode:
Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.
Use:
filename=$1
IFS=$'\n'
for next in `cat $filename`; do
echo "$next read from $filename"
done
exit 0
If you have set IFS
differently you will get odd results.
BLOB :
BLOB
(Binary Large Object) is a large object data type in the database system. BLOB
could store a large chunk of data, document types and even media files like audio or video files. BLOB
fields allocate space only whenever the content in the field is utilized. BLOB
allocates spaces in Giga Bytes.
USAGE OF BLOB :
You can write a binary large object (BLOB
) to a database as either binary or character data, depending on the type of field at your data source. To write a BLOB
value to your database, issue the appropriate INSERT or UPDATE
statement and pass the BLOB
value as an input parameter. If your BLOB
is stored as text, such as a SQL Server text field, you can pass the BLOB
as a string parameter. If the BLOB
is stored in binary format, such as a SQL Server image field, you can pass an array of type byte as a binary parameter.
A useful link : Storing documents as BLOB in Database - Any disadvantages ?
One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:
Array(8).fill().map((_, i) => i * i);
This should solve your problem:
td {
/* <http://www.w3.org/wiki/CSS/Properties/text-align>
* left, right, center, justify, inherit
*/
text-align: center;
/* <http://www.w3.org/wiki/CSS/Properties/vertical-align>
* baseline, sub, super, top, text-top, middle,
* bottom, text-bottom, length, or a value in percentage
*/
vertical-align: top;
}
Applying the recursive function on numpy arrays will be faster than the current answer.
df = pd.DataFrame(np.repeat(np.arange(2, 6),3).reshape(4,3), columns=['A', 'B', 'D'])
new = [df.D.values[0]]
for i in range(1, len(df.index)):
new.append(new[i-1]*df.A.values[i]+df.B.values[i])
df['C'] = new
Output
A B D C
0 1 1 1 1
1 2 2 2 4
2 3 3 3 15
3 4 4 4 64
4 5 5 5 325
After this
Two things to do:
Project Settings > Project compiler output > Set it as "Project path(You actual project's path)”+”\out”.
Project Settings > Module > Path > Choose "Inherit project compile path""
If button ran is not active
You must reload IDEA
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
Could use CASE WHEN
to leave those with no ';' alone.
SELECT
CASE WHEN CHARINDEX(';', MyText) > 0 THEN
LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
MyText END
FROM MyTable
This seems to work well for me. Tested on Touchwiz 5.1, LineageOS 7.1, and CyanogenMod 11.
ip route list match 0 table all scope global
Gives output similar to this:
default via 192.168.1.1 dev wlan0 table wlan0 proto static
Browsers with HTML5 support has files property for input type. This will of course not work in older IE versions.
var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
var size = inpFiles.files.item(i).size;
alert("File Size : " + size);
}
Click wamp icon :
1- apache -> httpd.conf (A notepad file will be opened)
2- Find 80
3 -Replace with 81
Listen 12.34.56.78:81 Listen 0.0.0.0:81 Listen [::0]:81
4- Restart wamp services
!!Done
That is a pretty standard use case for apply()
:
R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
start end newcol
1 1 2 1.5
2 3 6 4.5
3 5 7 6.0
4 7 9 8.0
R>
You can also use plyr
if you prefer but here is no real need to go beyond functions from base R.
sep=''
in the context of a function call sets the named argument sep
to an empty string. See the print()
function; sep
is the separator used between multiple values when printing. The default is a space (sep=' '
), this function call makes sure that there is no space between Property tax: $
and the formatted tax
floating point value.
Compare the output of the following three print()
calls to see the difference
>>> print('foo', 'bar')
foo bar
>>> print('foo', 'bar', sep='')
foobar
>>> print('foo', 'bar', sep=' -> ')
foo -> bar
All that changed is the sep
argument value.
\t
in a string literal is an escape sequence for tab character, horizontal whitespace, ASCII codepoint 9.
\t
is easier to read and type than the actual tab character. See the table of recognized escape sequences for string literals.
Using a space or a \t
tab as a print separator shows the difference:
>>> print('eggs', 'ham')
eggs ham
>>> print('eggs', 'ham', sep='\t')
eggs ham
I think inline scripts are hard to stop instead you can try with this:
<div id="test">
<div>Click Me</div>
</div>
and script:
$(function () {
$('#test').children().click(function(){
alert('hello');
});
$('#test').children().off('click');
});
I had the same issue. I think it would be appropriate to check whether your class can be compiled or not. Click recompile (Ctrl+Shift+F9 by default). If its not working then you have to investigate why it isn't compiling.
In my case the code wasn't autocompiling because there were hidden errors with compilation (they weren't shown in logs anywhere and maven clean-install was working). The rootcause was incorrect Project Structure -> Modules configuration, so Intellij Idea wasn't able to build it according to this configuration.
Here's how I do it using a DataTable. This is a working piece of TEST code.
using (SqlConnection con = new SqlConnection(connStr))
{
con.Open();
// Create a table with some rows.
DataTable table = MakeTable();
// Get a reference to a single row in the table.
DataRow[] rowArray = table.Select();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";
try
{
// Write the array of rows to the destination.
bulkCopy.WriteToServer(rowArray);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}//using
If you have spaces in the filename, try these:
[file](./file%20with%20spaces.md)
[file](<./file with spaces.md>)
First one seems more reliable
I needed this command to make it work on El Capitan:
sudo security add-trust -d -r trustRoot -p basic -p codeSign -k /Library/Keychains/System.keychain ~/Desktop/gdb-cert.cer
Having searched around several posts. On Windows 10 having downloaded and installed Github for Windows 2.10.2 I found the git.exe in
C:\Users\<user>\AppData\Local\Programs\Git\bin
and the git-cmd.exe in
C:\Users\<user>\AppData\Local\Programs\Git
Please note the change to Programs folder within Local from the above posts.
I am responding this question bounced from another angle.
This is an eternal topic, and we could open a flame war in a lot of forums.
When people assert that JavaScript is an OO programming language because they can use OOD with this, then I ask: Why is not C an OO programming language? Repeat, you can use OOD with C and if you said that C is an OO programming language everybody will said you that you are crazy.
We could put here a lot of references about this topic in very old books and forums, because this topic is older than the Internet :)
JavaScript has not changed for many years, but new programmers want to show JavaScript is an OO programming language. Why? JavaScript is a powerful language, but is not an OO programming language.
An OO programming language must have objects, method, property, classes, encapsulation, aggregation, inheritance and polymorphism. You could implement all this points, but JavaScript has not them.
An very illustrate example: In chapter 6 of "Object-Oriented JavaScript" describe 10 manners to implement "inheritance". How many manners there are in Java? One, and in C++? One, and in Delphi (Object Pascal)? One, and in Objective-C? One.
Why is this different? Because Java, C++, Delphi and Objective-C are designed with OOP in mind, but not JavaScript.
When I was a student (in 1993), in university, there was a typical home work: Implement a program designed using a OOD (Object-oriented design) with a non-OO language. In those times, the language selected was C (not C++). The objective of this practices was to make clear the difference between OOD and OOP, and could differentiate between OOP and non-OOP languages.
Anyway, it is evidence that not all people have some opinion about this topic :)
Anyway, in my opinion, JavaScript is a powerful language and the future in the client side layer!
This is a slightly more general answer with more explanation for future viewers.
If you want to find the text length or do something else after the text has been changed, you can add a text changed listener to your edit text.
EditText editText = (EditText) findViewById(R.id.testEditText);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
}
});
The listener needs a TextWatcher
, which requires three methods to be overridden: beforeTextChanged
, onTextChanged
, and afterTextChanged
.
You can get the character count in onTextChanged
or beforeTextChanged
with
charSequence.length()
or in afterTextChanged
with
editable.length()
The parameters are a little confusing so here is a little extra explanation.
beforeTextChanged
beforeTextChanged(CharSequence charSequence, int start, int count, int after)
charSequence
: This is the text content before the pending change is made. You should not try to change it.start
: This is the index of where the new text will be inserted. If a range is selected, then it is the beginning index of the range.count
: This is the length of selected text that is going to be replaced. If nothing is selected then count
will be 0
.after
: this is the length of the text to be inserted. onTextChanged
onTextChanged(CharSequence charSequence, int start, int before, int count)
charSequence
: This is the text content after the change was made. You should not try to modify this value here. Modify the editable
in afterTextChanged
if you need to.start
: This is the index of the start of where the new text was inserted.before
: This is the old value. It is the length of previously selected text that was replaced. This is the same value as count
in beforeTextChanged
.count
: This is the length of text that was inserted. This is the same value as after
in beforeTextChanged
.afterTextChanged
afterTextChanged(Editable editable)
Like onTextChanged
, this is called after the change has already been made. However, now the text may be modified.
editable
: This is the editable text of the EditText
. If you change it, though, you have to be careful not to get into an infinite loop. See the documentation for more details.I use this line for Spring Boot applications:
logging.level.org.springframework.jdbc.core = TRACE
This approach pretty universal and I usually use it for any other classes inside my application.
The below code works always even if any image makes the window scroll.
$(function() {
$("#demo-box").click(function(e) {
var offset = $(this).offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert("X: " + relativeX + " Y: " + relativeY);
});
});
Ref: http://css-tricks.com/snippets/jquery/get-x-y-mouse-coordinates/
Check your local hosts file (C:\Windows\System32\drivers\etc\hosts for example). In my case I had previously used this to point a URL to a dev box and then forgotten about it. When I then reused the same URL I kept getting Bad Request (Invalid Hostname) because the traffic was going to the wrong server.
You can run conda install --file requirements.txt
instead of the loop, but there is no target directory in conda install. conda install
installs a list of packages into a specified conda environment.
Right click on your MVC Project. Go to Properties. Go to the Web tab.
Change the port number in the Project Url. Example. localhost:50645
Changing the bold number, 50645, to anything else will change the port the site runs under.
Press the Create Virtual Directory button to complete the process.
See also: http://msdn.microsoft.com/en-us/library/ms178109.ASPX
Image shows the web tab of an MVC Project
Maven way
If you use Maven, you can run the following command to run all your test cases:
mvn clean test
Or you can run a particular test as below
mvn clean test -Dtest=your.package.TestClassName
mvn clean test -Dtest=your.package.TestClassName#particularMethod
If you would like to see the stack trace (if any) in the console instead of report files in the target\surefire-reports folder, set the user property surefire.useFile to false. For example:
mvn clean test -Dtest=your.package.TestClassName -Dsurefire.useFile=false
Gradle way
If you use Gradle, you can run the following command to run all your test cases:
gradle test
Or you can run a particular test as below
gradle test --tests your.package.TestClassName
gradle test --tests your.package.TestClassName.particularMethod
If you would like more information, you can consider options such as --stacktrace, or --info, or --debug.
For example, when you run Gradle with the info logging level --info, it will show you the result of each test while they are running. If there is any exception, it will show you the stack trace, pointing out what the problem is.
gradle test --info
If you would like to see the overall test results, you can open the report in the browser, for example (Open it using Google Chrome in Ubuntu):
google-chrome build/reports/tests/index.html
Ant way
Once you set up your Ant build file build.xml, you can run your JUnit test cases from the command line as below:
ant -f build.xml <Your JUnit test target name>
You can follow the link below to read more about how to configure JUnit tests in the Ant build file: https://ant.apache.org/manual/Tasks/junit.html
Normal way
If you do not use Maven, or Gradle or Ant, you can follow the following way:
First of all, you need to compile your test cases. For example (in Linux):
javac -d /absolute/path/for/compiled/classes -cp /absolute/path/to/junit-4.12.jar /absolute/path/to/TestClassName.java
Then run your test cases. For example:
java -cp /absolute/path/for/compiled/classes:/absolute/path/to/junit-4.12.jar:/absolute/path/to/hamcrest-core-1.3.jar org.junit.runner.JUnitCore your.package.TestClassName
it doesn't matter what type of value you wish to post, just enclose it within the quotation marks, to get it as string. Not for complex types.
javascript:
var myData = null, url = 'api/' + 'Named/' + 'NamedMethod';
myData = 7;
$http.post(url, "'" + myData + "'")
.then(function (response) { console.log(response.data); });
myData = "some sentence";
$http.post(url, "'" + myData + "'")
.then(function (response) { console.log(response.data); });
myData = { name: 'person name', age: 21 };
$http.post(url, "'" + JSON.stringify(myData) + "'")
.then(function (response) { console.log(response.data); });
$http.post(url, "'" + angular.toJson(myData) + "'")
.then(function (response) { console.log(response.data); });
c#:
public class NamedController : ApiController
{
[HttpPost]
public int NamedMethod([FromBody] string value)
{
return value == null ? 1 : 0;
}
}
Here is an example to load js script from the asset on WebView
.
Put script to a file will help reading easier
I load the script in onPageFinished
because I need to access some DOM element inside the script (to able to access it should be loaded or it will be null). Depend on the purpose of the script, we may load it earlier
assets/myjsfile.js
document.getElementById("abc").innerText = "def"
document.getElementById("abc").onclick = function() {
document.getElementById("abc").innerText = "abc"
}
WebViewActivity
webView.settings.javaScriptEnabled = true
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
val script = readTextFromAsset("myjsfile.js")
view.loadUrl("javascript: $script")
}
}
fun readTextFromAsset(context: Context, fileName: String): String {
return context.assets.open(fileName).bufferedReader().use { it.readText()
}
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
In iReport 5.5.0, just right click the report base hierarchy in Report Inspector Bloc Window viewer, then click Compile Report
You can now see the result in the console down. If no Errors, you may see something like this.
Looks like you are running afoul of this rule for updating views from Books Online: "INSERT statements must specify values for any columns in the underlying table that do not allow null values and have no DEFAULT definitions."
Can you consider using Nix http://nixos.org/nix/ ?
Nix supports multi-user package management: multiple users can share a common Nix store securely, don’t need to have root privileges to install software, and can install and use different versions of a package.
It says you don't have a local grunt
so try:
npm install grunt
(without the -g
it's a local grunt
)
Though not directly related, make sure you have Gruntfile.js
in your current folder.
Open dynamically
string addres= "Print/" + Id + ".htm";
System.Diagnostics.Process.Start(Path.Combine(Environment.CurrentDirectory, addres));
user-scalable:
user-scalable=yes (default) to allow the user to zoom in or out on the web page;
user-scalable=no to prevent the user from zooming in or out.
You can get more detailed information by reading the following articles.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=3.0">_x000D_
</head>_x000D_
<body>_x000D_
<header>_x000D_
</header>_x000D_
<main>_x000D_
<section>_x000D_
<h1>do not using <mark>user-scalable=no</mark></h1>_x000D_
</section>_x000D_
</main>_x000D_
<footer>_x000D_
</footer>_x000D_
</body>_x000D_
</html>
_x000D_
If the jre is installed on your machine properly then look for keytool in jre or in jre/bin
to find where jre is installed, use this
sudo find / -name jre
Then look for keytool in path_to_jre or in path_to_jre/bin
cd to keytool location
then run ./keytool
Make sure to add the the path to $PATH by
export PATH=$PATH:location_to_keytool
To make sure you got it right after this, run
where keytool
for future edit you bash or zshrc file and source it
Using these libraries:
Using this code:
List<Object[]> testNovedads = crudService.createNativeQuery(
"SELECT cantidad, id FROM NOVEDADES GROUP BY id ");
Gson gson = new Gson();
String json = gson.toJson(new TestNovedad());
JSONObject jsonObject = new JSONObject(json);
Collection<TestNovedad> novedads = new ArrayList<>();
for (Object[] object : testNovedads) {
Iterator<String> iterator = jsonObject.keys();
int pos = 0;
for (Iterator i = iterator; i.hasNext();) {
jsonObject.put((String) i.next(), object[pos++]);
}
novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
}
for (TestNovedad testNovedad : novedads) {
System.out.println(testNovedad.toString());
}
/**
* Autores: Chalo Mejia
* Fecha: 01/10/2020
*/
package org.main;
import java.io.Serializable;
public class TestNovedad implements Serializable {
private static final long serialVersionUID = -6362794385792247263L;
private int id;
private int cantidad;
public TestNovedad() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
@Override
public String toString() {
return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
}
}
my mistake was making the target name "filename.c:" instead of just "filename:"
Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:
NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy")
I had a problem where files from one folder wont get added to the Github source control. To solve that I deleted the .git folder that was created under that folder.
I've chmoded my keypair to 600 in order to get into my personal instance last night,
And this is the way it is supposed to be.
From the EC2 documentation we have "If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you." The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.
The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.
Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.
Any problems you are having are client side, so be sure to include local OS information with any follow up questions!
Here is couple of ways to calculate length of variable :
echo ${#VAR}
echo -n $VAR | wc -m
echo -n $VAR | wc -c
printf $VAR | wc -m
expr length $VAR
expr $VAR : '.*'
and to set the result in another variable just assign above command with back quote into another variable as following:
otherVar=`echo -n $VAR | wc -m`
echo $otherVar
http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html
You are better off using a native array instead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.
What you are looking for here is an inline interface definition for your array that defines every element in that array, whether initially present or introduced later:
let userTestStatus: { id: number, name: string }[] = [
{ "id": 0, "name": "Available" },
{ "id": 1, "name": "Ready" },
{ "id": 2, "name": "Started" }
];
userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]
If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:
let userTestStatus = [
{ "id": 0, "name": "Available" },
...
];
userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]
If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling
exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");
and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo
and adding the following line to the very end of it
www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2
All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.
you can do it another way - Let there be n numbers.Take a pair of consecutive numbers and save its lcm in another array. Doing this at first iteration program does n/2 iterations.Then next pick up pair starting from 0 like (0,1) , (2,3) and so on.Compute their LCM and store in another array. Do this until you are left with one array. (it is not possible to find lcm if n is odd)
@Pietrovismara's solution is correct but I'd just like to add: rather than having a separate line to add column names, it's possible to do this from pd.read_csv.
df = pd.read_csv('output_list.txt', sep=" ", header=None, names=["a", "b", "c"])
You could try this solution :
In your location
block when you use proxy_pass
do something like this:
location ... {
add_header yourHeaderName yourValue;
proxy_pass xxxx://xxx_my_proxy_addr_xxx;
# Now use this solution:
proxy_ignore_headers yourHeaderName // but set by proxy
# Or if above didn't work maybe this:
proxy_hide_header yourHeaderName // but set by proxy
}
I'm not sure would it be exactly what you need but try some manipulation of this method and maybe result will fit your problem.
Also you can use this combination:
proxy_hide_header headerSetByProxy;
set $sent_http_header_set_by_proxy yourValue;
unsigned char
takes only positive values....like 0 to 255
where as
signed char
takes both positive and negative values....like -128 to +127
This what worked for me on Amazon Linux
sudo yum list | grep python3
sudo yum install python36.x86_64 python36-tools.x86_64
$ python3 --version Python 3.6.8
$ pip -V pip 9.0.3 from /usr/lib/python2.7/dist-packages (python 2.7)
]$ sudo python3.6 -m pip install --upgrade pip Collecting pip Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.4MB 969kB/s Installing collected packages: pip Found existing installation: pip 9.0.3 Uninstalling pip-9.0.3: Successfully uninstalled pip-9.0.3 Successfully installed pip-19.0.3
$ pip -V pip 19.0.3 from /usr/local/lib/python3.6/site-packages/pip (python 3.6)
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
I think that Alex Martelli's answer is definitely the most elegant way to do this, but just wanted to add a way to satisfy your want for a super awesome dictionary.filter(f)
method in a Pythonic sort of way:
class FilterDict(dict):
def __init__(self, input_dict):
for key, value in input_dict.iteritems():
self[key] = value
def filter(self, criteria):
for key, value in self.items():
if (criteria(value)):
self.pop(key)
my_dict = FilterDict( {'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)} )
my_dict.filter(lambda x: x[0] < 5 and x[1] < 5)
Basically we create a class that inherits from dict
, but adds the filter method. We do need to use .items()
for the the filtering, since using .iteritems()
while destructively iterating will raise exception.
The below code helps to get the details of elements from the specific form with the form id,
$('#formId input, #formId select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements from all the forms which are place in the loading page,
$('form input, form select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,
$('input, select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
NOTE: We add the more element tag name what we need in the object list like as below,
Example: to get name of attribute "textarea",
$('input, select, textarea').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
Breaking Changes to LocalDB: Applies to SQL 2014; take a look over this article and try to use (localdb)\mssqllocaldb
as server name to connect to the LocalDB automatic instance, for example:
<connectionStrings>
<add name="ProductsContext" connectionString="Data Source=(localdb)\mssqllocaldb;
...
The article also mentions the use of 2012 SSMS to connect to the 2014 LocalDB. Which leads me to believe that you might have multiple versions of SQL installed - which leads me to point out this SO answer that suggests changing the default name of your LocalDB "instance" to avoid other version mismatch issues that might arise going forward; mentioned not as source of issue, but to raise awareness of potential clashes that multiple SQL version installed on a single dev machine might lead to ... and something to get in the habit of in order to avoid some.
Another thing worth mentioning - if you've gotten your instance in an unusable state due to tinkering with it to try and fix this problem, then it might be worth starting over - uninstall, reinstall - then try using the mssqllocaldb
value instead of v12.0
and see if that corrects your issue.
I have found an elegant solution that would cover most of your bases. I wrote about it initially here and answered another similar StackOverflow question here which references it.
FYI this solution also includes hardcoded fallback tags in case Javascript isn't picked up by the crawler. I haven't explicitly outlined it, but it is worth mentioning that you should be activating HTML5 mode for proper URL support.
Also note: these aren't the complete files, just the important parts of those that are relevant. If you need help writing the boilerplate for directives, services, etc. that can be found elsewhere. Anyway, here goes...
app.js
This is where you provide the custom metadata for each of your routes (title, description, etc.)
$routeProvider
.when('/', {
templateUrl: 'views/homepage.html',
controller: 'HomepageCtrl',
metadata: {
title: 'The Base Page Title',
description: 'The Base Page Description' }
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
metadata: {
title: 'The About Page Title',
description: 'The About Page Description' }
})
metadata-service.js (service)
Sets the custom metadata options or use defaults as fallbacks.
var self = this;
// Set custom options or use provided fallback (default) options
self.loadMetadata = function(metadata) {
self.title = document.title = metadata.title || 'Fallback Title';
self.description = metadata.description || 'Fallback Description';
self.url = metadata.url || $location.absUrl();
self.image = metadata.image || 'fallbackimage.jpg';
self.ogpType = metadata.ogpType || 'website';
self.twitterCard = metadata.twitterCard || 'summary_large_image';
self.twitterSite = metadata.twitterSite || '@fallback_handle';
};
// Route change handler, sets the route's defined metadata
$rootScope.$on('$routeChangeSuccess', function (event, newRoute) {
self.loadMetadata(newRoute.metadata);
});
metaproperty.js (directive)
Packages the metadata service results for the view.
return {
restrict: 'A',
scope: {
metaproperty: '@'
},
link: function postLink(scope, element, attrs) {
scope.default = element.attr('content');
scope.metadata = metadataService;
// Watch for metadata changes and set content
scope.$watch('metadata', function (newVal, oldVal) {
setContent(newVal);
}, true);
// Set the content attribute with new metadataService value or back to the default
function setContent(metadata) {
var content = metadata[scope.metaproperty] || scope.default;
element.attr('content', content);
}
setContent(scope.metadata);
}
};
index.html
Complete with the hardcoded fallback tags mentioned earlier, for crawlers that can't pick up any Javascript.
<head>
<title>Fallback Title</title>
<meta name="description" metaproperty="description" content="Fallback Description">
<!-- Open Graph Protocol Tags -->
<meta property="og:url" content="fallbackurl.com" metaproperty="url">
<meta property="og:title" content="Fallback Title" metaproperty="title">
<meta property="og:description" content="Fallback Description" metaproperty="description">
<meta property="og:type" content="website" metaproperty="ogpType">
<meta property="og:image" content="fallbackimage.jpg" metaproperty="image">
<!-- Twitter Card Tags -->
<meta name="twitter:card" content="summary_large_image" metaproperty="twitterCard">
<meta name="twitter:title" content="Fallback Title" metaproperty="title">
<meta name="twitter:description" content="Fallback Description" metaproperty="description">
<meta name="twitter:site" content="@fallback_handle" metaproperty="twitterSite">
<meta name="twitter:image:src" content="fallbackimage.jpg" metaproperty="image">
</head>
This should help dramatically with most search engine use cases. If you want fully dynamic rendering for social network crawlers (which are iffy on Javascript support), you'll still have to use one of the pre-rendering services mentioned in some of the other answers.
Hope this helps!
I know it's old and old question but Microsoft appears to have provided this through MSDN now.
One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.
Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.
Below is the reusable code for alert view and action sheet, Just write one line to show alert anywhere in application
class AlertView{
static func show(title:String? = nil,message:String?,preferredStyle: UIAlertControllerStyle = .alert,buttons:[String] = ["Ok"],completionHandler:@escaping (String)->Void){
let alert = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
for button in buttons{
var style = UIAlertActionStyle.default
let buttonText = button.lowercased().replacingOccurrences(of: " ", with: "")
if buttonText == "cancel"{
style = .cancel
}
let action = UIAlertAction(title: button, style: style) { (_) in
completionHandler(button)
}
alert.addAction(action)
}
DispatchQueue.main.async {
if let app = UIApplication.shared.delegate as? AppDelegate, let rootViewController = app.window?.rootViewController {
rootViewController.present(alert, animated: true, completion: nil)
}
}
}
}
Usage :
class ViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
AlertView.show(title: "Alert", message: "Are you sure ?", preferredStyle: .alert, buttons: ["Yes","No"]) { (button) in
print(button)
}
}
}
/**
* @param no
* : Decimal no
* @return binary as integer array
*/
public int[] convertBinary(int no) {
int i = 0, temp[] = new int[7];
int binary[];
while (no > 0) {
temp[i++] = no % 2;
no /= 2;
}
binary = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binary[k++] = temp[j];
}
return binary;
}
Short but simple explanation:
I the worst case you would need to visit all the vertex and edge hence the time complexity in the worst case is O(V+E)
Try this: if you need pass values between the activities you use this...
This is code for Main_Activity put the values to intent
String name="aaaa";
Intent intent=new Intent(Main_Activity.this,Other_Activity.class);
intent.putExtra("name", name);
startActivity(intent);
This code for Other_Activity and get the values form intent
Bundle b = new Bundle();
b = getIntent().getExtras();
String name = b.getString("name");
The area of abcd`s PDF is not one, which is impossible like pointed out in many comments. Assumptions done in many answers here
pdf
should be 1. The normalization should be done as Normalization
with probability
, not as Normalization
with pdf
, in histogram() and hist(). Fig. 1 Output of hist() approach, Fig. 2 Output of histogram() approach
The max amplitude differs between two approaches which proposes that there are some mistake in hist()'s approach because histogram()'s approach uses the standard normalization.
I assume the mistake with hist()'s approach here is about the normalization as partially pdf
, not completely as probability
.
Some remarks
sum(f)/N
gives 1
if Nbins
manually set. dx
) in the graph g
Code
%http://stackoverflow.com/a/5321546/54964
N=10000;
Nbins=50;
[f,x]=hist(randn(N,1),Nbins); % create histogram from ND
%METHOD 4: Count Densities, not Sums!
figure(3)
dx=diff(x(1:2)); % width of bin
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND with dx
% 1.0000
bar(x, f/sum(f));hold on
plot(x,g,'r');hold off
Output is in Fig. 1.
Some remarks
sum(f)
is 1
if Nbins
adjusted with histogram()'s Normalization as probability, b) sum(f)/N
is 1 if Nbins
is manually set without normalization. dx
) in the graph g
Code
%%METHOD 5: with histogram()
% http://stackoverflow.com/a/38809232/54964
N=10000;
figure(4);
h = histogram(randn(N,1), 'Normalization', 'probability') % hist() deprecated!
Nbins=h.NumBins;
edges=h.BinEdges;
x=zeros(1,Nbins);
f=h.Values;
for counter=1:Nbins
midPointShift=abs(edges(counter)-edges(counter+1))/2; % same constant for all
x(counter)=edges(counter)+midPointShift;
end
dx=diff(x(1:2)); % constast for all
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND
% Use if Nbins manually set
%new_area=sum(f)/N % diff of consecutive edges constant
% Use if histogarm() Normalization probability
new_area=sum(f)
% 1.0000
% No bar() needed here with histogram() Normalization probability
hold on;
plot(x,g,'r');hold off
Output in Fig. 2 and expected output is met: area 1.0000.
Matlab: 2016a
System: Linux Ubuntu 16.04 64 bit
Linux kernel 4.6
I have just found a PHP function "strip_tags()" and its working in my case.
I tried to convert the following HTML :
<p><span style="font-family: 'Verdana','sans-serif'; color: black; font-size: 7.5pt;"> </span>Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects? Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry's lackluster performance during this time, revenue has grown at an average annual rate of 2.2% over the last five years, to $9.0 billion in 2010. So despite the downturn, how were we able to manage growth as an industry?</p>
After applying strip_tags() function, I have got the following output :
&nbsp;Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects?&nbsp; Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry's lackluster performance during this time, revenue has grown at an average annual rate&nbsp;of 2.2% over the last five years, to $9.0 billion in 2010.&nbsp; So despite the downturn, how were we able to manage growth as an industry?
As David pointed out, I would go with KB in most cases.
php_value post_max_size 2K
Note: my form is simple, just a few text boxes, not long text.
(PHP shorthand for KB is K, as outlined here.)
If you don't/can't keep the connection open you could use screen, if you have the rights to install it.
user@localhost $ screen -t remote-command
user@localhost $ ssh user@target # now inside of a screen session
user@remotehost $ cd /some/directory; program-to-execute &
To detach the screen session: ctrl-a d
To list screen sessions:
screen -ls
To reattach a session:
screen -d -r remote-command
Note that screen can also create multiple shells within each session. A similar effect can be achieved with tmux.
user@localhost $ tmux
user@localhost $ ssh user@target # now inside of a tmux session
user@remotehost $ cd /some/directory; program-to-execute &
To detach the tmux session: ctrl-b d
To list screen sessions:
tmux list-sessions
To reattach a session:
tmux attach <session number>
The default tmux control key, 'ctrl-b', is somewhat difficult to use but there are several example tmux configs that ship with tmux that you can try.
I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.
Path : img type : jpg random uniqid
function resim(url) {
var http = require("http");
var fs = require("fs");
var sayi = Math.floor(Math.random()*10000000000);
var uzanti = ".jpg";
var file = fs.createWriteStream("img/"+sayi+uzanti);
var request = http.get(url, function(response) {
response.pipe(file);
});
return sayi+uzanti;
}
event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.
$("p").click(function(event)
{ event.stopImmediatePropagation();
});
$("p").click(function(event)
{ // This function won't be executed
$(this).css("color", "#fff7e3");
});
If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.
on my mac i found this file .gitignore_global
..it was in my home directory hidden so do a ls -altr
to see it.
I added eclipse files i wanted git to ignore. the contents looks like this:
*~
.DS_Store
.project
.settings
.classpath
.metadata
You need to treat a table valued udf like a table, eg JOIN it
select Emp_Id
from Employee E JOIN dbo.Splitfn(@Id,',') CSV ON E.Emp_Id = CSV.items
in python 2.x, xrange is used to return a generator while range is used to return a list. In python 3.x , xrange has been removed and range returns a generator just like xrange in python 2.x. Therefore, in python 3.x you need to use range rather than xrange.
std::vector
has random-access iterators. You can do pointer arithmetic with them. In particular, this my_vec.begin() + my_vec.size() == my_vec.end()
always holds. So you could do
const vector<type>::const_iterator pos = std::find_if( firstVector.begin()
, firstVector.end()
, some_predicate(parameter) );
if( position != firstVector.end() ) {
const vector<type>::size_type idx = pos-firstVector.begin();
doAction( secondVector[idx] );
}
As an alternative, there's always std::numeric_limits<vector<type>::size_type>::max()
to be used as an invalid value.
You can use this simple plugin to add scrollUp
and scrollDown
to your jQuery
https://github.com/phpust/JQueryScrollDetector
var lastScrollTop = 0;
var action = "stopped";
var timeout = 100;
// Scroll end detector:
$.fn.scrollEnd = function(callback, timeout) {
$(this).scroll(function(){
// get current scroll top
var st = $(this).scrollTop();
var $this = $(this);
// fix for page loads
if (lastScrollTop !=0 )
{
// if it's scroll up
if (st < lastScrollTop){
action = "scrollUp";
}
// else if it's scroll down
else if (st > lastScrollTop){
action = "scrollDown";
}
}
// set the current scroll as last scroll top
lastScrollTop = st;
// check if scrollTimeout is set then clear it
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
// wait until timeout done to overwrite scrolls output
$this.data('scrollTimeout', setTimeout(callback,timeout));
});
};
$(window).scrollEnd(function(){
if(action!="stopped"){
//call the event listener attached to obj.
$(document).trigger(action);
}
}, timeout);
Same Answer in Swift 4.2
For UILable
extension UILabel {
func underline() {
if let textString = self.text {
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: textString.count))
self.attributedText = attributedString
}
}
}
Call for UILabel like below
myLable.underline()
For UIButton
extension UIButton {
func underline() {
if let textString = self.titleLabel?.text {
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: NSRange(location: 0, length: textString.count))
self.setAttributedTitle(attributedString, for: .normal)
}
}
}
Call for UIButton like below
myButton.underline()
I looked into above answers and some of them are force unwrapping text value. I will suggest to get value by safely unwrapping. This will avoid crash in case of nil value. Hope This helps :)
It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.
To remove 'whitespace',
import re
t = """
\n\t<p> </p>\n\t<p> </p>\n\t<p> </p>\n\t<p> </p>\n\t<p>
"""
pat = re.compile(r'[\t\n]')
print(pat.sub("", t))
You need to link with the math library, libm:
$ gcc -Wall foo.c -o foo -lm
You can use a query in the AWS Config Console here. (Region may change for you) https://console.aws.amazon.com/config/home?region=us-east-1#/resources/query
the query will look like.
SELECT
resourceId,
resourceName,
resourceType,
relationships
WHERE
relationships.resourceId = 'vpc-#######'
var string = 123 (is string),
parseInt(parameter is string);
var string = '123';
var int= parseInt(string );
console.log(int); //Output will be 123.
How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids
, but Perl complains.
Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open
returned an error, and make sure you are using use strict; use warnings;
.
my ($ids, $nIds)
is a list, right? With two elements?
It's a (very special) function call. $ids,$nIds
is a list with two elements.
use jquery Every time Plugin .using this you can do ajax call for "X" time period
$("#select").everyTime(1000,function(i) {
//ajax call
}
you can also use setInterval
the style is:
<style type="text/css">
.topcorner{
position:absolute;
top:0;
right:0;
}
</style>
hope it will work. Thanks
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}
try this,use preg_replace
$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
You can use in
operator in conjunction with lower
method of strings.
if "mandy" in line.lower():
For Android 5.0, if you want to set it directly into a style use:
<item name="android:elevation">0dp</item>
and for Support library compatibility use:
<item name="elevation">0dp</item>
Example of style for a AppCompat light theme:
<style name="Theme.MyApp.ActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<!-- remove shadow below action bar -->
<!-- <item name="android:elevation">0dp</item> -->
<!-- Support library compatibility -->
<item name="elevation">0dp</item>
</style>
Then apply this custom ActionBar style to you app theme:
<style name="Theme.MyApp" parent="Theme.AppCompat.Light">
<item name="actionBarStyle">@style/Theme.MyApp.ActionBar</item>
</style>
For pre 5.0 Android, add this too to your app theme:
<!-- Remove shadow below action bar Android < 5.0 -->
<item name="android:windowContentOverlay">@null</item>
Well, the AssetManager
lists files within the assets
folder that is inside of your APK file. So what you're trying to list in your example above is [apk]/assets/sdcard/Pictures.
If you put some pictures within the assets
folder inside of your application, and they were in the Pictures
directory, you would do mgr.list("/Pictures/")
.
On the other hand, if you have files on the sdcard that are outside of your APK file, in the Pictures
folder, then you would use File
as so:
File file = new File(Environment.getExternalStorageDirectory(), "Pictures");
File[] pictures = file.listFiles();
...
for (...)
{
log.e("FILE:", pictures[i].getAbsolutePath());
}
And relevant links from the docs:
File
Asset Manager
You need imagesLoaded if the container have images inside. This works for responsive too.
$(document).ready(function () {
equalHeight('.column');
});
$(window).resize(function(){equalHeight('.column');});
function equalHeight(columnClass){
$('.eq-height-wrap').imagesLoaded(function(){
$('.eq-height-wrap').each(function(){
var maxHeight = Math.max.apply(null, $(this).find(columnClass).map(function ()
{
return $(this).innerHeight();
}).get());
$(columnClass,this).height(maxHeight);
});
});
}
boost:ptr_array
http://www.boost.org/doc/libs/1_43_0/libs/ptr_container/doc/ptr_array.html
It's the quickest way I've found without doing any subclasses:
UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10., 10.)];
[textField setLeftViewMode:UITextFieldViewModeAlways];
[textField setLeftView:spacerView];
In Swift:
let spacerView = UIView(frame:CGRect(x:0, y:0, width:10, height:10))
textField.leftViewMode = UITextFieldViewMode.Always
textField.leftView = spacerView
zxing does not (only) provide a web API; really, that is Google providing the API, from source code that was later open-sourced in the project.
As Rob says here you can use the Java source code for the QR code encoder to create a raw barcode and then render it as a Bitmap.
I can offer an easier way still. You can call Barcode Scanner by Intent to encode a barcode. You need just a few lines of code, and two classes from the project, under android-integration
. The main one is IntentIntegrator. Just call shareText()
.
Merge takes a DataTable, Load requires an IDataReader - so depending on what your data layer gives you access to, use the required method. My understanding is that Load will internally call Merge, but not 100% sure about that.
If you have two DataTables, use Merge.
Non-jquery:
// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');
// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');
for(var i in linkList){
linkList[i].setAttribute('target', '_blank');
}
Reviving an old question because it seems to appear at the top of search results.
I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.
<div class="parent-style-one"> @Html.ActionLink("Homepage", "Home", "Home") </div>
.parent-style-one { /* your styles here */ }
.parent-style-one a { text-decoration: none; }
.parent-style-one a:hover { text-decoration: underline; -webkit-transition-duration: 1.1s; /* Safari */ transition-duration: 1.1s; }
This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.
As others have said, the minumum/maximum values the column can store and how much storage it takes in bytes is only defined by the type, not the length.
A lot of these answers are saying that the (11)
part only affects the display width which isn't exactly true, but mostly.
A definition of int(2)
with no zerofill specified will:
100
100
when output (not 0
or 00
)The only thing the (2)
will do is if zerofill is also specified:
1
will be shown 01
. The best way to see all the nuances is to run:
CREATE TABLE `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`int1` int(10) NOT NULL,
`int2` int(3) NOT NULL,
`zf1` int(10) ZEROFILL NOT NULL,
`zf2` int(3) ZEROFILL NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `mytable`
(`int1`, `int2`, `zf1`, `zf2`)
VALUES
(10000, 10000, 10000, 10000),
(100, 100, 100, 100);
select * from mytable;
which will output:
+----+-------+-------+------------+-------+
| id | int1 | int2 | zf1 | zf2 |
+----+-------+-------+------------+-------+
| 1 | 10000 | 10000 | 0000010000 | 10000 |
| 2 | 100 | 100 | 0000000100 | 100 |
+----+-------+-------+------------+-------+
This answer is tested against MySQL 5.7.12 for Linux and may or may not vary for other implementations.
A lot of the answers here are out of date/bad. So I'm going to attempt to answer it better. Granted I'm answering this question in 2020, so it's expected things would change.
How do I run CMake for each target type (debug/release)?
First off Debug/Release are called configurations in cmake (nitpick).
If you are using a single configuration generator (Ninja/Unix-Makefiles)
Then you need a build folder for each configuration.
Like this:
# Configure the build
cmake -S . -B build/Debug -D CMAKE_BUILD_TYPE=Release
# Actually build the binaries
cmake --build build/Debug
For multi-configuration generators it's slightly different (Ninja Multi-Config, Visual Studio)
# Configure the build
cmake -S . -B build
# Actually build the binaries
cmake --build build --config Debug
If you are wondering why this is necessary it's because cmake isn't a build system. It's a meta-build system (IE a build system that build's build systems). This is basically the result of handling build systems that support multiple-configurations in 1 build. If you'd like a deeper understanding I'd suggest reading a bit about cmake in Craig Scott's book "Professional CMake: A Practical Guide
How do I specify debug and release C/C++ flags using CMake?
The modern practice is to use target's and properties.
Here is an example:
add_library(foobar)
# Add this compile definition for debug builds, this same logic works for
# target_compile_options, target_link_options, etc.
target_compile_definitions(foobar PRIVATE
$<$<CONFIG:Debug>:
FOOBAR_DEBUG=1
>
)
NOTE: How I'm using generator expressions to specify the configuration! Using CMAKE_BUILD_TYPE will result in bad builds for any multi-configuration generator!
Further more sometimes you need to set things globally and not just for one target. Use add_compile_definitions, add_compile_options, etc. Those functions support generator expressions. Don't use old style cmake unless you have to (that path is a land of nightmares)
How do I express that the main executable will be compiled with g++ and one nested library with gcc?
Your last question really doesn't make sense.
Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.
For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.
If you want update your JSON file cross-browser you have to use server and client side together.
On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// we convert your JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// we add new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// we send with new request the updated JSON file to the server:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// if you want to handle the POST response write (in this case you do not need it):
// xhr.onreadystatechange = function(){ /* handle POST response */ };
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// but on this place you have to have a server for write updated JSON to the file
}
};
xhr.send(null);
You can use a lot of different servers, but I would like to write about PHP and Node.js servers.
By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.
PHP server side script solution
The PHP script for reading and writing from JSON file:
<?php
// This PHP script must be in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
file_put_contents($file, $_POST["jsonTxt"]);
//may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
echo file_get_contents($file);
//may be some error handeling if you want
}
?>
Node.js server side script solution
I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:
The Node.js script for reading and writing from JSON file:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Related links for Node.js:
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
# COLUMN is integer column number
# INPUT_FILE is input file name
cut -f ${COLUMN} < ${INPUT_FILE} | sort -u | wc -l
This is how I've always done it:
<ItemTemplate>
<%# Boolean.Parse(Eval("Active").ToString()) ? "Yes" : "No" %>
</ItemTemplate>
Hope that helps.
It bugged me too to find a solution to mimic interfaces with the lower impacts possible.
One solution could be to make a tool :
/**
@parameter {Array|object} required : method name list or members types by their name
@constructor
*/
let Interface=function(required){
this.obj=0;
if(required instanceof Array){
this.obj={};
required.forEach(r=>this.obj[r]='function');
}else if(typeof(required)==='object'){
this.obj=required;
}else {
throw('Interface invalid parameter required = '+required);
}
};
/** check constructor instance
@parameter {object} scope : instance to check.
@parameter {boolean} [strict] : if true -> throw an error if errors ar found.
@constructor
*/
Interface.prototype.check=function(scope,strict){
let err=[],type,res={};
for(let k in this.obj){
type=typeof(scope[k]);
if(type!==this.obj[k]){
err.push({
key:k,
type:this.obj[k],
inputType:type,
msg:type==='undefined'?'missing element':'bad element type "'+type+'"'
});
}
}
res.success=!err.length;
if(err.length){
res.msg='Class bad structure :';
res.errors=err;
if(strict){
let stk = new Error().stack.split('\n');
stk.shift();
throw(['',res.msg,
res.errors.map(e=>'- {'+e.type+'} '+e.key+' : '+e.msg).join('\n'),
'','at :\n\t'+stk.join('\n\t')
].join('\n'));
}
}
return res;
};
Exemple of use :
// create interface tool
let dataInterface=new Interface(['toData','fromData']);
// abstract constructor
let AbstractData=function(){
dataInterface.check(this,1);// check extended element
};
// extended constructor
let DataXY=function(){
AbstractData.apply(this,[]);
this.xy=[0,0];
};
DataXY.prototype.toData=function(){
return [this.xy[0],this.xy[1]];
};
// should throw an error because 'fromData' is missing
let dx=new DataXY();
With classes
class AbstractData{
constructor(){
dataInterface.check(this,1);
}
}
class DataXY extends AbstractData{
constructor(){
super();
this.xy=[0,0];
}
toData(){
return [this.xy[0],this.xy[1]];
}
}
It's still a bit performance consumming and require dependancy to the Interface class, but can be of use for debug or open api.
Try ftp://test.rebex.net/
It is read-only used for testing Rebex components to list directory and download. Allows also to test FTP/SSL and IMAP.
Username is "demo", password is "password"
See https://test.rebex.net/ for more information.
This is the right way to clear this error.
export ORACLE_HOME=/u01/app/oracle/product/10.2.0/db_1 sqlplus / as sysdba
If you face this error when you start Symfony project with docker (my Symfony version 5.1). Or errors like these:
Uncaught Exception: Failed to write file "/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainer.xml"" while reading upstream
Uncaught Warning: file_put_contents(/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainerDeprecations.log): failed to open stream: Permission denied" while reading upstream
Fix below helped me.
In Dockerfile for nginx container add line:
RUN usermod -u 1000 www-data
In Dockerfile for php-fpm container add line:
RUN usermod -u 1000 www-data
Then remove everything in directories "/var/cache", "/var/log" and rebuild docker's containers.
I had the URL from run time, below gave the correct answer:
let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);
hope this helps
There will definitely be an open bracket which caused the error.
I'd suggest that you open the page in Firefox, then open Firebug and check the console – it'll show the missing symbol.
Example screenshot:
You can pass the configuration name to the post-build script and check it in there to see if it should run.
Pass the configuration name with $(ConfigurationName)
.
Checking it is based on how you are implementing the post-build step -- it will be a command-line argument.
You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.
Because you do not provide any context or code for your question it is not possible to give a direct answer.
I suggest you study how unicode and character encoding is done in Python:
Git has two types of branches: local
and remote
. To use git pull
and git push
as you'd like, you have to tell your local branch (my_test
) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master
branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test
.
You can then push
and pull
without specifying which local and remote.
However if you've already created the branch then you can use the -u
switch to tell git's push
and pull
you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test
Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config
and add the following to the bottom.
[remote "origin"]
url = [email protected]:username/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
remote = origin
merge = refs/heads/my_test
This specifies a remote called origin
, in this case a GitHub style one, and then tells the branch my_test
to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:
in hive 0.1 you can use SHOW CREATE TABLE
to find the path where hive store data.
in other versions, there is no good way to do this.
upadted:
thanks Joe K
use DESCRIBE FORMATTED <table>
to show table information.
ps: database.tablename is not supported here.
ctrl + w, w as mentioned can be used for navigating from pane to pane.
Now you can select a particular change alone and paste it to the other pane as follows.Here I am giving an eg as if I wanted to change my piece of code from pane 1 to pane 2 and currently my cursor is in pane1
Use Shift-v to highlight a line and use up or down keys to select the piece of code you require and continue from step 3 written below to paste your changes in the other pane.
Use visual mode and then change it
1 click 'v' this will take you to visual mode 2 use up or down key to select your required code 3 click on ,Esc' escape key 4 Now use 'yy' to copy or 'dd' to cut the change 5 do 'ctrl + w, w' to navigate to pane2 6 click 'p' to paste your change where you require
The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.
For example:
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
neither try any above ways nor sudo apt autoremove python3
because it will remove all gnome based applications from your system including gnome-terminal. In case if you have done that mistake and left with kernal only than trysudo apt install gnome
on kernal.
try to change your default python version instead removing it. you can do this through bashrc file or export path command.
Swift 3
This is doable in a safe way by presenting the splash controller for what ever time you specify then remove it and display your normal rootViewController.
In AppDelegate you can create these 2 methods:
private func extendSplashScreenPresentation(){
// Get a refernce to LaunchScreen.storyboard
let launchStoryBoard = UIStoryboard.init(name: "LaunchScreen", bundle: nil)
// Get the splash screen controller
let splashController = launchStoryBoard.instantiateViewController(withIdentifier: "splashController")
// Assign it to rootViewController
self.window?.rootViewController = splashController
self.window?.makeKeyAndVisible()
// Setup a timer to remove it after n seconds
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(dismissSplashController), userInfo: nil, repeats: false)
}
2.
@objc private func dismissSplashController() {
// Get a refernce to Main.storyboard
let mainStoryBoard = UIStoryboard.init(name: "Main", bundle: nil)
// Get initial viewController
let initController = mainStoryBoard.instantiateViewController(withIdentifier: "initController")
// Assign it to rootViewController
self.window?.rootViewController = initController
self.window?.makeKeyAndVisible()
}
Now you call
self.extendSplashScreenPresentation()
in didFinishLaunchingWithOptions.
You are set to go...
I tried everything listed in the answers here but none of them worked.
Then all I did was to re-start XAMPP with administrator rights by:
Start menu - right click on XAMPP - select run as administartor
It worked. It is that simple.
I uninstalled IIS services, stopped WWW services, changed ports back to 80, blocked all apache and mysql connections from windows 10 firewall, but yes it still works!
Just use CSS transitions instead of animations.
A {
color: #999;
transition: color 1s ease-in-out;
}
A:hover {
color: #000;
}
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}
There are awk
built-in variables.
NR
- It gives the total number of records processed.
FNR
- It gives the total number of records for each input file.