Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor()
. Direct to the point check this out!
function digitCount ( num )
{
return Math.floor( num.toString()).length;
}
digitCount(2343) ;
// ES5+
const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;
console.log(digitCount2(3343))
Basically What's going on here. toString()
and String()
same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length
.
Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs()
in it;
Cheer You!
Use StringUtils, in case you need string result:
String last = StringUtils.right(number.toString(), 1);
Try this
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
alert(pad("5", 2));
Example
Or
var number = 5;
var i;
if (number < 10) {
alert("0"+number);
}
Example
You could use regular expressions.
You can detect digits using:
if(re.search([0-9], yourstring[:1])):
#do something
The [0-9] par matches any digit, and yourstring[:1] matches the first character of your string
One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))
For example, if you have a vector as elements
and would like to get sum
of it
elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432
Apparently, the last digital as 1
been truncated, the ideal result should be -876.54321
, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements))
, redundant zero(s) generate as -876.5432100000
Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321
, there are 5 decimal digits need to print, then we can set up a parameter for format
function as below:
decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321
We can change the decimal_length
based on each time query, so it can satisfy different decimal printing requirement.
Here is the best solution I found:
function digitsum(n) {
n = n.toString();
let result = 0;
for (let i = 0; i < n.length; i++) {
result += parseInt(n[i]);
}
return result;
}
console.log(digitsum(192));
Code for finding Length of int and decimal number:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int len,num;
cin >> num;
len = log10(num) + 1;
cout << len << endl;
return 0;
}
//sample input output
/*45566
5
Process returned 0 (0x0) execution time : 3.292 s
Press any key to continue.
*/
let input = 12345664
const output = []
while (input !== 0) {
const roundedInput = Math.floor(input / 10)
output.push(input - roundedInput * 10)
input = roundedInput
}
console.log(output)
Based on what @user225312 said, you can use .zfill() to add paddng to numbers converted to strings.
My approach is to leave number as a number until the moment you want to convert it into string:
>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011
Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so:
Locale locale = Locale.ENGLISH;
NumberFormat nf = NumberFormat.getNumberInstance(locale);
// for trailing zeros:
nf.setMinimumFractionDigits(2);
// round to 2 digits:
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(.99));
System.out.println(nf.format(123.567));
System.out.println(nf.format(123.0));
Will print in English locale (no matter what your locale is): 0.99 123.57 123.00
The example is taken from Farenda - how to convert double to String correctly.
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
int x = 1000;
int numberOfDigits = x ? static_cast<int>(log10(abs(x))) + 1 : 1;
You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
Characters that need escaping are different in Bourne or POSIX shell than Bash. Generally (very) Bash is a superset of those shells, so anything you escape in shell
should be escaped in Bash.
A nice general rule would be "if in doubt, escape it". But escaping some characters gives them a special meaning, like \n
. These are listed in the man bash
pages under Quoting
and echo
.
Other than that, escape any character that is not alphanumeric, it is safer. I don't know of a single definitive list.
The man pages list them all somewhere, but not in one place. Learn the language, that is the way to be sure.
One that has caught me out is !
. This is a special character (history expansion) in Bash (and csh) but not in Korn shell. Even echo "Hello world!"
gives problems. Using single-quotes, as usual, removes the special meaning.
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
The updated dplyr solution, as for 2020
1: summarise_each_()
is deprecated as of dplyr 0.7.0.
and
2: funs()
is deprecated as of dplyr 0.8.0.
ag.dplyr <- DF %>% group_by(ID) %>% summarise(across(.cols = everything(),list(mean = mean, sd = sd)))
There are various scripts floating around that will do that depending on how crazy you want to get. I would personally use Pete Finnigan's find_all_privs script.
If you want to write it yourself, the query gets rather challenging. Users can be granted system privileges which are visible in DBA_SYS_PRIVS
. They can be granted object privileges which are visible in DBA_TAB_PRIVS
. And they can be granted roles which are visible in DBA_ROLE_PRIVS
(roles can be default or non-default and can require a password as well, so just because a user has been granted a role doesn't mean that the user can necessarily use the privileges he acquired through the role by default). But those roles can, in turn, be granted system privileges, object privileges, and additional roles which can be viewed by looking at ROLE_SYS_PRIVS
, ROLE_TAB_PRIVS
, and ROLE_ROLE_PRIVS
. Pete's script walks through those relationships to show all the privileges that end up flowing to a user.
I recently found out that :active:focus
does the same thing in css as :active:hover
if you need to override a custom css library, they might use both.
In Java 7 you can do this:
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
BSTR
to std::wstring
:
// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));
std::wstring
to BSTR
:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
Doc refs:
Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'
So, you need to do below
>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
getResource()
directly on the class.Use DATE_ADD function
DATE_ADD(datecolumn, INTERVAL 30 MINUTE);
When thinking about pointers, it helps to draw diagrams. A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.
d
in main
is a pointer to c
which is of type char
. A char
is one byte of memory, so when d
is dereferenced, you get the value in that one byte of memory. In the diagram below, each cell represents one byte.
-+----+----+----+----+----+----+-
| | c | | | | |
-+----+----+----+----+----+----+-
^~~~
| char
d
When you cast d
to int*
, you're saying that d
really points to an int
value. On most systems today, an int
occupies 4 bytes.
-+----+----+----+----+----+----+-
| | c | ?1 | ?2 | ?3 | |
-+----+----+----+----+----+----+-
^~~~~~~~~~~~~~~~~~~
| int
(int*)d
When you dereference (int*)d
, you get a value that is determined from these four bytes of memory. The value you get depends on what is in these cells marked ?
, and on how an int
is represented in memory.
A PC is little-endian, which means that the value of an int
is calculated this way (assuming that it spans 4 bytes):
* ((int*)d) == c + ?1 * 28 + ?2 * 2¹6 + ?3 * 2²4
. So you'll see that while the value is garbage, if you print in in hexadecimal (printf("%x\n", *n)
), the last two digits will always be 35
(that's the value of the character '5'
).
Some other systems are big-endian and arrange the bytes in the other direction: * ((int*)d) == c * 2²4 + ?1 * 2¹6 + ?2 * 28 + ?3
. On these systems, you'd find that the value always starts with 35
when printed in hexadecimal. Some systems have a size of int
that's different from 4 bytes. A rare few systems arrange int
in different ways but you're extremely unlikely to encounter them.
Depending on your compiler and operating system, you may find that the value is different every time you run the program, or that it's always the same but changes when you make even minor tweaks to the source code.
On some systems, an int
value must be stored in an address that's a multiple of 4 (or 2, or 8). This is called an alignment requirement. Depending on whether the address of c
happens to be properly aligned or not, the program may crash.
In contrast with your program, here's what happens when you have an int
value and take a pointer to it.
int x = 42;
int *p = &x;
-+----+----+----+----+----+----+-
| | x | |
-+----+----+----+----+----+----+-
^~~~~~~~~~~~~~~~~~~
| int
p
The pointer p
points to an int
value. The label on the arrow correctly describes what's in the memory cell, so there are no surprises when dereferencing it.
This is fairly easy to answer from the internet. Set system properties http.proxyHost
and http.proxyPort
. You can do this with System.setProperty()
, or from the command line with the -D
syntax.
The simplest way to install setuptools when it isn't already there and you can't use a package manager is to download ez_setup.py and run it with the appropriate Python interpreter. This works even if you have multiple versions of Python around: just run ez_setup.py once with each Python.
Edit: note that recent versions of Python 3 include setuptools in the distribution so you no longer need to install separately. The script mentioned here is only relevant for old versions of Python.
I recently answered a similar question here. Applying the same approach to your problem would yield following solution:
list.sort(
p2Ord(stringOrd, stringOrd).comap(new F<String, P2<String, String>>() {
public P2<String, String> f(String s) {
return p(s.toLowerCase(), s);
}
})
);
The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time
If you get an OutOfMemoryError then it's usually too late to call the garbage collector...
Here is quote from Android Developer:
Most of the time, garbage collection occurs because of tons of small, short-lived objects and some garbage collectors, like generational garbage collectors, can optimize the collection of these objects so that the application does not get interrupted too often. The Android garbage collector is unfortunately not able to perform such optimizations and the creation of short-lived objects in performance critical code paths is thus very costly for your application.
So to my understanding, there is no urgent need to call the gc. It's better to spend more effort in avoiding the unnecessary creation of objects (like creation of objects inside loops)
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
$('#Search').keyup(function(e)_x000D_
{_x000D_
if (event.keyCode === 13) {_x000D_
e.preventDefault();_x000D_
var searchtext = $('#Search').val();_x000D_
window.location.href = "searchData.php?Search=" + searchtext + '&bit=1';_x000D_
}_x000D_
});
_x000D_
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
I don't see any documentation that says the order in app.xml is guaranteed to be the order of the sheets. It PROBABLY is, but not according to the OOXML specification.
The workbook.xml file, on the other hand, includes the sheetId attribute, which does determine the sequence - from 1 to the number of sheets. This is according to the OOXML specification. workbook.xml is described as the place where the sequence of the sheets is kept.
So reading workbook.xml after it is extracted form the XLSX would be my recommendation. NOT app.xml. Instead of docProps/app.xml, use xl/workbook.xml and look at the element, as shown here -
`
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="9303" />
<workbookPr defaultThemeVersion="124226" />
- <bookViews>
<workbookView xWindow="120" yWindow="135" windowWidth="19035" windowHeight="8445" />
</bookViews>
- <sheets>
<sheet name="By song" sheetId="1" r:id="rId1" />
<sheet name="By actors" sheetId="2" r:id="rId2" />
<sheet name="By pit" sheetId="3" r:id="rId3" />
</sheets>
- <definedNames>
<definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">'By song'!$A$1:$O$59</definedName>
</definedNames>
<calcPr calcId="145621" />
</workbook>
`
Not only PDO. If sql answer like '????' symbols, preset of you charset (hope UTF-8) really recommended:
if (!$mysqli->set_charset("utf8"))
{ printf("Can't set utf8: %s\n", $mysqli->error); }
or via procedure style mysqli_set_charset($db,"utf8")
Use, a global variable or property for assigning the value to the textbox, give the value for the variable in another class and assign it to the textbox.text in form class.
Specify the paths explicitly:
git diff HEAD:full/path/to/foo full/path/to/bar
Check out the --find-renames
option in the git-diff
docs.
Credit: twaggs.
I've taken Anas Nakawa's idea and improved it. First of all, there is no reason to actually run the function being declared. We want to know whether it parses correctly, not whether the code works. Second, a literal object is a better context for our purpose than var XXX
as it's harder to break out of.
function isValidVarName( name ) {
try {
return name.indexOf('}') === -1 && eval('(function() { a = {' + name + ':1}; a.' + name + '; var ' + name + '; }); true');
} catch( e ) {
return false;
}
return true;
}
// so we can see the test code
var _eval = eval;
window.eval = function(s) {
console.log(s);
return _eval(s);
}
console.log(isValidVarName('name'));
console.log(isValidVarName('$name'));
console.log(isValidVarName('not a name'));
console.log(isValidVarName('a:2,b'));
console.log(isValidVarName('"a string"'));
console.log(isValidVarName('xss = alert("I\'m in your vars executin mah scrip\'s");;;;;'));
console.log(isValidVarName('_;;;'));
console.log(isValidVarName('_=location="#!?"'));
console.log(isValidVarName('?'));
console.log(isValidVarName('HELLO'));
console.log(isValidVarName('????'));
console.log(isValidVarName('?????????????'));
console.log(isValidVarName('KingGeorge?'));
console.log(isValidVarName('}; }); alert("I\'m in your vars executin\' mah scripts"); true; // yeah, super valid'));
console.log(isValidVarName('if'));
It will work like this:
$('input[type="email"]').keyup(function() {
if ($(this).val() != '') {
$(':button[type="submit"]').prop('disabled', false);
} else {
$(':button[type="submit"]').prop('disabled', true);
}
});
Make sure there is an 'disabled' attribute in your HTML
If you'd like to overwrite column B in the dataframe, this should work:
df = df.groupby('A',as_index=False).agg(lambda x:'\n'.join(x))
You can restart an existing container after it exited and your changes are still there.
docker start `docker ps -q -l` # restart it in the background
docker attach `docker ps -q -l` # reattach the terminal & stdin
When your are three tables or more, just add union and left outer join:
select a.col1, b.col2, a.col3, b.col4, a.category_id
from
(
select category_id from a
union
select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
For me the solution was to download the Android SDK and launch adb devices
which started the adb daemon.
$('#navigation ul li').css({'display' : 'inline-block'});
It seems a typo there ...syntax mistake :))
There is a much easier and more compact solution for multilevel prototype lookup, but it requires Proxy
support. Usage: SUPER(<instance>).<method>(<args>)
, for example, assuming two classes A
and B extends A
with method m
: SUPER(new B).m()
.
function SUPER(instance) {
return new Proxy(instance, {
get(target, prop) {
return Object.getPrototypeOf(Object.getPrototypeOf(target))[prop].bind(target);
}
});
}
hadoop.tmp.dir
in the core-site.xml is defaulted to /tmp/hadoop-${user.name}
which is cleaned after every reboot. Change this to some other directory which doesn't get cleaned on reboot.
How did you actually define the structure? If
struct {
char name[32];
int size;
int start;
int popularity;
} stasher_file;
is to be taken as type definition, it's missing a typedef
. When written as above, you actually define a variable called stasher_file
, whose type is some anonymous struct type.
Try
typedef struct { ... } stasher_file;
(or, as already mentioned by others):
struct stasher_file { ... };
The latter actually matches your use of the type. The first form would require that you remove the struct
before variable declarations.
alter user username superuser;
There aren't any quotes. It's just VS debugger. Try printing to the console or saving to a file and you'll see. As a side note: always dispose disposable objects:
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xmlDoc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
}
RedirectToAction("actionName", "controllerName");
It has other overloads as well, please check up!
Also, If you are new and you are not using T4MVC, then I would recommend you to use it!
It gives you intellisence for actions,Controllers,views etc (no more magic strings)
In an application level, here are something a developer can do:
From server side:
Check if load balancer(if you have),works correctly.
Turn slow TCP timeouts into 503 Fast Immediate response, if you load balancer work correctly, it should pick the working resource to serve, and it's better than hanging there with unexpected error massages.
Eg: If you are using node server, u can use toobusy from npm. Implementation something like:
var toobusy = require('toobusy');
app.use(function(req, res, next) {
if (toobusy()) res.send(503, "I'm busy right now, sorry.");
else next();
});
Why 503? Here are some good insights for overload: http://ferd.ca/queues-don-t-fix-overload.html
We can do some work in client side too:
Try to group calls in batch, reduce the traffic and total requests number b/w client and server.
Try to build a cache mid-layer to handle unnecessary duplicates requests.
C# is a programming language, .NET is the framework that the language is built on.
First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.
select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable
1) C:\Program Files\xampp\php\php.ini
2) Uncomment the following line on your php.ini file by removing the semicolon.
;extension=php_curl.dll
3) Restart your apache server.
Additionally, if you have the NDK installed, you can also find the listing in ${ndk_path}platforms\android-${api}\${architecture}\usr\include\android\keycodes.h
.
I'm only mentioning it because I've found it simpler to navigate and read than the KeyEvent class or docs.
Use Hibernate.initialize()
within @Transactional
to initialize lazy objects.
start Transaction
Hibernate.initialize(entity.getAddresses());
Hibernate.initialize(entity.getPersons());
end Transaction
Now out side of the Transaction you are able to get lazy objects.
entity.getAddresses().size();
entity.getPersons().size();
This method work for me:
DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
BEGIN
INSERT INTO USER VALUES(id,NAME);
END$$
DELIMITER ;
urllib2
is no longer available in Python 3You can try following code.
import urllib.request
res = urllib.request.urlopen('url')
output = res.read()
print(output)
You can get more idea about urllib.request
from this link.
urllib3
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'url')
print(r.status)
print( r.headers)
print(r.data)
Also if you want more details about urllib3
. follow this link.
There are two techniques commonly used for this:
Given the HTML you provided here is the solution using Absolute positioning:
body #one {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
width: auto;_x000D_
height: auto;_x000D_
}_x000D_
body #two {_x000D_
width: auto; _x000D_
}_x000D_
body #three {_x000D_
position: absolute;_x000D_
top: 60px;_x000D_
bottom: 0;_x000D_
height: auto;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
html, body {width:100%;height:100%;margin:0;padding:0;}_x000D_
.border {border:1px solid black;}_x000D_
.margin { margin:5px;}_x000D_
#one {width:100%;height:100%;}_x000D_
#two {width:100%;height:50px;}_x000D_
#three {width:100px;height:100%;}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div id="one" class="border">_x000D_
<div id="two" class="border margin"></div>_x000D_
<div id="three" class="border margin"></div>_x000D_
</div>_x000D_
</body
_x000D_
You can always just use the table, tr, and td elements directly despite common criticisms as it will get the job done. If you prefer to use CSS there is no equivalent for colspan so you will likely end up with nested tables. Here is an example:
html, body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
width: 100%;_x000D_
}_x000D_
#one {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#two {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 50px;_x000D_
padding: 5px;_x000D_
width: 100%;_x000D_
}_x000D_
#three {_x000D_
box-sizing: border-box;_x000D_
display: table;_x000D_
height: 100%;_x000D_
padding-bottom: 60px;_x000D_
padding-left: 5px;_x000D_
_x000D_
}_x000D_
#four {_x000D_
display: table-cell;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#five {_x000D_
display: table-cell;_x000D_
width: 100px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#six {_x000D_
display: table-cell; _x000D_
}
_x000D_
<html>_x000D_
<div id="one">_x000D_
<div id="two">_x000D_
<div id="four"></div>_x000D_
</div>_x000D_
<div id="three">_x000D_
<div id="five"></div>_x000D_
<div id="six"></div>_x000D_
</div>_x000D_
</div>_x000D_
</html>
_x000D_
[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'
foreach($server in $servers)
{
$srvc = Get-WmiObject -query "SELECT * FROM win32_service WHERE name LIKE '$service' " -computername $server ;
$res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;
$srvc.startservice()
$res
}
It could be related to log4j.
Do you have log4j.jar file in the websphere java classpath (as defined in the startup file) as well as the application classpath ?
If you do make sure that the log4j.jar file is in the java classpath and that it is NOT in the web-inf/lib directory of your webapp.
It can also be related with the ant version (may be not your case, but I do put it here for reference):
You have a .class file in your class path (i.e. not a directory or a .jar file). Starting with ant 1.6, ant will open the files in the classpath checking for manifest entries. This attempted opening will fail with the error "java.util.zip.ZipException"
The problem does not exist with ant 1.5 as it does not try to open the files. - so make sure that your classpath's do not contain .class files.
On a side note, did you consider having separate jars ?
You could in the manifest of your main jar, refer to the other jars with this attribute:
Class-Path: one.jar two.jar three.jar
Then, place all of your jars in the same folder.
Again, may be not valid for your case, but still there for reference.
A function call needs to be performed with objects. You are doing the equivalent of this:
// function declaration/definition
void foo(int) {}
// function call
foo(int); // wat!??
i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing
int i = 42;
foo(i);
or
foo(42);
In order to test your app on a real device rather than pay the Apple Developer fee (or jailbreak your device), you can use the new free provisioning that Xcode 7 and iOS 9 supports.
Here are the steps taken more or less from the documentation (which is pretty good, so give it a read):
1. Add your Apple ID in Xcode
Go to XCode > Preferences > Accounts tab > Add button (+) > Add Apple ID. See the docs for more help.
2. Click the General tab in the Project Navigator
3. Choose your Apple ID from the Team popup menu.
4. Connect your device and choose it in the scheme menu.
5. Click the Fix Issues button
If you get an error about the bundle name being invalid, change it to something unique.
6. Run your app
In Xcode, click the Build and run button.
7. Trust the app developer in the device settings
After running your app, you will get a security error because the app you want to run is not from the App Store.
On your device, go to Settings > General > Profile > your-Apple-ID-name > Trust your-Apple-ID-name > Trust.
8. Run your app on your device again.
That's it. You can now run your own (or any other apps that you have the source code for) without having to dish out the $99 dollars. Thank you, Apple, for finally allowing this.
If you're running on PHP 5.5+, you can use ::class
resolution to obtain the name of the class with expectException
/setExpectedException
. This provides several benefits:
string
so it will work with any version of PHPUnit.Example:
namespace \My\Cool\Package;
class AuthTest extends \PHPUnit_Framework_TestCase
{
public function testLoginFailsForWrongPassword()
{
$this->expectException(WrongPasswordException::class);
Auth::login('Bob', 'wrong');
}
}
PHP compiles
WrongPasswordException::class
into
"\My\Cool\Package\WrongPasswordException"
without PHPUnit being the wiser.
Note: PHPUnit 5.2 introduced
expectException
as a replacement forsetExpectedException
.
I used quite @Eyuel method:
node cli.js install npm -gf
Now you should have node + npm working, use theses commands to check: node --version
and npm --version
Update 27/07/2017 : I noticed that the latest version of node 8.2.1 with the latest version of npm are quite different from the one I was using at the time of this answer. The install with theses versions won't work. It is working with node 6.11.1 and npm 5.2.3. Also if you are running with a proxy don't forget this to connect on internet :
Update May 2014
Google crawlers now executes javascript - you can use the Google Webmaster Tools to better understand how your sites are rendered by Google.
Original answer
If you want to optimize your app for search engines there is unfortunately no way around serving a pre-rendered version to the crawler. You can read more about Google's recommendations for ajax and javascript-heavy sites here.
If this is an option I'd recommend reading this article about how to do SEO for Angular with server-side rendering.
I’m not sure what the crawler does when it encounters custom tags.
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
void CallFunction ()
{ // <----- At this point the compiler knows
// nothing about the members of B.
B b;
b.bFunction();
}
This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.
To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.
class A
{
public:
void CallFunction ();
};
class B: public A
{
public:
virtual void bFunction()
{ ... }
};
void A::CallFunction ()
{
B b;
b.bFunction();
}
Change it to this:
switch (enumExample) {
case VALUE_A: {
//..
break;
}
}
The clue is in the error. You don't need to qualify case
labels with the enum type, just its value.
Here's a gist I put together. I was wondering the same and this helped improve my understanding. Open this up in an Xcode Playground to see what's going on.
protocol YelpRequestDelegate {
func getYelpData() -> AnyObject
func processYelpData(data: NSData) -> NSData
}
class YelpAPI {
var delegate: YelpRequestDelegate?
func getData() {
println("data being retrieved...")
let data: AnyObject? = delegate?.getYelpData()
}
func processYelpData(data: NSData) {
println("data being processed...")
let data = delegate?.processYelpData(data)
}
}
class Controller: YelpRequestDelegate {
init() {
var yelpAPI = YelpAPI()
yelpAPI.delegate = self
yelpAPI.getData()
}
func getYelpData() -> AnyObject {
println("getYelpData called")
return NSData()
}
func processYelpData(data: NSData) -> NSData {
println("processYelpData called")
return NSData()
}
}
var controller = Controller()
Recursion is a fancy way of saying "Do this thing again until its done".
Two important things to have:
Imagine a simple task: Sort a stack of books alphabetically. A simple process would be take the first two books, sort them. Now, here comes the recursive part: Are there more books? If so, do it again. The "do it again" is the recursion. The "are there any more books" is the test. And "no, no more books" is the base case.
I have did it on windows machine. Detail mentioned below 1. From windows start menu open “Anaconda Prompt enter image description here 2. Find .jupyter folder file path . In command prompt just type enter image description here or enter image description here to find the .jupyter path
if do not have administrator permission then Some time you could not find .jupyter folder . Still you can open config file from any of the text editor
In addition to MR Chandru"s answer above, do these steps after configuring XAMPP:
C:\xampp
xampp-control.exe
, the XAMPP Control PanelC:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
or
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
The XAMPP Control Panel should now auto-start whenever you reboot Windows.
For i=1 To 10
Do
'Do everything in here and
If I_Dont_Want_Finish_This_Loop Then
Exit Do
End If
'Of course, if I do want to finish it,
'I put more stuff here, and then...
Loop While False 'quit after one loop
Next i
If you're looking for a solution that returns proper number or days between e.g. 11/30/2014 23:59
and 12/01/2014 00:01
here's solution using Joda Time.
private int getDayDifference(long past, long current) {
DateTime currentDate = new DateTime(current);
DateTime pastDate = new DateTime(past);
return currentDate.getDayOfYear() - pastDate.getDayOfYear();
}
This implementation will return 1
as a difference in days. Most of the solutions posted here calculate difference in milliseconds between two dates. It means that 0
would be returned because there's only 2 minutes difference between these two dates.
If you want to be able to control which files are selected from the command line, I managed to do this for Angular 7.
In summary, you need to install @angular-devkit/build-angular:browser
and then create a custom webpack plugin to pass the test file regex through. For example:
angular.json - change the test builder from @angular-devkit/build-angular:browser
and set a custom config file:
...
"test": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
...
extra-webpack.config.js - create a webpack configuration that reads the regex from the command line:
const webpack = require('webpack');
const FILTER = process.env.KARMA_FILTER;
let KARMA_SPEC_FILTER = '/.spec.ts$/';
if (FILTER) {
KARMA_SPEC_FILTER = `/${FILTER}.spec.ts$/`;
}
module.exports = {
plugins: [new webpack.DefinePlugin({KARMA_SPEC_FILTER})]
}
test.ts - edit the spec
...
// Then we find all the tests.
declare const KARMA_CONTEXT_SPEC: any;
const context = require.context('./', true, KARMA_CONTEXT_SPEC);
Then use as follows to override the default:
KARMA_FILTER='somefile-.*\.spec\.ts$' npm run test
I documented the backstory here, apologies in advance for types and mis-links. Credit to the answer above by @Aish-Anu for pointing me in the right direction.
The other scenario you mush verify is that the file you're trying to unpack is not empty and is valid.
In my case I wasn't downloading the file correctly, after double check and I made sure I had the right file I could unpack it without any issues.
There is a C# Google Voice API... there is limited documentation, however the download has an application that 'works' using the API that is included:
You can change the encoding of a file with an editor such as notepad++. Just go to Encoding and select what you want.
I always prefer the Windows 1252
In pre-commit/post-checkout an option would be to use "mtree" (FreeBSD), or "fmtree" (Ubuntu) utility which "compares a file hierarchy against a specification, creates a specification for a file hierarchy, or modifies a specification."
The default set are flags, gid, link, mode, nlink, size, time, type, and uid. This can be fitted to the specific purpose with -k switch.
Implement custom adapter for your class:
public class MyClassAdapter extends ArrayAdapter<MyClass> {
private static class ViewHolder {
private TextView itemView;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.listview_association, parent, false);
viewHolder = new ViewHolder();
viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
MyClass item = getItem(position);
if (item!= null) {
// My layout has only one TextView
// do whatever you want with your string and long
viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
}
return convertView;
}
}
For those not very familiar with the Android framework, this is explained in better detail here: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
If you're using the public API, the best way to do it is using if
statements.
If the video is public or unlisted, you set the thumbnail using the URL method. If the video is private you use the API to get the thumbnail.
<?php
if($video_status == 'unlisted'){
$video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
$video_status = '<i class="fa fa-lock"></i> Unlisted';
}
elseif($video_status == 'public'){
$video_thumbnail = 'http://img.youtube.com/vi/'.$video_url.'/mqdefault.jpg';
$video_status = '<i class="fa fa-eye"></i> Public';
}
elseif($video_status == 'private'){
$video_thumbnail = $playlistItem['snippet']['thumbnails']['maxres']['url'];
$video_status = '<i class="fa fa-lock"></i> Private';
}
There is one more hint that not in this conversation. for asp.net core 3.1 first add the key that you need to put it in the header, something like this:
Response.Headers.Add("your-key-to-use-it-axios", "your-value");
where you define the cors policy (normaly is in Startup.cs
) you should add this key to WithExposedHeaders like this.
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders("your-key-to-use-it-axios"));
});
}
you can add all the keys here. now in your client side you can easily access to the your-key-to-use-it-axios by using the response result.
localStorage.setItem("your-key", response.headers["your-key-to-use-it-axios"]);
you can after use it in all the client side by accessing to it like this:
const jwt = localStorage.getItem("your-key")
You need to use javascript for this.
<form id="form1" action="showMessage.jsp" method="post">
<a href="javascript:;" onclick="document.getElementById('form1').submit();"><%=n%></a>
<input type="hidden" name="mess" value=<%=n%>/>
</form>
If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:
overflow: hidden;
You can do this with PureBasic and MsScriptControl
All you need to do is pasting the MsScriptControl to the Purebasic editor and add something like this below
InitScriptControl()
SCtr_AddCode("MsgBox 1")
In 2012, use the python requests library
>>> import requests
>>>
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760
You can run pip install requests
to get it.
Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case.
2015-12-30
People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including tqdm
:
from tqdm import tqdm
import requests
url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)
with open("10MB", "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
This is essentially the implementation @kvance described 30 months ago.
I am assuming you are using msys git. If you are, the editor that is popping up to write your commit message is vim. Vim is not friendly at first. You may prefer to switch to a different editor. If you want to use a different editor, look at this answer: How do I use Notepad++ (or other) with msysgit?
If you want to use vim, type i
to type in your message. When happy hit ESC. Then type :wq
, and git will then be happy.
Or just type git commit -m "your message here"
to skip the editor altogether.
The first code line, Option Explicit
means (in simple terms) that all of your variables have to be explicitly declared by Dim
statements. They can be any type, including object, integer, string, or even a variant.
This line: Dim envFrmwrkPath As Range
is declaring the variable envFrmwrkPath
of type Range
. This means that you can only set it to a range.
This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value
is attempting to set the Range
type variable to a specific Value that is in cell D6
. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.
I'm assuming you want the value stored in a variable. Try something like this:
Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value
This assumes you have a number (like 5) in cell D6. Now your variable will have the value.
For simplicity sake of learning, you can remove or comment out the Option Explicit
line and VBA will try to determine the type of variables at run time.
Try this to get through this part of your code
Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String
Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".
Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.
For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.
Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.
Others already answered your question as stated, but I find that I usually want to execute the lines that I just wrote. for that, CtrlAltx in the lisp works just fine.
VS2019 - ASP.NET Forms In my case was Tools - Options - Windows Forms Designer - "Optimized Code Generation" <- to false
Syntax:
SELECT <Expression>[Arithmetic_Operator]<expression>...
FROM [Table_Name]
WHERE [expression];
(Windows 10 pro x64) Here have some ways!
Alt + click
Alt + Ctrl + up/down
Keybindings: Ctrl + click
(??? it doesn't work!)
Just dot is working. The doctype makes a difference however as sometimes the ./ is fine as well.
<a href=".">Link to this folder</a>
I was facing the same issue in bitbucket, and this worked for me:
line1
##<2 white spaces><enter>
line2
Streams are often accessed by threads that periodically empty their content and, for example, display it on the screen, send it to a socket or write it to a file. This is done for performance reasons. Flushing an output stream means that you want to stop, wait for the content of the stream to be completely transferred to its destination, and then resume execution with the stream empty and the content sent.
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
this will get added to the recipe or cuisine depending on what was the last index.
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
During migration from Ubuntu 12.04 to 14.04 I stumbled over this as well and wanted to share that as of Ubuntu 14.04 LTS the IMAP extension seems no longer to be loaded per default.
Check to verify if the extension is installed:
dpkg -l | grep php5-imap
should give a response like this:
ii php5-imap 5.4.6-0ubuntu5 amd64 IMAP module for php5
if not, install it.
To actually enable the extension
cd /etc/php5/apache2/conf.d
ln -s ../../mods-available/imap.ini 20-imap.ini
service apache2 restart
should fix it for apache. For CLI do the same in /etc/php5/cli/conf.d
The following lines will do the trick:
ActiveSheet.EnableCalculation = False
ActiveSheet.EnableCalculation = True
Edit: The .Calculate()
method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I'm using is complex enough that I don't want to test the .CalculateFull()
method, but it may work.
I have a similar problem but all mentioned requirements are met. In my case I try to save some entity class (Type of OBJEKTE) back to the DB. Other places do work but only in this case it fails and raises this exception.
My solution (HACK) was to re-map the objet of type OBJEKTE again and store it then. Suddenly it works. But don't ask why.
OBJEKTE t = _mapper.Map<OBJEKTE>(inparam);
OBJEKTE res = await _objRepo.UpdateAsync(t);
If inparam would go straight to UpdateAsync() it cannot find a matching persistor.
It could be explained by the way NH does this. It derives a proxy from your mapping class and implements the properties with dirty handling included. See this:
t.GetType()
{Name = "OBJEKTE" FullName = "MyComp.Persistence.OBJEKTE"}
inparam.GetType()
{Name = "OBJEKTEProxyForFieldInterceptor" FullName = "OBJEKTEProxyForFieldInterceptor"}
The fun thing though is that the source of inparam
is in fact the NH repository itself. Anyways. I stay with this reassign hack for the next time being.
While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:
PRAGMA writable_schema = 1;
UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
PRAGMA writable_schema = 0;
You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.
For example:
Y:\> **sqlite3 booktest**
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT
NULL);**
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**
Error: BOOKS.publication_date may not be NULL
sqlite> **PRAGMA writable_schema = 1;**
sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT
NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**
sqlite> **PRAGMA writable_schema = 0;**
sqlite> **.q**
Y:\> **sqlite3 booktest**
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**
sqlite> **.q**
REFERENCES FOLLOW:
pragma writable_schema
When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.
[alter table](From http://www.sqlite.org/lang_altertable.html)
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.
Try this:
String output = response.getEntity(String.class);
EDIT
Thanks to @Martin Spamer to mention that it will work for Jersey 1.x jars only. For Jersey 2.x use
String output = response.readEntity(String.class);
Actually, the jQuery documentation has a more simple approach than the chained examples shown above (although they'll work just fine):
$("#myElement").unbind('mouseenter mouseleave');
As of jQuery 1.7, you are also able use $.on()
and $.off()
for event binding, so to unbind the hover event, you would use the simpler and tidier:
$('#myElement').off('hover');
The pseudo-event-name "hover" is used as a shorthand for "mouseenter mouseleave" but was handled differently in earlier jQuery versions; requiring you to expressly remove each of the literal event names. Using $.off()
now allows you to drop both mouse events using the same shorthand.
Edit 2016:
Still a popular question so it's worth drawing attention to @Dennis98's point in the comments below that in jQuery 1.9+, the "hover" event was deprecated in favour of the standard "mouseenter mouseleave" calls. So your event binding declaration should now look like this:
$('#myElement').off('mouseenter mouseleave');
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);
Just supply -s to your read call like so:
$ read -s PASSWORD
$ echo $PASSWORD
I prefer to do this via a script nowadays
REM install the needed Windows IIS features for WCF
dism /Online /Enable-Feature /FeatureName:WAS-WindowsActivationService
dism /Online /Enable-Feature /FeatureName:WAS-ProcessModel
dism /Online /Enable-Feature /FeatureName:WAS-NetFxEnvironment
dism /Online /Enable-Feature /FeatureName:WAS-ConfigurationAPI
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
dism /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45
REM Feature Install Complete
pause
This is an old post but...
You can reference the working directory (the folder the .html file is located in) with ./
, and the directory above that with ../
Example directory structure:
/html/public/
- index.html
- script2.js
- js/
- script.js
To load script.js from inside index.html:
<script type="text/javascript" src="./js/script.js">
This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.
You could also specify ../
to go one directory above the working directory, to load things from there. But that is unusual.
When remoted into a machine (target is Windows XP anyway; I am not sure about target Windows Vista), although Shutdown on the start menu is replaced by Disconnect Session or something like that, there should be one called 'Windows Security' which also does the same thing as Ctrl + Alt + End as pointed to by Owen.
Visiblity property has not been implemented on the Tabpages, and there is no Insert method also.
You need to manually insert and remove tab pages.
Here is a work around for the same.
http://www.dotnetspider.com/resources/18344-Hiding-Showing-Tabpages-Tabcontrol.aspx
While waiting for the adoption of CSS3 targeting by the major browsers, one could run the following sed
command once the (X)HTML has been created:
sed -i 's|href="http|target="_blank" href="http|g' index.html
It will add target="_blank"
to all external hyperlinks. Variations are also possible.
EDIT
I use this at the end of the makefile
which generates every web page on my site.
Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story.
Apply to the body seems to get rid of the horizontal scrollbar
overflow-x: hidden;
Method 1:
extension UILabel {//Write this extension after close brackets of your class
func lblFunction() {
numberOfLines = 0
lineBreakMode = .byWordWrapping//If you want word wraping
//OR
lineBreakMode = .byCharWrapping//If you want character wraping
}
}
Now call simply like this
myLbl.lblFunction()//Replace your label name
EX:
Import UIKit
class MyClassName: UIViewController {//For example this is your class.
override func viewDidLoad() {
super.viewDidLoad()
myLbl.lblFunction()//Replace your label name
}
}//After close of your class write this extension.
extension UILabel {//Write this extension after close brackets of your class
func lblFunction() {
numberOfLines = 0
lineBreakMode = .byWordWrapping//If you want word wraping
//OR
lineBreakMode = .byCharWrapping//If you want character wraping
}
}
Method 2:
Programmatically
yourLabel.numberOfLines = 0
yourLabel.lineBreakMode = .byWordWrapping//If you want word wraping
//OR
yourLabel.lineBreakMode = .byCharWrapping//If you want character wraping
Method 3:
Through Story board
To display multiple lines set 0(Zero), this will display more than one line in your label.
If you want to display n lines, set n.
See below screen.
If you want to set minimum font size for label Click Autoshrink and Select Minimum Font Size option
See below screens
Here set minimum font size
EX: 9 (In this image)
If your label get more text at that time your label text will be shrink upto 9
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Not really sure what you mean by no "function"
Obviously, change ECHO
to SET
to set the variables rather thon ECHOing them...
See for
documentation for a full list.
ceztko's test case (for reference)
@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)
Comment : please see comments.
Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20080701</version>
</dependency>
Connect with SSH and follow these instructions to install Node on a shared hosting
In short you first install NVM, then you install the Node version of your choice with NVM.
wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash
Your restart your shell (close and reopen your sessions). Then you
nvm install stable
to install the latest stable version for example. You can install any version of your choice. Check node --version
for the node version you are currently using and nvm list
to see what you've installed.
In bonus you can switch version very easily (nvm use <version>
)
There's no need of PHP or whichever tricky workaround if you have SSH.
This happens when you index a row/column with a number that is larger than the dimensions of your dataframe
. For instance, getting the eleventh column when you have only three.
import pandas as pd
df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})
You have 5 rows and three columns:
Name City Car
0 Mark Lisbon Tesla
1 Laura Montreal Audi
2 Adam Lisbon Porsche
3 Roger Berlin Ford
4 Anna Glasgow Honda
Let's try to index the eleventh column (it doesn't exist):
df.iloc[:, 10] # there is obviously no 11th column
IndexError: single positional indexer is out-of-bounds
If you are a beginner with Python, remember that df.iloc[:, 10]
would refer to the eleventh column.
Just search for the string in plain old indexOf
arr.forEach(function(a){
if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
console.log(a);
}
});
Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:
// ...
url: "MyUrl", // For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,
data:
$('#myForm').serialize() +
"¶m1="xxx" +
"¶m2="33" +
"&" + $.param({ paramArray: ["1","2","3"]}, true)
,
// ...
I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress
P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.
You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.
[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.
For the noobs out there who find this stuff fun and interesting, the fastest way to read an entire file into a string in most cases (according to these benchmarks) is by the following:
using (StreamReader sr = File.OpenText(fileName))
{
string s = sr.ReadToEnd();
}
//you then have to process the string
However, the absolute fastest to read a text file overall appears to be the following:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
//do what you have to here
}
}
Put up against several other techniques, it won out most of the time, including against the BufferedReader.
The following can be used to retreive an environment parameter:
println System.getenv("MY_PARAM")
The <section>
tag defines sections in a document, such as chapters, headers, footers, or any other sections of the document.
whereas:
The <div>
tag defines a division or a section in an HTML document.
The <div>
tag is used to group block-elements to format them with CSS.
There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:
.\mydocuments\folder\mybat.bat
.\mydocuments\folder\subfolder\file.txt
And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:
@Echo OFF
REM Do anything with ".\Subfolder\File1.txt"
PUSHD ".\Subfolder"
Type "File1.txt"
Pause&Exit
Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:
@Echo OFF
Echo Launch dir: "%~dp0"
Echo Current dir: "%CD%"
Pause&Exit
Besides all above solutions, check if you have the "id" or any custom defined parameter in the DELETE method is matching the route config.
public void Delete(int id)
{
//some code here
}
If you hit with repeated 405 errors better reset the method signature to default as above and try.
The route config by default will look for id in the URL. So the parameter name id is important here unless you change the route config under App_Start folder.
You may change the data type of the id though.
For example the below method should work just fine:
public void Delete(string id)
{
//some code here
}
Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.
DELETE http://{url}/{action}/{id}
Example:
DELETE http://localhost/item/1
Hope it helps.
Quick review,
From x86 assembly tutorial,
The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.
Your num is 1 byte. Try declaring it with DD
so that it becomes 4 bytes and matches with pop
semantics.
public class SwitCase {
public static void main (String[] args){
String hello = JOptionPane.showInputDialog("Input a letter: ");
char hi = hello.charAt(0); //get the first char.
switch(hi){
case 'a': System.out.println("a");
}
}
}
You can create an std::string
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
// check if there is more than one argument and use the second one
// (the first argument is the executable)
if (argc > 1)
{
std::string arg1(argv[1]);
// do stuff with arg1
}
// Or, copy all arguments into a container of strings
std::vector<std::string> allArgs(argv, argv + argc);
}
$ sudo port install py27-pip
Then update your PATH to include py27-pip bin directory (you can add this in ~/.bash_profile PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATH
pip will be available in new terminal window.
If you really want to avoid putting something with a name (either an iteration variable as in the OP, or unwanted list or unwanted generator returning true the wanted amount of time) you could do it if you really wanted:
for type('', (), {}).x in range(somenumber):
dosomething()
The trick that's used is to create an anonymous class type('', (), {})
which results in a class with empty name, but NB that it is not inserted in the local or global namespace (even if a nonempty name was supplied). Then you use a member of that class as iteration variable which is unreachable since the class it's a member of is unreachable.
This error tells you everything:
undefined reference toHash::insert(int, char)
You're not linking with the implementations of functions defined in Hash.h
. Don't you have a Hash.cpp
to also compile and link?
npm i -g @angular/[email protected]
x,y,z--> ur desired version number
Will this answer Help you?
If you are receiving the following message in the EventViewer
The Module DLL aspnetcorev2.dll failed to load. The data is the error.
Then yes this will solve your problem
To check your event Viewer
eventvwr
, then press ENTER.Windows Event Viewer
click on Windows Logs
-> Application
.IIS-W3SVC-WP
in the middle window.Install Microsoft Visual C++ 2015 Redistributable 86x AND 64X (both of them)
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
TextMarks gives you access to its shared shortcode to send and receive text messages from your app via their API. Messages come from/to 41411 (instead of e.g. a random phone# and unlike e-mail gateways you have the full 160 chars to work with).
You can also tell people to text in your keyword(s) to 41411 to invoke various functionality in your app. There is a JAVA API client along with several other popular languages and very comprehensive documentation and technical support.
The 14 day free trial can be easily extended for developers who are still testing it out and building their apps.
Check it out here: TextMarks API Info
In iTunes 11 you can go to the view menu, and "Show Sidebar", this will give you the sidebar, that you can drag 'n drop to.
You'll drag 'n drop to the open area that will be near the bottom of the sidebar (I'm typically doing this with both an IPA and a provisioning profile). After you do that, there will be an apps menu that appears in the sidebar with your app in it. Click on that, and you'll see your application in the main view. You can then drag your application from there to your device. Below, please find a video (it's private, so you'll need the URL) that outlines the steps visually: http://youtube.com/watch?v=0ACq4CRpEJ8&feature=youtu.be
Please try this
<?php
$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>
if you want to include float values also you can use the following code
theValue=$('#balanceinput').val();
var isnum1 = /^\d*\.?\d+$/.test(theValue);
var isnum2 = /^\d*\.?\d+$/.test(theValue.split("").reverse().join(""));
alert(isnum1+' '+isnum2);
this will test for only digits and digits separated with '.' the first test will cover values such as 0.1 and 0 but also .1 , it will not allow 0. so the solution that I propose is to reverse theValue so .1 will be 1. then the same regular expression will not allow it .
example :
theValue=3.4; //isnum1=true , isnum2=true
theValue=.4; //isnum1=true , isnum2=false
theValue=3.; //isnum1=flase , isnum2=true
I was facing the similar type of issue: Code Snippet :
<c:forEach items="${orderList}" var="xx">
${xx.id} <br>
</c:forEach>
There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.
So make sure about space. They play crucial role sometimes. :p
just use synchronization context of ui
using System.Threading;
// ...
public partial class MyForm : Form
{
private readonly SynchronizationContext uiContext;
public MyForm()
{
InitializeComponent();
uiContext = SynchronizationContext.Current; // get ui thread context
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(() =>
{// set ui thread context to new thread context
// for operations with ui elements to be performed in proper thread
SynchronizationContext
.SetSynchronizationContext(uiContext);
label1.Text = "some text";
});
t.Start();
}
}
For those who can't install wkhtmltopdf in their systems, one more method other than many already mentioned in the answers to this question is to simply download the file as an html file from the jupyter notebook, upload that to HTML to PDF, and download the converted pdf files from there.
Here you have your IPython notebook(.ipynb) converted to both PDF(.pdf) & HTML(.html) formats.
(WINDOWS - AWS solution)
Solved for windows by putting tripple quotes around files and paths.
Benefits:
1) Prevents excludes that quietly were getting ignored.
2) Files/folders with spaces in them, will no longer kick errors.
aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/" --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '
r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)
I assume you want to link to a library called foo, its filename is usually something link foo.dll
or libfoo.so
.
1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB
use
find_library(FOO_LIB foo)
CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib
, /usr/lib64
and the paths in PATH
.
You already know the location of your library. Add it to the CMAKE_PREFIX_PATH
when you call CMake, then CMake will look for your library in the passed paths, too.
Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html
2. Link the library
From 1. you have the full library name in FOO_LIB
. You use this to link the library to your target GLBall
as in
target_link_libraries(GLBall PRIVATE "${FOO_LIB}")
You should add PRIVATE
, PUBLIC
, or INTERFACE
after the target, cf. the documentation:
https://cmake.org/cmake/help/latest/command/target_link_libraries.html
If you don't add one of these visibility specifiers, it will either behave like PRIVATE
or PUBLIC
, depending on the CMake version and the policies set.
3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path
similar to find_library
and search for a header file. Then add the include directory with target_include_directories
similar to target_link_libraries
.
Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html
If available for the external software, you can replace find_library
and find_path
by find_package
.
When you use : scene.remove(object); The object is removed from the scene, but the collision with it is still enabled !
To remove also the collsion with the object, you can use that (for an array) : objectsArray.splice(i, 1);
Example :
for (var i = 0; i < objectsArray.length; i++) {
//::: each object ::://
var object = objectsArray[i];
//::: remove all objects from the scene ::://
scene.remove(object);
//::: remove all objects from the array ::://
objectsArray.splice(i, 1);
}
The jackson API has changed:
new ObjectMapper()
.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(new HashMap<String, Object>());
The standard procedures are:
Add a service to the Angular 4 app using Angular CLI
An Angular 2 service is simply a javascript function along with it's associated properties and methods, that can be included (via dependency injection) into Angular 2 components.
To add a new Angular 4 service to the app, use the command ng g service serviceName
. On creation of the service, the Angular CLI shows an error:
To solve this, we need to provide the service reference to the src\app\app.module.ts
inside providers
input of @NgModule
method.
Initially, the default code in the service is:
import { Injectable } from '@angular/core';
@Injectable()
export class ServiceNameService {
constructor() { }
}
A service has to have a few public methods.
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});
Just notice that if you work with Fragments using ViewPager, it's pretty easy. You only need to call this method: setOffscreenPageLimit()
.
Accordign to the docs:
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
Just add your text between the font tags:
for blue color
<string name="hello_world"><font color='blue'>Hello world!</font></string>
or for red color
<string name="hello_world"><font color='red'>Hello world!</font></string>
No-one has mentioned the map
function, which allows a function to operate element-wise on a list:
mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']
values = list( map(mydictionary.get, keys) )
# values = ['bear', 'castle']
This is the one-liner I copy-and-paste:
curl https://bootstrap.pypa.io/get-pip.py | python3
Alternate:
curl -L get-pip.io | python3
From Installing with get-pip.py:
To install pip, securely download
get-pip.py
by following this link: get-pip.py. Alternatively, use curl:curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then run the following command in the folder where you have downloaded get-pip.py:
python get-pip.py
Warning: Be cautious if you are using a Python install that is managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.
I had the same question. I tried invoking php through the shell interface, and it produced the desired result:
var exec = require("child_process").exec;
app.get('/', function(req, res){exec("php index.php", function (error, stdout, stderr) {res.send(stdout);});});
I'm sure this is not high on the recommended practices list, but it seemed to do what I wanted. If, on the other hand, you don't want to execute PHP scripts directly from Node.js but want to relay them from another web server that does, this seems to do the trick:
var exec = require("child_process").exec;
app.get('/', function(req, res){exec("wget -q -O - http://localhost/", function (error, stdout, stderr) {res.send(stdout);});});
This will also give external links an absolute path without having to use php.ini
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.your_external_website.com/$2$3', $result);
echo $result
?>
If you have skype shutdown and the problem still persists. Try this. It could be that apache is set to automatic on restart. Meaning apache is already using that port. Go to services in your XAMPP control and look for apache (whatever version you have). Look for startup type and double-click it to set it to manual.
Hope this works!
In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.
Often a volatile boolean
field is used which the thread periodically checks and terminates when it is set to the corresponding value.
I would not use a boolean
to check whether the thread should terminate. If you use volatile
as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while
loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.
Certain blocking library methods support interruption.
Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:
public void run() {
try {
while (!interrupted()) {
// ...
}
} catch (InterruptedException consumed)
/* Allow thread to exit */
}
}
public void cancel() { interrupt(); }
Source code adapted from Java Concurrency in Practice. Since the cancel()
method is public you can let another thread invoke this method as you wanted.
Without the combined child selector you would probably do something similar to this:
foo {
bar {
baz {
color: red;
}
}
}
If you want to reproduce the same syntax with >
, you could to this:
foo {
> bar {
> baz {
color: red;
}
}
}
This compiles to this:
foo > bar > baz {
color: red;
}
Or in sass:
foo
> bar
> baz
color: red
Here is code by AbacusUtil
Stream.of(names).indexed()
.filter(e -> e.value().length() <= e.index())
.map(Indexed::value).toList();
Disclosure: I'm the developer of AbacusUtil.
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
The CSS solution is: http://www.w3.org/TR/css3-multicol/
The browser support is exactly what you'd expect..
It works "everywhere" except Internet Explorer 9 or older: http://caniuse.com/multicolumn
ul {
-moz-column-count: 4;
-moz-column-gap: 20px;
-webkit-column-count: 4;
-webkit-column-gap: 20px;
column-count: 4;
column-gap: 20px;
}
See: http://jsfiddle.net/pdExf/
If IE support is required, you'll have to use JavaScript, for example:
http://welcome.totheinter.net/columnizer-jquery-plugin/
Another solution is to fallback to normal float: left
for only IE. The order will be wrong, but at least it will look similar:
See: http://jsfiddle.net/NJ4Hw/
<!--[if lt IE 10]>
<style>
li {
width: 25%;
float: left
}
</style>
<![endif]-->
You could apply that fallback with Modernizr if you're already using it.
Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.
Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.
result = sorted(set(map(tuple, my_list)), reverse=True)
Additional note: If a tuple contains a list, the tuple is still considered mutable.
Some examples:
>>> hash( tuple() )
3527539
>>> hash( dict() )
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
hash( list() )
TypeError: unhashable type: 'list'
Here is my solution after trying other ones available on this post, I'm using it to upload photo on TwitPic:
def upload(photo)
`curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`
end
It would be best to have a TIMESTAMP
column that defaults to CURRENT_TIMESTAMP
.. it is the only true predictive behavior you can find here.
The second-best thing you can do is ORDER BY ID DESC LIMIT 1
and hope the newest ID is the largest value.
Within a module, Verilog contains essentially two constructs: items and statements. Statements are always found in procedural contexts, which include anything in between begin..end, functions, tasks, always blocks and initial blocks. Items, such as generate constructs, are listed directly in the module. For loops and most variable/constant declarations can exist in both contexts.
In your code, it appears that you want the for loop to be evaluated as a generate item but the loop is actually part of the procedural context of the always block. For a for loop to be treated as a generate loop it must be in the module context. The generate..endgenerate keywords are entirely optional(some tools require them) and have no effect. See this answer for an example of how generate loops are evaluated.
//Compiler sees this
parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
genvar c;
always @(posedge sysclk) //Procedural context starts here
begin
for (c = 0; c < ROWBITS; c = c + 1) begin: test
temp[c] <= 1'b0; //Still a genvar
end
end
In java a char is an int. Your first snippet prints out the character corresponding to the value of 1 in the default character encoding scheme (which is probably Unicode). The Unicode character U+0001 is a non-printing character, which is why you don't see any output.
If you want to print out the character '1', you can look up the value of '1' in the encoding scheme you are using. In Unicode this is 49 (the same as ASCII). But this will only work for digits 0-9.
You might be better off using a String rather than a char, and using Java's built-in toString()
method:
int a = 1;
String b = toString(a);
System.out.println(b);
This will work whatever your system encoding is, and will work for multi-digit numbers.
The obvious answer is to use one of the special forms of parameter expansion:
: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}
Or, better (see section on 'Position of double quotes' below):
: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"
The first variant (using just ?
) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.
The second variant (using :?
) requires DEST to be set and non-empty.
If you supply no message, the shell provides a default message.
The ${var?}
construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?}
construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.
It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash
manual says:
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#
' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#
' hash) or the Bourne shell (a ':
' colon). Then the kernel got in on the act and added support for '#!/path/to/program
' and the Bourne shell got '#
' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.
Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749
The gist of the discussion is:
… However, when I
shellcheck
it (with version 0.4.1), I get this message:In script.sh line 13: : ${FOO:?"The environment variable 'FOO' must be set and non-empty"} ^-- SC2086: Double quote to prevent globbing and word splitting.
Any advice on what I should do in this case?
The short answer is "do as shellcheck
suggests":
: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"
To illustrate why, study the following. Note that the :
command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n"
in place of :
.
$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$
$ x="*"
$ printf "%s\n" ${x:?You must set x} # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x} # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}" # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}" # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"} # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"} # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"} # Not quite careful enough
bash: x: You must set x
$
Note how the value in $x
is expanded to first *
and then a list of file names when the overall expression is not in double quotes. This is what shellcheck
is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.
This line:
public object Hours { get; set; }}
Your have a redundand }
at the end
string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)
For Symfony3 In your controller try
$request->server->get('DOCUMENT_ROOT').$request->getBasePath()
Hardcoding a password in an expect script is the same as having a passwordless sudo, actually worse, since sudo at least logs its commands.
I am not sure if this is still bothering you but take a look at this page for slack text formatting:
https://api.slack.com/docs/message-formatting#linking_to_urls
For example using Python and the slack API:
from slackclient import SlackClient
slack_client = SlackClient(your_slack_token)
link_as_text_example = '<http://www.hyperlinkcode.com/|Hyperlink Code>'
slack_client.api_call("chat.postMessage", channel=channel_to_post, text=link_as_text_example , as_user=True)
You can also send a more advance JSON following the link: https://api.slack.com/docs/message-attachments
You can also use str.partition
:
>>> text = "123mango abcd mango kiwi peach"
>>> text.partition("mango")
('123', 'mango', ' abcd mango kiwi peach')
>>> text.partition("mango")[-1]
' abcd mango kiwi peach'
>>> text.partition("mango")[-1].lstrip() # if whitespace strip-ing is needed
'abcd mango kiwi peach'
The advantage of using str.partition
is that it's always gonna return a tuple in the form:
(<pre>, <separator>, <post>)
So this makes unpacking the output really flexible as there's always going to be 3 elements in the resulting tuple.
mysql> show tables;
it will show the names of the tables, then the count on tables.
For Angular 7+,
1) add a file "typings.d.ts" to the project's root folder (e.g., src/typings.d.ts):
declare module "*.json" {
const value: any;
export default value;
}
2) import and access JSON data either:
import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
constructor() {
console.log(data.default);
}
}
or:
import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
constructor() {
console.log(data);
}
}
Seems you can just use the prop method on the angular element:
var top = $el.prop('offsetTop');
Works for me. Does anyone know any downside to this?
purple.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you
This is a quirk of the C grammar. A label (Cleanup:
) is not allowed to appear immediately before a declaration (such as char *str ...;
), only before a statement (printf(...);
). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.
You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:
int main (void)
{
char *str;
printf("Hello ");
goto Cleanup;
Cleanup:
str = "World\n";
printf("%s\n", str);
return 0;
}
For what it's worth, I just created a directory on an ext4
file system with 1,000,000 files in it, then randomly accessed those files through a web server. I didn't notice any premium on accessing those over (say) only having 10 files there.
This is radically different from my experience doing this on ntfs
a few years back.
svn move
— Move a file or directory.
For a nice looking screencast, have a look at SimFinger. You will still need a screen recoder such as Snapz Pro.
import re
Text = " You can select below trims for removing white space!! BR Aliakbar "
# trims all white spaces
print('Remove all space:',re.sub(r"\s+", "", Text), sep='')
# trims left space
print('Remove leading space:', re.sub(r"^\s+", "", Text), sep='')
# trims right space
print('Remove trailing spaces:', re.sub(r"\s+$", "", Text), sep='')
# trims both
print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", Text), sep='')
# replace more than one white space in the string with one white space
print('Remove more than one space:',re.sub(' +', ' ',Text), sep='')
Result:
Remove all space:Youcanselectbelowtrimsforremovingwhitespace!!BRAliakbar
Remove leading space:You can select below trims for removing white space!! BR Aliakbar
Remove trailing spaces: You can select below trims for removing white space!! BR Aliakbar
Remove leading and trailing spaces:You can select below trims for removing white space!! BR Aliakbar
Remove more than one space: You can select below trims for removing white space!! BR Aliakbar
You need to import the module datetime
first:
>>> import datetime
After that it works:
>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
Complex types are in the C language since C99 standard (-std=c99
option of GCC). Some compilers may implement complex types even in more earlier modes, but this is non-standard and non-portable extension (e.g. IBM XL, GCC, may be intel,... ).
You can start from http://en.wikipedia.org/wiki/Complex.h - it gives a description of functions from complex.h
This manual http://pubs.opengroup.org/onlinepubs/009604499/basedefs/complex.h.html also gives some info about macros.
To declare a complex variable, use
double _Complex a; // use c* functions without suffix
or
float _Complex b; // use c*f functions - with f suffix
long double _Complex c; // use c*l functions - with l suffix
To give a value into complex, use _Complex_I
macro from complex.h
:
float _Complex d = 2.0f + 2.0f*_Complex_I;
(actually there can be some problems here with (0,-0i)
numbers and NaNs in single half of complex)
Module is cabs(a)
/cabsl(c)
/cabsf(b)
; Real part is creal(a)
, Imaginary is cimag(a)
. carg(a)
is for complex argument.
To directly access (read/write) real an imag part you may use this unportable GCC-extension:
__real__ a = 1.4;
__imag__ a = 2.0;
float b = __real__ a;
I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i>
tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.
It does make really bad practice because when I saw it I went through the template and changed all the <i>
tags to <span style="font-style:italic">
instead and then wondered why the entire template looked strange.
This is the main reason it is a bad idea to use the <i>
tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code
<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">
that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i>
- and also it passes W3C standard.
Snagged from Oracle OTN forums
Use alter table to add column, for example:
alter table tableName add(columnName NUMBER);
Then create a sequence:
CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;
and, the use update
to insert values in column like this
UPDATE tableName SET columnName = seq_test_id.NEXTVAL
It's simple, set a specific value for that label (XXXXXXX for example) and run it, open html source of output (in browser) and look for XXXXXXX, you will see something like this <span id="mylabel">XXXXXX</span>
it's what you want, the ID of <span>
(I think it's usually same as Label name in asp code) now you can get its value by innerHTML or another method in JQuery
Late, but to be completed with options here: A handy tool to install any apk via gui to a running emulator is: http://apkinstaller.com
This can directly connect to a running instance via adb and can successfully install any kind of apk packages.
Maybe this is also helpful for other people. ;)
Save sub object first and then call final repository save method.
@PostMapping("/save")
public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
if (existingShortcode != null) {
result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
}
if (result.hasErrors()) {
return "redirect:/shortcode/create";
}
**shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
shortcodeService.save(shortcode);
return "redirect:/shortcode/create?success";
}
datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2)
will return True
.
datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2)
will return datetime.timedelta(-1)
.
datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2)
will return datetime.timedelta(1)
.
see the docs.
Add this: jQuery.support.cors = true;
It enables cross-site scripting in jQuery (introduced after 1.4x, I believe).
We were using a really old version of jQuery (1.3.2) and swapped it out for 1.6.1. Everything was working, except .ajax() calls. Adding the above line fixed the problem.
Though the question has a decent answer already, I just want to stress that the :first-child
tag goes on the item type that represents the children.
For example, in the code:
<div id"someDiv">
<input id="someInput1" />
<input id="someInput2" />
<input id="someInput2" />
</div
If you want to affect only the second two elements with a margin, but not the first, you would do:
#someDiv > input {
margin-top: 20px;
}
#someDiv > input:first-child{
margin-top: 0px;
}
that is, since the input
s are the children, you would place first-child
on the input portion of the selector.
encapsulate all of your js code within a window.onload function. I had a similar issue. Everything is loaded asynchronously in javascript so some parts load quicker than others, including your browser. Putting all of your code inside the onload function will ensure everything your code will need from the browser will be ready to use before attempting to execute.
First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]
$doc = [xml]@'
<xml>
<Section name="BackendStatus">
<BEName BE="crust" Status="1" />
<BEName BE="pizza" Status="1" />
<BEName BE="pie" Status="1" />
<BEName BE="bread" Status="1" />
<BEName BE="Kulcha" Status="1" />
<BEName BE="kulfi" Status="1" />
<BEName BE="cheese" Status="1" />
</Section>
</xml>
'@
Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:
$doc.xml.Section.BEName
Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where
$doc.xml.Section.BEName | ? { $_.Status -eq 1 }
The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).
If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:
$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }
Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.
The same way as you'd set the type (number format mask) after writing a value to it:
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_GENERAL
);
or
$objPHPExcel->getActiveSheet()
->getStyle('A1')
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
Though "Number" isn't a valid format mask.
You can find a list of pre-defined format masks in Classes/PHPExcel/Style/NumberFormat.php or set the value to any valid Excel number format masking string.
May be you think the combination like this:
SELECT *
FROM table t INNER JOIN
(
SELECT * FROM (VALUES('bla'),('foo'),('batz')) AS list(col)
) l ON t.column LIKE '%'+l.Col+'%'
If you have defined full text index for your target table then you may use this alternative:
SELECT *
FROM table t
WHERE CONTAINS(t.column, '"bla*" OR "foo*" OR "batz*"')
Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");
If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:
Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or = (Color) ColorConverter.ConvertFromString("#FFCC66") ;
With the dplyr
package, you can use summarise_all
, summarise_at
or summarise_if
functions to aggregate multiple variables simultaneously. For the example dataset you can do this as follows:
library(dplyr)
# summarising all non-grouping variables
df2 <- df1 %>% group_by(year, month) %>% summarise_all(sum)
# summarising a specific set of non-grouping variables
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(x1, x2), sum)
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(-date), sum)
# summarising a specific set of non-grouping variables using select_helpers
# see ?select_helpers for more options
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(starts_with('x')), sum)
df2 <- df1 %>% group_by(year, month) %>% summarise_at(vars(matches('.*[0-9]')), sum)
# summarising a specific set of non-grouping variables based on condition (class)
df2 <- df1 %>% group_by(year, month) %>% summarise_if(is.numeric, sum)
The result of the latter two options:
year month x1 x2
<dbl> <dbl> <dbl> <dbl>
1 2000 1 -73.58134 -92.78595
2 2000 2 -57.81334 -152.36983
3 2000 3 122.68758 153.55243
4 2000 4 450.24980 285.56374
5 2000 5 678.37867 384.42888
6 2000 6 792.68696 530.28694
7 2000 7 908.58795 452.31222
8 2000 8 710.69928 719.35225
9 2000 9 725.06079 914.93687
10 2000 10 770.60304 863.39337
# ... with 14 more rows
Note: summarise_each
is deprecated in favor of summarise_all
, summarise_at
and summarise_if
.
As mentioned in my comment above, you can also use the recast
function from the reshape2
-package:
library(reshape2)
recast(df1, year + month ~ variable, sum, id.var = c("date", "year", "month"))
which will give you the same result.
When dealing with corrupted shards you can set the replication factor to 0 and then set it back to the original value. This should clear up most if not all your corrupted shards and relocate the new replicas in the cluster.
Setting indexes with unassigned replicas to use a replication factor of 0:
curl -XGET http://localhost:9200/_cat/shards |\
grep UNASSIGNED | grep ' r ' |\
awk '{print $1}' |\
xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
-d '{ "index":{ "number_of_replicas": 0}}'
Setting them back to 1:
curl -XGET http://localhost:9200/_cat/shards |\
awk '{print $1}' |\
xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
-d '{ "index":{ "number_of_replicas": 1}}'
Note: Do not run this if you have different replication factors for different indexes. This would hardcode the replication factor for all indexes to 1.
You could try some sort of COALESCE trick, eg:
SELECT COALESCE( CASE WHEN condition1 THEN calculation1 ELSE NULL END, CASE WHEN condition2 THEN calculation2 ELSE NULL END, etc... )
for single array Item use reset($item)
<Resource>
tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password=""
maxActive="10"
maxIdle="10"
minIdle="5"
maxWait="10000"/>
<ResourceLink>
inside the <Context>
tag.<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" />
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>
Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->