I personally would add a click handler to the child element that did nothing but stop the propagation of the click. So it would look something like:
$('.example > div').click(function (e) {
e.stopPropagation();
});
Use insert
:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]
import numpy as np
def get_median(xs):
mid = len(xs) // 2 # Take the mid of the list
if len(xs) % 2 == 1: # check if the len of list is odd
return sorted(xs)[mid] #if true then mid will be median after sorting
else:
#return 0.5 * sum(sorted(xs)[mid - 1:mid + 1])
return 0.5 * np.sum(sorted(xs)[mid - 1:mid + 1]) #if false take the avg of mid
print(get_median([7, 7, 3, 1, 4, 5]))
print(get_median([1,2,3, 4,5]))
You could regex it:
"string".replace(/^\/?|\/?$/, "")
"/installers/services/".replace(/^\/?|\/?$/, "") // -> installers/services
The regex explained:
- Optional first slash: ^/?
, escaped -> ^\/?
(the ^
means beginning of string)
- The pipe ( | ) can be read as or
- Than the option slash at the end -> /?$
, escaped -> \/?$
( the $
means end of string)
Combined it would be ^/?|/$
without escaping. Optional first slash OR optional last slash
Use this to get the page scroll position.
var screenTop = $(document).scrollTop();
$('#content').css('top', screenTop);
In theory, yes, it's just a matter of plugging things in. Zipfile can give you a file-like object for a file in a zip archive, and image.load will accept a file-like object. So something like this should work:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
try:
image = pygame.image.load(imgfile, 'img_01.png')
finally:
imgfile.close()
Same pdo error in sql query while trying to insert into database value from multidimential array:
$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);
$sth->execute();
Extracting array arr[$s][a]
from sql query, using instead variable containing it fixes the problem.
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
in your action performed method, call:
label1.setText(nameField.getText());
This way, when the button is clicked, label will be updated to the nameField text.
Since a variable in a class is declared as final AND initialised in the same command, there is absolutely no reason to not declare it as static, since it will have the same value no matter the instance. So, all instances can share the same memory address for a value, thus saving processing time by eliminating the need to create a new variable for each instance and saving memory by sharing 1 common address.
No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.
To get what you want you will need to move the +1 outside the computation:
r = ((double) rand() / (RAND_MAX)) + 1;
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
They are both rubbish! XCOPY
was older and unreliable, so Microsoft replaced it with ROBOCOPY
, which is still rubbish.
Don't worry though, it is a long-standing tradition that was started by the original COPY
command, which to this day, still needs the /B
switch to get it to actually copy properly!
<script>_x000D_
document.onkeydown = function(e) {_x000D_
if(event.keyCode == 123) {_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'S'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'H'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'A'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
}_x000D_
</script>
_x000D_
Try this code
Have a look at these pages. They contain many open source CSV parsers. JSaPar is one of them.
Example:
function Foo () { console.log('Foo function'); }_x000D_
var Bar = function () { console.log('Bar function'); };_x000D_
var Abc = function Xyz() { console.log('Abc function'); };_x000D_
_x000D_
var f = new Foo();_x000D_
var b = new Bar();_x000D_
var a = new Abc();_x000D_
_x000D_
console.log('f', f.constructor.name); // -> "Foo"_x000D_
console.log('b', b.constructor.name); // -> "Function"_x000D_
console.log('a', a.constructor.name); // -> "Xyz"
_x000D_
To whoever it might concern, here's my version that checks for Office 95-2019 & O365, both MSI based and ClickAndRun are supported, on both 32 and 64 bit systems (falls back to 32 bits when 64 bit version is not installed).
Written in Python 3.5 but of course you can always use that logic in order to write your own code in another language:
from winreg import *
from typing import Tuple, Optional, List
# Let's make sure the dictionnary goes from most recent to oldest
KNOWN_VERSIONS = {
'16.0': '2016/2019/O365',
'15.0': '2013',
'14.0': '2010',
'12.0': '2007',
'11.0': '2003',
'10.0': '2002',
'9.0': '2000',
'8.0': '97',
'7.0': '95',
}
def get_value(hive: int, key: str, value: Optional[str], arch: int = 0) -> str:
"""
Returns a value from a given registry path
:param hive: registry hive (windows.registry.HKEY_LOCAL_MACHINE...)
:param key: which registry key we're searching for
:param value: which value we query, may be None if unnamed value is searched
:param arch: which registry architecture we seek (0 = default, windows.registry.KEY_WOW64_64KEY, windows.registry.KEY_WOW64_32KEY)
Giving multiple arches here will return first result
:return: value
"""
def _get_value(hive: int, key: str, value: Optional[str], arch: int) -> str:
try:
open_reg = ConnectRegistry(None, hive)
open_key = OpenKey(open_reg, key, 0, KEY_READ | arch)
value, type = QueryValueEx(open_key, value)
# Return the first match
return value
except (FileNotFoundError, TypeError, OSError) as exc:
raise FileNotFoundError('Registry key [%s] with value [%s] not found. %s' % (key, value, exc))
# 768 = 0 | KEY_WOW64_64KEY | KEY_WOW64_32KEY (where 0 = default)
if arch == 768:
for _arch in [KEY_WOW64_64KEY, KEY_WOW64_32KEY]:
try:
return _get_value(hive, key, value, _arch)
except FileNotFoundError:
pass
raise FileNotFoundError
else:
return _get_value(hive, key, value, arch)
def get_keys(hive: int, key: str, arch: int = 0, open_reg: HKEYType = None, recursion_level: int = 1,
filter_on_names: List[str] = None, combine: bool = False) -> dict:
"""
:param hive: registry hive (windows.registry.HKEY_LOCAL_MACHINE...)
:param key: which registry key we're searching for
:param arch: which registry architecture we seek (0 = default, windows.registry.KEY_WOW64_64KEY, windows.registry.KEY_WOW64_32KEY)
:param open_reg: (handle) handle to already open reg key (for recursive searches), do not give this in your function call
:param recursion_level: recursivity level
:param filter_on_names: list of strings we search, if none given, all value names are returned
:param combine: shall we combine multiple arch results or return first match
:return: list of strings
"""
def _get_keys(hive: int, key: str, arch: int, open_reg: HKEYType, recursion_level: int, filter_on_names: List[str]):
try:
if not open_reg:
open_reg = ConnectRegistry(None, hive)
open_key = OpenKey(open_reg, key, 0, KEY_READ | arch)
subkey_count, value_count, _ = QueryInfoKey(open_key)
output = {}
values = []
for index in range(value_count):
name, value, type = EnumValue(open_key, index)
if isinstance(filter_on_names, list) and name not in filter_on_names:
pass
else:
values.append({'name': name, 'value': value, 'type': type})
if not values == []:
output[''] = values
if recursion_level > 0:
for subkey_index in range(subkey_count):
try:
subkey_name = EnumKey(open_key, subkey_index)
sub_values = get_keys(hive=0, key=key + '\\' + subkey_name, arch=arch,
open_reg=open_reg, recursion_level=recursion_level - 1,
filter_on_names=filter_on_names)
output[subkey_name] = sub_values
except FileNotFoundError:
pass
return output
except (FileNotFoundError, TypeError, OSError) as exc:
raise FileNotFoundError('Cannot query registry key [%s]. %s' % (key, exc))
# 768 = 0 | KEY_WOW64_64KEY | KEY_WOW64_32KEY (where 0 = default)
if arch == 768:
result = {}
for _arch in [KEY_WOW64_64KEY, KEY_WOW64_32KEY]:
try:
if combine:
result.update(_get_keys(hive, key, _arch, open_reg, recursion_level, filter_on_names))
else:
return _get_keys(hive, key, _arch, open_reg, recursion_level, filter_on_names)
except FileNotFoundError:
pass
return result
else:
return _get_keys(hive, key, arch, open_reg, recursion_level, filter_on_names)
def get_office_click_and_run_ident():
# type: () -> Optional[str]
"""
Try to find the office product via clickandrun productID
"""
try:
click_and_run_ident = get_value(HKEY_LOCAL_MACHINE,
r'Software\Microsoft\Office\ClickToRun\Configuration',
'ProductReleaseIds',
arch=KEY_WOW64_64KEY |KEY_WOW64_32KEY,)
except FileNotFoundError:
click_and_run_ident = None
return click_and_run_ident
def _get_used_word_version():
# type: () -> Optional[int]
"""
Try do determine which version of Word is used (in case multiple versions are installed)
"""
try:
word_ver = get_value(HKEY_CLASSES_ROOT, r'Word.Application\CurVer', None)
except FileNotFoundError:
word_ver = None
try:
version = int(word_ver.split('.')[2])
except (IndexError, ValueError, AttributeError):
version = None
return version
def _get_installed_office_version():
# type: () -> Optional[str, bool]
"""
Try do determine which is the highest current version of Office installed
"""
for possible_version, _ in KNOWN_VERSIONS.items():
try:
office_keys = get_keys(HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Office\{}'.format(possible_version),
recursion_level=2,
arch=KEY_WOW64_64KEY |KEY_WOW64_32KEY,
combine=True)
try:
is_click_and_run = True if office_keys['ClickToRunStore'] is not None else False
except:
is_click_and_run = False
try:
is_valid = True if office_keys['Word'] is not None else False
if is_valid:
return possible_version, is_click_and_run
except KeyError:
pass
except FileNotFoundError:
pass
return None, None
def get_office_version():
# type: () -> Tuple[str, Optional[str]]
"""
It's plain horrible to get the office version installed
Let's use some tricks, ie detect current Word used
"""
word_version = _get_used_word_version()
office_version, is_click_and_run = _get_installed_office_version()
# Prefer to get used word version instead of installed one
if word_version is not None:
office_version = word_version
version = float(office_version)
click_and_run_ident = get_office_click_and_run_ident()
def _get_office_version():
# type: () -> str
if version:
if version < 16:
try:
return KNOWN_VERSIONS['{}.0'.format(version)]
except KeyError:
pass
# Special hack to determine which of 2016, 2019 or O365 it is
if version == 16:
if isinstance(click_and_run_ident, str):
if '2016' in click_and_run_ident:
return '2016'
if '2019' in click_and_run_ident:
return '2019'
if 'O365' in click_and_run_ident:
return 'O365'
return '2016/2019/O365'
# Let's return whatever we found out
return 'Unknown: {}'.format(version, click_and_run_ident)
if isinstance(click_and_run_ident, str) or is_click_and_run:
click_and_run_suffix = 'ClickAndRun'
else:
click_and_run_suffix = None
return _get_office_version(), click_and_run_suffix
You can than use the code like the following example:
office_version, click_and_run = get_office_version()
print('Office {} {}'.format(office_version, click_and_run))
Remarks
DBMS is the software program that is used to manage all the database that are stored on the network or system hard disk. whereas RDBMS is the database system in which the relationship among different tables are maintained.
Not exactly sure this is what you are asking but you can do something like:
new Thread() {
public void run() {
System.out.println("blah");
}
}.start();
Notice the start()
method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.
Better than creating an anonymous Thread
class is to create an anonymous Runnable
class:
new Thread(new Runnable() {
public void run() {
System.out.println("blah");
}
}).start();
Instead overriding the run()
method in the Thread
you inject a target Runnable
to be run by the new thread. This is a better pattern.
If you use ng > 1.2, here is an example of using ng-repeat-start/end
without generating unnecessary tags:
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script>_x000D_
angular.module('mApp', []);_x000D_
</script>_x000D_
</head>_x000D_
<body ng-app="mApp">_x000D_
<table border="1" width="100%">_x000D_
<tr ng-if="0" ng-repeat-start="elem in [{k: 'A', v: ['a1','a2']}, {k: 'B', v: ['b1']}, {k: 'C', v: ['c1','c2','c3']}]"></tr>_x000D_
_x000D_
<tr>_x000D_
<td rowspan="{{elem.v.length}}">{{elem.k}}</td>_x000D_
<td>{{elem.v[0]}}</td>_x000D_
</tr>_x000D_
<tr ng-repeat="v in elem.v" ng-if="!$first">_x000D_
<td>{{v}}</td>_x000D_
</tr>_x000D_
_x000D_
<tr ng-if="0" ng-repeat-end></tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
The important point: for tags used for ng-repeat-start
and ng-repeat-end
set ng-if="0"
, to let not be inserted in the page. In this way the inner content will be handled exactly as it is in knockoutjs (using commands in <!--...-->
), and there will be no garbage.
[project structure]: http://i.stack.imgur.com/RAGX3.jpg
-------------------------------
package beans;
import java.util.Properties;
import java.util.Set;
public class PropertiesBeans {
private Properties properties;
public void setProperties(Properties properties) {
this.properties = properties;
}
public void getProperty(){
Set keys = properties.keySet();
for (Object key : keys) {
System.out.println(key+" : "+properties.getProperty(key.toString()));
}
}
}
----------------------------
package beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
PropertiesBeans p = (PropertiesBeans)ap.getBean("p");
p.getProperty();
}
}
----------------------------
- driver.properties
Driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test
username = root
password = root
----------------------------
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="p" class="beans.PropertiesBeans">
<property name="properties">
<util:properties location="classpath:resource/driver.properties"/>
</property>
</bean>
</beans>
There is a very simple way for Python 3.5
or + (Actually tested on Python 3.8
)
import subprocess, signal, time
p = subprocess.Popen(['cmd'], shell=True)
time.sleep(5) #Wait 5 secs before killing
p.send_signal(signal.CTRL_C_EVENT)
Then, your code may crash at some point if you have a keyboard input detection, or sth like this. In this case, on the line of code/function where the error is given, just use:
try:
FailingCode #here goes the code which is raising KeyboardInterrupt
except KeyboardInterrupt:
pass
What this code is doing is just sending a "CTRL+C" signal to the running process, what will cause the process to get killed.
In my case I was migrating from 9.5 to 9.6. So to restore a database, I was doing :
sudo -u postgres psql -d databse -f dump.sql
Of course it was executing on the old postgreSQL database where there are datas! If your new instance is on port 5433, the correct way is :
sudo -u postgres psql -d databse -f dump.sql -p 5433
<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;
$.ajax({
type:"GET",
url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
crossDomain:true,
dataType:'jsonp',
success: function jsondata(data)
{
var parsedata=JSON.parse(JSON.stringify(data));
var logindata=parsedata["Status"];
if("sucess"==logindata)
{
alert("success");
}
else
{
alert("failed");
}
}
});
<script>
You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.
To create root password in PHPMyAdmin in UI easy way, you can follow simple steps below:
Click on root > Edit privileges
Then click on Change password
Enter your desired password -> Go
Logout and log-in again with new password
If you installed rspec as a plugin rather than as a gem, then you won't have the spec
executable.
At any rate, All you need to do is run the file using ruby. The rspec code is clever enough to run the tests for you.
eg:
ruby myclass_spec.rb
$ git remote add origin https://github.com/git/git.git
--- You will run this command to link your github project to origin. Here origin is user-defined.
You can rename it by $ git remote rename old-name new-name
$ git fetch origin
- Downloads objects and refs from remote repository to your local computer [origin/master]. That means it will not affect your local master branch unless you merge them using $ git merge origin/master
. Remember to checkout the correct branch where you need to merge before run this command
Note: Fetched content is represented as a remote branch. Fetch gives you a chance to review changes before integrating them into your copy of the project. To show changes between yours and remote $git diff master..origin/master
<?php
$val = $myService->getValue(); // Makes an API and database call
echo "
<script>
myPlugin.start({$val});
</script> ";
?>
Try the below
select Convert(Varchar(50),yourcolumn,103) as Converted_Date from yourtbl
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
From the docs:
"a UNIQUE index permits multiple NULL values for columns that can contain NULL"
This applies to all engines but BDB.
Just for people stopping by and what to have a random string in just one single line of code
int yourRandomStringLength = 12; //maximum: 32
Guid.NewGuid().ToString("N").Substring(0, yourRandomStringLength);
PS: Please keep in mind that yourRandomStringLength
cannot exceed 32 as Guid
has max length of 32.
val array2 = array :+ 4
//Array(1, 2, 3, 4)
Works also "reversed":
val array2 = 4 +: array
Array(4, 1, 2, 3)
There is also an "in-place" version:
var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)
In my case i had to load images on radio button click,
I just uses the regular onclick
event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
You can use indexOf(). Like:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.indexOf("brown");
alert(a);
The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.
If you want to search from end to start, use the lastIndexOf() method:
var Color = ["blue", "black", "brown", "gold"];
var a = Color.lastIndexOf("brown");
alert(a);
The search will start at the specified position, or at the end if no start position is specified, and end the search at the beginning of the array.
Returns -1 if the item is not found.
Also have a look into the built-in DataFrame.filter
function.
Minimalistic but greedy approach (sufficient for the given df):
df.filter(regex="[^BD]")
Conservative/lazy approach (exact matches only):
df.filter(regex="^(?!(B|D)$).*$")
Conservative and generic:
exclude_cols = ['B','C']
df.filter(regex="^(?!({0})$).*$".format('|'.join(exclude_cols)))
Change
<serviceMetadata httpsGetEnabled="true"/>
to
<serviceMetadata httpsGetEnabled="false"/>
You're telling WCF to use https for the metadata endpoint and I see that your'e exposing your service on http, and then you get the error in the title.
You also have to set <security mode="None" />
if you want to use HTTP as your URL suggests.
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
If your grep
supports Perl regular expression with -P
option you can do (if bash; if tcsh you'll need to escape the !
):
grep -P '(?!.*unwanted_word)keyword' file
Demo:
$ cat file
foo1
foo2
foo3
foo4
bar
baz
Let us now list all foo
except foo3
$ grep -P '(?!.*foo3)foo' file
foo1
foo2
foo4
$
To check if a string is empty or contains only whitespace you could use:
shopt -s extglob # more powerful pattern matching
if [ -n "${str##+([[:space:]])}" ]; then
echo '$str is not null or space'
fi
See Shell Parameter Expansion and Pattern Matching in the Bash Manual.
This may be of help to a few who are struggling like I was:
var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];
Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.
I have an automatically updated last_modified field, defined as:
`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC
SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`
In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.
Run this twice, first without setting the time_zone.
Here's a way that does it using the built-in ellipsis setting, and adds the title
attribute on-demand (with jQuery) building on Martin Smith's comment:
$('.mightOverflow').bind('mouseenter', function(){
var $this = $(this);
if(this.offsetWidth < this.scrollWidth && !$this.attr('title')){
$this.attr('title', $this.text());
}
});
use .val()
, it will return the value of the <input>
$("#spa").val().length > 0
And you had a typo, length
not lenght
.
If your page is refreshed on submitting - yes, but only through the querystring: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx (You must use method "GET" then). Else, you can return its value from the php script.
building on XGreen's approach above, with a few tweaks you can have an animated looping background. See here for example:
$(document).ready(function(){
var images = Array("http://placekitten.com/500/200",
"http://placekitten.com/499/200",
"http://placekitten.com/501/200",
"http://placekitten.com/500/199");
var currimg = 0;
function loadimg(){
$('#background').animate({ opacity: 1 }, 500,function(){
//finished animating, minifade out and fade new back in
$('#background').animate({ opacity: 0.7 }, 100,function(){
currimg++;
if(currimg > images.length-1){
currimg=0;
}
var newimage = images[currimg];
//swap out bg src
$('#background').css("background-image", "url("+newimage+")");
//animate fully back in
$('#background').animate({ opacity: 1 }, 400,function(){
//set timer for next
setTimeout(loadimg,5000);
});
});
});
}
setTimeout(loadimg,5000);
});
The answer is a simple PowerShell
one-liner:
Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A
If you only want to pull the UNC
for one particular drive, add a where statement:
Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:' | ft "RemoteName","LocalName" -A
Also you might want to log in via browser and get the command with all headers including cookies:
Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".
(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:
$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();
Oh, also: count()
instead if exists
but this could be something used after get
.
This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!
randomFill()
to the current location of the array.Note: Your array is double
, but you are returning int
s from randomFill
. So there's something you need to fix there.
Bass can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..
You can do something like this:
int min_num = INT_MAX; // 2^31-1
int max_num = INT_MIN; // -2^31
int input;
while (!std::cin.eof()) {
std::cin >> input;
min_num = min(input, min_num);
max_num = max(input, max_num);
}
cout << "min: " << min_num;
cout << "max: " << max_num;
This reads numbers from standard input until eof (it does not care how many you have - 5 or 1,000,000).
Since git 1.8 you can do
git submodule update --remote --merge
This will update the submodule to the latest remote commit. You will then need to commit the change so the gitlink in the parent repository is updated
git commit
And then push the changes as without this, the SHA-1 identity the pointing to the submodule won't be updated and so the change won't be visible to anyone else.
Given an activated Python 3.6 virtualenv in somepath/venv, the following aliases resolved the various issues on a macOS Sierra where pip insisted on pointing to Apple's 2.7 Python.
alias pip='python somepath/venv/lib/python3.6/site-packages/pip/__main__.py'
This didn't work so well when I had to do sudo pip
as the root user doesn't know anything about my alias or the virtualenv, so I had to add an extra alias to handle this as well. It's a hack, but it works, and I know what it does:
alias sudopip='sudo somepath/venv/bin/python somepath/venv/lib/python3.6/site-packages/pip/__main__.py'
pip3 did not exist to start (command not found) with and which pip
would return /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/pip, the Apple Python.
Python 3.6 was installed via macports.
After activation of the 3.6 virtualenv I wanted to work with, which python
would return somepath/venv/bin/python
Somehow pip install
would do the right thing and hit my virtualenv, but pip list
would rattle off Python 2.7 packages.
For Python, this is batting way beneath my expectations in terms of beginner-friendliness.
I had the same problem and it was due to several installations of cygwin.
Check the link (the icon) that you click on to start the terminal. In case it does not point to the directory of your updated cygwin installation, you have the wrong installation of cygwin. When updating, double check the location of cygwin, and start exactly this instance of cygwin.
As with @Kametrixom answer here I believe returning an array would be better than returning AnySequence, since you can have access to all of Array's goodies such as count, etc.
Here's the re-write:
public protocol EnumCollection : Hashable {}
extension EnumCollection {
public static func allValues() -> [Self] {
typealias S = Self
let retVal = AnySequence { () -> AnyGenerator<S> in
var raw = 0
return AnyGenerator {
let current : Self = withUnsafePointer(&raw) { UnsafePointer($0).memory }
guard current.hashValue == raw else { return nil }
raw += 1
return current
}
}
return [S](retVal)
}
}
Also make sure you don't miss the dnrTV webcast show that Carl Franklin (the man behind .NET rocks) publishes. Even if it's a not a podcast and requires a more attention while watching it it's really informative and if you're into .NET and Microsoft related techniques you'll learn a lot.
As a completion to Gustavo Bezerra's answer:
If you want each histogram to be normalized (normed
for mpl<=2.1 and density
for mpl>=3.1) you cannot just use normed/density=True
, you need to set the weights for each value instead:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
x_w = np.empty(x.shape)
x_w.fill(1/x.shape[0])
y_w = np.empty(y.shape)
y_w.fill(1/y.shape[0])
bins = np.linspace(-10, 10, 30)
plt.hist([x, y], bins, weights=[x_w, y_w], label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()
As a comparison, the exact same x
and y
vectors with default weights and density=True
:
Do you mean the mysql text console? Then:
START TRANSACTION;
...
your queries.
...
COMMIT;
Is what I recommend.
However if you want to avoid typing this each time you need to run this sort of query, add the following to the [mysqld] section of your my.cnf file.
init_connect='set autocommit=0'
This would set autocommit
to be off for every client though.
by using replaceChild():
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
the OOP way to do this in ES5 is to make that variable into a property using the this keyword.
function first(){
this.nameContent=document.getElementById('full_name').value;
}
function second() {
y=new first();
alert(y.nameContent);
}
I found passing variables from $routeProvider usefull.
For example, you use one controller MyController for multiple screens, passing some very important variable "mySuperConstant" inside.
Use that simple structure:
Router:
$routeProvider
.when('/this-page', {
templateUrl: 'common.html',
controller: MyController,
mySuperConstant: "123"
})
.when('/that-page', {
templateUrl: 'common.html',
controller: MyController,
mySuperConstant: "456"
})
.when('/another-page', {
templateUrl: 'common.html',
controller: MyController,
mySuperConstant: "789"
})
MyController:
MyController: function ($scope, $route) {
var mySuperConstant: $route.current.mySuperConstant;
alert(mySuperConstant);
}
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
From a sqlite prompt:
sqlite> .read db.sql
Or:
cat db.sql | sqlite3 database.db
Also, your SQL is invalid - you need ;
on the end of your statements:
create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);
Small modification to the code I found in bitbucket
Code is now able to select/highlight with start/end points if given 2 positions. Tested and works fine in FF/Chrome/IE9/Opera.
$('#field').caret(1, 9);
The code is listed below, only a few lines changed:
(function($) {
$.fn.caret = function(pos) {
var target = this[0];
if (arguments.length == 0) { //get
if (target.selectionStart) { //DOM
var pos = target.selectionStart;
return pos > 0 ? pos : 0;
}
else if (target.createTextRange) { //IE
target.focus();
var range = document.selection.createRange();
if (range == null)
return '0';
var re = target.createTextRange();
var rc = re.duplicate();
re.moveToBookmark(range.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
else return 0;
}
//set
var pos_start = pos;
var pos_end = pos;
if (arguments.length > 1) {
pos_end = arguments[1];
}
if (target.setSelectionRange) //DOM
target.setSelectionRange(pos_start, pos_end);
else if (target.createTextRange) { //IE
var range = target.createTextRange();
range.collapse(true);
range.moveEnd('character', pos_end);
range.moveStart('character', pos_start);
range.select();
}
}
})(jQuery)
not nearly as concise as the link you provided: but the following chapter 14 - 24 may help :) hehe
Complete reference is not available for the mentioned files, as they are extensible by various plug-ins.
Basically, .project files store project-settings, such as builder and project nature settings, while .classpath files define the classpath to use during running. The classpath files contains src and target entries that correspond with folders in the project; the con entries are used to describe some kind of "virtual" entries, such as the JVM libs or in case of eclipse plug-ins dependencies (normal Java project dependencies are displayed differently, using a special src entry).
function supportFullCss3()
{
var div = document.createElement("div");
div.style.display = 'flex';
var s1 = div.style.display == 'flex';
var s2 = 'perspective' in div.style;
return (s1 && s2);
};
function getZoomLevel()
{
var screenPixelRatio = 0, zoomLevel = 0;
if(window.devicePixelRatio && supportFullCss3())
screenPixelRatio = window.devicePixelRatio;
else if(window.screenX == '0')
screenPixelRatio = (window.outerWidth - 8) / window.innerWidth;
else
{
var scr = window.frames.screen;
screenPixelRatio = scr.deviceXDPI / scr.systemXDPI;
}
//---------------------------------------
if (screenPixelRatio <= .11){ //screenPixelRatio >= .01 &&
zoomLevel = "-7";
} else if (screenPixelRatio <= .25) {
zoomLevel = "-6";
}else if (screenPixelRatio <= .33) {
zoomLevel = "-5.5";
} else if (screenPixelRatio <= .40) {
zoomLevel = "-5";
} else if (screenPixelRatio <= .50) {
zoomLevel = "-4";
} else if (screenPixelRatio <= .67) {
zoomLevel = "-3";
} else if (screenPixelRatio <= .75) {
zoomLevel = "-2";
} else if (screenPixelRatio <= .85) {
zoomLevel = "-1.5";
} else if (screenPixelRatio <= .98) {
zoomLevel = "-1";
} else if (screenPixelRatio <= 1.03) {
zoomLevel = "0";
} else if (screenPixelRatio <= 1.12) {
zoomLevel = "1";
} else if (screenPixelRatio <= 1.2) {
zoomLevel = "1.5";
} else if (screenPixelRatio <= 1.3) {
zoomLevel = "2";
} else if (screenPixelRatio <= 1.4) {
zoomLevel = "2.5";
} else if (screenPixelRatio <= 1.5) {
zoomLevel = "3";
} else if (screenPixelRatio <= 1.6) {
zoomLevel = "3.3";
} else if (screenPixelRatio <= 1.7) {
zoomLevel = "3.7";
} else if (screenPixelRatio <= 1.8) {
zoomLevel = "4";
} else if (screenPixelRatio <= 1.9) {
zoomLevel = "4.5";
} else if (screenPixelRatio <= 2) {
zoomLevel = "5";
} else if (screenPixelRatio <= 2.1) {
zoomLevel = "5.2";
} else if (screenPixelRatio <= 2.2) {
zoomLevel = "5.4";
} else if (screenPixelRatio <= 2.3) {
zoomLevel = "5.6";
} else if (screenPixelRatio <= 2.4) {
zoomLevel = "5.8";
} else if (screenPixelRatio <= 2.5) {
zoomLevel = "6";
} else if (screenPixelRatio <= 2.6) {
zoomLevel = "6.2";
} else if (screenPixelRatio <= 2.7) {
zoomLevel = "6.4";
} else if (screenPixelRatio <= 2.8) {
zoomLevel = "6.6";
} else if (screenPixelRatio <= 2.9) {
zoomLevel = "6.8";
} else if (screenPixelRatio <= 3) {
zoomLevel = "7";
} else if (screenPixelRatio <= 3.1) {
zoomLevel = "7.1";
} else if (screenPixelRatio <= 3.2) {
zoomLevel = "7.2";
} else if (screenPixelRatio <= 3.3) {
zoomLevel = "7.3";
} else if (screenPixelRatio <= 3.4) {
zoomLevel = "7.4";
} else if (screenPixelRatio <= 3.5) {
zoomLevel = "7.5";
} else if (screenPixelRatio <= 3.6) {
zoomLevel = "7.6";
} else if (screenPixelRatio <= 3.7) {
zoomLevel = "7.7";
} else if (screenPixelRatio <= 3.8) {
zoomLevel = "7.8";
} else if (screenPixelRatio <= 3.9) {
zoomLevel = "7.9";
} else if (screenPixelRatio <= 4) {
zoomLevel = "8";
} else if (screenPixelRatio <= 4.1) {
zoomLevel = "8.1";
} else if (screenPixelRatio <= 4.2) {
zoomLevel = "8.2";
} else if (screenPixelRatio <= 4.3) {
zoomLevel = "8.3";
} else if (screenPixelRatio <= 4.4) {
zoomLevel = "8.4";
} else if (screenPixelRatio <= 4.5) {
zoomLevel = "8.5";
} else if (screenPixelRatio <= 4.6) {
zoomLevel = "8.6";
} else if (screenPixelRatio <= 4.7) {
zoomLevel = "8.7";
} else if (screenPixelRatio <= 4.8) {
zoomLevel = "8.8";
} else if (screenPixelRatio <= 4.9) {
zoomLevel = "8.9";
} else if (screenPixelRatio <= 5) {
zoomLevel = "9";
}else {
zoomLevel = "unknown";
}
return zoomLevel;
};
You have to create an item of type ListBoxItem and add that to the Items collection:
list.Items.add( new ListBoxItem("clan", "sifOsoba"));
As to formulas being "updated" in the new row, since all the copying occurs after the shift, the old row (now one index up from the new row) has already had its formula shifted, so copying it to the new row will make the new row reference the old rows cells. A solution would be to parse out the formulas BEFORE the shift, then apply those (a simple String array would do the job. I'm sure you can code that in a few lines).
At start of function:
ArrayList<String> fArray = new ArrayList<String>();
Row origRow = sheet.getRow(sourceRow);
for (int i = 0; i < origRow.getLastCellNum(); i++) {
if (origRow.getCell(i) != null && origRow.getCell(i).getCellType() == Cell.CELL_TYPE_FORMULA)
fArray.add(origRow.getCell(i).getCellFormula());
else fArray.add(null);
}
Then when applying the formula to a cell:
newCell.setCellFormula(fArray.get(i));
To check multiple values, you can use numpy.in1d(), which is an element-wise function version of the python keyword in. If your data is sorted, you can use numpy.searchsorted():
import numpy as np
data = np.array([1,4,5,5,6,8,8,9])
values = [2,3,4,6,7]
print np.in1d(values, data)
index = np.searchsorted(data, values)
print data[index] == values
@recursive's solusion (The accepted answer) is 100% right. I am just adding a sample code for your reference.
My case is to display price with two decimal digits.This is part of back-end response: "price": 2300, "currencySymbol": "CD", ...
.
This is my helper class:
public class CurrencyUtils
{
private static final String[] suffix = { "", "K", "M" };
public static String getCompactStringForDisplay(final int amount)
{
int suffixIndex;
if (amount >= 1_000_000) {
suffixIndex = 2;
} else if (amount >= 1_000) {
suffixIndex = 1;
} else {
suffixIndex = 0;
}
int quotient;
int remainder;
if (amount >= 1_000_000) {
quotient = amount / 1_000_000;
remainder = amount % 1_000_000;
} else if (amount >= 1_000) {
quotient = amount / 1_000;
remainder = amount % 1_000;
} else {
return String.valueOf(amount);
}
if (remainder == 0) {
return String.valueOf(quotient) + suffix[suffixIndex];
}
// Keep two most significant digits
if (remainder >= 10_000) {
remainder /= 10_000;
} else if (remainder >= 1_000) {
remainder /= 1_000;
} else if (remainder >= 100) {
remainder /= 10;
}
return String.valueOf(quotient) + '.' + String.valueOf(remainder) + suffix[suffixIndex];
}
}
This is my test class (based on Junit 4):
public class CurrencyUtilsTest {
@Test
public void getCompactStringForDisplay() throws Exception {
int[] numbers = {0, 5, 999, 1_000, 5_821, 10_500, 101_800, 2_000_000, 7_800_000, 92_150_000, 123_200_000, 9_999_999};
String[] expected = {"0", "5", "999", "1K", "5.82K", "10.50K", "101.80K", "2M", "7.80M", "92.15M", "123.20M", "9.99M"};
for (int i = 0; i < numbers.length; i++) {
int n = numbers[i];
String formatted = CurrencyUtils.getCompactStringForDisplay(n);
System.out.println(n + " => " + formatted);
assertEquals(expected[i], formatted);
}
}
}
In case of Java 8 you can do:
int n = 4;
String existing = "...";
String result = existing + String.join("", Collections.nCopies(n, "*"));
Output:
...****
In Java 8 the String.join
method was added. But Collections.nCopies
is even in Java 5.
Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.
If you already have a dictionary, a counter can easily be formed by:
c = Counter(d['123'])
as an example from your data.
The most_common
function allows easy access to descending order of the items in the counter
The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
The stash command will stash any changes you have made since your last commit. In your case there is no reason to stash if you are gonna continue working on it the next day. I would only use stash to undo changes that you don't want to commit.
DELETE FROM on_search
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))
Absolutely - you basically want:
var results = from p in persons
group p.car by p.PersonId into g
select new { PersonId = g.Key, Cars = g.ToList() };
Or as a non-query expression:
var results = persons.GroupBy(
p => p.PersonId,
p => p.car,
(key, g) => new { PersonId = key, Cars = g.ToList() });
Basically the contents of the group (when viewed as an IEnumerable<T>
) is a sequence of whatever values were in the projection (p.car
in this case) present for the given key.
For more on how GroupBy
works, see my Edulinq post on the topic.
(I've renamed PersonID
to PersonId
in the above, to follow .NET naming conventions.)
Alternatively, you could use a Lookup
:
var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);
You can then get the cars for each person very easily:
// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];
use "Content-type: application/x-www-form-urlencoded" instead of "application/json"
If I understand your request correctly, you have to do the following:
public class Section
{
public String Head
{
get
{
return SubHead.LastOrDefault();
}
set
{
SubHead.Add(value);
}
public List<string> SubHead { get; private set; }
public List<string> Content { get; private set; }
}
You use it like this:
var section = new Section();
section.Head = "Test string";
Now "Test string" is added to the subHeads collection and will be available through the getter:
var last = section.Head; // last will be "Test string"
Hope I understood you correctly.
I followed brain storm's instructions and still wasn't getting different results - any new terminal windows would not recognize the mvn command. I don't know why, but breaking out the declarations in smaller chunks .bash_profile worked. As far as I can tell, I'm essentially doing the same thing he did. Here's what looks different in my .bash_profile:
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home
export PATH JAVA_HOME
J2=$JAVA_HOME/bin
export PATH J2
M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
export PATH M2_HOME
M2=$M2_HOME/bin
export PATH M2
There are many plugins for doing that. I normally use datatables it works great. http://datatables.net/
You are printing the enum object. Use the .value
attribute if you wanted just to print that:
print(D.x.value)
See the Programmatic access to enumeration members and their attributes section:
If you have an enum member and need its name or value:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
You could add a __str__
method to your enum, if all you wanted was to provide a custom string representation:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
Demo:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);
Providing javac
is set up through /etc/alternatives/javac
, you can add to your .bash_profile:
JAVA_HOME=$(l=$(which javac) ; while : ; do nl=$(readlink ${l}) ; [ "$nl" ] || break ; l=$nl ; done ; echo $(cd $(dirname $l)/.. ; pwd) )
export JAVA_HOME
This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):
class CameraControl {
zoomMode: boolean = false
press: boolean = false
sensitivity: number = 0.02
constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
renderer.domElement.addEventListener('mousemove', event => {
if(!this.press){ return }
if(event.button == 0){
camera.position.y -= event.movementY * this.sensitivity
camera.position.x -= event.movementX * this.sensitivity
} else if(event.button == 2){
camera.quaternion.y -= event.movementX * this.sensitivity/10
camera.quaternion.x -= event.movementY * this.sensitivity/10
}
updateCallback()
})
renderer.domElement.addEventListener('mousedown', () => { this.press = true })
renderer.domElement.addEventListener('mouseup', () => { this.press = false })
renderer.domElement.addEventListener('mouseleave', () => { this.press = false })
document.addEventListener('keydown', event => {
if(event.key == 'Shift'){
this.zoomMode = true
}
})
document.addEventListener('keyup', event => {
if(event.key == 'Shift'){
this.zoomMode = false
}
})
renderer.domElement.addEventListener('mousewheel', event => {
if(this.zoomMode){
camera.fov += event.wheelDelta * this.sensitivity
camera.updateProjectionMatrix()
} else {
camera.position.z += event.wheelDelta * this.sensitivity
}
updateCallback()
})
}
}
drop it in like:
this.cameraControl = new CameraControl(renderer, camera, () => {
// you might want to rerender on camera update if you are not rerendering all the time
window.requestAnimationFrame(() => renderer.render(scene, camera))
})
Controls:
Additionally:
If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:
// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)
What I would do is put a span inside the <a>
tag, set the span to block, and add size to the span, or just apply the styling to the <a>
tag. Definitely handle the positioning in the <a>
tag style. Add an onclick event
to the a where
JavaScript will catch the event, then return false at the end of the JavaScript event to prevent default action of the href
and bubbling of the click. This works in cases with or without JavaScript enabled, and any AJAX can be handled in the Javascript listener.
If you're using jQuery, you can use this as your listener and omit the onclick
in the a
tag.
$('#idofdiv').live("click", function(e) {
//add stuff here
e.preventDefault; //or use return false
});
this allows you to attach listeners to any changed elements as necessary.
printf("%.*s\n",n,(char *) memset(buffer,c,n));
n
<= sizeof(buffer)
[ maybe also n < 2^16]
However the optimizer may change it to puts(buffer)
and then the lack of EoS will .....
And the assumption is that memset is an assembler instruction (but still a loop be it on chip).
Strictly seen there is no solution given you precondition 'No loop'.
You can also use a small function that will loop through and remove any spaces.
This is very clean and simple.
Public Shared Function RemoveXtraSpaces(strVal As String) As String
Dim iCount As Integer = 1
Dim sTempstrVal As String
sTempstrVal = ""
For iCount = 1 To Len(strVal)
sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
Next
RemoveXtraSpaces = sTempstrVal
Return RemoveXtraSpaces
End Function
There is, of course, another way to do this which has not been discussed in this thread, i.e. by way of inheritance of the class containing the TestMethod. In the following example, only one TestMethod has been defined but two test cases have been made.
In Visual Studio 2012, it creates two tests in the TestExplorer:
DemoTest_A12_B4.test
public class Demo
{
int a, b;
public Demo(int _a, int _b)
{
this.a = _a;
this.b = _b;
}
public int Sum()
{
return this.a + this.b;
}
}
public abstract class DemoTestBase
{
Demo objUnderTest;
int expectedSum;
public DemoTestBase(int _a, int _b, int _expectedSum)
{
objUnderTest = new Demo(_a, _b);
this.expectedSum = _expectedSum;
}
[TestMethod]
public void test()
{
Assert.AreEqual(this.expectedSum, this.objUnderTest.Sum());
}
}
[TestClass]
public class DemoTest_A12_B4 : DemoTestBase
{
public DemoTest_A12_B4() : base(12, 4, 16) { }
}
public abstract class DemoTest_B10_Base : DemoTestBase
{
public DemoTest_B10_Base(int _a) : base(_a, 10, _a + 10) { }
}
[TestClass]
public class DemoTest_B10_A5 : DemoTest_B10_Base
{
public DemoTest_B10_A5() : base(5) { }
}
Maybe remove the semi-colon after set because now the where statement doesn't belong to the update statement. Also the idRequest
could be a problem, better write BookingRequest.idRequest
One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.
public void ImportCsvFile(string filename)
{
FileInfo file = new FileInfo(filename);
using (OleDbConnection con =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
file.DirectoryName + "\";
Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
{
using (OleDbCommand cmd = new OleDbCommand(string.Format
("SELECT * FROM [{0}]", file.Name), con))
{
con.Open();
// Using a DataReader to process the data
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// Process the current reader entry...
}
}
// Using a DataTable to process the data
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
DataTable tbl = new DataTable("MyTable");
adp.Fill(tbl);
foreach (DataRow row in tbl.Rows)
{
// Process the current row...
}
}
}
}
}
Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.
' Assume that the code name the worksheet is Sheet1
' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)
' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"
Just discovered this:
SELECT * FROM OPENROWSET(BULK N'<PATH_TO_FILE>', SINGLE_CLOB) AS Contents
It'll pull in the contents of the file as varchar(max). Replace SINGLE_CLOB
with:
SINGLE_NCLOB
for nvarchar(max)
SINGLE_BLOB
for varbinary(max)
Thanks to http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/ for this!
There is no need to involve any image classes, you can simply call WebClient.DownloadFile
:
string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}
Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download oit
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
In brief, it makes a request for the file, verifies that the response code is one of OK
, Moved
or Redirect
and also that the ContentType
is an image. If those conditions are true, the file is downloaded.
If you can live with 3. and 3.0 appearing as "3.0", a very simple approach that right-strips zeros from float representations:
print("%s"%3.140)
(thanks @ellimilial for pointing out the exceptions)
break
interacts solely with the closest enclosing loop or switch, whether it be a for
, while
or do .. while
type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, continue
and break
interact with virtual labels automatically placed by the compiler. This is similar to what return
does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding break
as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that G
would cause a jump to I
, but it jumps to J
. The intended function would use if (!G) H;
instead.
Node.js is a runtime that compiles and executes javaScript. It can be used to develop application that runs end-to-end in JavaScript i..e both client side and server side uses javascript code unlike most of todays' application with rich client framework (angularJs, extJs) and RESTful server side APIs
I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.
Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.
NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)
For short strings, strtol
, strtoll
, and strtoimax
will work just fine (note that the third argument is the base to use in processing the string...set it to 16). If your input is longer than number-of-bits-in-the-longest-integer-type/4
then you'll need one of the more flexible methods suggested by other answers.
Here is a VB.NET solution based on ShravankumarKumar's solution.
This will ONLY give you the text. The images are a different story.
Public Shared Function GetTextFromPDF(PdfFileName As String) As String
Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)
Dim sOut = ""
For i = 1 To oReader.NumberOfPages
Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy
sOut &= iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)
Next
Return sOut
End Function
If you are looking for 10 and only 10 digits, ignore everything but the digits-
return value.match(/\d/g).length===10;
select with no lock - will select records which may / may not going to be inserted. you will read a dirty data.
for example - lets say a transaction insert 1000 rows and then fails.
when you select - you will get the 1000 rows.
This also work proper in chrome and internet Explorer
$("#MainContent_cmbEvalStatus").prop("selectedIndex", 1).change();
Put according your choice possition value of DropDown 0,1,2,3,4.....
The first answer you posted (System is a built-in class...) is pretty spot on.
You can add that the System
class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out
printstream to the native output stream associated with the "standard out" (console).
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxImage.Checked)
{
groupBoxImage.Show();
}
else if (!checkBoxImage.Checked)
{
groupBoxImage.Hide();
}
}
Am Using windows Operating system.
I killed all the node process and restarted the app it worked.
try
taskkill /im node.exe
I know this question is 5+ years old, and the given answers are good, but I wanted something a bit more powerful for express, so i created the express-map2
package for npm. I was going to name it simply express-map
, however the people at yahoo already have a package with that name, so i had to rename my package.
1. basic usage:
app.js (or whatever you call it)
var app = require('express'); // 1. include express
app.set('controllers',__dirname+'/controllers/');// 2. set path to your controllers.
require('express-map2')(app); // 3. patch map() into express
app.map({
'GET /':'test',
'GET /foo':'middleware.foo,test',
'GET /bar':'middleware.bar,test'// seperate your handlers with a comma.
});
controller usage:
//single function
module.exports = function(req,res){
};
//export an object with multiple functions.
module.exports = {
foo: function(req,res){
},
bar: function(req,res){
}
};
2. advanced usage, with prefixes:
app.map('/api/v1/books',{
'GET /': 'books.list', // GET /api/v1/books
'GET /:id': 'books.loadOne', // GET /api/v1/books/5
'DELETE /:id': 'books.delete', // DELETE /api/v1/books/5
'PUT /:id': 'books.update', // PUT /api/v1/books/5
'POST /': 'books.create' // POST /api/v1/books
});
As you can see, this saves a ton of time and makes the routing of your application dead simple to write, maintain, and understand. it supports all of the http verbs that express supports, as well as the special .all()
method.
There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:
<input type="hidden" name="type" value="<?= $var ?>" >
which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:
<?= $var1, $var2 ?>
<?php echo $var1, $var2 ?>
That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.
I also encountered same problem. I do not know why, i just add -lpthread
option to compiler and everything ok.
Old:
$ g++ -rdynamic -m64 -fPIE -pie -o /tmp/node/out/Release/mksnapshot ...*.o *.a -ldl -lrt
got following error. If i append -lpthread
option to above command then OK.
/usr/bin/ld: /tmp/node/out/Release/obj.host/v8_libbase/deps/v8/src/base/platform/condition-variable.o: undefined reference to symbol 'pthread_condattr_setclock@@GLIBC_2.3.3'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
You dont inherit in css, you simply add another class to the element which overrides the values
.base{
color:green;
...other props
}
.basealt{
color:red;
}
<span class="base basealt"></span>
install exceljs and use the following code,
var Excel = require('exceljs');
var wb = new Excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'sample.xlsx');
wb.xlsx.readFile(filePath).then(function(){
var sh = wb.getWorksheet("Sheet1");
sh.getRow(1).getCell(2).value = 32;
wb.xlsx.writeFile("sample2.xlsx");
console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);
console.log(sh.rowCount);
//Get all the rows data [1st and 2nd column]
for (i = 1; i <= sh.rowCount; i++) {
console.log(sh.getRow(i).getCell(1).value);
console.log(sh.getRow(i).getCell(2).value);
}
});
If all vectors have equal size, create a matrix and plot it.
Each column is plotted with a different color automatically
Then you can use legend
to indicate columns:
data = randn(100, 5);
figure;
plot(data);
legend(cellstr(num2str((1:size(data,2))')))
Or, if you have a cell with kernels names, use
legend(names)
Example: http://jsfiddle.net/kCpNQ/
var myString = "0String";
if( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
If there could be several 0
characters at the beginning, you can change the if()
to a while()
.
Example: http://jsfiddle.net/kCpNQ/1/
var myString = "0000String";
while( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
The ASHOT framework from Yandex can be used for taking screenshots in Selenium WebDriver scripts for
This framework can be found on https://github.com/yandex-qatools/ashot.
The code for taking the screenshots is very straightforward:
ENTIRE PAGE
screenshot = new AShot().shootingStrategy(
new ViewportPastingStrategy(1000)).takeScreenshot(driver);
ImageIO.write(screenshot.getImage(), "PNG", new File("c:\\temp\\results.png"));
SPECIFIC WEB ELEMENT
screenshot = new AShot().takeScreenshot(driver,
driver.findElement(By.xpath("(//div[@id='ct_search'])[1]")));
ImageIO.write(screenshot.getImage(), "PNG", new File("c:\\temp\\div_element.png"));
See more details and more code samples on this article.
<?xml version="1.0" encoding="utf-8"?>
<gradient
android:angle="90"
android:startColor="@color/colorPrimary"
android:endColor="@color/colorPrimary"
android:centerColor="@color/white"
android:type="linear"/>
<corners android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topRightRadius="10dp"
android:topLeftRadius="10dp"/>
You could always add it to your Connection String:
connect timeout=180;
You can do this easily in vanilla JS:
Using find
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.find(obj => {_x000D_
return obj.description === view;_x000D_
}).id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
Using filter
(original answer)
const savedViews = [{"description":"object1","id":1},{"description":"object2","id":2},{"description":"object3","id":3},{"description":"object4","id":4}];_x000D_
_x000D_
const view = 'object2';_x000D_
_x000D_
const delete_id = savedViews.filter(function (el) {_x000D_
return el.description === view;_x000D_
})[0].id;_x000D_
_x000D_
console.log(delete_id);
_x000D_
Converted the input file to include \N
for the blank column data using the below sed command in UNix terminal:
sed -i 's/,,/,\\N,/g' $file_name
and then use LOAD DATA INFILE
command to load to mysql
@Override
public void onBackPressed() {
Intent intent = new Intent(this,DesiredActivity.class);
startActivity(intent);
super.onBackPressed();
}
Here is a complete tutorial how to make it quickly if you need to make worgking again a website after PHP upgrade. I used it after upgrading hosting for my customers from 5.4 (OMG!!!) to 7.x PHP version.
This is a workaround and it is better to rewrite all code using PDO or mysqli Class.
First of all, you need to put the connection to a new variable $link
or $con
, or whatever you want.
Example
Change the connection from :
@mysql_connect($host, $username, $password) or die("Error message...");
@mysql_select_db($db);
or
@mysql_connect($host, $username, $password, $db) or die("Error message...");
to:
$con = mysqli_connect($host, $username, $password, $db) or die("Error message...");
With Notepad++ I use "Find in files" (Ctrl + Shift + f) :
in the following order I choose "Replace in Files" :
mysql_query( -> mysqli_query($con,
mysql_error() -> mysqli_error($con)
mysql_close() -> mysqli_close($con)
mysql_insert_id() -> mysqli_insert_id($con)
mysql_real_escape_string( -> mysqli_real_escape_string($con,
mysql_ -> mysqli_
if you get errors it is maybe because your $con is not accessible from your functions.
You need to add a global $con;
in all your functions, for example :
function my_function(...) {
global $con;
...
}
In SQL class, you will put connection to $this->con
instead of $con
. and replace it in each functions call (for example : mysqli_query($con, $query);
)
Add a Button
and on click of the Button
add this code:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
Useful links:
Copy all .dll from /bin in System32
FIRST OF ALL KNOW THE REASON WHY ECLIPSE IS DOING SO.
Date has only one constructor Date(long date) which asks for date in long data type.
The constructor you are using
Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
Thats why eclipse tells that this function is not good.
See this official docs
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Deprecated methods from your context -- Source -- http://www.coderanch.com/t/378728/java/java/Deprecated-methods
There are a number of reasons why a method or class may become deprecated. An API may not be easily extensible without breaking backwards compatibility, and thus be superseded by a more powerful API (e.g., java.util.Date has been deprecated in favor of Calendar, or the Java 1.0 event model). It may also simply not work or produce incorrect results under certain circumstances (e.g., some of the java.io stream classes do not work properly with some encodings). Sometimes an API is just ill-conceived (SingleThreadModel in the servlet API), and gets replaced by nothing. And some of the early calls have been replaced by "Java Bean"-compatible methods (size by getSize, bounds by getBounds etc.)
SEVRAL SOLUTIONS ARE THERE JUST GOOGLE IT--
You can use date(long date) By converting your date String into long milliseconds and stackoverflow has so many post for that purpose.
$(this).parent().parent().attr('id');
Is how you would get the id of the parent's parent.
EDIT:
$(this).closest('ul').attr('id');
Is a more foolproof solution for your case.
You need to use %2.6f
instead of %f
in your printf statement
I am on mingw bash, so I have created ~.profile file with following: alias atom='~/AppData/Local/atom/bin/atom'
You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:
ifstream file(argv[1]);
if (!file)
{
// Can't open file
}
It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.
Try this:
div.container {
max-width: 200px;//real picture size
max-height: 100px;
}
/* resize images */
div.container img {
width: 100%;
height: auto;
}
I fixed it by re-adding the key to my ssh-agent.
with the following command:
ssh-add ~/.ssh/path_to_private_key_you_generated
For some reasons it was gone.
Use break
and continue
to do this. Breaking nested loops can be done in Python using the following:
for a in range(...):
for b in range(..):
if some condition:
# break the inner loop
break
else:
# will be called if the previous loop did not end with a `break`
continue
# but here we end up right after breaking the inner loop, so we can
# simply break the outer loop as well
break
Another way is to wrap everything in a function and use return
to escape from the loop.
You cannot just put in a function to pause Javascript unfortunately.
You have to use setTimeout()
Example:
function startTimer () {
timer.start();
setTimeout(stopTimer,5000);
}
function stopTimer () {
timer.stop();
}
EDIT:
For your user generated countdown, it is just as simple.
HTML:
<input type="number" id="delay" min="1" max="5">
JS:
var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;
function startTimer () {
timer.start();
setTimeout(stopTimer,delayInMilliseconds);
}
function stopTimer () {
timer.stop;
}
Now you simply need to add a trigger for startTimer()
, such as onchange
.
When I used CocoaPods to develop iOS projects, there is a .xcworkspace
file, you need to open the project with .xcworkspace
file related with CocoaPods.
But when you Show Package Contents
with .xcworkspace
file, you will find the contents.xcworkspacedata
file.
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:BluetoothColorLamp24G.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
pay attention to this line:
location = "group:BluetoothColorLamp24G.xcodeproj"
The .xcworkspace
file has reference with the .xcodeproj
file.
Development Environment:
macOS 10.14
Xcode 10.1
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
If you're trying to create a single jar that contains your application and its required libraries, there are two ways (that I know of) to do that. The first is One-Jar, which uses a special classloader to allow the nesting of jars. The second is UberJar, (or Shade), which explodes the included libraries and puts all the classes in the top-level jar.
I should also mention that UberJar and Shade are plugins for Maven1 and Maven2 respectively. As mentioned below, you can also use the assembly plugin (which in reality is much more powerful, but much harder to properly configure).
Basically you are doing it the right way. However, you should use an instance of the DataContext
for querying (it's not obvious that DataContext
is an instance or the type name from your query):
var result = (from a in new DataContext().Persons
where a.Age > 18
select new Person { Name = a.Name, Age = a.Age }).ToList();
Apparently, the Person
class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:
class PersonInformation {
public string Name {get;set;}
public int Age {get;set;}
}
var result = (from a in new DataContext().Persons
where a.Age > 18
select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();
You can freely swap var
with List<PersonInformation>
here without affecting anything (as this is what the compiler does).
Otherwise, if you are working locally with the query, I suggest considering an anonymous type:
var result = (from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age }).ToList();
Note that in all of these cases, the result
is statically typed (it's type is known at compile time). The latter type is a List
of a compiler generated anonymous class similar to the PersonInformation
class I wrote above. As of C# 3.0, there's no dynamic typing in the language.
If you really want to return a List<Person>
(which might or might not be the best thing to do), you can do this:
var result = from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age };
List<Person> list = result.AsEnumerable()
.Select(o => new Person {
Name = o.Name,
Age = o.Age
}).ToList();
You can merge the above statements too, but I separated them for clarity.
Using VS Professional 2019, I was trying to run a downloaded solution from a Udemy class on selenium automation testing, and most of the projects had errors in the project references sections. I tried cleaning, rebuilding, closing VS. Then, in VS, when I right clicked on the solution in Solution Explorer and chose Manage Nuget Packages for Solution, there were 2 available updates: for MSTest.TestAdapter and MSTest.TestFramework, and when I installed those, the error messages on the references for all the projects went away, for the references to those, as well as for the references to System and System.Core.
You Can Get With This Query
Unique Constraint,
Default Constraint With Value,
Foreign Key With referenced Table And Column
And Primary Key Constraint.
Select C.*, (Select definition From sys.default_constraints Where object_id = C.object_id) As dk_definition,
(Select definition From sys.check_constraints Where object_id = C.object_id) As ck_definition,
(Select name From sys.objects Where object_id = D.referenced_object_id) As fk_table,
(Select name From sys.columns Where column_id = D.parent_column_id And object_id = D.parent_object_id) As fk_col
From sys.objects As C
Left Join (Select * From sys.foreign_key_columns) As D On D.constraint_object_id = C.object_id
Where C.parent_object_id = (Select object_id From sys.objects Where type = 'U'
And name = 'Table Name Here');
There is no float
type. Looks like you want float64
. You could also use float32
if you only need a single-precision floating point value.
package main
import "fmt"
func main() {
i := 5
f := float64(i)
fmt.Printf("f is %f\n", f)
}
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
You can get the values for the width and height of the browser using the following:
$(window).height();
$(window).width();
To get notified when the browser is resized, use this bind callback:
$(window).resize(function() {
// Do something
});
I am using visual studio 2010 to make a program on SMSC Server. What you have to do is go to build-->publish. you will be asked be asked to few simple things and the location where you want to store your application, browse the location where you want to put it.
I hope this is what you are looking for
Here's a really simple example that might get you started:
$(document).ready(function() {
var $dragging = null;
$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY,
left: e.pageX
});
}
});
$(document.body).on("mousedown", "div", function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
});
Example: http://jsfiddle.net/Jge9z/
I understand that I shall use the mouse position relative to the container div (in which the div shall be dragged) and that I shall set the divs offset relative to those values.
Not so sure about that. It seems to me that in drag and drop you'd always want to use the offset of the elements relative to the document.
If you mean you want to constrain the dragging to a particular area, that's a more complicated issue (but still doable).
When using git rm, the removal will part of your next commit. So if you want to push the change you should use git rm
For multiple permission you can use this code :
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
private void insertDummyContactWrapper() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("GPS");
if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
permissionsNeeded.add("Read Contacts");
if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
permissionsNeeded.add("Write Contacts");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
});
return;
}
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
insertDummyContact();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
I noticed a lot of these answers, use this command:
use admin
which switches to the admin database. At least in Mongo v4.0.6, creating a user in the context of the admin database will create a user with "_id" : "admin.administrator"
:
> use admin
> db.getUsers()
[ ]
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' } ] })
> db.getUsers()
[
{
"_id" : "admin.administrator",
"user" : "administrator",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
]
I emphasize "admin.administrator"
, for I have a Mongoid (mongodb ruby adapter) application with a different database than admin and I use the URI to reference the database in my mongoid.yml configuration:
development:
clients:
default:
uri: <%= ENV['MONGODB_URI'] %>
options:
connect_timeout: 15
retry_writes: false
This references the following environment variable:
export MONGODB_URI='mongodb://administrator:[email protected]/mysite_development?retryWrites=true&w=majority'
Notice the database is mysite_development, not admin. When I try to run the application, I get an error "User administrator (mechanism: scram256) is not authorized to access mysite_development".
So I return to the Mongo shell delete the user, switch to the specified database and recreate the user:
$ mongo
> db.dropUser('administrator')
> db.getUsers()
[]
> use mysite_development
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' } ] })
> db.getUsers()
[
{
"_id" : "mysite_development.administrator",
"user" : "administrator",
"db" : "mysite_development",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
]
Notice that the _id and db changed to reference the specific database my application depends on:
"_id" : "mysite_development.administrator",
"db" : "mysite_development",
After making this change, the error went away and I was able to connect to MongoDB fine inside my application.
Extra Notes:
In my example above, I deleted the user and recreated the user in the right database context. Had you already created the user in the right database context but given it the wrong roles, you could assign a mongodb built-in role to the user:
db.grantRolesToUser('administrator', [{ role: 'root', db: 'admin' }])
There is also a db.updateUser
command, albiet typically used to update the user password.
I was getting the same error but it's sorted now. In my case, I had columns with the heading "Key1", "Key2", and "Key3". I have changed the column names to something else and it's sorted.
It seems that these are reserved keywords.
Regards, Mahesh
If you are looking for retrieving remote user IDSID/Username, use:
echo gethostbyaddr($_SERVER['REMOTE_ADDR']);
You will get something like iamuser1-mys.corp.company.com
Filter the rest of the domain behind, and you are able to get the idsid only.
For more information visit http://lostwithin.net/how-to-get-users-ip-and-computer-name-using-php/
I have the Problem with debugged processes with gdb in Code::Blocks. As soon it is hanging while accidentally stepping into instructions out of scope of your sources (as libs without sources or system functions) you cannot quit the debugging neither from Code::Blocks nor from Task-Manager.
I think it is an error in the implementation of gdb in Code::Blocks, but could also be in gdb ;)
My Solution:
taskkill /F /IM process.exe /T
This shows the PID of the parent process. Now kill the parent:
taskkill /PID yyyy
Both are gone.
Done.
You can't extend Enum
as it's a static class. You can only extend instances of a type. With this in mind, you're going to have to create a static method yourself to do this; the following should work when combined with your existing method GetDescription
:
public static class EnumHelper
{
public static T GetEnumFromString<T>(string value)
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
else
{
string[] enumNames = Enum.GetNames(typeof(T));
foreach (string enumName in enumNames)
{
object e = Enum.Parse(typeof(T), enumName);
if (value == GetDescription((Enum)e))
{
return (T)e;
}
}
}
throw new ArgumentException("The value '" + value
+ "' does not match a valid enum name or description.");
}
}
And the usage of it would be something like this:
Animal giantPanda = EnumHelper.GetEnumFromString<Animal>("Giant Panda");
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
YES, you can overload main()
But to be clear -- although you can overload main, only the version with the standard signature will be executable as an application from the command line. e.g
public static void main(String a,String... args){
// some code
}
2)public static void main(String[] args){//JVM will call this method to start
// some code
}
Alternatively there is the built-in function pd.get_dummies for these kinds of assignments:
w['female'] = pd.get_dummies(w['female'],drop_first = True)
This gives you a data frame with two columns, one for each value that occurs in w['female'], of which you drop the first (because you can infer it from the one that is left). The new column is automatically named as the string that you replaced.
This is especially useful if you have categorical variables with more than two possible values. This function creates as many dummy variables needed to distinguish between all cases. Be careful then that you don't assign the entire data frame to a single column, but instead, if w['female'] could be 'male', 'female' or 'neutral', do something like this:
w = pd.concat([w, pd.get_dummies(w['female'], drop_first = True)], axis = 1])
w.drop('female', axis = 1, inplace = True)
Then you are left with two new columns giving you the dummy coding of 'female' and you got rid of the column with the strings.
If your TaskDetailsFragment
extending android.app.Fragment
, do change in onCreateView()
.
Return your view which you want to show in the Fragment or convert your Layout to view by using LayoutInflater and return it.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainview = inflater.inflate(R.layout.main, null);
return mainview;
}
Hope this works. :)
The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.
try
SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC
You can make use of the SlimScroll plugin to make a div scrollable even if it is set to overflow: hidden;
(i.e. scrollbar hidden).
You can also control touch scroll as well as the scroll speed using this plugin.
Hope this helps :)
Somehow a setup.cfg file with a prefix="" in the project folder
running pip install on the virtualenv outside the project folder worked so from the inside it was telling pip to use an empty prefix which defaults to "/"
removing the file fixed it
Given it's SQL 2005, you can also try this It's similar to Oracle's MINUS command (opposite of UNION)
But I would also suggest adding the DATEPART ( hour, insertDate) column for debug
SELECT idCustomer FROM reservations
EXCEPT
SELECT idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2
Actually AllocConsole with SetStdHandle in a GUI application might be a safer approach. The problem with the "console hijacking" already mentioned, is that the console might not be a foreground window at all, (esp. considering the influx of new window managers in Vista/Windows 7) among other things.
Add this line to dependencies in build.gradle
:
dependencies {
compile 'com.android.support:appcompat-v7:18.0.+'
}
What if you create two boolean arrays: 1 for negative values and 1 for positive values and init it all on false.
Then you cycle thorugh the input array and lookup in the arrays if you've encoutered the value already. If not, you add it to the output array and mark it as already used.
Since Java 8, there are lambda and method references:
For example, if you want a functional interface A -> B
such as:
import java.util.function.Function;
public MyClass {
public static String applyFunction(String name, Function<String,String> function){
return function.apply(name);
}
}
then you can call it like so
MyClass.applyFunction("42", str -> "the answer is: " + str);
// returns "the answer is: 42"
Also you can pass class method. Say you have:
@Value // lombok
public class PrefixAppender {
private String prefix;
public String addPrefix(String suffix){
return prefix +":"+suffix;
}
}
Then you can do:
PrefixAppender prefixAppender= new PrefixAppender("prefix");
MyClass.applyFunction("some text", prefixAppender::addPrefix);
// returns "prefix:some text"
Note:
Here I used the functional interface Function<A,B>
, but there are many others in the package java.util.function
. Most notable ones are
Supplier
: void -> A
Consumer
: A -> void
BiConsumer
: (A,B) -> void
Function
: A -> B
BiFunction
: (A,B) -> C
and many others that specialize on some of the input/output type. Then, if it doesn't provide the one you need, you can create your own functional interface like so:
@FunctionalInterface
interface Function3<In1, In2, In3, Out> { // (In1,In2,In3) -> Out
public Out apply(In1 in1, In2 in2, In3 in3);
}
Example of use:
String computeAnswer(Function3<String, Integer, Integer, String> f){
return f.apply("6x9=", 6, 9);
}
computeAnswer((question, a, b) -> question + "42");
// "6*9=42"
And you can also do that with thrown exception:
@FunctionalInterface
interface FallibleFunction<In, Out, Ex extends Exception> {
Out get(In input) throws Ex;
}
public <Ex extends IOException> String yo(FallibleFunction<Integer, String, Ex> f) throws Ex {
return f.get(42);
}
EditText editText= ....;
InputFilter[] fa= new InputFilter[1];
fa[0] = new InputFilter.LengthFilter(8);
editText.setFilters(fa);
LEFT OUTER JOIN
SELECT * FROM A, B WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT * FROM A, B WHERE A.column (+)= B.column
'mutable' means that we can change the content of the string, 'immutable' means that we can't add an extra string.
Was toying with this for hours, here's what worked for me.
Remove all the elevation
attributes from the appBarLayout
and Toolbar
widgets (including styles.xml
if you are applying any styling).
Now inside activity,apply the elvation
on your actionBar
:
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setElevation(3.0f);
This should work.
Here's a simple example using reduce. It runs serially, maintains insertion order, and does not require Bluebird.
/**
*
* @param items An array of items.
* @param fn A function that accepts an item from the array and returns a promise.
* @returns {Promise}
*/
function forEachPromise(items, fn) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item);
});
}, Promise.resolve());
}
And use it like this:
var items = ['a', 'b', 'c'];
function logItem(item) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
resolve();
})
});
}
forEachPromise(items, logItem).then(() => {
console.log('done');
});
We have found it useful to send an optional context into loop. The context is optional and shared by all iterations.
function forEachPromise(items, fn, context) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item, context);
});
}, Promise.resolve());
}
Your promise function would look like this:
function logItem(item, context) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
context.itemCount++;
resolve();
})
});
}
The problem with some of this solutions is that they access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.
The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.
If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.
This function downsample to half at a time until reaching the desired size:
function resize_image( src, dst, type, quality ) {
var tmp = new Image(),
canvas, context, cW, cH;
type = type || 'image/jpeg';
quality = quality || 0.92;
cW = src.naturalWidth;
cH = src.naturalHeight;
tmp.src = src.src;
tmp.onload = function() {
canvas = document.createElement( 'canvas' );
cW /= 2;
cH /= 2;
if ( cW < src.width ) cW = src.width;
if ( cH < src.height ) cH = src.height;
canvas.width = cW;
canvas.height = cH;
context = canvas.getContext( '2d' );
context.drawImage( tmp, 0, 0, cW, cH );
dst.src = canvas.toDataURL( type, quality );
if ( cW <= src.width || cH <= src.height )
return;
tmp.src = dst.src;
}
}
// The images sent as parameters can be in the DOM or be image objects
resize_image( $( '#original' )[0], $( '#smaller' )[0] );
Credits to this post
Neither UIImageView not UIImage holds on to the filename of the image loaded.
You can either
1: (as suggested by Kenny Winker above) subclass UIImageView to have a fileName property or
2: name the image files with numbers (image1.jpg, image2.jpg etc) and tag those images with the corresponding number (tag=1 for image1.jpg, tag=2 for image2.jpg etc) or
3: Have a class level variable (eg. NSString *currentFileName) which updates whenever you update the UIImageView's image
I believe your 1:m relationships should already implicitly create DISTINCT JOINs.
But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.
SELECT DISTINCT a.valueA, c.valueC
FROM C
INNER JOIN B ON B.lookupC = C.id
INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC
The return statement only makes sense inside functions:
def foo():
while True:
return False
In my case , I used the 'is' a jQuery function, I had a HTML element with different css classes added , I was looking for a specific class in the middle of these , so I used the "is" a good alternative to check a class dynamically added to an html element , which already has other css classes, it is another good alternative.
simple example :
<!--element html-->
<nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>
<!--jQuery "is"-->
$('#menu').is('.cbp-spmenu-open');
advanced example :
<!--element html-->
<nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>
<!--jQuery "is"-->
if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){
$("#menu").show();
}
What is "it" in the statement "it just says the procedure is completed"?
By default, most tools do not configure a buffer for dbms_output
to write to and do not attempt to read from that buffer after code executes. Most tools, on the other hand, have the ability to do so. In SQL*Plus, you'd need to use the command set serveroutput on [size N|unlimited]
. So you'd do something like
SQL> set serveroutput on size 30000;
SQL> exec print_actor_quotes( <<some value>> );
In SQL Developer, you'd go to View | DBMS Output
to enable the DBMS Output window, then push the green plus icon to enable DBMS Output for a particular session.
Additionally, assuming that you don't want to print the literal "a.firstNamea.lastName" for every row, you probably want
FOR row IN quote_recs
LOOP
DBMS_OUTPUT.PUT_LINE( row.firstName || ' ' || row.lastName );
END LOOP;
Class WebMvcConfigurerAdapter
is deprecated as of 5.0 WebMvcConfigurer
has default methods and can be implemented directly without the need for this adapter. For this case:
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
}
See also: Same-Site flag for session cookie
You are looking for the re.sub function.
import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced
will print axample atring
Here is the perfect example of downloading a file using javaScript.
Usage: download_file(fileURL, fileName);
$.ajax("youurl", function(data){
if (data.success == true)
setTimeout(function(){window.location = window.location}, 5000);
})
)
I personally prefer using the following code if it is for a single link. Otherwise it's probably best if you create a function with similar code.
onclick="this.target='_blank';"
I started using that to bypass the W3C's XHTML strict test.
In Python 3 use input()
:
input("Press Enter to continue...")
In Python 2 use raw_input()
:
raw_input("Press Enter to continue...")
This only waits for the user to press enter though.
One might want to use msvcrt ((Windows/DOS only) The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT)):
import msvcrt as m
def wait():
m.getch()
This should wait for a key press.
Additional info:
in Python 3 raw_input()
does not exist
In Python 2 input(prompt)
is equivalent to eval(raw_input(prompt))
I would omit the * { text-align:center }
declaration, as it sets center alignment for all elements.
Usually with a fixed width container margin: 0 auto
should be enough
@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the +
operator fails for strings in EL (which is correct), then just do:
<c:out value="abc${test}" />
Or if abc
is to obtained from another scoped variable named ${resp}
, then do:
<c:out value="${resp}${test}" />
With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.
You can download a full working demo from this post
I would use below,
insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;
on the p element, add 3 styling rules.
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}
You'd have to scan for include($tmp) and require(HTTP_REFERER) and *_once as well. If an exploit script can write to a temporary file, it could just include that later. Basically a two-step eval.
And it's even possible to hide remote code with workarounds like:
include("data:text/plain;base64,$_GET[code]");
Also, if your webserver has already been compromised you will not always see unencoded evil. Often the exploit shell is gzip-encoded. Think of include("zlib:script2.png.gz");
No eval here, still same effect.
I apparently can't comment yet, but I think you can just use the DAY_OF_YEAR to workout if you should adjust the years down one (copied and modified from current best answer)
public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
if (a.get(Calendar.DAY_OF_YEAR) > b.get(Calendar.DAY_OF_YEAR)) {
diff--;
}
return diff;
}
public static Calendar getCalendar(Date date) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(date);
return cal;
}
Similarly you could probably just diff the ms representations of the time and divide by the number of ms in a year. Just keep everything in longs and that should be good enough most of the time (leap years, ouch) but it depends on your application for the number of years and how performant that function has to be weather it would be worth that kind of hack.
I know you're talking about MySQL, but anyway: In Oracle 9 explicit joins and implicit joins would generate different execution plans. AFAIK that has been solved in Oracle 10+: there's no such difference anymore.
Use the Equals method:
object value2 = null;
Console.WriteLine(object.Equals(value2,null));
If you want just a simple reader without sections and any other dlls here is simple solution:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tool
{
public class Config
{
Dictionary <string, string> values;
public Config (string path)
{
values = File.ReadLines(path)
.Where(line => (!String.IsNullOrWhiteSpace(line) && !line.StartsWith("#")))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0].Trim(), parts => parts.Length>1?parts[1].Trim():null);
}
public string Value (string name, string value=null)
{
if (values!=null && values.ContainsKey(name))
{
return values[name];
}
return value;
}
}
}
Usage sample:
file = new Tool.Config (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\config.ini");
command = file.Value ("command");
action = file.Value ("action");
string value;
//second parameter is default value if no key found with this name
value = file.Value("debug","true");
this.debug = (value.ToLower()=="true" || value== "1");
value = file.Value("plain", "false");
this.plain = (value.ToLower() == "true" || value == "1");
Config file content meanwhile (as you see supports # symbol for line comment):
#command to run
command = php
#default script
action = index.php
#debug mode
#debug = true
#plain text mode
#plain = false
#icon = favico.ico
Here's a maketrans/translate solution
import string
rot13 = string.maketrans(
"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",
"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World!", rot13)
# 'Uryyb Jbeyq!'