Full disclosure, I am one of the maintainers of pdfminer.six.
Nowadays, there are multiple api's to extract text from a PDF, depending on your needs. Behind the scenes, all of these api's use the same logic for parsing and analyzing the layout.
(All the examples assume your PDF file is called example.pdf)
Commandline
If you want to extract text just once you can use the commandline tool pdf2txt.py:
$ pdf2txt.py example.pdf
High-level api
If you want to extract text with Python, you can use the high-level api. This approach is the go-to solution if you want to extract text programmatically from many PDF's.
from pdfminer.high_level import extract_text
text = extract_text('example.pdf')
Composable api
There is also a composable api that gives a lot of flexibility in handling the resulting objects. For example, you can implement your own layout algorithm using that. This method is suggested in the other answers, but I would only recommend this when you need to customize the way pdfminer.six behaves.
from io import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
output_string = StringIO()
with open('example.pdf', 'rb') as in_file:
parser = PDFParser(in_file)
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
device = TextConverter(rsrcmgr, output_string, laparams=LAParams())
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.create_pages(doc):
interpreter.process_page(page)
print(output_string.getvalue())
It is at the same location: ~/.android/debug.keystore
The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)
For that,
for (int i=0;i<myString.length;i++) {
System.out.println(myString[i]);
}
is correct.
For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this
List<String> list = ....load up with stuff
for (String string : list) {
System.out.println(string);
}
instead of
for (int i=0; i<list.size();i++) {
System.out.println(list.get(i));
}
So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.
What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String string=it.next();
System.out.println(string);
}
In the end it's just syntactic sugar, but rather convenient.
IMPORTANT: Spaces are the preferred method - see PEP008 Indentation and Tabs or Spaces?. (Thanks to @Siha for this.)
For Sublime Text
users:
Set Sublime Text
to use tabs for indentation:
View
--> Indentation
--> Convert Indentation to Tabs
Uncheck the Indent Using Spaces
option as well in the same sub-menu above.
This will immediately resolve this issue.
To add to other questions, let me provide how I did it with a Python 2.0 function using Numpy:
def one_hot(y_):
# Function to encode output labels from number indexes
# e.g.: [[5], [0], [3]] --> [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]
y_ = y_.reshape(len(y_))
n_values = np.max(y_) + 1
return np.eye(n_values)[np.array(y_, dtype=np.int32)] # Returns FLOATS
The line n_values = np.max(y_) + 1
could be hard-coded for you to use the good number of neurons in case you use mini-batches for example.
Demo project/tutorial where this function has been used: https://github.com/guillaume-chevalier/LSTM-Human-Activity-Recognition
I found very in-depth videos which cover $watch
, $apply
, $digest
and digest cycles in:
AngularJS - Understanding Watcher, $watch, $watchGroup, $watchCollection, ng-change
AngularJS - Understanding digest cycle (digest phase or digest process or digest loop)
AngularJS Tutorial - Understanding $apply and $digest (in depth)
Following are a couple of slides used in those videos to explain the concepts (just in case, if the above links are removed/not working).
In the above image, "$scope.c" is not being watched as it is not used in any of the data bindings (in markup). The other two ($scope.a
and $scope.b
) will be watched.
From the above image: Based on the respective browser event, AngularJS captures the event, performs digest cycle (goes through all the watches for changes), execute watch functions and update the DOM. If not browser events, the digest cycle can be manually triggered using $apply
or $digest
.
More about $apply
and $digest
:
If we setaside the syntax error of print, then the way to use input in multiple scenarios are -
If using python 2.x :
then for evaluated input use "input"
example: number = input("enter a number")
and for string use "raw_input"
example: name = raw_input("enter your name")
If using python 3.x :
then for evaluated result use "eval" and "input"
example: number = eval(input("enter a number"))
for string use "input"
example: name = input("enter your name")
There's no need to require a big library like jQuery to accomplish this, if you don't want to. To achieve this with built-in DOM manipulation, get a collection of the li
siblings in an array, and on click, check the indexOf
the clicked element in that array.
const lis = [...document.querySelectorAll('#wizard > li')];_x000D_
lis.forEach((li) => {_x000D_
li.addEventListener('click', () => {_x000D_
const index = lis.indexOf(li);_x000D_
console.log(index);_x000D_
});_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, with event delegation:
const lis = [...document.querySelectorAll('#wizard li')];_x000D_
document.querySelector('#wizard').addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li> which is a child of wizard:_x000D_
if (!target.matches('#wizard > li')) return;_x000D_
_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
Or, if the child elements may change dynamically (like with a todo list), then you'll have to construct the array of li
s on every click, rather than beforehand:
const wizard = document.querySelector('#wizard');_x000D_
wizard.addEventListener('click', ({ target }) => {_x000D_
// Make sure the clicked element is a <li>_x000D_
if (!target.matches('li')) return;_x000D_
_x000D_
const lis = [...wizard.children];_x000D_
const index = lis.indexOf(target);_x000D_
console.log(index);_x000D_
});
_x000D_
<ul id="wizard">_x000D_
<li>Step 1</li>_x000D_
<li>Step 2</li>_x000D_
</ul>
_x000D_
You can build your own contextmanager
to check if the exception was raised.
import contextlib
@contextlib.contextmanager
def raises(exception):
try:
yield
except exception as e:
assert True
else:
assert False
And then you can use raises
like this:
with raises(Exception):
print "Hola" # Calls assert False
with raises(Exception):
raise Exception # Calls assert True
If you are using pytest
, this thing is implemented already. You can do pytest.raises(Exception)
:
Example:
def test_div_zero():
with pytest.raises(ZeroDivisionError):
1/0
And the result:
pigueiras@pigueiras$ py.test
================= test session starts =================
platform linux2 -- Python 2.6.6 -- py-1.4.20 -- pytest-2.5.2 -- /usr/bin/python
collected 1 items
tests/test_div_zero.py:6: test_div_zero PASSED
yu have to install the correct version for your computer 32 or 63 bits thats all
Use the Process class. The MSDN documentation has an example how to use it.
for (int i = 0; i < 8; i++) {
//code
}
In simplest terms
int i = 0;
if (i < 8) //code
i = i + 1; //i = 1
if (i < 8) //code
i = i + 1; //i = 2
if (i < 8) //code
i = i + 1; //i = 3
if (i < 8) //code
i = i + 1; //i = 4
if (i < 8) //code
i = i + 1; //i = 5
if (i < 8) //code
i = i + 1; //i = 6
if (i < 8) //code
i = i + 1; //i = 7
if (i < 8) //code
i = i + 1; //i = 8
if (i < 8) //code - this if won't pass
decodeURIComponent()
is fine, but you never want ot use encodeURIComponent()
directly. This fails to escape reserved characters like *
, !
, '
, (
, and )
. Check out RFC3986, where this is defined, for more info on that. The Mozilla Developer Network documentation gives both a good explanation and a solution. Explanation...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
Solution...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
In case you're not sure, check out a good, working demo at JSBin.com. Compare this with a bad, working demo at JSBin.com using encodeURIComponent()
directly.
Good code results:
thing%2athing%20thing%21
Bad code results from encodeURIComponent()
:
thing*thing%20thing!
File->Project Structure->Project pane->"Android plugin version".
Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects
minutes_diff = (datetime_end - datetime_start).total_seconds() / 60.0
xrange from Python 2 is a generator and implements iterator while range is just a function. In Python3 I don't know why was dropped off the xrange.
Both {{ request.path }} and {{ request.get_full_path }}
return the current URL but not absolute URL, for example:
your_website.com/wallpapers/new_wallpaper
Both will return
/new_wallpaper/
(notice the leading and trailing slashes)
So you'll have to do something like
{% if request.path == '/new_wallpaper/' %}
<button>show this button only if url is new_wallpaper</button>
{% endif %}
However, you can get the absolute URL using (thanks to the answer above)
{{ request.build_absolute_uri }}
NOTE:
you don't have to include request
in settings.py
, it's already there.
In order to uninstall miniconda, simply remove the miniconda
folder,
rm -r ~/miniconda/
As for avoiding conflicts between different Python environments, you can use virtual environments. In particular, with Miniconda, the following workflow could be used,
$ wget https://repo.continuum.io/miniconda/Miniconda3-3.7.0-Linux-x86_64.sh -O ~/miniconda.sh
$ bash miniconda
$ conda env remove --yes -n new_env # remove the environement new_env if it exists (optional)
$ conda create --yes -n new_env pip numpy pandas scipy matplotlib scikit-learn nltk ipython-notebook seaborn python=2
$ activate new_env
$ # pip install modules if needed, run python scripts, etc
# everything will be installed in the new_env
# located in ~/miniconda/envs/new_env
$ deactivate
I've created a class which helps to reduce errors in setting up custom handlers and takes advantage of the system property so there are no issues with calling a method first or not being in the right container. There's also an exception class if you get things wrong:
CustomURLScheme.java:
/*
* The CustomURLScheme class has a static method for adding cutom protocol
* handlers without getting bogged down with other class loaders and having to
* call setURLStreamHandlerFactory before the next guy...
*/
package com.cybernostics.lib.net.customurl;
import java.net.URLStreamHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Allows you to add your own URL handler without running into problems
* of race conditions with setURLStream handler.
*
* To add your custom protocol eg myprot://blahblah:
*
* 1) Create a new protocol package which ends in myprot eg com.myfirm.protocols.myprot
* 2) Create a subclass of URLStreamHandler called Handler in this package
* 3) Before you use the protocol, call CustomURLScheme.add(com.myfirm.protocols.myprot.Handler.class);
* @author jasonw
*/
public class CustomURLScheme
{
// this is the package name required to implelent a Handler class
private static Pattern packagePattern = Pattern.compile( "(.+\\.protocols)\\.[^\\.]+" );
/**
* Call this method with your handlerclass
* @param handlerClass
* @throws Exception
*/
public static void add( Class<? extends URLStreamHandler> handlerClass ) throws Exception
{
if ( handlerClass.getSimpleName().equals( "Handler" ) )
{
String pkgName = handlerClass.getPackage().getName();
Matcher m = packagePattern.matcher( pkgName );
if ( m.matches() )
{
String protocolPackage = m.group( 1 );
add( protocolPackage );
}
else
{
throw new CustomURLHandlerException( "Your Handler class package must end in 'protocols.yourprotocolname' eg com.somefirm.blah.protocols.yourprotocol" );
}
}
else
{
throw new CustomURLHandlerException( "Your handler class must be called 'Handler'" );
}
}
private static void add( String handlerPackage )
{
// this property controls where java looks for
// stream handlers - always uses current value.
final String key = "java.protocol.handler.pkgs";
String newValue = handlerPackage;
if ( System.getProperty( key ) != null )
{
final String previousValue = System.getProperty( key );
newValue += "|" + previousValue;
}
System.setProperty( key, newValue );
}
}
CustomURLHandlerException.java:
/*
* Exception if you get things mixed up creating a custom url protocol
*/
package com.cybernostics.lib.net.customurl;
/**
*
* @author jasonw
*/
public class CustomURLHandlerException extends Exception
{
public CustomURLHandlerException(String msg )
{
super( msg );
}
}
As others have noted, it is usually preferable to specify a minimum logging level to log that level and any others more severe than it. It seems like you are just thinking about the logging levels backwards.
However, if you want more fine-grained control over logging individual levels, you can tell log4net to log only one or more specific levels using the following syntax:
<filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="WARN"/>
</filter>
Or to exclude a specific logging level by adding a "deny" node to the filter.
You can stack multiple filters together to specify multiple levels. For instance, if you wanted only WARN and FATAL levels. If the levels you wanted were consecutive, then the LevelRangeFilter is more appropriate.
Reference Doc: log4net.Filter.LevelMatchFilter
If the other answers haven't given you enough information, hopefully this will help you get what you want out of log4net.
Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.
Javascript code embedded aswell:
$(document).ready(function () {
var map;
var elevator;
var myOptions = {
zoom: 1,
center: new google.maps.LatLng(0, 0),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map_canvas')[0], myOptions);
var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map
});
});
}
});
Use .unshift()
to add to the beginning of an array.
TheArray.unshift(TheNewObject);
See MDN for doc on unshift()
and here for doc on other array methods.
FYI, just like there's .push()
and .pop()
for the end of the array, there's .shift()
and .unshift()
for the beginning of the array.
Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.
If we have a method which is overloaded to accept different number of parameters, then instead of overloading the method different times, we can simply use varargs concept.
Also when the parameters' type is going to vary then using "Object...test" will simplify the code a lot.
For example:
public int calculate(int...list) {
int sum = 0;
for (int item : list) {
sum += item;
}
return sum;
}
Here indirectly an array of int type (list) is passed as parameter and is treated as an array in the code.
For a better understanding follow this link(it helped me a lot in understanding this concept clearly): http://www.javadb.com/using-varargs-in-java
P.S: Even I was afraid of using varargs when I didn't knw abt it. But now I am used to it. As it is said: "We cling to the known, afraid of the unknown", so just use it as much as you can and you too will start liking it :)
to set a div at position fixed you can use
position:fixed
top:0;
left:0;
width:100%;
height:50px; /* change me */
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
git checkout -b "Branch_name" [ B means Create local branch]
git branch --all
git checkout -b "Your Branch name"
git branch
successfully checkout from the master branch to dev branch
This question are greatly described here
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
TL;DR You are still always able to autoplay muted
videos
Also, if you're want to autoplay videos on iOS add playsInline
attribute, because by default iOS tries to fullscreen videos
https://webkit.org/blog/6784/new-video-policies-for-ios/
As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.
Your code would be updated as such:
import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)
An established connection was aborted by the software in your host machine
That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.
The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.
You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.
In the source header you can declare:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
It is described in the PEP 0263:
Then you can use UTF-8 in strings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
There is no difference between both, AS
is just a more explicit way of mentioning the alias which is good because some dependent libraries depends on this small keyword. e.g. JDBC 4.0. Depend on use of it, different behaviour can be observed.
See this. I would always suggest to use the full form of semantic to avoid such issues.
The options were changed a bit in ASP.NET Core, here they are (credits):
new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType);
(vNext only)
Mappings
property.MimeTypes
NuGet packageMimeMappings
file from the reference source of the .NET FrameworkUse the System.Web.MimeMapping.GetMimeMapping
method, that is part of the BCL in .NET Framework 4.5:
string mimeType = MimeMapping.GetMimeMapping(fileName);
If you need to add custom mappings you probably can use reflection to add mappings to the BCL MimeMapping
class, it uses a custom dictionary that exposes this method, so you should invoke the following to add mappings (never tested tho, but should prob. work).
Anyway, when using reflection to add MIME types, be aware that since you're accessing a private field, its name might change or even be totally removed, so you should be extra cautious and add double checks and provide fail safe action for every step.
MimeMapping._mappingDictionary.AddMapping(string fileExtension, string mimeType)
Where can I download (certified) 64 bit Apache httpd binaries for Windows?
Right now, there are none. The Apache Software Foundation produces Open Source Software. The 32 bit binaries provided are a courtesy of the community members.
Though there are some unofficial e.g. http://www.apachelounge.com/download/win64/, but I have no idea if they can be trusted.
You can use below methods to find the output
with Ctec AS
(
select *,Row_number() over(partition by name order by Name)Rnk
from Table_A
)
select Name from ctec
where rnk>1
select name from Table_A
group by name
having count(*)>1
After spending hours I have found the solution: just run the following SQL in your MySQL admin to convert the table to MyISAM:
USE db_name;
ALTER TABLE table_name ENGINE=MYISAM;
Apply this code in your css
::-webkit-scrollbar{
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
Why don't you just right click on the table and then properties -> Storage and it would tell you the row count. You can use the below for row count in a view
SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('Transactions')
AND (index_id=0 or index_id=1)`
From @K3---rnc response (the best for me) I've added a small modifications to get an OrderedDict from an XML text (some times order matters):
def etree_to_ordereddict(t):
d = OrderedDict()
d[t.tag] = OrderedDict() if t.attrib else None
children = list(t)
if children:
dd = OrderedDict()
for dc in map(etree_to_ordereddict, children):
for k, v in dc.iteritems():
if k not in dd:
dd[k] = list()
dd[k].append(v)
d = OrderedDict()
d[t.tag] = OrderedDict()
for k, v in dd.iteritems():
if len(v) == 1:
d[t.tag][k] = v[0]
else:
d[t.tag][k] = v
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
Following @K3---rnc example, you can use it:
from xml.etree import cElementTree as ET
e = ET.XML('''
<root>
<e />
<e>text</e>
<e name="value" />
<e name="value">text</e>
<e> <a>text</a> <b>text</b> </e>
<e> <a>text</a> <a>text</a> </e>
<e> text <a>text</a> </e>
</root>
''')
from pprint import pprint
pprint(etree_to_ordereddict(e))
Hope it helps ;)
I have a solution for your problem. You can check the ScrollView code it handles only vertical scrolling and ignores the horizontal one and modify this. I wanted a view like a webview, so modified ScrollView and it worked well for me. But this may not suit your needs.
Let me know what kind of UI you are targeting for.
Regards,
Ravi Pandit
If You cannot get Resources object like this in a class which is not an Activity, you have to add getContext() method for getResources() for example
ImageView image = (ImageView) v.findViewById(R.id.item_image);
int id = getContext().getResources().getIdentifier(imageName, "drawable", getContext().getPackageName());
image.setImageResource(id);
For increasing execution time and file size, you need to mention below values in your .htaccess file. It will work.
php_value upload_max_filesize 80M
php_value post_max_size 80M
php_value max_input_time 18000
php_value max_execution_time 18000
Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.
e.g for an Oracle database, use NVL
SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;
then check
if (rs.getInt('ID_PARENT') != -999)
{
}
Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.
If you have a Unicode string, and you want to write this to a file, or other serialised form, you must first encode it into a particular representation that can be stored. There are several common Unicode encodings, such as UTF-16 (uses two bytes for most Unicode characters) or UTF-8 (1-4 bytes / codepoint depending on the character), etc. To convert that string into a particular encoding, you can use:
>>> s= u'£10'
>>> s.encode('utf8')
'\xc2\x9c10'
>>> s.encode('utf16')
'\xff\xfe\x9c\x001\x000\x00'
This raw string of bytes can be written to a file. However, note that when reading it back, you must know what encoding it is in and decode it using that same encoding.
When writing to files, you can get rid of this manual encode/decode process by using the codecs module. So, to open a file that encodes all Unicode strings into UTF-8, use:
import codecs
f = codecs.open('path/to/file.txt','w','utf8')
f.write(my_unicode_string) # Stored on disk as UTF-8
Do note that anything else that is using these files must understand what encoding the file is in if they want to read them. If you are the only one doing the reading/writing this isn't a problem, otherwise make sure that you write in a form understandable by whatever else uses the files.
In Python 3, this form of file access is the default, and the built-in open
function will take an encoding parameter and always translate to/from Unicode strings (the default string object in Python 3) for files opened in text mode.
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
Sending your activity context to other classes could cause memoryleaks because holding that context alive is the reason that the GC can't dispose the object
You can omit window
and just use location.href
. For example:
location.href = 'http://google.im/';
In my case following solution worked.
I hope this may help someone.
In the default constructor (and any non-default ones if you have any too of course):
public foo() {
Bar = "bar";
}
This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.
Steps for MIUI 9 and Above:
Settings -> Additional Settings -> Developer options ->
Turn off "MIUI optimization" and Restart
Turn On "USB Debugging"
Turn On "Install via USB"
Set USB Configuration to Charging
Turn On "install via USB
MTP(Media Transfer Protocol) is the default mode.
Works even in MTP in some cases
Shallow Copy: lodash _.clone()
A shallow copy can be made by simply copying the reference.
let obj1 = {
a: 0,
b: {
c: 0,
e: {
f: 0
}
}
};
let obj3 = _.clone(obj1);
obj1.a = 4;
obj1.b.c = 4;
obj1.b.e.f = 100;
console.log(JSON.stringify(obj1));
//{"a":4,"b":{"c":4,"e":{"f":100}}}
console.log(JSON.stringify(obj3));
//{"a":0,"b":{"c":4,"e":{"f":100}}}
Deep Copy: lodash _.cloneDeep()
fields are dereferenced: rather than references to objects being copied
let obj1 = {
a: 0,
b: {
c: 0,
e: {
f: 0
}
}
};
let obj3 = _.cloneDeep(obj1);
obj1.a = 100;
obj1.b.c = 100;
obj1.b.e.f = 100;
console.log(JSON.stringify(obj1));
{"a":100,"b":{"c":100,"e":{"f":100}}}
console.log(JSON.stringify(obj3));
{"a":0,"b":{"c":0,"e":{"f":0}}}
No expensive forks, no pipes, no bashisms:
$ set -- $STRING
$ eval echo \${$N}
three
But beware of globbing.
Even though it does not exactly fit to your problem, I'll drop this here. My requirements were:
Let's talk about (3) first: Just having the jars in a folder and somehow merging them into the final jar will not work for here, since the IDE will not understand this. This means all libraries have to be installed properly. However, I dont want to have everyone installing it using "mvn install-file".
In my project I needed metawidget. Here we go:
Every time you have a new library, just add a new execution and tell everyone to build the project again (you can improve this process with project hierachies).
Using the -X
flag with whatever HTTP verb you want:
curl -X PUT -d arg=val -d arg2=val2 localhost:8080
This example also uses the -d
flag to provide arguments with your PUT request.
Simply add the bootstrap "row-fluid" class to the textarea. It will stretch to 100% width;
Update: For bootstrap 3.x use "col-xs-12" class for textarea;
Update II: Also if you want to extend the container to full width use: container-fluid class.
Try accessing a static file. If this is not working either then go to all directories from the root "/" or "c:\" to the directory of your file and check if they contain ".htaccess" files.
I once left a file in "c:\" and it had the most strange results.
Try this please, <a target="_blank" routerLink="/Page2">
Update1: Custom directives to the rescue! Full code is here: https://github.com/pokearound/angular2-olnw
import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';
@Directive({ selector: '[olinw007]' })
export class OpenLinkInNewWindowDirective {
//@Input('olinwLink') link: string; //intro a new attribute, if independent from routerLink
@Input('routerLink') link: string;
constructor(private el: ElementRef, @Inject(Window) private win:Window) {
}
@HostListener('mousedown') onMouseEnter() {
this.win.open(this.link || 'main/default');
}
}
Notice, Window is provided and OpenLinkInNewWindowDirective declared below:
import { AppAboutComponent } from './app.about.component';
import { AppDefaultComponent } from './app.default.component';
import { PageNotFoundComponent } from './app.pnf.component';
import { OpenLinkInNewWindowDirective } from './olinw.directive';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
const appRoutes: Routes = [
{ path: '', pathMatch: 'full', component: AppDefaultComponent },
{ path: 'home', component: AppComponent },
{ path: 'about', component: AppAboutComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
declarations: [
AppComponent, AppAboutComponent, AppDefaultComponent, PageNotFoundComponent, OpenLinkInNewWindowDirective
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
providers: [{ provide: Window, useValue: window }],
bootstrap: [AppComponent]
})
export class AppModule { }
First link opens in new Window, second one will not:
<h1>
{{title}}
<ul>
<li><a routerLink="/main/home" routerLinkActive="active" olinw007> OLNW</a></li>
<li><a routerLink="/main/home" routerLinkActive="active"> OLNW - NOT</a></li>
</ul>
<div style="background-color:#eee;">
<router-outlet></router-outlet>
</div>
</h1>
Tada! ..and you are welcome =)
Update2: As of v2.4.10 <a target="_blank" routerLink="/Page2">
works
It is always better to close the database/resource objects after usage.
Better close the connection, resultset and statement objects in the finally
block.
Until Java 7, all these resources need to be closed using a finally
block. If you are using Java 7, then for closing the resources, you can do as follows.
try(Connection con = getConnection(url, username, password, "org.postgresql.Driver");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
) {
// Statements
}
catch(....){}
Now, the con
, stmt
and rs
objects become part of try block and Java automatically closes these resources after use.
I want to be clear that the following code is not good practice. You can use GOTO Label:
For Each I As Item In Items
If I = x Then
'Move to next item
GOTO Label1
End If
' Do something
Label1:
Next
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
You create __main__.py
in yourpackage
to make it executable as:
$ python -m yourpackage
There is a better guide here for Windows:
https://shellcreeper.com/how-to-create-valid-ssl-in-localhost-for-xampp/
Basic steps:
Create an SSL certificate for your local domain using this: See more details in the link above https://gist.github.com/turtlepod/3b8d8d0eef29de019951aa9d9dcba546 https://gist.github.com/turtlepod/e94928cddbfc46cfbaf8c3e5856577d0
Install this cert in Windows (Trusted Root Certification Authorities) See more details in the link above
Add the site in Windows hosts (C:\Windows\System32\drivers\etc\hosts)
E.g.: 127.0.0.1 site.test
Add the site in XAMPP conf (C:\xampp\apache\conf\extra\httpd-vhosts.conf) E.g.:
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName site.test
ServerAlias *.site.test
</VirtualHost>
<VirtualHost *:443>
DocumentRoot "C:/xampp/htdocs"
ServerName site.test
ServerAlias *.site.test
SSLEngine on
SSLCertificateFile "crt/site.test/server.crt"
SSLCertificateKeyFile "crt/site.test/server.key"
</VirtualHost>
Restart Apache and your browser and it's done!
In JavaScript my practice has been to avoid constants as much as I can and use strings instead. Problems with constants appear when you want to expose your constants to the outside world:
For example one could implement the following Date API:
date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)
But it's much shorter and more natural to simply write:
date.add(5, "days").add(12, "hours")
This way "days" and "hours" really act like constants, because you can't change from the outside how many seconds "hours" represents. But it's easy to overwrite MyModule.Date.HOUR
.
This kind of approach will also aid in debugging. If Firebug tells you action === 18
it's pretty hard to figure out what it means, but when you see action === "save"
then it's immediately clear.
You can manually iterate over the elements of the set:
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
Integer element = iterator.next();
if (element % 2 == 0) {
iterator.remove();
}
}
You will often see this pattern using a for
loop rather than a while
loop:
for (Iterator<Integer> i = set.iterator(); i.hasNext();) {
Integer element = i.next();
if (element % 2 == 0) {
i.remove();
}
}
As people have pointed out, using a for
loop is preferred because it keeps the iterator variable (i
in this case) confined to a smaller scope.
Note: as of 2019, many of the old vulnerabilities that lead to the preventative measures discussed in this question are no longer an issue in modern browsers. I'll leave the answer below as a historical curiosity, but really the whole topic has changed radically since 2010 (!!) when this was asked.
It prevents it from being used as the target of a simple <script>
tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch your content.
edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object
and Array
constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.
After installing numpy
, scipy
,sklearn
still has error
Solution:
Setting Up System Path
Variable for Python & the PYTHONPATH
Environment Variable
System Variables: add C:\Python34
into path
User Variables: add new: (name)PYTHONPATH
(value)C:\Python34\Lib\site-packages;
For those who are using laravel 5 or above must use public modifier other wise it will throw an exception
Access level to App\yourModelName::$timestamps must be
public (as in class Illuminate\Database\Eloquent\Model)
public $timestamps = false;
The only thing that has worked for me (probably because I had inconsistencies with www. usage):
Paste this in to your .htaccess file:
<IfModule mod_headers.c>
<FilesMatch "\.(eot|font.css|otf|ttc|ttf|woff)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
<IfModule mod_mime.c>
# Web fonts
AddType application/font-woff woff
AddType application/vnd.ms-fontobject eot
# Browsers usually ignore the font MIME types and sniff the content,
# however, Chrome shows a warning if other MIME types are used for the
# following fonts.
AddType application/x-font-ttf ttc ttf
AddType font/opentype otf
# Make SVGZ fonts work on iPad:
# https://twitter.com/FontSquirrel/status/14855840545
AddType image/svg+xml svg svgz
AddEncoding gzip svgz
</IfModule>
# rewrite www.example.com ? example.com
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
http://ce3wiki.theturninggate.net/doku.php?id=cross-domain_issues_broken_web_fonts
I wrote a script that does just this, and it is available on my github for your use.
I utilized BeautifulSoup to allow me to parse any website for images. If you will be doing much web scraping (or intend to use my tool) I suggest you sudo pip install BeautifulSoup
. Information on BeautifulSoup is available here.
For convenience here is my code:
from bs4 import BeautifulSoup
from urllib2 import urlopen
import urllib
# use this image scraper from the location that
#you want to save scraped images to
def make_soup(url):
html = urlopen(url).read()
return BeautifulSoup(html)
def get_images(url):
soup = make_soup(url)
#this makes a list of bs4 element tags
images = [img for img in soup.findAll('img')]
print (str(len(images)) + "images found.")
print 'Downloading images to current working directory.'
#compile our unicode list of image links
image_links = [each.get('src') for each in images]
for each in image_links:
filename=each.split('/')[-1]
urllib.urlretrieve(each, filename)
return image_links
#a standard call looks like this
#get_images('http://www.wookmark.com')
The "onchange" is only fired when the attribute is programmatically changed or when the user makes a change and then focuses away from the field.
Have you looked at using YUI's calendar object? I've coded up a solution that puts the yui calendar inside a yui panel and hides the panel until an associated image is clicked. I'm able to see changes from either.
http://developer.yahoo.com/yui/examples/calendar/formtxt.html
On https://help.directadmin.com/item.php?id=589 they write:
If you need a quick way to reset your public_html data to 755 for directories and 644 for files, then you can use something like this:
cd /home/user/domains/domain.com/public_html
find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;
I tested and ... it works!
In 12c you can make use of the fact that columns which are set from invisible to visible are displayed as the last column of the table: Tips and Tricks: Invisible Columns in Oracle Database 12c
Maybe that is the 'trick' @jeffrey-kemp was talking about in his comment, but the link there does not work anymore.
Example:
ALTER TABLE my_tab ADD (col_3 NUMBER(10));
ALTER TABLE my_tab MODIFY (
col_1 invisible,
col_2 invisible
);
ALTER TABLE my_tab MODIFY (
col_1 visible,
col_2 visible
);
Now col_3 would be displayed first in a SELECT * FROM my_tab
statement.
Note: This does not change the physical order of the columns on disk, but in most cases that is not what you want to do anyway. If you really want to change the physical order, you can use the DBMS_REDEFINITION package.
You can import json files by using the node.js v14 experimental json modules flag. More details here
file.js
import data from './folder/file.json'
export default {
foo () {
console.log(data)
}
}
And you call it with node --experimental-json-modules file.js
The only difference between files that causing the issue is the 8th byte of file
CA FE BA BE 00 00 00 33 - Java 7
vs.
CA FE BA BE 00 00 00 32 - Java 6
Setting -XX:-UseSplitVerifier
resolves the issue. However, the cause of this issue is https://bugs.eclipse.org/bugs/show_bug.cgi?id=339388
Sometimes you need to reset ADB. To do that, in Eclipse, go:
Window>> Show View >> Android (Might be found in the "Other" option)>>Devices
in the device Tab, click the down arrow, and choose reset adb.
The core problem is the js errors:
$('#purpose').on('change', function () {
// if (this.value == '1'); { No semicolon and I used === instead of ==
if (this.value === '1'){
$("#business").show();
} else {
$("#business").hide();
}
});
// }); remove
http://jsfiddle.net/Bushwazi/2kGzZ/3/
I had to clean up the html & js...I couldn't help myself.
HTML:
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<form id="business">
<label for="business">Business Name</label>
<input type='text' class='text' name='business' value size='20' />
</form>
CSS:
#business {
display:none;
}
JS:
$('#purpose').on('change', function () {
if(this.value === "1"){
$("#business").show();
} else {
$("#business").hide();
}
});
You typically restore purchases with this code:
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
It will reinvoke -paymentQueue:updatedTransactions
on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.
Not all types of In-App purchases can be restored.
vertical-align:middle; text-align:right;
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
Just change your line of code to
<a href="~/Required/[email protected]">Edit</a>
from where you are calling this function that will pass corect id
You should hook onto the change event of the <select>
element instead of on the individual options.
var select = document.getElementById('test'),
onChange = function(event) {
var shown = this.options[this.selectedIndex].value == 1;
document.getElementById('hidden_div').style.display = shown ? 'block' : 'none';
};
// attach event handler
if (window.addEventListener) {
select.addEventListener('change', onChange, false);
} else {
// of course, IE < 9 needs special treatment
select.attachEvent('onchange', function() {
onChange.apply(select, arguments);
});
}
No there is not. And I will tell you a little story on why it is not. But first, quick solutions:
a) Use CSS class for basic elements span
/div
, e.g.: <span class="vr"></span>
:
.vr{
display: inline-block;
vertical-align: middle;
/* note that height must be precise, 100% does not work in some major browsers */
height: 100px;
width: 1px;
background-color: #000;
}
Demonstration of use => https://jsfiddle.net/fe3tasa0/
b) Make a use of a one-side-only border and possibly CSS :first-child
selector if you want to apply a general dividers among sibling/neigbour elements.
<vr>
FITTING in the original paradigm,Many answers here suggest, that vertical divider does not fit the original HTML paradigm/approach ... that is completely wrong. Also the answers contradict themselves a lot.
Those same people are probably calling their clear CSS class "clearfix" - there is nothing to fix about floating, you are just clearing it ... There was even an element in HTML3: <clear>
. Sadly, this and clearance of floating is one of the few common misconceptions.
Anyway. "Back then" in the "original HTML ages", there was no thought about something like inline-block
, there were just blocks
, inlines
and tables
.
The last one is actually the reason why <vr>
does not exist.
Back then it was assumed that:
If you want to verticaly divide something and/or make more blocks from left to right =>
=> you are making/want to make columns =>
=> that implies you are creating a table =>
=> tables have natural borders between their cells => no reason to make a <vr>
This approach is actually still valid, but as time showed, the syntax made for tables is not suitable for every case as well as it's default styles.
:first-child
selector I suggested above...
Try display phpinfo() by file and check this var.
From MSDN, here's a list of characters that aren't allowed:
Use almost any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:
- The following reserved characters are not allowed: < > : " / \ | ? *
- Characters whose integer representations are in the range from zero through 31 are not allowed.
- Any other character that the target file system does not allow.
I've been using the following extension method on my DataRow types:
public static string ColumnIsNull(this System.Data.DataRow row, string colName, string defaultValue = "")
{
string val = defaultValue;
if (row.Table.Columns.Contains(colName))
{
if (row[colName] != DBNull.Value)
{
val = row[colName]?.ToString();
}
}
return val;
}
usage:
MyControl.Text = MyDataTable.Rows[0].ColumnIsNull("MyColumn");
MyOtherControl.Text = MyDataTable.Rows[0].ColumnIsNull("AnotherCol", "Doh! I'm null");
I'm checking for the existence of the column first because if none of query results has a non-null value for that column, the DataTable object won't even provide that column.
I would like to shared with you my implementation for find first responder in anywhere of UIView. I hope it helps and sorry for my english. Thanks
+ (UIView *) findFirstResponder:(UIView *) _view {
UIView *retorno;
for (id subView in _view.subviews) {
if ([subView isFirstResponder])
return subView;
if ([subView isKindOfClass:[UIView class]]) {
UIView *v = subView;
if ([v.subviews count] > 0) {
retorno = [self findFirstResponder:v];
if ([retorno isFirstResponder]) {
return retorno;
}
}
}
}
return retorno;
}
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
I answered a similar question here. I looked in a lot of places that always created the same problem. Basically, I did not want to assign a value to the weights, but simply change the weights. The short version of the above answer is:
tf.keras.backend.set_value(tf_var, numpy_weights)
Using jQuery:
$(document).ready(function(){
$('div').click(function(){
$(this).toggleClass('clicked');
});
});?
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
For OSX, you can go to your user's $HOME
(probably /Users/yourname/) and, if it doesn't already exist, create an .npmrc
file (a file that npm uses for user configuration), and create a directory for your npm packages to be installed in (e.g., /Users/yourname/npm). In that .npmrc file, set "prefix" to your new npm directory, which will be where "globally" installed npm packages will be installed; these "global" packages will, obviously, be available only to your user account.
In .npmrc:
prefix=${HOME}/npm
Then run this command from the command line:
npm config ls -l
It should give output on both your own local configuration and the global npm configuration, and you should see your local prefix configuration reflected, probably near the top of the long list of output.
For security, I recommend this approach to configuring your user account's npm behavior over chown-ing your /usr/local
folders, which I've seen recommended elsewhere.
If you have a hash structure like this:
Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}
Then this is how I got it to work:
params.require(:link).permit(:title, time_span: [[:start, :end]])
Make sure you are following the Same Origin Policy. This means same domain, same subdomain, same protocol (http vs https) and same port.
How does pushState protect against potential content forgeries?
EDIT: As @robertc aptly pointed out in his comment, some browsers actually implement slightly different security policies when the origin is file:///
. Not to mention you can encounter problems when testing locally with file:///
when the page expects it is running from a different origin (and so your pushState
assumes production origin scenarios, not localhost scenarios)
Yes there is. With .NET 3.5:
int sum = arr.Sum();
Console.WriteLine(sum);
If you're not using .NET 3.5 you could do this:
int sum = 0;
Array.ForEach(arr, delegate(int i) { sum += i; });
Console.WriteLine(sum);
If your date is already a DateTime
or DateTimeImmutable
you can use the format
method.
$day_of_week = intval($date_time->format('w'));
The format string is identical to the one used by the date function.
To answer the intended question:
$date_time->modify($target_day_of_week - $day_of_week . ' days');
This worked perfectly for me without css. I think css would put some icing on the cake though.
<form>
<label for="First Name" >First Name:</label>
<input type="text" name="username" size="15" maxlength="30" />
<label for="Last Name" >Last Name:</label>
<input type="text" name="username" size="15" maxlength="30" />
</form>
you can make guid variable to accept null first using ? operator then you use Guid.Empty or typecast it to null using (Guid?)null;
eg:
Guid? id = Guid.Empty;
or
Guid? id = (Guid?)null;
For a set of images (each image has 3 dimensions), where I wanted to reject outliers for each pixel I used:
mean = np.mean(imgs, axis=0)
std = np.std(imgs, axis=0)
mask = np.greater(0.5 * std + 1, np.abs(imgs - mean))
masked = np.multiply(imgs, mask)
Then it is possible to compute the mean:
masked_mean = np.divide(np.sum(masked, axis=0), np.sum(mask, axis=0))
(I use it for Background Subtraction)
I just solved this kind of a problem. What I've learned is:
my.cnf
and set the bind-address = your.mysql.server.address
under [mysqld]
check if it's running
mysql -u root -h your.mysql.server.address –p
create a user (usr or anything) with % as domain and grant her access to the database in question.
mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)
you should be able to now connect mysql server form your client server php script.
It looks like your utf-8 is being interpreted as iso8859-1 or Win-1250 at some point.
When you say "In my database I have a few instances of bad encodings" - how did you check this? Through your app, phpmyadmin or the command line client? Are all utf-8 encodings showing up like this or only some? Is it possible you had the encodings wrong and it has been incorrectly converted from iso8859-1 to utf-8 when it was utf-8 already?
<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
It targets some specified feature to execute some other codes...
For example:
@media all and (max-width: 600px) {
.navigation {
-webkit-flex-flow: column wrap;
flex-flow: column wrap;
padding: 0;
}
the above snippet say if the device that run this program have screen with 600px or less than 600px width, in this case our program must execute this part .
Think of !
(negation operator) as "not", ||
(boolean-or operator) as "or" and &&
(boolean-and operator) as "and". See Operators and Operator Precedence.
Thus:
if(!(a || b)) {
// means neither a nor b
}
However, using De Morgan's Law, it could be written as:
if(!a && !b) {
// is not a and is not b
}
a
and b
above can be any expression (such as test == 'B'
or whatever it needs to be).
Once again, if test == 'A'
and test == 'B'
, are the expressions, note the expansion of the 1st form:
// if(!(a || b))
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')
You can also define the pointcut as
public pointcut publicMethodInsideAClassMarkedWithAtMonitor() : execution(public * (@Monitor *).*(..));
I find a 'dist' function in matplotlib.mlab, but I don't think it's handy enough.
I'm posting it here just for reference.
import numpy as np
import matplotlib as plt
a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
# Distance between a and b
dis = plt.mlab.dist(a, b)
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
The second formula on that page uses the GCD function of the Analysis ToolPak, you can add it from Tools > Add-Ins.
=A1/GCD(A1,B1)&":"&B1/GCD(A1,B1)
This is a more mathematical formula rather than a text manipulation based on.
Building on the previous answer by @BadPirate, I experimented a bit further and came up with some clarifications/corrections. I found that layoutSubviews:
will be called on a view if and only if:
Some relevant details:
layoutSubviews:
is called whenever a UIScrollView scrolls, as it performs the scrolling by changing its bounds' origin.layoutSubviews:
when the view is eventually added to a view hierarchy.setNeedsLayout
, which sets/raises a flag. Each iteration of the run loop, for all views in the view hierarchy, this flag is checked. For each view where the flag is found raised, layoutSubviews:
is called on it and the flag is reset. Views higher up the hierarchy will be checked/called first.While other answers already fulfilled the question (it's a 3 years old question after all), I'm just gonna add some info, and probably fixed a bit of misunderstanding.
Em, while originally meant as the term for a single 'M' character's width in typography, in digital medium it was shifted to a unit relative to the point size of the typeface (font-size or textSize), in other words it's uses the height of the text, not the width of a single 'M'.
In Android, that means when you specify the ems of a TextView, it uses the said TextView's textSize as the base, excluding the added padding for accents/diacritics. When you set a 16sp TextView's ems to 4, it means its width will be 64sp wide, thus explained @stefan 's comment about why a 10 ems wide EditText is able to fit 17 'M'.
Does this work:
$msgid = $_GET['msgid'];
$oldMessage = '';
$deletedFormat = '';
//read the entire string
$str=file_get_contents('msghistory.txt');
//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);
//write the entire string
file_put_contents('msghistory.txt', $str);
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
You can make the query using convert to varbinary – it’s very easy. Example:
Select * from your_table where convert(varbinary, your_column) = convert(varbinary, 'aBcD')
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
HTML
<form ... id ="GoogleMapsApiKeyForm">
...
<input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
....
<span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
...
<button type="submit" class="btn btn-primary">Save</button>
</form>
Javascript
$(function () {
$("#GoogleMapsApiKeyForm").validate({
rules: {
GoogleMapsAPIKey: {
required: true
}
},
messages: {
GoogleMapsAPIKey: 'Google maps api key is required',
},
errorPlacement: function (error, element) {
if (element.attr("name") == "GoogleMapsAPIKey")
$("#GoogleMapsAPIKey-errorMsg").html(error);
},
submitHandler: function (form) {
// form.submit(); //if you need Ajax submit follow for rest of code below
}
});
//If you want to use ajax
$("#GoogleMapsApiKeyForm").submit(function (e) {
e.preventDefault();
if (!$("#GoogleMapsApiKeyForm").valid())
return;
//Put your ajax call here
});
});
('my string'.match(/\s/g) || []).length;
Just follow these steps:
crontab -e
.Type your cron job, for example:
30 * * * * /usr/bin/curl --silent --compressed http://example.com/crawlink.php
Press Esc to exit vim's insert mode.
crontab: installing new crontab
. You can verify the crontab file by using crontab -l
.Note however that this might not work depending on the content of your ~/.vimrc
file.
Here is a very simple method. There are a different ways to do it, like you can get it by Expanded
, Sizedbox
or Container
and it should be used according to needs.
Use Expanded
: A widget that expands a child of a Row
, Column
, or Flex
so that the child fills the available space.
Expanded(
child: ListView(scrollDirection: Axis.horizontal,
children: <Widget>[
OutlineButton(onPressed: null,
child: Text("Facebook")),
Padding(padding: EdgeInsets.all(5.00)),
OutlineButton(onPressed: null,
child: Text("Google")),
Padding(padding: EdgeInsets.all(5.00)),
OutlineButton(onPressed: null,
child: Text("Twitter"))
]),
),
Using an Expanded
widget makes a child of a Row
, Column
, or Flex
expand to fill the available space along the main axis (e.g., horizontally for a Row or vertically for a Column).
Use SizedBox
: A box with a specified size.
SizedBox(
height: 100,
child: ListView(scrollDirection: Axis.horizontal,
children: <Widget>[
OutlineButton(
color: Colors.white,
onPressed: null,
child: Text("Amazon")
),
Padding(padding: EdgeInsets.all(5.00)),
OutlineButton(onPressed: null,
child: Text("Instagram")),
Padding(padding: EdgeInsets.all(5.00)),
OutlineButton(onPressed: null,
child: Text("SoundCloud"))
]),
),
If given a child, this widget forces its child to have a specific width and/or height (assuming values are permitted by this widget's parent).
Use Container
: A convenience widget that combines common painting, positioning, and sizing widgets.
Container(
height: 80.0,
child: ListView(scrollDirection: Axis.horizontal,
children: <Widget>[
OutlineButton(onPressed: null,
child: Text("Shopify")),
Padding(padding: EdgeInsets.all(5.00)),
OutlineButton(onPressed: null,
child: Text("Yahoo")),
Padding(padding: EdgeInsets.all(5.00)),
OutlineButton(onPressed: null,
child: Text("LinkedIn"))
]),
),
The output to all three would be something like this
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
((frmMain)this.Owner).MyListControl.Items.Add("abc");
Make sure to provide access level you want at Modifiers properties other than Private for MyListControl
at frmMain
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
JavaScript
If you want to return matched letters:
('Example 123').match(/[A-Z]/gi)
// Result: ["E", "x", "a", "m", "p", "l", "e"]
If you want to replace matched letters with stars ('*') for example:
('Example 123').replace(/[A-Z]/gi, '*')
//Result: "****** 123"*
Assuming that your phone numbers always have this exact format, you can use this snippet:
$from = "+11234567890";
$to = sprintf("%s-%s-%s",
substr($from, 2, 3),
substr($from, 5, 3),
substr($from, 8));
t1 = datetime.datetime.strptime(StartTime, "%H:%M:%S %d-%m-%y")
t2 = datetime.datetime.strptime(EndTime, "%H:%M:%S %d-%m-%y")
return str(t2-t1)
So for:
StartTime = '15:28:53 21-07-13'
EndTime = '15:32:40 21-07-13'
returns:
'0:03:47'
Using an &&
expression to join two comparisons is simply the most elegant way to do this. If you try using fancy extension methods and such, you run into the question of whether to include the upper bound, the lower bound, or both. Once you start adding additional variables or changing the extension names to indicate what is included, your code becomes longer and harder to read (for the vast majority of programmers). Furthermore, tools like Resharper will warn you if your comparison doesn't make sense (number > 100 && number < 1
), which they won't do if you use a method ('i.IsBetween(100, 1)').
The only other comment I'd make is that if you're checking inputs with the intention to throw an exception, you should consider using code contracts:
Contract.Requires(number > 1 && number < 100)
This is more elegant than if(...) throw new Exception(...)
, and you could even get compile-time warnings if someone tries to call your method without ensuring that the number is in bounds first.
Without access to the type (and no "InternalsVisibleTo" etc) you would have to use reflection. But a better question would be: should you be accessing this data? It isn't part of the public type contract... it sounds to me like it is intended to be treated as an opaque object (for their purposes, not yours).
You've described it as a public instance field; to get this via reflection:
object obj = ...
string value = (string)obj.GetType().GetField("test").GetValue(obj);
If it is actually a property (not a field):
string value = (string)obj.GetType().GetProperty("test").GetValue(obj,null);
If it is non-public, you'll need to use the BindingFlags
overload of GetField
/GetProperty
.
Important aside: be careful with reflection like this; the implementation could change in the next version (breaking your code), or it could be obfuscated (breaking your code), or you might not have enough "trust" (breaking your code). Are you spotting the pattern?
I think the problem is not in sub-query but in WHERE clause of outer query. When you use
WHERE account_code between 503100 and 503105
SQL server will try to convert every value in your Account_code field to integer to test it in provided condition. Obviously it will fail to do so if there will be non-integer characters in some rows.
In Spring 5, or maybe in earlier versions, there is MediaType
class. It has already correct line, if you want to follow DRY:
public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
So I use this set of controller-related annotations:
@RestController
@RequestMapping(value = "my/api/url", produces = APPLICATION_JSON_UTF8_VALUE)
public class MyController {
// ... Methods here
}
It is marked deprecated in the docs, but I've run into this issue and it is better than copy-pastying the aforementioned line on every method/controller throughout your application, I think.
I know the original poster has a great answer, but for anyone stumbling on this thread like I have there's an important note from the proposal that I think adds something of value to the discussion here, particularly to concerns in the comments about if the typedef
keyword is going to be marked as deprecated in the future, or removed for being redundant/old:
It has been suggested to (re)use the keyword typedef ... to introduce template aliases:
template<class T> typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages [sic] among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector<•, MyAllocator<•> >
– where the bullet is a placeholder for a type-name.Consequently we do not propose the “typedef” syntax.On the other hand the sentencetemplate<class T> using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
To me, this implies continued support for the typedef
keyword in C++ because it can still make code more readable and understandable.
Updating the using
keyword was specifically for templates, and (as was pointed out in the accepted answer) when you are working with non-templates using
and typedef
are mechanically identical, so the choice is totally up to the programmer on the grounds of readability and communication of intent.
I had the same problem, only need to show shortdate (without the time), moreover it was needed to have multi-language settings, so depends of the language, show dd-mm-yyyy or mm-dd-yyyy.
Finally using DataFormatString="{0:d}
, all works fine and show only the date with culture format.
For me, my issue was that I was
android:background="?attr/selectableItemBackground"
To a LinearLayout background, once I removed it the test passed.
You want to add libraries to your project and in doing so you have two options as you yourself identified:
Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.
This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).
Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.
As for the other alernatives you have either global libraries using Library Manager
or jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager
.
Not Just HTML, Using atom-beautify
- Package for Atom, you can format code for HTML, CSS, JavaScript, PHP, Python, Ruby, Java, C, C++, C#, Objective-C, CoffeeScript, TypeScript, Coldfusion, SQL, and more) in Atom within a matter of seconds.
To Install the atom-beautify
package :
Install Packages & Themes
. A Install Package window comes up.Beautify
package, you will see a lot of beautify packages. Install any. I will recommend for atom-beautify
.To Format text Using atom-beautify
:
In httpd.conf file you need to remove #
#LoadModule rewrite_module modules/mod_rewrite.so
after removing # line will look like this:
LoadModule rewrite_module modules/mod_rewrite.so
And Apache restart
The C++ FAQ Lite has a entry specifically for this
I think this quote sums it up nicely
As long as you're careful, it's OK for an object to commit suicide (delete this).
you can get the values of the cell also as the current selection is referenced under CurrentRow
dataGridView1.CurrentRow.Cell[indexorname].FormattedValue
Here you can use index or column name and get the value.
With Java 9, Java 8u161, Java 7u171 and Java 6u181 the limitation is now disabled by default. See issue in Java Bug Database.
Beginning with Java 8u151 you can disable the limitation programmatically.
In older releases, JCE jurisdiction files had to be downloaded and installed separately to allow unlimited cryptography to be used by the JDK. The download and install steps are no longer necessary.
Instead you can now invoke the following line before first use of JCE classes (i.e. preferably right after application start):
Security.setProperty("crypto.policy", "unlimited");
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
If it's just a true/false test, have your function return 0
for success, and return 1
for failure. The test would then be:
if function_name; then
do something
else
error condition
fi
There is an important detail that has been omitted in the answer above.
MySQL imposes a limit of 65,535 bytes for the max size of each row.
The size of a VARCHAR
column is counted towards the maximum row size, while TEXT
columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR
field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.
Also note that the actual number of bytes required by a VARCHAR
field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4
(which you almost certainly should) it will use up even more of your maximum row size.
Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR
/TEXT
field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)
Reasons to use TEXT
:
Reasons to use VARCHAR
:
To complete the above answers, I had the case using an XML mapping file where neither the @Transient
nor transient
worked...
I had to put the transient information in the xml file:
<attributes>
(...)
<transient name="field" />
</attributes>
There is kind of two solutions on the client. One is with frames like you posted. You can use an iframe though:
var content = document.getElementById("divcontents");
var pri = document.getElementById("ifmcontentstoprint").contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();
This expects this html to exist
<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>
The other solution is to use the media selector and on the media="print"
styles hide everything you don't want to print.
<style type="text/css" media="print">
.no-print { display: none; }
</style>
Last way requires some work on the server. You can send all the HTML+CSS to the server and use one of many components to generate a printable document like PDF. I've tried setups doing this with PhantomJs.
Imagine you have a product called 'Zebra' that can be extended by plugins. It finds the plugins by searching for DLLs in some directory. It loads all those DLLs and uses reflection to find any classes that implement IZebraPlugin
, and then calls the methods of that interface to communicate with the plugins.
This makes it completely independent of any specific plugin class - it doesn't care what the classes are. It only cares that they fulfill the interface specification.
Interfaces are a way of defining points of extensibility like this. Code that talks to an interface is more loosely coupled - in fact it is not coupled at all to any other specific code. It can inter-operate with plugins written years later by people who have never met the original developer.
You could instead use a base class with virtual functions - all plugins would be derived from the base class. But this is much more limiting because a class can only have one base class, whereas it can implement any number of interfaces.
So for a lot of the issues here, it seems that people were already running psql and had to remove postmaster.pid
. However, I did not have that issue as I never even had postgres installed in my system properly.
Here's a solution that worked for me in MAC OSX Yosemite
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin
Hope this helps! Toodles!
Also, this answer helped me the most: https://stackoverflow.com/a/21503349/3173748
The string you are returning is not valid JSON. The names in the objects needs to be quoted and the whole string needs to be put in { … }
to form an object. JSON also cannot contain something like new Date()
. JSON is just a small subset of JavaScript that has only strings, numbers, objects, arrays, true
, false
and null
.
See the JSON grammar for more information.
You need BEGIN ... END to create a block spanning more than one statement. So, if you wanted to do 2 things in one 'leg' of an IF statement, or if you wanted to do more than one thing in the body of a WHILE loop, you'd need to bracket those statements with BEGIN...END.
The GO keyword is not part of SQL. It's only used by Query Analyzer to divide scripts into "batches" that are executed independently.
A1 A2
Toronto<b> is nice =LEFT(A1,(FIND("<",A1,1)-1))
Not sure if the syntax is correct but the forumla in A2 will work for you,
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x = np.array([1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
y = np.array([10.35,12.3,13,14.0,16,17,18.2,20,20.7,22.5])
gradient, intercept, r_value, p_value, std_err = stats.linregress(x,y)
mn=np.min(x)
mx=np.max(x)
x1=np.linspace(mn,mx,500)
y1=gradient*x1+intercept
plt.plot(x,y,'ob')
plt.plot(x1,y1,'-r')
plt.show()
USe this ..
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
Messing around with cookies.
Its cookies! Kids loooovvve cookies!
I found a similar approach (it uses a category as well) with gcamp's answer that helped me greatly here. In your case is as simple as this:
aView.topLeft = CGPointMake(100, 200);
but if you want for example to centre horizontal and to the left with another view you can simply:
aView.topLeft = anotherView.middleLeft;
There is a library on Github for tab support in your textareas by wjbryant: Tab Override
This is how it works:
// get all the textarea elements on the page
var textareas = document.getElementsByTagName('textarea');
// enable Tab Override for all textareas
tabOverride.set(textareas);
You shall probably use the "Resolve Auto Layout Issues" (bottom right - triangle icon in the storyboard view) to add/reset to suggested constraints (Xcode 6.0.1).
In Font Awesome 5 it can be done using pure CSS as in some of the above answers with some modifications.
ul {
list-style-type: none;
}
li:before {
position: absolute;
font-family: 'Font Awesome 5 free';
/* Use the Name of the Font Awesome free font, e.g.:
- 'Font Awesome 5 Free' for Regular and Solid symbols;
- 'Font Awesome 5 Brand' for Brands symbols.
- 'Font Awesome 5 Pro' for Regular and Solid symbols (Professional License);
*/
content: "\f1fc"; /* Unicode value of the icon to use: */
font-weight: 900; /* This is important, change the value according to the font family name
used above. See the link below */
color: red;
}
Without the correct font-weight, it will only show a blank square.
https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements#define
I'm coding a chess engine named foolsmate. The best move extraction using a minimax-based tree search to depth 9 (from a certain position) took:
on Win32
configuration: ~17.0s
;
after switching to x64
configuration: ~10.3s
;
This is 41% of acceleration!
In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.
$letters = array("a", "b", "c", "d", "e", "f", "g"); // this array can n no. of values
$result = substr(implode(", ", $letters), 0);
echo $result
output-> a,b,c,d,e,f,g
with()
is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation')
that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
whereHas()
works basically the same as has()
but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.
Breaking this down to a simple answer for .Net core 3.1:
If it is a MSTest project:
rename file in project to testhost.dll.config
OR
Use post-build command provided by DeepSpace101
Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto
or set a specific height to your div
. Live example: http://jsfiddle.net/tw16/xRcXL/3/
.Tab{
overflow:auto; /* add this */
border:solid 1px #faa62a;
border-bottom:none;
padding:7px 10px;
background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}
This may be created sql injection point "SQL Injection Piggy-backed Queries". attackers able to append multiple malicious sql statements. so do not append user inputs directly to the queries.
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.
When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator
that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.
So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.
Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.
String str = (String)Class.forName("java.lang.String").newInstance();
There can be a difference for loops. This is the practical application of post/pre-increment.
int i = 0;
while(i++ <= 10) {
Console.Write(i);
}
Console.Write(System.Environment.NewLine);
i = 0;
while(++i <= 10) {
Console.Write(i);
}
Console.ReadLine();
While the first one counts to 11 and loops 11 times, the second does not.
Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).
I would consider using something like:
function GetList
{
. {
$a = new-object Collections.ArrayList
$a.Add(5)
$a.Add('next 5')
} | Out-Null
$a
}
$x = GetList
Output from $a.Add
is not returned -- that holds for all $a.Add
method calls. Otherwise you would need to prepend [void]
before each the call.
In simple cases I would go with [void]$a.Add
because it is quite clear that output will not be used and is discarded.
Although it looks logical, the accepted answer is incorrect because JavaScript dates don't work like that.
It's super important to note here that the numerical value of a date (i.e., new Date()-0
or Date.now()
) in JavaScript is always measured as millseconds since the epoch which is a timezone-free quantity based on a precise exact instant in the history of the universe. You do not need to add or subtract anything to the numerical value returned from Date()
to convert the numerical value into a timezone, because the numerical value has no timezone. If it did have a timezone, everything else in JavaScript dates wouldn't work.
Timezones, leap years, leap seconds, and all of the other endlessly complicated adjustments to our local times and dates, are based on this consistent and unambiguous numerical value, not the other way around.
Here are examples of how the numerical value of a date (provided to the date constructor) is independent of timezone:
In Central Standard Time:
new Date(0);
// Wed Dec 31 1969 18:00:00 GMT-0600 (CST)
In Anchorage, Alaska:
new Date(0);
// Wed Dec 31 1969 15:00:00 GMT-0900 (AHST)
In Paris, France:
new Date(0);
// Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
It is critical to observe that in ALL cases, based on the timezone-free epoch offset of zero milliseconds, the resulting time is identical. 1 am in Paris, France is the exact same moment as 3 pm the day before in Anchorage, Alaska, which is the exact same moment as 6 pm in Chicago, Illinois.
For this reason, the accepted answer on this page is incorrect. Observe:
// Create a date.
date = new Date();
// Fri Jan 27 2017 18:16:35 GMT-0600 (CST)
// Observe the numerical value of the date.
date.valueOf();
// 1485562595732
// n.b. this value has no timezone and does not need one!!
// Observe the incorrectly "corrected" numerical date value.
date.valueOf() + date.getTimezoneOffset() * 60000;
// 1485584195732
// Try out the incorrectly "converted" date string.
new Date(date.valueOf() + date.getTimezoneOffset() * 60000);
// Sat Jan 28 2017 00:16:35 GMT-0600 (CST)
/* Not the correct result even within the same script!!!! */
If you have a date string in another timezone, no conversion to the resulting object created by new Date("date string")
is needed. Why? JavaScript's numerical value of that date will be the same regardless of its timezone. JavaScript automatically goes through amazingly complicated procedures to extract the original number of milliseconds since the epoch, no matter what the original timezone was.
The bottom line is that plugging a textual date string x
into the new Date(x)
constructor will automatically convert from the original timezone, whatever that might be, into the timezone-free epoch milliseconds representation of time which is the same regardless of any timezone. In your actual application, you can choose to display the date in any timezone that you want, but do NOT add/subtract to the numerical value of the date in order to do so. All the conversion already happened at the instant the date object was created. The timezone isn't even there anymore, because the date object is instantiated using a precisely-defined and timezone-free sense of time.
The timezone only begins to exist again when the user of your application is considered. The user does have a timezone, so you simply display that timezone to the user. But this also happens automatically.
Let's consider a couple of the dates in your original question:
date1 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300");
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)
date2 = new Date("Fri Jan 20 2012 11:51:36 GMT-0300")
// Fri Jan 20 2012 08:51:36 GMT-0600 (CST)
The console already knows my timezone, and so it has automatically shown me what those times mean to me.
And if you want to know the time in GMT/UTC representation, also no conversion is needed! You don't change the time at all. You simply display the UTC string of the time:
date1.toUTCString();
// "Fri, 20 Jan 2012 14:51:36 GMT"
Code that is written to convert timezones numerically using the numerical value of a JavaScript date is almost guaranteed to fail. Timezones are way too complicated, and that's why JavaScript was designed so that you didn't need to.
Source size is not really a sensible thing to measure. For example, the following shell script:
cat foobar
is much shorter than either its Python or C++ equivalents.
You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick
- i.e. anything on the page) and then check if the element clicked (event.srcElement
/ e.target
) has a class and that that class name is the one you want:
document.body.onclick = function(e) { //when the document body is clicked
if (window.event) {
e = event.srcElement; //assign the element clicked to e (IE 6-8)
}
else {
e = e.target; //assign the element clicked to e
}
if (e.className && e.className.indexOf('someclass') != -1) {
//if the element has a class name, and that is 'someclass' then...
alert('hohoho');
}
}
Or a more concise version of the above:
document.body.onclick= function(e){
e=window.event? event.srcElement: e.target;
if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
Ideally, the source code file should go within the src/default package even if you haven't provided any package name. For some reason, the source file might be outside src folder. Create within the scr folder it will work!
The modern way is to use ParentNode.append()
, like so:
let element = document.createElement('div');_x000D_
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';_x000D_
document.body.append(element);
_x000D_
After looking at the code you're having typos, here is the updated code
var clicks = 0; // should be var not int
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit
}
Note: Don't use in-built handlers, as .click()
is javascript function try giving different name like clickME()
I have found that if you don't put the variable directly against the scope it updates more reliably.
Try using some "dateObj.selectedDate" and in the controller add the selectedDate to a dateObj object as so:
$scope.dateObj = {selectedDate: new Date()}
This worked for me.
It is indeed possible with the following code
<div href="#" id='a'>
Hover me
</div>
<div id='b'>
Show me
</div>
and css
#a {
display: block;
}
#a:hover + #b {
display:block;
}
#b {
display:none;
}
Now by hovering on element #a shows element #b.
To avoid reflection you could set up a Dictionary with your propery names as keys and functions in the dictionary value part that return the corresponding values from the properties that you request.
As of PostgreSQL 9.4, you can use the ?
operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
You can even index the ?
query on the "food"
key if you switch to the jsonb type instead:
alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
Of course, you probably don't have time for that as a full-time rabbit keeper.
Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:
d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):
Public oConn As ADODB.Connection
Sub MySqlInit()
If oConn Is Nothing Then
Dim str As String
str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
Set oConn = New ADODB.Connection
oConn.Open str
End If
End Sub
The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\
You could take a Set
and filter the values who are alreday seen.
var array = ["q", "w", "w", "e", "i", "u", "r"],_x000D_
seen = array.filter((s => v => s.has(v) || !s.add(v))(new Set));_x000D_
_x000D_
console.log(seen);
_x000D_
git aliases (and sections in git configs) to the rescue!
add an alias (from command line):
git config --global alias.identity '! git config user.name "$(git config user.$1.name)"; git config user.email "$(git config user.$1.email)"; :'
then, set, for example
git config --global user.github.name "your github username"
git config --global user.github.email [email protected]
and in a new or cloned repo you can run this command:
git identity github
This solution isn't automatic, but unsetting user and email in your global ~/.gitconfig
and setting user.useConfigOnly
to true
would force git to remind you to set them manually in each new or cloned repo.
git config --global --unset user.name
git config --global --unset user.email
git config --global user.useConfigOnly true
We had today a problem like this, but we didn't wanted to change the HTML. So we used mouseenter event to achieve that
var doThingsOnClick = function() {
// your click function here
};
$(document).on({
'mouseenter': function () {
$(this).removeAttr('disabled').bind('click', doThingsOnClick);
},
'mouseleave': function () {
$(this).unbind('click', doThingsOnClick).attr('disabled', 'disabled');
},
}, 'input.disabled');
Find the below-mentioned code, it might be helpful for you.
val stringDate = spark.sparkContext.parallelize(Seq("12/16/2019")).toDF("StringDate")
val dateCoversion = stringDate.withColumn("dateColumn", to_date(unix_timestamp($"StringDate", "dd/mm/yyyy").cast("Timestamp")))
dateCoversion.show(false)
+----------+----------+
|StringDate|dateColumn|
+----------+----------+
|12/16/2019|2019-01-12|
+----------+----------+
Fiddle: http://jsfiddle.net/uenrX/1/
The opacity property of the outer DIV cannot be undone by the inner DIV. If you want to achieve transparency, use rgba
or hsla
:
Outer div:
background-color: rgba(255, 255, 255, 0.9); /* Color white with alpha 0.9*/
Inner div:
background-color: #FFF; /* Background white, to override the background propery*/
EDIT
Because you've added filter:alpha(opacity=90)
to your question, I assume that you also want a working solution for (older versions of) IE. This should work (-ms-
prefix for the newest versions of IE):
/*Padded for readability, you can write the following at one line:*/
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
/*Similarly: */
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
I've used the Gradient filter, starting with the same start-
and end-color
, so that the background doesn't show a gradient, but a flat colour. The colour format is in the ARGB hex format. I've written a JavaScript snippet to convert relative opacity values to absolute alpha-hex values:
var opacity = .9;
var A_ofARGB = Math.round(opacity * 255).toString(16);
if(A_ofARGB.length == 1) A_ofARGB = "0"+a_ofARGB;
else if(!A_ofARGB.length) A_ofARGB = "00";
alert(A_ofARGB);
Don't use a base class unless you know what it means, and that it applies in this case. If it applies, use it, otherwise, use interfaces. But note the answer about small interfaces.
Public Inheritance is overused in OOD and expresses a lot more than most developers realize or are willing to live up to. See the Liskov Substitutablity Principle
In short, if A "is a" B then A requires no more than B and delivers no less than B, for every method it exposes.
PDFBox contains tools for text extraction.
iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.
iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.
If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.
COPY . destinatio-directory/
From the oracle documentation, the below query explains it better
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
You can read this link
Your query would be as follows
//just the concept
INSERT INTO quotedb
(COLUMN_NAMES) //seperated by comma
SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker
Note: Make sure the columns in insert and select are in right position as per your requirement
Hope this helps!
When you decorate a model property with [DataType(DataType.Date)]
the default template in ASP.NET MVC 4 generates an input field of type="date"
:
<input class="text-box single-line"
data-val="true"
data-val-date="The field EstPurchaseDate must be a date."
id="EstPurchaseDate"
name="EstPurchaseDate"
type="date" value="9/28/2012" />
Browsers that support HTML5 such Google Chrome render this input field with a date picker.
In order to correctly display the date, the value must be formatted as 2012-09-28
. Quote from the specification:
value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.
You could enforce this format using the DisplayFormat
attribute:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }
if you have autoplay property in the iframe src it wont help to reload the src attr/prop so you have to replace the autoplay=1 to autoplay=0
var stopVideo = function(player) {
var vidSrc = player.prop('src').replace('autoplay=1','autoplay=0');
player.prop('src', vidSrc);
};
stopVideo($('#video'));
Use the length
property of the [String]
type:
if ($dbUserName.length -gt 8) {
Write-Output "Please enter more than 8 characters."
$dbUserName = Read-Host "Re-enter database username"
}
Please note that you have to use -gt
instead of >
in your if
condition. PowerShell uses the following comparison operators to compare values and test conditions:
Just the heads up, there seems to be special CSS class for this called form-horizontal
input-append has another side effect, that it drops font-size to zero
I would like to propose a version, which seems to be more robust, since I ran into a lot of problems using quantile()
in the breaks option cut()
on my dataset.
I am using the ntile
function of plyr
, but it also works with ecdf
as input.
temp[, `:=`(quartile = .bincode(x = ntile(value, 100), breaks = seq(0,100,25), right = TRUE, include.lowest = TRUE)
decile = .bincode(x = ntile(value, 100), breaks = seq(0,100,10), right = TRUE, include.lowest = TRUE)
)]
temp[, `:=`(quartile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.25), right = TRUE, include.lowest = TRUE)
decile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.1), right = TRUE, include.lowest = TRUE)
)]
Is that correct?
No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.
First, create your queue:
Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();
Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):
YourProducer producer = new YourProducer(queue);
and:
YourConsumer consumer = new YourConsumer(queue);
and add stuff to it in your producer:
queue.offer(myObject);
and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):
YourObject myObject = queue.poll();
For more info see the Javadoc
If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.
If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:
Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());
A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.
Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:
BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();
queue.put(myObject); // Blocks until queue isn't full.
YourObject myObject = queue.take(); // Blocks until queue isn't empty.
Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
Another method (2's complement):
public int reverse(int x){
x~=x;
x++;
return x;
}
It does a one's complement first (by complementing all the bits) and then adds 1 to x. This method does the job as well.
Note: This method is written in Java, and will be similar to a lot of other languages
output=[]
trends=list(set(trends))
This script works for most things
function timer(start) {
setTimeout(function () { //The timer
alert('hello');
}, start*3000); //needs the "start*" or else all the timers will run at 3000ms
}
for(var start = 1; start < 10; start++) {
timer(start);
}
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
you can try to put this in your php.ini:
ini_set("display_errors", "1");
error_reporting(E_ALL);
In php.ini file also you can set error_reporting();
In PHPMailer.php, there are lines as below:
echo $e->getMessage()
Just comment these lines and you will be good to go.