If you need one-off sync with the solution pane, then there is new command "Sync with Active Document" (default shortcut: Ctrl+[, S). Explained here: Visual Studio 2012 New Features: Solution Explorer
The problem could be in the path of the file you want to open. Try and print the path and see if it is fine I had a similar problem
def scrap(soup,filenm):
htm=(soup.prettify().replace("https://","")).replace("http://","")
if ".php" in filenm or ".aspx" in filenm or ".jsp" in filenm:
filenm=filenm.split("?")[0]
filenm=("{}.html").format(filenm)
print("Converted a file into html that was not compatible")
if ".aspx" in htm:
htm=htm.replace(".aspx",".aspx.html")
print("[process]...conversion fron aspx")
if ".jsp" in htm:
htm=htm.replace(".jsp",".jsp.html")
print("[process]..conversion from jsp")
if ".php" in htm:
htm=htm.replace(".php",".php.html")
print("[process]..conversion from php")
output=open("data/"+filenm,"w",encoding="utf-8")
output.write(htm)
output.close()
print("{} bits of data written".format(len(htm)))
but after adding this code:
nofilenametxt=filenm.split('/')
nofilenametxt=nofilenametxt[len(nofilenametxt)-1]
if (len(nofilenametxt)==0):
filenm=("{}index.html").format(filenm)
I have similar situation. In my case, it doesn't have a parent with position:relative. Just paste my solution here for those that might need.
position: fixed;
left: 0;
right: 0;
Okay, it is a few days ago... In my current case, the answer from ZloiAdun does not work for me, but brings me very close to my solution...
Instead of:
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
the following code makes me happy:
element.sendKeys(Keys.HOME, Keys.chord(Keys.SHIFT, Keys.END), "55");
So I hope that helps somebody!
You can specify a width on string fields, e.g.
printf("%-20s", "initialization...");
And then whatever's printed with that field will be blank-padded to the width you indicate.
The -
left-justifies your text in that field.
Using defaults (historically specific to nodejs but now usable from the browser thanks to modern JS):
import defaults from 'object.defaults';
const myCopy = defaults({}, myObject);
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super
to call the parent method, inside the body of the child method.
public class PolyTest{
public static void main(String args[]){
new Child().foo();
}
}
class Parent{
public void foo(){
System.out.println("I'm the parent.");
}
}
class Child extends Parent{
@Override
public void foo(){
//super.foo();
System.out.println("I'm the child.");
}
}
This would print:
I'm the child.
Uncomment the commented line and it would print:
I'm the parent.
I'm the child.
You should look for the concept of Polymorphism.
Thread
Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.
The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.
There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.
ThreadPool
ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.
Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.
Task
Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.
Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.
You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.
Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.
All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.
Conclusion
The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.
The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.
I'm assuming you're using VS2010 (that's what you've tagged the question as) I had problems getting them to add automatically to the toolbox as in VS2008/2005. There's actually an option to stop the toolbox auto populating!
Go to Tools > Options > Windows Forms Designer > General
At the bottom of the list you'll find Toolbox > AutoToolboxPopulate which on a fresh install defaults to False. Set it true and then rebuild your solution.
Hey presto they user controls in you solution should be automatically added to the toolbox. You might have to reload the solution as well.
A simple example if you only are looking for a process name exist or not:
import os
def pname_exists(inp):
os.system('ps -ef > /tmp/psef')
lines=open('/tmp/psef', 'r').read().split('\n')
res=[i for i in lines if inp in i]
return True if res else False
Result:
In [21]: pname_exists('syslog')
Out[21]: True
In [22]: pname_exists('syslog_')
Out[22]: False
Using psql : \dt
Or:
SELECT c.relname AS Tables_in FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.pg_table_is_visible(c.oid)
AND c.relkind = 'r'
AND relname NOT LIKE 'pg_%'
ORDER BY 1
<script>
$(document).ready(function(){
alert('Hi');
});
</script>
If using Datatable > 1.1.0 then lengthChange
option is what you need as below :
$('#example').dataTable( {
"lengthChange": false
});
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
You can use the .not() method:
$(".content_box a").not(".button")
Alternatively, you can also use the :not() selector:
$(".content_box a:not('.button')")
There is little difference between the two approaches, except .not()
is more readable (especially when chained) and :not()
is very marginally faster. See this Stack Overflow answer for more info on the differences.
Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.
Difference between OpenJDK and AdoptOpenJDK
The first provides source-code, the other provides builds of that source-code.
Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:
See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.
Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.
Here is a list of considerations and motivations to consider in choosing a vendor and implementation.
Some vendors offer you a choice of JIT technologies.
To understand more about this Java ecosystem, read Java Is Still Free
Using dependency injection is much better in my opinion if you are: 1. deploying your code in small partition, because it handles well in decoupling of one big code. 2. testability is one of the case DI is ok to use because you can mock easily the non decoupled objects. with the use of interfaces you can easily mock and test each objects. 3. you can simultaneously revised each part of the program without needing to code the other part of it since its loosely decoupled.
As the accepted solution of @Shane is not supported in RStudio (see here) as of now (Sep 2015), I would like to add an advice to @James Thompson answer regarding workflow:
If you use SumatraPDF as viewer you do not need to close the PDF file before making changes to it. Sumatra does not put a opened file in read-only and thus does not prevent it from being overwritten. Therefore, once you opened your PDF file with Sumatra, changes out of RStudio (or any other R IDE) are immediately displayed in Sumatra.
According to the documentation of the PropertyFile
task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.
On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.
EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .
The solutions above are superior, especially if using Java, and encountering more numbers with more than 10 digits such as the international code prefix or additional extension numbers. This solution is basic (I'm a beginner in the regex world) and designed with US Phone numbers in mind and is only useful for strings with just 10 numbers with perhaps some formatting characters, or perhaps no formatting characters at all (just 10 numbers). As such I would recomend this solution only for semi-automatic applications. I Personally prefer to store numbers as just 10 numbers without formatting characters, but also want to be able to convert or clean phone numbers to the standard format normal people and apps/phones will recognize instantly at will.
I came across this post looking for something I could use with a text cleaner app that has PCRE Regex capabilities (but no java functions). I will post this here for people who could use a simple pure Regex solution that could work in a variety of text editors, cleaners, expanders, or even some clipboard managers. I personally use Sublime and TextSoap. This solution was made for Text Soap as it lives in the menu bar and provides a drop-down menu where you can trigger text manipulation actions on what is selected by the cursor or what's in the clipboard.
My approach is essentially two substitution/search and replace regexes. Each substitution search and replace involves two regexes, one for search and one for replace.
Substitution/ Search & Replace #1
First Substitution/ Search Regex: \D
First Substitution/ Replace Regex: "" (nothing, not even a space)
Substitution/ Search & Replace #2
$1
, a capture group for the second set of three numbers $2
, and the last capture group for the last set of four numbers $3
. The regex for the substitute portion of the operation inserts US phone number formatting in between the captured group of digits.Second Substitution/ Search Regex: (\d{3})(\d{3})(\d{4})
Second Substitution/ Replace Regex: \($1\) $2\-$3
The backslash \
escapes the special characters (
, )
,
(<-whitespace), and -
since we are inserting them between our captured numbers in capture groups $1
, $2
, & $3
for US phone number formatting purposes.
In TextSoap I created a custom cleaner that includes the two substitution operation actions, so in practice it feels identical to executing a script. I'm sure this solution could be improved but I expect complexity to go up quite a bit. An improved version of this solution is welcomed as a learning experience if anyone wants to add to this.
This is because there is not only 1 answer...
shell
command line expansionxargs
dedicated toolwhile read
with some remarkswhile read -u
using dedicated fd
, for interactive processing (sample)Regarding the OP request: running chmod
on all targets listed in file, xargs
is the indicated tool. But for some other applications, small amount of files, etc...
If your file is not too big and all files are well named (without spaces or other special chars like quotes), you could use shell
command line expansion. Simply:
chmod 755 $(<file.txt)
For small amount of files (lines), this command is the lighter one.
xargs
is the right toolFor bigger amount of files, or almost any number of lines in your input file...
For many binutils tools, like chown
, chmod
, rm
, cp -t
...
xargs chmod 755 <file.txt
If you have special chars and/or a lot of lines in file.txt
.
xargs -0 chmod 755 < <(tr \\n \\0 <file.txt)
if your command need to be run exactly 1 time by entry:
xargs -0 -n 1 chmod 755 < <(tr \\n \\0 <file.txt)
This is not needed for this sample, as chmod
accept multiple files as argument, but this match the title of question.
For some special case, you could even define location of file argument in commands generateds by xargs
:
xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd < <(tr \\n \\0 <file.txt)
seq 1 5
as inputTry this:
xargs -n 1 -I{} echo Blah {} blabla {}.. < <(seq 1 5)
Blah 1 blabla 1..
Blah 2 blabla 2..
Blah 3 blabla 3..
Blah 4 blabla 4..
Blah 5 blabla 5..
Where commande is done once per line.
while read
and variants.As OP suggest cat file.txt | while read in; do chmod 755 "$in"; done
will work, but there is 2 issues:
cat |
is an useless fork, and
| while ... ;done
will become a subshell where environment will disapear after ;done
.
So this could be better written:
while read in; do chmod 755 "$in"; done < file.txt
But,
You may be warned about $IFS
and read
flags:
help read
read: read [-r] ... [-d delim] ... [name ...] ... Reads a single line from the standard input... The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on... Only the characters found in $IFS are recognized as word delimiters. ... Options: ... -d delim continue until the first character of DELIM is read, rather than newline ... -r do not allow backslashes to escape any characters ... Exit Status: The return code is zero, unless end-of-file is encountered...
In some case, you may need to use
while IFS= read -r in;do chmod 755 "$in";done <file.txt
For avoiding problems with stranges filenames. And maybe if you encouter problems with UTF-8
:
while LANG=C IFS= read -r in ; do chmod 755 "$in";done <file.txt
While you use STDIN
for reading file.txt
, your script could not be interactive (you cannot use STDIN
anymore).
while read -u
, using dedicated fd
.Syntax: while read ...;done <file.txt
will redirect STDIN
to file.txt
. That mean, you won't be able to deal with process, until they finish.
If you plan to create interactive tool, you have to avoid use of STDIN
and use some alternative file descriptor.
Constants file descriptors are: 0
for STDIN, 1
for STDOUT and 2
for STDERR. You could see them by:
ls -l /dev/fd/
or
ls -l /proc/self/fd/
From there, you have to choose unused number, between 0
and 63
(more, in fact, depending on sysctl
superuser tool) as file descriptor:
For this demo, I will use fd 7
:
exec 7<file.txt # Without spaces between `7` and `<`!
ls -l /dev/fd/
Then you could use read -u 7
this way:
while read -u 7 filename;do
ans=;while [ -z "$ans" ];do
read -p "Process file '$filename' (y/n)? " -sn1 foo
[ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'
done
if [ "$ans" = "y" ] ;then
echo Yes
echo "Processing '$filename'."
else
echo No
fi
done 7<file.txt
done
To close fd/7
:
exec 7<&- # This will close file descriptor 7.
ls -l /dev/fd/
Nota: I let striked version because this syntax could be usefull, when doing many I/O with parallels process:
mkfifo sshfifo
exec 7> >(ssh -t user@host sh >sshfifo)
exec 6<sshfifo
Here is my proposal implemented with ES6
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
scrollToTop();
Tip: for slower motion of the scrolling, increase the hardcoded number 8
. The bigger the number - the smoother/slower the scrolling.
If swfobject
won't suffice, or you need to create something a little more bespoke, try this:
var hasFlash = false;
try {
hasFlash = Boolean(new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
} catch(exception) {
hasFlash = ('undefined' != typeof navigator.mimeTypes['application/x-shockwave-flash']);
}
It works with 7 and 8.
Isn't the 'date' command much simpler? No need for awk, stat, etc.
date -r <filename>
Also, consider looking at the man page for date formatting; for example with common date and time format:
date -r <filename> "+%m-%d-%Y %H:%M:%S"
Env: macOS Mojave 10.14.4
Install: homebrew
Location:/usr/local/Cellar/mongodb/4.0.3_1
Note :If update version by
brew upgrade mongo
,the folder 4.0.4_1
will be removed and replace with the new version folder
Note: cuongle's helfpul answer has all the ingredients, but the solution can be streamlined (no need for .ItemArray
) and can be reframed to better match the question as asked.
To create an (isolated) clone of a given System.Data.DataRow
instance, you can do the following:
// Assume that variable `table` contains the source data table.
// Create an auxiliary, empty, column-structure-only clone of the source data table.
var tableAux = table.Clone();
// Note: .Copy(), by contrast, would clone the data rows also.
// Select the data row to clone, e.g. the 2nd one:
var row = table.Rows[1];
// Import the data row of interest into the aux. table.
// This creates a *shallow clone* of it.
// Note: If you'll be *reusing* the aux. table for single-row cloning later, call
// tableAux.Clear() first.
tableAux.ImportRow(row);
// Extract the cloned row from the aux. table:
var rowClone = tableAux.Rows[0];
Note: Shallow cloning is performed, which works as-is with column values that are value type instances, but more work would be needed to also create independent copies of column values containing reference type instances (and creating such independent copies isn't always possible).
SELECT CASE CHARINDEX(' ', @Foo, 1)
WHEN 0 THEN @Foo -- empty or single word
ELSE SUBSTRING(@Foo, 1, CHARINDEX(' ', @Foo, 1) - 1) -- multi-word
END
You could perhaps use this in a UDF:
CREATE FUNCTION [dbo].[FirstWord] (@value varchar(max))
RETURNS varchar(max)
AS
BEGIN
RETURN CASE CHARINDEX(' ', @value, 1)
WHEN 0 THEN @value
ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END
END
GO -- test:
SELECT dbo.FirstWord(NULL)
SELECT dbo.FirstWord('')
SELECT dbo.FirstWord('abc')
SELECT dbo.FirstWord('abc def')
SELECT dbo.FirstWord('abc def ghi')
I like a lot of answers, particularly @saineshwar 's one. I'm using .net Core 3.0 with AutoMapper 9.0, so I feel it's time to update its answer.
What worked for me was in Startup.ConfigureServices(...) register the service in this way:
services.AddAutoMapper(cfg => cfg.AddProfile<MappingProfile>(),
AppDomain.CurrentDomain.GetAssemblies());
I think that rest of @saineshwar answer keeps perfect. But if anyone is interested my controller code is:
[HttpGet("{id}")]
public async Task<ActionResult> GetIic(int id)
{
// _context is a DB provider
var Iic = await _context.Find(id).ConfigureAwait(false);
if (Iic == null)
{
return NotFound();
}
var map = _mapper.Map<IicVM>(Iic);
return Ok(map);
}
And my mapping class:
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Iic, IicVM>()
.ForMember(dest => dest.DepartmentName, o => o.MapFrom(src => src.Department.Name))
.ForMember(dest => dest.PortfolioTypeName, o => o.MapFrom(src => src.PortfolioType.Name));
//.ReverseMap();
}
}
----- EDIT -----
After reading the docs linked in the comments by Lucian Bargaoanu, I think it's better to change this answer a bit.
The parameterless services.AddAutoMapper()
(that had the @saineshwar answer) doesn't work anymore (at least for me). But if you use the NuGet assembly AutoMapper.Extensions.Microsoft.DependencyInjection, the framework is able to inspect all the classes that extend AutoMapper.Profile (like mine, MappingProfile).
So, in my case, where the class belong to the same executing assembly, the service registration can be shortened to services.AddAutoMapper(System.Reflection.Assembly.GetExecutingAssembly());
(A more elegant approach could be a parameterless extension with this coding).
Thanks, Lucian!
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
Rolo's answer is excellent, however I had to reinstall Pillow by bypassing pip cache (introduced with pip 7) otherwise it won't get properly recompiled!!! The command is:
pip install -I --no-cache-dir -v Pillow
and you can see if Pillow has been properly configured by reading in the logs this:
PIL SETUP SUMMARY
--------------------------------------------------------------------
version Pillow 2.8.2
platform linux 3.4.3 (default, May 25 2015, 15:44:26)
[GCC 4.8.2]
--------------------------------------------------------------------
*** TKINTER support not available
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
--- LIBTIFF support available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
as you can see the support for jpg, tiff and so on is enabled, because I previously installed the required libraries via apt (libjpeg-dev libpng12-dev libfreetype6-dev libtiff-dev)
-z
string is null, that is, has zero length
String='' # Zero-length ("null") string variable.
if [ -z "$String" ]
then
echo "\$String is null."
else
echo "\$String is NOT null."
fi # $String is null.
/* comment here */
here is an example: SELECT 1 /* this is an in-line comment */ + 1;
@marcio-junior's answer (https://stackoverflow.com/a/6497462/4038790) works perfectly, but I wanted to explain for those who don't understand why it works:
@a7omiton Along with @psyren89's response to your question
Think of the outer div
as a movie screen and the inner div
as the setting in which the characters move around. If you were viewing the setting in person, that is without a screen around it, you would be able to see all of the characters at once assuming your eyes have a large enough field of vision. That would mean the setting wouldn't have to scroll (move left to right) in order for you to see more of it and so it would stay still.
However, you are not at the setting in person, you are viewing it from your computer screen which has a width of 500px while the setting has a width of 1000px. Thus, you will need to scroll (move left to right) the setting in order to see more of the characters inside of it.
I hope that helps anyone who was lost on the principle.
You can create a C# like extension/helper method by (RE) implementing the Collections interface and adding- example for Java Collection:
public class RockCollection<T extends Comparable<T>> implements Collection<T> {
private Collection<T> _list = new ArrayList<T>();
//###########Custom extension methods###########
public T doSomething() {
//do some stuff
return _list
}
//proper examples
public T find(Predicate<T> predicate) {
return _list.stream()
.filter(predicate)
.findFirst()
.get();
}
public List<T> findAll(Predicate<T> predicate) {
return _list.stream()
.filter(predicate)
.collect(Collectors.<T>toList());
}
public String join(String joiner) {
StringBuilder aggregate = new StringBuilder("");
_list.forEach( item ->
aggregate.append(item.toString() + joiner)
);
return aggregate.toString().substring(0, aggregate.length() - 1);
}
public List<T> reverse() {
List<T> listToReverse = (List<T>)_list;
Collections.reverse(listToReverse);
return listToReverse;
}
public List<T> sort(Comparator<T> sortComparer) {
List<T> listToReverse = (List<T>)_list;
Collections.sort(listToReverse, sortComparer);
return listToReverse;
}
public int sum() {
List<T> list = (List<T>)_list;
int total = 0;
for (T aList : list) {
total += Integer.parseInt(aList.toString());
}
return total;
}
public List<T> minus(RockCollection<T> listToMinus) {
List<T> list = (List<T>)_list;
int total = 0;
listToMinus.forEach(list::remove);
return list;
}
public Double average() {
List<T> list = (List<T>)_list;
Double total = 0.0;
for (T aList : list) {
total += Double.parseDouble(aList.toString());
}
return total / list.size();
}
public T first() {
return _list.stream().findFirst().get();
//.collect(Collectors.<T>toList());
}
public T last() {
List<T> list = (List<T>)_list;
return list.get(_list.size() - 1);
}
//##############################################
//Re-implement existing methods
@Override
public int size() {
return _list.size();
}
@Override
public boolean isEmpty() {
return _list == null || _list.size() == 0;
}
Thanks to Seb33300 I got this working. However, an important part seems to be missing. At least in Bootstrap version 3.1.1.
My problem was that the navbar collapsed accordingly at the correct width, but the menu button didn't work. I couldn't expand and collapse the menu.
This is because the collapse.in class is overrided by the !important in .navbar-collapse.collapse, and can be solved by also adding the "collapse.in". Seb33300's example completed below:
@media (max-width: 991px) {
.navbar-header {
float: none;
}
.navbar-toggle {
display: block;
}
.navbar-collapse {
border-top: 1px solid transparent;
box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
}
.navbar-collapse.collapse {
display: none!important;
}
.navbar-collapse.collapse.in {
display: block!important;
}
.navbar-nav {
float: none!important;
margin: 7.5px -15px;
}
.navbar-nav>li {
float: none;
}
.navbar-nav>li>a {
padding-top: 10px;
padding-bottom: 10px;
}
}
Yes, you can use regular expressions
in C#.
Using regular expressions with C#
:
using System.Text.RegularExpressions;
string your_String = "Hello@Hello&Hello(Hello)";
string my_String = Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");
Yes, template member functions are perfectly legal and useful on numerous occasions.
The only caveat is that template member functions cannot be virtual.
There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.
Update:
As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile
to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile
on OS X now requires the output to be a socket and the code won't work!
The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.
#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif
int OSCopyFile(const char* source, const char* destination)
{
int input, output;
if ((input = open(source, O_RDONLY)) == -1)
{
return -1;
}
if ((output = creat(destination, 0660)) == -1)
{
close(input);
return -1;
}
//Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
//fcopyfile works on FreeBSD and OS X 10.5+
int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
//sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
off_t bytesCopied = 0;
struct stat fileinfo = {0};
fstat(input, &fileinfo);
int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif
close(input);
close(output);
return result;
}
EDIT: Replaced the opening of the destination with the call to creat()
as we want the flag O_TRUNC
to be specified. See comment below.
This should do the trick
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
dow <- function(x) format(as.Date(x), "%A")
df$day <- dow(df$date)
df
#Returns:
date day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02 Thursday
Hidden iframes can help
add to your code:
"#include < stdlib.h>"
return EXIT_SUCCESS;
at the end of main()
Answering old thread here (and a bit off-topic) because it's what I found when I was searching how to install Image Magick on Mac OS to run on the local webserver. It's not enough to brew install Imagemagick. You have to also PECL install it so the PHP module is loaded.
From this SO answer:
brew install php
brew install imagemagick
brew install pkg-config
pecl install imagick
And you may need to sudo apachectl restart
. Then check your phpinfo()
within a simple php script running on your web server.
If it's still not there, you probably have an issue with running multiple versions of PHP on the same Mac (one through the command line, one through your web server). It's beyond the scope of this answer to resolve that issue, but there are some good options out there.
How about plain JavaScript? More about Array.prototype.filter()
.
var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]_x000D_
_x000D_
var item73 = myArray.filter(function(item) {_x000D_
return item.id === '73';_x000D_
})[0];_x000D_
_x000D_
// even nicer with ES6 arrow functions:_x000D_
// var item73 = myArray.filter(i => i.id === '73')[0];_x000D_
_x000D_
console.log(item73); // {"id": "73", "name": "john"}
_x000D_
There are 4 ways to do it as far as I know.
Number(x);
parseInt(x, 10);
parseFloat(x);
+x;
By this quick test I made, it actually depends on browsers.
http://jsperf.com/best-of-string-to-number-conversion/2
Implicit
marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!
How about pdf2tiff? http://python.net/~gherman/pdf2tiff.html
I know this is old but neither an <svg>
group tag nor a <g>
fixed the issue I was facing. I needed to adjust the y position of a tag which also had animation on it.
The solution was to use both the and tag together:
<svg y="1190" x="235">
<g class="light-1">
<path />
</g>
</svg>
Call the Below Action Method from your JS file (To get the ipv4 ip address).
[HttpGet]
public string GetIP()
{
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
return ipv4Addresses.ToString();
}
Check after keeping Breakpoint, and use as per your requirement. Its working fine for me.
STRING TO URI.
Uri uri=Uri.parse("YourString");
URI TO STRING
Uri uri;
String andro=uri.toString();
happy coding :)
Fustigador answer was great, but I found some device (Like Samsung Galaxy Note V) cannot reach 0, have 2 point left, after the calculation. I suggest to add a little buffer like below:
@Override
public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {
// We take the last son in the scrollview
View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));
// if diff is zero, then the bottom has been reached
if (diff <= 10) {
// do stuff
}
}
I found a more generic solution with the most angular-native solution I can think. Basically you can pass your own comparator to the default filterFilter
function. Here's plunker as well.
One thing I do is to add to .bashrc/.profile this function:
function each() {
while read line; do
for f in "$@"; do
$f $line
done
done
}
then you can do things like
... | each command1 command2 "command3 has spaces"
which is less verbose than xargs or -exec. You could also modify the function to insert the value from the read at an arbitrary location in the commands to each, if you needed that behavior also.
Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun. http://frisbyjs.com
Example:
var frisby = require('../lib/frisby');
var URL = 'http://localhost:3000/';
var URL_AUTH = 'http://username:password@localhost:3000/';
frisby.globalSetup({ // globalSetup is for ALL requests
request: {
headers: { 'X-Auth-Token': 'fa8426a0-8eaf-4d22-8e13-7c1b16a9370c' }
}
});
frisby.create('GET user johndoe')
.get(URL + '/users/3.json')
.expectStatus(200)
.expectJSONTypes({
id: Number,
username: String,
is_admin: Boolean
})
.expectJSON({
id: 3,
username: 'johndoe',
is_admin: false
})
// 'afterJSON' automatically parses response body as JSON and passes it as an argument
.afterJSON(function(user) {
// You can use any normal jasmine-style assertions here
expect(1+1).toEqual(2);
// Use data from previous result in next test
frisby.create('Update user')
.put(URL_AUTH + '/users/' + user.id + '.json', {tags: ['jasmine', 'bdd']})
.expectStatus(200)
.toss();
})
.toss();
There's nothing wrong with your code, the following works fine for me when I have the file.txt in the user.dir directory.
import java.io.File;
import java.util.Scanner;
public class testme {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
File file = new File("file.txt");
try {
Scanner scanner = new Scanner(file);
} catch (Exception e) {
System.out.println(e);
}
}
}
Don't trust Eclipse with where it says the file is. Go out to the actual filesystem with Windows Explorer or equivalent and check.
Based on your edit, I think we need to see your import statements as well.
The keycodes returned by waitKey
seem platform dependent.
However, it may be very educative, to see what the keys return
(and by the way, on my platform, Esc does not return 27...)
The integers thay Abid's answer lists are mosty useless to the human mind (unless you're a prodigy savant...). However, if you examine them in hex, or take a look at the Least Significant Byte, you may notice patterns...
My script for examining the return values from waitKey
is below:
#!/usr/bin/env python
import cv2
import sys
cv2.imshow(sys.argv[1], cv2.imread(sys.argv[1]))
res = cv2.waitKey(0)
print('You pressed %d (0x%x), LSB: %d (%s)' % (res, res, res % 256,
repr(chr(res%256)) if res%256 < 128 else '?'))
You can use it as a minimal, command-line image viewer.
Some results, which I got:
q letter:
You pressed 1048689 (0x100071), LSB: 113 ('q')
Escape key (traditionally, ASCII 27):
You pressed 1048603 (0x10001b), LSB: 27 ('\x1b')
Space:
You pressed 1048608 (0x100020), LSB: 32 (' ')
This list could go on, however you see the way to go, when you get 'strange' results.
BTW, if you want to put it in a loop, you can just waitKey(0)
(wait forever), instead of ignoring the -1
return value.
EDIT: There's more to these high bits than meets the eye - please see Andrew C's answer (hint: it has to do with keyboard modifiers like all the "Locks" e.g. NumLock).
My recent experience shows however, that there is a platform dependence - e.g. OpenCV 4.1.0 from Anaconda on Python 3.6 on Windows doesn't produce these bits, and for some (important) keys is returns 0
from waitKey()
(arrows, Home, End, PageDn, PageUp, even Del and Ins). At least Backspace returns 8
(but... why not Del?).
So, for a cross platform UI you're probably restricted to W, A, S, D, letters, digits, Esc, Space and Backspace ;)
EDIT:
Indeed there was a patch which included sign()
in math, but it wasn't accepted, because they didn't agree on what it should return in all the edge cases (+/-0, +/-nan, etc)
So they decided to implement only copysign, which (although more verbose) can be used to delegate to the end user the desired behavior for edge cases - which sometimes might require the call to cmp(x,0)
.
I don't know why it's not a built-in, but I have some thoughts.
copysign(x,y):
Return x with the sign of y.
Most importantly, copysign
is a superset of sign
! Calling copysign
with x=1 is the same as a sign
function. So you could just use copysign
and forget about it.
>>> math.copysign(1, -4)
-1.0
>>> math.copysign(1, 3)
1.0
If you get sick of passing two whole arguments, you can implement sign
this way, and it will still be compatible with the IEEE stuff mentioned by others:
>>> sign = functools.partial(math.copysign, 1) # either of these
>>> sign = lambda x: math.copysign(1, x) # two will work
>>> sign(-4)
-1.0
>>> sign(3)
1.0
>>> sign(0)
1.0
>>> sign(-0.0)
-1.0
>>> sign(float('nan'))
-1.0
Secondly, usually when you want the sign of something, you just end up multiplying it with another value. And of course that's basically what copysign
does.
So, instead of:
s = sign(a)
b = b * s
You can just do:
b = copysign(b, a)
And yes, I'm surprised you've been using Python for 7 years and think cmp
could be so easily removed and replaced by sign
! Have you never implemented a class with a __cmp__
method? Have you never called cmp
and specified a custom comparator function?
In summary, I've found myself wanting a sign
function too, but copysign
with the first argument being 1 will work just fine. I disagree that sign
would be more useful than copysign
, as I've shown that it's merely a subset of the same functionality.
Don't do this!
Stay away from putting the events inline with the elements! If you don't, you're missing the point of JQuery (or one of the biggest ones at least).
The reason why it's easy to define click() handlers one way and not the other is that the other way is simply not desirable. Since you're just learning JQuery, stick to the convention. Now is not the time in your learning curve for JQuery to decide that everyone else is doing it wrong and you have a better way!
If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);
Hope it helps.
Incorrect:
people:
empId: 123
empName: John
empDept: IT
Correct:
people:
emp:
id: 123
name: John
dept: IT
JavaScript is object-oriented, but is not a class-based object-oriented language like Java, C++, C#, etc. Class-based OOP languages are a subset of the larger family of OOP languages which also include prototype-based languages like JavaScript and Self.
A signed char
is a signed value which is typically smaller than, and is guaranteed not to be bigger than, a short
. An unsigned char
is an unsigned value which is typically smaller than, and is guaranteed not to be bigger than, a short
. A type char
without a signed
or unsigned
qualifier may behave as either a signed or unsigned char
; this is usually implementation-defined, but there are a couple of cases where it is not:
Part of the reason there are two dialects of "C" (those where char
is signed, and those where it is unsigned) is that there are some implementations where char
must be unsigned, and others where it must be signed.
Update gradle to the latest available version and implement libraries to the latest version available, also check if google play services is latest if used.
You can do the following:
$scope.traveler.map(o=>o.Amount).reduce((a,c)=>a+c);
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
In python:
>>> 1.0 / 10
0.10000000000000001
Explain how some fractions cannot be represented precisely in binary. Just like some fractions (like 1/3) cannot be represented precisely in base 10.
You are using ES6 Module syntax.
This means your environment (e.g. node.js) must support ES6 Module syntax.
NodeJS uses CommonJS Module syntax (module.exports
) not ES6 module syntax (export
keyword).
Solution:
babel
npm package to transpile your ES6 to a commonjs
targetor
Examples of CommonJS syntax are (from flaviocopes.com/commonjs/):
exports.uppercase = str => str.toUpperCase()
exports.a = 1
It was very useful for me i have used in the following way to add user in active directory:
:: This file is used to automatically add list of user to activedirectory
:: First ask for username,pwd,dc details and run in loop
:: dsadd user cn=jai,cn=users,dc=mandrac,dc=com -pwd `1q`1q`1q`1q
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 1"
set /p lent="Enter how many Users you want to create : "
set /p Uname="Enter the user name which will be rotated with number ex:ram then ram1 ..etc : "
set /p DcName="Enter the DC name ex:mandrac : "
set /p Paswd="Enter the password you want to give to all the users : "
cls
:while1
if %x% leq %lent% (
dsadd user cn=%Uname%%x%,cn=users,dc=%DcName%,dc=com -pwd %Paswd%
echo User %Uname%%x% with DC %DcName% is created
set /a "x = x + 1"
goto :while1
)
endlocal
Need not to use HTML properties, let's focus on java xD I had the same problem, i found the way to do it in java:
String text="Hide post";
TextView tvHide=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(text);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
tvHide.setText(spanString );
Try This :
--Default Instance
SQLCMD -S SERVERNAME -E
--OR
--Named Instance
SQLCMD -S SERVERNAME\INSTANCENAME -E
--OR
SQLCMD -S SERVERNAME\INSTANCENAME,1919 -E
More details can be found here
Based on the comments try
*/5 * * * * wget http://example.com/check
[Edit: 10 Apr 2017]
This answer still seems to be getting a few hits so I thought I'd add a link to a new page I stumbled across which may help create cron commands: https://crontab.guru
You can use >>
to print in another file.
echo "hello" >> logfile.txt
All the other solutions posted here cause the toggle to get out of sync if it is double clicked. The following solution uses the events provided by the Bootstrap framework, and the toggle always matches the state of the collapsible element:
HTML:
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button id="intro-switch" class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...
</div>
</div>
JS:
$('#intro').on('show', function() {
$('#intro-switch').html('-')
})
$('#intro').on('hide', function() {
$('#intro-switch').html('+')
})
That should work for most cases.
However, I also ran into an additional problem when trying to nest one collapsible element and its toggle switch inside another collapsible element. With the above code, when I click the nested toggle to hide the nested collapsible element, the toggle for the parent element also changes. It may be a bug in Bootstrap. I found a solution that seems to work: I added a "collapsed" class to the toggle switches (Bootstrap adds this when the collapsible element is hidden but they don't start out with it), then added that to the jQuery selector for the hide function:
HTML:
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button id="intro-switch" class="btn btn-success collapsed" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...<br>
<a id="details-switch" class="collapsed" data-toggle="collapse" href="#details">Show details</a>
<div id="details" class="collapse">
More details...
</div>
</div>
</div>
JS:
$('#intro').on('show', function() {
$('#intro-switch').html('-')
})
$('#intro').on('hide', function() {
$('#intro-switch.collapsed').html('+')
})
$('#details').on('show', function() {
$('#details-switch').html('Hide details')
})
$('#details').on('hide', function() {
$('#details-switch.collapsed').html('Show details')
})
In Windows 10, I had to run the windows command prompt (cmd) as administrator. Doing that solved this problem for me.
<font color="red">This is some text!</font>
This worked the best for me when I only wanted to change one word into the color red in a sentence.
You can use the jar tool bundled with the SDK and create an executable version of the program.
This is how it's done.
I'm posting the results from my command prompt because it's easier, but the same should apply when using JCreator.
First create your program:
$cat HelloWorldSwing.java
package start;
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
frame.add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
class Dummy {
// just to have another thing to pack in the jar
}
Very simple, just displays a window with "Hello World"
Then compile it:
$javac -d . HelloWorldSwing.java
Two files were created inside the "start" folder Dummy.class and HelloWorldSwing.class.
$ls start/
Dummy.class HelloWorldSwing.class
Next step, create the jar file. Each jar file have a manifest file, where attributes related to the executable file are.
This is the content of my manifest file.
$cat manifest.mf
Main-class: start.HelloWorldSwing
Just describe what the main class is ( the one with the public static void main method )
Once the manifest is ready, the jar executable is invoked.
It has many options, here I'm using -c -m -f ( -c to create jar, -m to specify the manifest file , -f = the file should be named.. ) and the folder I want to jar.
$jar -cmf manifest.mf hello.jar start
This creates the .jar file on the system
You can later just double click on that file and it will run as expected.
To create the .jar file in JCreator you just have to use "Tools" menu, create jar, but I'm not sure how the manifest goes there.
Here's a video I've found about: Create a Jar File in Jcreator.
I think you may proceed with the other links posted in this thread once you're familiar with this ".jar" approach.
You can also use jnlp ( Java Network Launcher Protocol ) too.
If you don't care about the keys, then valueAt(int)
can be used to while iterating through the sparse array to access the values directly.
for(int i = 0, nsize = sparseArray.size(); i < nsize; i++) {
Object obj = sparseArray.valueAt(i);
}
There is a problem with every answer provided that can be summarized as "just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code." They will not work in every possible situation!
For example, one such magical incantation uses __file__
. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.
Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.
Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.
import inspect
import os
import sys
# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.
def GetScriptDirectory():
if hasattr(GetScriptDirectory, "dir"):
return GetScriptDirectory.dir
module_path = ""
try:
# The easy way. Just use __file__.
# Unfortunately, __file__ is not available when cx_Freeze is used or in IDLE.
module_path = __file__
except NameError:
if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
module_path = sys.argv[0]
else:
module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
if not os.path.exists(module_path):
# If cx_Freeze is used the value of the module_path variable at this point is in the following format.
# {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
# path.
module_path = os.path.dirname(module_path)
GetScriptDirectory.dir = os.path.dirname(module_path)
return GetScriptDirectory.dir
sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)
As you can see, this is no easy task!
You cannot use var
in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this
in a field and Master as Site
is the same as this.Master as Site
. So just initialize the field from Page_Init
when the page is fully initialized and you can use this
:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.
If you're using compass:
compass watch --output-style compressed
List
The easiest way, that I know of, is to create a fixed-size single element List
with Arrays.asList(T...)
like
// Returns a List backed by a varargs T.
return Arrays.asList(s);
List
If it needs vary in size you can construct an ArrayList
and the fixed-sizeList
like
return new ArrayList<String>(Arrays.asList(s));
and (in Java 7+) you can use the diamond operator <>
to make it
return new ArrayList<>(Arrays.asList(s));
Collections can return a list with a single element with list being immutable:
Collections.singletonList(s)
The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.
For those who want to make this change from Visual Studio 2019
Open Team Explorer (Ctrl+M)
Home -> Settings
Git -> Repository Settings
Remotes -> Edit
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
if (property_exists($ob, 'a'))
if (isset($ob->a))
isset() will return false if property is null
Example 1:
$ob->a = null
var_dump(isset($ob->a)); // false
Example 2:
class Foo
{
public $bar = null;
}
$foo = new Foo();
var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false
for unable to verify the first certificate in nodejs reject unauthorized is needed
request({method: "GET",
"rejectUnauthorized": false,
"url": url,
"headers" : {"Content-Type": "application/json",
function(err,data,body) {
}).pipe(
fs.createWriteStream('file.html'));
You can set a callback function for the onSubmit event of the form and check the contents of each field. If it contains nothing you can then fill it with the string "empty":
<form name="my_form" action="validate.php" onsubmit="check()">
<input type="text" name="text1" />
<input type="submit" value="submit" />
</form>
and in your js:
function check() {
if(document.forms["my_form"]["text1"].value == "")
document.forms["my_form"]["text1"].value = "empty";
}
I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell
and change the date manually.
For converting an entire xml document to a pretty xml document
(ex: assuming you've extracted [unzipped] a LibreOffice Writer .odt or .ods file, and you want to convert the ugly "content.xml" file to a pretty one for automated git version control and git difftool
ing of .odt/.ods files, such as I'm implementing here)
import xml.dom.minidom
file = open("./content.xml", 'r')
xml_string = file.read()
file.close()
parsed_xml = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = parsed_xml.toprettyxml()
file = open("./content_new.xml", 'w')
file.write(pretty_xml_as_string)
file.close()
References:
- Thanks to Ben Noland's answer on this page which got me most of the way there.
This helped me: just wait about a minute or two.
Wait a few minutes, then retry your operation.
The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException
. It's well worth reading and digesting.
A simple json POST request example for those that need it even simpler than what Tom is linking to:
require 'net/http'
uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})
By using a border-radius of 50% you can make a circle. Here is an example:
CSS:
#exampleCircle{
width: 500px;
height: 500px;
background: red;
border-radius: 50%;
}
HTML:
<div id = "exampleCircle"></div>
I had the same issue. After about two hours of googling, retries, regenerating API Key many times, etc. i discovered that i enabled the wrong service in the Google APis Console. I enabled Google Maps API v2 Service, but for Android Apps you have to use Google Maps Android API v2. After enabling the right service all started working.
The solution seems to be to add multiple @font-face
rules, for example:
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans.ttf");
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Bold.ttf");
font-weight: bold;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-Oblique.ttf");
font-style: italic, oblique;
}
@font-face {
font-family: "DejaVu Sans";
src: url("fonts/DejaVuSans-BoldOblique.ttf");
font-weight: bold;
font-style: italic, oblique;
}
By the way, it would seem Google Chrome doesn't know about the format("ttf")
argument, so you might want to skip that.
(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)
Reading binary file in Python and looping over each byte
New in Python 3.5 is the pathlib
module, which has a convenience method specifically to read in a file as bytes, allowing us to iterate over the bytes. I consider this a decent (if quick and dirty) answer:
import pathlib
for byte in pathlib.Path(path).read_bytes():
print(byte)
Interesting that this is the only answer to mention pathlib
.
In Python 2, you probably would do this (as Vinay Sajip also suggests):
with open(path, 'b') as file:
for byte in file.read():
print(byte)
In the case that the file may be too large to iterate over in-memory, you would chunk it, idiomatically, using the iter
function with the callable, sentinel
signature - the Python 2 version:
with open(path, 'b') as file:
callable = lambda: file.read(1024)
sentinel = bytes() # or b''
for chunk in iter(callable, sentinel):
for byte in chunk:
print(byte)
(Several other answers mention this, but few offer a sensible read size.)
Let's create a function to do this, including idiomatic uses of the standard library for Python 3.5+:
from pathlib import Path
from functools import partial
from io import DEFAULT_BUFFER_SIZE
def file_byte_iterator(path):
"""given a path, return an iterator over the file
that lazily loads the file
"""
path = Path(path)
with path.open('rb') as file:
reader = partial(file.read1, DEFAULT_BUFFER_SIZE)
file_iterator = iter(reader, bytes())
for chunk in file_iterator:
yield from chunk
Note that we use file.read1
. file.read
blocks until it gets all the bytes requested of it or EOF
. file.read1
allows us to avoid blocking, and it can return more quickly because of this. No other answers mention this as well.
Let's make a file with a megabyte (actually mebibyte) of pseudorandom data:
import random
import pathlib
path = 'pseudorandom_bytes'
pathobj = pathlib.Path(path)
pathobj.write_bytes(
bytes(random.randint(0, 255) for _ in range(2**20)))
Now let's iterate over it and materialize it in memory:
>>> l = list(file_byte_iterator(path))
>>> len(l)
1048576
We can inspect any part of the data, for example, the last 100 and first 100 bytes:
>>> l[-100:]
[208, 5, 156, 186, 58, 107, 24, 12, 75, 15, 1, 252, 216, 183, 235, 6, 136, 50, 222, 218, 7, 65, 234, 129, 240, 195, 165, 215, 245, 201, 222, 95, 87, 71, 232, 235, 36, 224, 190, 185, 12, 40, 131, 54, 79, 93, 210, 6, 154, 184, 82, 222, 80, 141, 117, 110, 254, 82, 29, 166, 91, 42, 232, 72, 231, 235, 33, 180, 238, 29, 61, 250, 38, 86, 120, 38, 49, 141, 17, 190, 191, 107, 95, 223, 222, 162, 116, 153, 232, 85, 100, 97, 41, 61, 219, 233, 237, 55, 246, 181]
>>> l[:100]
[28, 172, 79, 126, 36, 99, 103, 191, 146, 225, 24, 48, 113, 187, 48, 185, 31, 142, 216, 187, 27, 146, 215, 61, 111, 218, 171, 4, 160, 250, 110, 51, 128, 106, 3, 10, 116, 123, 128, 31, 73, 152, 58, 49, 184, 223, 17, 176, 166, 195, 6, 35, 206, 206, 39, 231, 89, 249, 21, 112, 168, 4, 88, 169, 215, 132, 255, 168, 129, 127, 60, 252, 244, 160, 80, 155, 246, 147, 234, 227, 157, 137, 101, 84, 115, 103, 77, 44, 84, 134, 140, 77, 224, 176, 242, 254, 171, 115, 193, 29]
Don't do the following - this pulls a chunk of arbitrary size until it gets to a newline character - too slow when the chunks are too small, and possibly too large as well:
with open(path, 'rb') as file:
for chunk in file: # text newline iteration - not for bytes
yield from chunk
The above is only good for what are semantically human readable text files (like plain text, code, markup, markdown etc... essentially anything ascii, utf, latin, etc... encoded) that you should open without the 'b'
flag.
To make height:100% work for the inner div, you have to set a height for the parent td. For my particular case it worked using height:100%. This made the inner div height stretch, while the other elements of the table didn't allow the td to become too big. You can of course use other values than 100%
If you want to also make the table cell have a fixed height so that it does not get bigger based on content (to make the inner div scroll or hide overflow), that is when you have no choice but do some js tricks. The parent td will need to have the height specified in a non relative unit (not %). And you will most probably have no choice but to calculate that height using js. This would also need the table-layout:fixed style set for the table element
This is another random number generator that i use often, it also prevent the first digit from been zero(0)
function randomNumber(length) {_x000D_
var text = "";_x000D_
var possible = "123456789";_x000D_
for (var i = 0; i < length; i++) {_x000D_
var sup = Math.floor(Math.random() * possible.length);_x000D_
text += i > 0 && sup == i ? "0" : possible.charAt(sup);_x000D_
}_x000D_
return Number(text);_x000D_
}
_x000D_
You can sort an array using usort function.
$array = array(
array('price'=>'1000.50','product'=>'product 1'),
array('price'=>'8800.50','product'=>'product 2'),
array('price'=>'200.0','product'=>'product 3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output :
Array
(
[0] => Array
(
[price] => 134.50
[product] => product 1
)
[1] => Array
(
[price] => 2033.0
[product] => product 3
)
[2] => Array
(
[price] => 8340.50
[product] => product 2
)
)
I think it's possible in Java 9:
animalMap.entrySet().stream()
.forEach(
pair -> Optional.ofNullable(pair.getValue())
.ifPresentOrElse(v -> myMap.put(pair.getKey(), v), v -> myList.add(pair.getKey())))
);
Need the ifPresentOrElse for it to work though. (I think a for loop looks better.)
The Date class already implements Comparator interface. Assuming you have the class below:
public class A {
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
.... other variables
}
And let's say you have a list of A objects as List<A> aList
, you can easily sort it with Java 8's stream API (snippet below):
import java.util.Comparator;
import java.util.stream.Collectors;
...
aList = aList.stream()
.sorted(Comparator.comparing(A::getDateTime))
.collect(Collectors.toList())
Well one way to do it is set the height of your body to the height
that you want your page
to be. In this example I did 600px
.
Then set your wrapper
height to a percentage of the body here I did 70%
This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.
body {
padding-top: 70px;
border:1px solid black;
height:600px;
}
.mygrid-wrapper-div {
border: solid red 5px;
overflow: scroll;
height: 70%;
}
Update How about a jQuery approach.
$(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
$( window ).resize(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
I was also having the same problem So I just removed the JDK path from the end and put it in start even before all System or Windows 32 paths.
Before it was like this:
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%JAVA_HOME%\bin;%ANT_HOME%\bin
So I made it like this:
%JAVA_HOME%\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%ANT_HOME%\bin
javascript is a bit tricky getting the answer, I fixed it by getting the api from the backend and then calling it to the frontend.
public function get_typechange () {
$ url = "https://........";
$ json = file_get_contents ($url);
$ data = json_decode ($ json, true);
$ resp = json_encode ($data);
$ error = json_last_error_msg ();
return $ resp;
}
Try this: service crond restart
, Hence it's crond
not cron
.
Now, this seems to work:
$('#example').DataTable({
"info": false
});
it hides that div
, altogether
I know i am probably the only one that will have this problem in this way. but if you deleted the mdf files in the C:/{user}/ directory, you will get this error too. restore it and you are golden
I've come across this problem on Typescript Version 3.8.3.
Intellisense is the best thing we could have but for me, the auto-import feature doesn't seem to work either. I've tried installing an extension even though auto-import didn't work. I've rechecked all the settings related to extensions. Finally, the auto-import feature started working when I clear the cache, from
C:\Users\username\AppData\Roaming\Code\Cache
& reload the VSCode
Note: AppData can only be visible in username if you select, Show (Hidden Items) from (View) Menu.
In some cases, we may end up thinking there is an import related error, while in actuality, unknowingly we might be coding using deprecated features or APIs in angular.
For example: if you're trying to code something like this
constructor (http: Http) {
//...}
Where Http is already deprecated and replaced with HttpClient in the newer version, so we may end up thinking an error related to this might be related to the auto-import error. For more information, you can refer Deprecated APIs and Features
Look at http://ss64.com/nt/if.html for an answer; the command is IF [%1]==[] GOTO NO_ARGUMENT
or similar.
Try this:
=FORMAT(Cdate(today), "dd-MM-yyyy")
or
=FORMAT(Cdate(today), "MM-dd-yyyy")
or
=FORMAT(Cdate(today), "yyyy-MM-dd")
or
=Report Generation Date: " & FORMAT(Cdate(today), "dd-MM-yyyy")
You should format the date in the same format your customer (internal or external) wants to see the date. For example In one of my servers it is running on American date format (MM-dd-yyyy) and on my reports I must ensure the dates displayed are European (yyyy-MM-dd).
Use an call thru section, it works
<div id="content">
<section id="home">
...
</section>
Call the above the thru
<a href="#home">page1</a>
Scrolling needs jquery paste this.. on above to ending body closing tag..
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.
E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.
I've profiled Justins two solutions. a.Any(a => b.Contains(a))
is fastest.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AnswersOnSO
{
public class Class1
{
public static void Main(string []args)
{
// How to check if list A contains any value from list B?
// e.g. something like A.contains(a=>a.id = B.id)?
var a = new List<int> {1,2,3,4};
var b = new List<int> {2,5};
var times = 10000000;
DateTime dtAny = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Any(b.Contains);
}
var timeAny = (DateTime.Now - dtAny).TotalSeconds;
DateTime dtIntersect = DateTime.Now;
for (var i = 0; i < times; i++)
{
var aContainsBElements = a.Intersect(b).Any();
}
var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;
// timeAny: 1.1470656 secs
// timeIn.: 3.1431798 secs
}
}
}
List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
DTO dTO = new DTO();
dTO.setrarchyID((Long) (rowMap.get("ID")));
}
foreach($array as $key => $value) echo $key, ' => ', $value;
I had the same as well.Making the Id (0) doing "(your Model value).setId(0)" solved my problem.
Now there is a Native support in SQL Server (CTP3) for import, export, query and validate JSON inside T-SQL Refer to https://msdn.microsoft.com/en-us/library/dn921897.aspx
I encount this while I was calculating np.var(np.array([]))
. np.var
will divide size of the array which is zero in this case.
You are trying to read the set value before Angular is done assigning.
Demo:
var testController = function ($scope, $timeout) {
console.log('test');
$timeout(function(){
console.log($scope.testInput);
},1000);
}
Ideally you should use $watch
as suggested by @Beterraba to get rid of the timer:
var testController = function ($scope) {
console.log('test');
$scope.$watch("testInput", function(){
console.log($scope.testInput);
});
}
while true; do (echo -e 'HTTP/1.1 200 OK\r\nConnection: close\r\n';) | timeout 1 nc -lp 8080 ; done
Closes connection after 1 sec, so curl doesn't hang on it.
As you say, you don't need to request the file twice. Pass it from your controller to your directive. Assuming you use the directive inside the scope of the controller:
.controller('MyController', ['$scope', '$http', function($scope, $http) {
$http.get('locations/locations.json').success(function(data) {
$scope.locations = data;
});
}
Then in your HTML (where you call upon the directive).
Note: locations
is a reference to your controllers $scope.locations
.
<div my-directive location-data="locations"></div>
And finally in your directive
...
scope: {
locationData: '=locationData'
},
controller: ['$scope', function($scope){
// And here you can access your data
$scope.locationData
}]
...
This is just an outline to point you in the right direction, so it's incomplete and not tested.
All the above not working for me.. Because I am using Facebook Ad dependency..
Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'
Try this code instead of above
compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}
After reading these answers and android documentation here's the code to resize bitmap without loading it into memory:
public Bitmap getResizedBitmap(int targetW, int targetH, String imagePath) {
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
//inJustDecodeBounds = true <-- will not load the bitmap into memory
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
return(bitmap);
}
This error comes because compile does not know where to find the class..so it occurs mainly when u copy or import item ..to solve this .. 1.change the namespace in the formname.cs and formname.designer.cs to the name of your project .
I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:
from time import strftime
from time import gmtime
strftime("%H:%M:%S", gmtime(666))
'00:11:06'
strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'
gmtime is used to convert seconds to special tuple format that strftime()
requires.
Note: Truncates after 23:59:59
try something like this:
DECLARE @YourTable table (PK int, col1 varchar(20), col2 varchar(20), col3 varchar(20))
INSERT @YourTable VALUES (1, 'ok','ok','ok')
INSERT @YourTable VALUES (2, 'BA'+char(182)+'D','ok','ok')
INSERT @YourTable VALUES (3, 'ok',char(182)+'BAD','ok')
INSERT @YourTable VALUES (4, 'ok','ok','B'+char(182)+'AD')
INSERT @YourTable VALUES (5, char(182)+'BAD','ok',char(182)+'BAD')
INSERT @YourTable VALUES (6, 'BAD'+char(182),'B'+char(182)+'AD','BAD'+char(182)+char(182)+char(182))
--if you have a Numbers table use that, other wise make one using a CTE
;WITH AllNumbers AS
( SELECT 1 AS Number
UNION ALL
SELECT Number+1
FROM AllNumbers
WHERE Number<1000
)
SELECT
pk, 'Col1' BadValueColumn, CONVERT(varchar(20),col1) AS BadValue --make the XYZ in convert(varchar(XYZ), ...) the largest value of col1, col2, col3
FROM @YourTable y
INNER JOIN AllNumbers n ON n.Number <= LEN(y.col1)
WHERE ASCII(SUBSTRING(y.col1, n.Number, 1))<32 OR ASCII(SUBSTRING(y.col1, n.Number, 1))>127
UNION
SELECT
pk, 'Col2' BadValueColumn, CONVERT(varchar(20),col2) AS BadValue --make the XYZ in convert(varchar(XYZ), ...) the largest value of col1, col2, col3
FROM @YourTable y
INNER JOIN AllNumbers n ON n.Number <= LEN(y.col2)
WHERE ASCII(SUBSTRING(y.col2, n.Number, 1))<32 OR ASCII(SUBSTRING(y.col2, n.Number, 1))>127
UNION
SELECT
pk, 'Col3' BadValueColumn, CONVERT(varchar(20),col3) AS BadValue --make the XYZ in convert(varchar(XYZ), ...) the largest value of col1, col2, col3
FROM @YourTable y
INNER JOIN AllNumbers n ON n.Number <= LEN(y.col3)
WHERE ASCII(SUBSTRING(y.col3, n.Number, 1))<32 OR ASCII(SUBSTRING(y.col3, n.Number, 1))>127
order by 1
OPTION (MAXRECURSION 1000)
OUTPUT:
pk BadValueColumn BadValue
----------- -------------- --------------------
2 Col1 BA¶D
3 Col2 ¶BAD
4 Col3 B¶AD
5 Col1 ¶BAD
5 Col3 ¶BAD
6 Col1 BAD¶
6 Col2 B¶AD
6 Col3 BAD¶¶¶
(8 row(s) affected)
Try the query below:
select count(*),d.dname from emp e , dept d where d.deptno = e.deptno
group by d.dname
I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.
Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.
new Vue({
methods: {
setValue: function() {
this.$data.oldPeople = _.cloneDeep(this.$data.people);
},
},
mounted() {
this.setValue();
},
el: '#app',
data: {
people: [
{id: 0, name: 'Bob', age: 27},
{id: 1, name: 'Frank', age: 32},
{id: 2, name: 'Joe', age: 38}
],
oldPeople: []
},
watch: {
people: {
handler: function (after, before) {
// Return the object that changed
var vm = this;
let changed = after.filter( function( p, idx ) {
return Object.keys(p).some( function( prop ) {
return p[prop] !== vm.$data.oldPeople[idx][prop];
})
})
// Log it
vm.setValue();
console.log(changed)
},
deep: true,
}
}
})
See the updated codepen
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
if you want destroy dark background of dialog , use this
dialog.getWindow().setDimAmount(0);
If your Google password doesn't work, you may need to create an app-specific password for Gmail on Google. https://support.google.com/accounts/answer/185833?hl=en
Attribute is a public variable inside the class/object. length attribute is a variable of int type.
memcpy expects the first two arguments to be void*.
Try:
memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );
P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.
Maybe join
+split
:
>>> a=12345
>>> list(map(int,' '.join(str(a)).split()))
[1, 2, 3, 4, 5]
>>> [int(i) for i in ' '.join(str(a)).split()]
[1, 2, 3, 4, 5]
>>>
str.join
+ str.split
is your friend, also we use map
or list comprehension
to get a list, (split what we join :-)).
This error occurs, due to connection limit reaches the maximum limit, defined in the configuration file my.cnf
.
In order to fix this error, login to MySQL as root
user (Note: you can login as root, since, mysql will pre-allocate additional one connection for root user
) and increase the max_connections variable by using the following command:
SET GLOBAL max_connections = 500;
This change will be there, until next server restart. In order to make this change permanent, you have to modify in your configuration file. You can do this by,
vi /etc/my.cnf
[mysqld]
max_connections = 500
This article has detailed step by step workaround to fix this error. Have a look at it, I hope it may help you. Thanks.
Best practice of getting length is use length
filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}
But you can calculate count of elements in for
loop. For example:
{% set count = 0 %}
{% for nc in notcount %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
This solution helps if you want to calculate count of elements by condition, for example you have a property name
inside object and you want to calculate count of objects with not empty names:
{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
{% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}
{{ countNotEmpty }}
Useful links:
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
Update Sep 2017 - tl;dr
Download a single file from a remote ftp server to your machine:
sftp {user}@{host}:{remoteFileName} {localFileName}
Upload a single file from your machine to a remote ftp server:
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
Original answer:
Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:
sftp user@host remoteFile localFile
The only documentation shown in the terminal is this:
sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]
However, I came across this site which shows the following under the synopsis:
sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host
sftp [[user@]host[:file [file]]]
sftp [[user@]host[:dir[/]]]
So the simple answer is you just do :
after your user and host then the remote file and local filename. Incredibly simple!
Single line, sftp copy remote file:
sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log
Update Feb 2016
In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp
command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
Use white-space:nowrap
and overflow:hidden
You cannot directly create a table stored as a sequence file and insert text into it. You must do this:
Example:
CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;
CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;
DROP TABLE test_txt;
If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer map
over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a map
function to overload python's map
. Then by passing the appropriate map
function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).
I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.
As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:
{
"rules": {
".read": true,
".write": true
}
}
Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"
*Don't write bin at the end
One must use behavior: JsonRequestBehavior.AllowGet
in Post Json Return
in C#
I just got caught out but not necessarily due to Chrome.
I am using jQuery to make AJAX requests. I had the cache attribute set to true in the request:
$.ajax({
type: 'GET',
cache: true,
....
Setting this to false fixed my problem but this is not ideal.
I have no idea where this data is saved but I do know that chrome never hit the server for a request.
Open the "MySQL Workbench" DMG file and
# Adjust the path to the version of MySQL Workbench you downloaded
cp "/Volumes/MySQL Workbench 6.3.9.CE/MySQLWorkbench.app/Contents/MacOS/mysql" /usr/local/bin
# Make sure it's executable
chmod +x /usr/local/bin/mysql
Eject the DMG disk
Here is what I have that helps you and others about markdown checkbox table. Enjoy!
| Projects | Operating Systems | Programming Languages | CAM/CAD Programs | Microcontrollers and Processors |
|---------------------------------- |---------------|---------------|----------------|-----------|
| <ul><li>[ ] Blog </li></ul> | <ul><li>[ ] CentOS</li></ul> | <ul><li>[ ] Python </li></ul> | <ul><li>[ ] AutoCAD Electrical </li></ul> | <ul><li>[ ] Arduino </li></ul> |
| <ul><li>[ ] PyGame</li></ul> | <ul><li>[ ] Fedora </li></ul> | <ul><li>[ ] C</li></ul> | <ul><li>[ ] 3DsMax </li></ul> |<ul><li>[ ] Raspberry Pi </li></ul> |
| <ul><li>[ ] Server Info Display</li></ul>| <ul><li>[ ] Ubuntu</li></ul> | <ul><li>[ ] C++ </li></ul> | <ul><li>[ ] Adobe AfterEffects </li></ul> |<ul><li>[ ] </li></ul> |
| <ul><li>[ ] Twitter Subs Bot </li></ul> | <ul><li>[ ] ROS </li></ul> | <ul><li>[ ] C# </li></ul> | <ul><li>[ ] Adobe Illustrator </li></ul> |<ul><li>[ ] </li></ul> |
Kinda related, you might want to look at Shuttle (http://fitztrev.github.io/shuttle/), it's a SSH shortcut menu for OSX.
Now I use the following to get the list of changed files my current branch has, comparing it to master (the compare-to branch is easily changed):
git log --oneline --pretty="format:" --name-only master.. | awk 'NF' | sort -u
Before, I used to rely on this:
git log --name-status <branch>..<branch> | grep -E '^[A-Z]\b' | sort -k 2,2 -u
which outputs a list of files only and their state (added, modified, deleted):
A foo/bar/xyz/foo.txt
M foo/bor/bar.txt
...
The -k2,2
option for sort, makes it sort by file path instead of the type of change (A, M, D,).
Check the information in registry : HKEY_CURRENT_USER\SOFTWARE\Microsoft\VSCommon\Keychain\Accounts and delete the related keys under Accounts section.
Clear the cache in these paths:
%localappdata%\Microsoft\TeamTest
%localappdata%\Microsoft\Team Foundation
%localappdata%\Microsoft\VisualStudio
%appdata%\Roaming\Microsoft\VisualStudio
Hope this will work.
Note: By doing this may clear all the cookies and caches and load the Visual Studio New.
You can save excel
as unicode
text, it is tab-delimited.
When using either a DISABLE or ENABLE TRIGGER statement in a batch that has other statements in it, the statement just before it must end with a semicolon. Otherwise, you'll get a syntax error. I tore my hair out with this one... And afterwards, I stumbled on this MS Connect item about the same thing. It is closed as won't fix.
see here
Such a silly solution in my case:
// Example a
#include <iostream>
#include "stdafx.h"
The above was odered as per example a, when I changed it to resemble example b below...
// Example b
#include "stdafx.h"
#include <iostream>
My code compiled like a charm. Try it, guaranteed to work.
For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.
Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.
Extensions can be loaded in unpacked mode by following the following steps:
chrome://extensions
(via omnibox or menu -> Tools -> Extensions).If you have a crx
file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.
These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
Perhaps "the most pythonic way" should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.
Example:
import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)
Which result might you want if this were in a function in your problem?
I solved the problem by applying box-sizing:border-box
; to the table cells themselves, besides doing the same with the input and the wrapper.
go to C:\Windows\System32\drivers\etc and open hosts file and add this
127.0.0.1 example.com
127.0.0.1 www.example.com
then go to C:\xampp\apache\conf\extra open httpd-ajp.conf file and add
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs/pojectroot"
ServerName example.com
ServerAlias www.example.com
<Directory "C:/xampp/htdocs/projectroot">
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Simply mutiply the bottom of the division by 1.0 (or as many decimal places as you want)
PRINT @set1
PRINT @set2
SET @weight= @set1 / @set2 *1.00000;
PRINT @weight
It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.
However, given that within if/else statements it is best practice to do the following:
var foo = "bar";
if(foo == "bar") {
return 0;
}
else {
return 100;
}
Based on this, the argument could be made that option one is better practice.
In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.
If you are using git
, you can add *.swp
to .gitignore
.
This is not possible with CSS selectors. But you could use two classes instead of one, e.g. status and important instead of status-important.
Here is what worked for me.
Get the container ID and restart.
docker ps -a --no-trunc
ace7ca65e6e3fdb678d9cdfb33a7a165c510e65c3bc28fecb960ac993c37ef33
docker restart ace7ca65e6e3fdb678d9cdfb33a7a165c510e65c3bc28fecb960ac993c37ef33
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=PORT_NUMBER
gradle bootrun --debug-jvm
mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
Quite a busy one-liner, but here it is:
myarray
, is normalised with the max value at 1.0
.myarray
.0-255
range.np.uint8()
.Image.fromarray()
.And you're done:
from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))
with plt.savefig()
:
with im.save()
:
I like Çagatay's solution, but I the popups were not hiding on mouseout. I added this extra functionality with this:
// hides the popup
$('*[data-poload]').bind('mouseout',function(){
var e=$(this);
e.popover('hide');
});
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
Don't drop, just take the rows where EPS is not NA:
df = df[df['EPS'].notna()]
The use of levels is really up tp you. You need to decide what is severe in your application, what is a warning and what is just information. You need to split your logging so that your users can easily set up a level of logging that doesn't kill the system with excessing IO but which will report serious errors so you can fix them.
Associative Arrays in JavaScript don't really work the same as they do in other languages. for each
statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push
method:
jsArr = [];
for (var i = 1; i <= 10; i++) {
jsArr.push('example ' + 1);
}
Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].
If you don't mind the binary size, you can use iproute2 as library.
Pros:
Cons:
i've solve all with
.setInputType(InputType.TYPE_CLASS_NUMBER);
for see clear data and
.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
for see the dots (if the data is a number, it isn't choice che other class)
Yes, you can program Android apps in C++ (for the most part), using the Native Development Kit (NDK), although Java is the primary/preferred language for programming Android, and your C++ code will likely have to interface with Java components, and you'll likely need to read and understand the documentation for Java components, as well. Therefore, I'd advise you to use Java unless you have some existing C++ code base that you need to port and that isn't practical to rewrite in Java.
Java is very similar to C++, I don't think you will have any problems picking it up... going from C++ to Java is incredibly easy; going from Java to C++ is a little more difficult, though not terrible. Java for C++ Programmers does a pretty good job at explaining the differences. Writing your Android code in Java will be more idiomatic and will also make the development process easier for you (as the tooling for the Java Android SDK is significantly better than the corresponding NDK tooling)
In terms of setup, Google provides the Android Studio IDE for both Java and C++ Android development (with Gradle as the build system), but you are free to use whatever IDE or build system you want so long as, under the hood, you are using the Android SDK / NDK to produce the final outputs.
Use StringTokenizer to parse the string.
String s ="SALES:0,SALE_PRODUCTS:1,EXPENSES:2,EXPENSES_ITEMS:3";
Map<String, Integer> lMap=new HashMap<String, Integer>();
StringTokenizer st=new StringTokenizer(s, ",");
while(st.hasMoreTokens())
{
String [] array=st.nextToken().split(":");
lMap.put(array[0], Integer.valueOf(array[1]));
}
According to php docs (see $_SERVER) $_SERVER['PHP_SELF'] is the "filename of the currently executing script".
The INCLUDE statement "includes and evaluates the specified" file and "the code it contains inherits the variable scope of the line on which the include occurs" (see INCLUDE).
I believe $_SERVER['PHP_SELF'] will return the filename of the 1st file, even when used by code in the 'second.php'.
I tested this with the following code and it works as expected ($phpSelf is the name of the first file).
// In the first.php file
// get the value of $_SERVER['PHP_SELF'] for the 1st file
$phpSelf = $_SERVER['PHP_SELF'];
// include the second file
// This slurps in the contents of second.php
include_once('second.php');
// execute $phpSelf = $_SERVER['PHP_SELF']; in the secod.php file
// echo the value of $_SERVER['PHP_SELF'] of fist file
echo $phpSelf; // This echos the name of the First.php file.
I had the same error. Basically, I suspect that the path cannot start either with "U" or "User" after "C:\". I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.
In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.
The proper way to initialize a multidimensional array in C or C++ is
int arr[2][5] = {{1,8,12,20,25}, {5,9,13,24,26}};
You can use this same trick to initialize even higher-dimensional arrays if you want.
Also, be careful in your initial code - you were trying to use 1-indexed offsets into the array to initialize it. This didn't compile, but if it did it would cause problems because C arrays are 0-indexed!
arr = arr.filter(v => v);
as returned v
is implicity converted to truthy
That's strange, it definitely works for me:
from matplotlib import pyplot as plt
plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')
I am using the "MacOSX" backend, btw.
NOTE: Pure Swift 3 (Xcode 8) example:
Please try out the following sample code. It is the simple example of dataTask
function of URLSession
.
func simpleDataRequest() {
//Get the url from url string
let url:URL = URL(string: "YOUR URL STRING")!
//Get the session instance
let session = URLSession.shared
//Create Mutable url request
var request = URLRequest(url: url as URL)
//Set the http method type
request.httpMethod = "POST"
//Set the cache policy
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
//Post parameter
let paramString = "key=value"
//Set the post param as the request body
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let _:Data = data as Data?, let _:URLResponse = response , error == nil else {
//Oops! Error occured.
print("error")
return
}
//Get the raw response string
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
//Print the response
print(dataString!)
}
//resume the task
task.resume()
}
Modules go in site-packages
and executables go in your system's executable path. For your environment, this path is /usr/local/bin/
.
To avoid having to deal with this, simply use easy_install
, distribute
or pip
. These tools know which files need to go where.
Combination of lambda and map function can also do the job:
list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2
The answer of @abbotto did not work for me, had to do some things differently:
Starting with Ruby 2.4.0, you may use RegExp#match?
:
pattern.match?(string)
Regexp#match?
is explicitly listed as a performance enhancement in the release notes for 2.4.0, as it avoids object allocations performed by other methods such as Regexp#match
and =~
:
Regexp#match?
AddedRegexp#match?
, which executes a regexp match without creating a back reference object and changing$~
to reduce object allocation.
Similar to above, using filter
from dplyr
:
filter(df, fct %in% vc)
Both are correct. Oracle allows the use of both.
saving a last click time when clicking will prevent this problem.
i.e.
private long mLastClickTime = 0;
...
// inside onCreate or so:
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// mis-clicking prevention, using threshold of 1000 ms
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
// do your magic here
}
}
If you give the code a .c extension the compiler thinks it is C code, not C++. And the C++ compiler driver is called g++, if you use the gcc driver you will have linker problems, as the standard C++ libraries will not be linked by default. So you want:
g++ myprog.cpp
And do not even consider using an uppercase .C extension, unless you never want to port your code, and are prepared to be hated by those you work with.
This works for setting the value of the INPUT:
strftime('%Y-%m-%dT%H:%M:%S', time())
This is how I did it.
private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if(Convert.ToBoolean(this.Grid.Rows[e.RowIndex].Cells["Selected"].Value) == false)
{
this.Grid.Rows[e.RowIndex].Cells["Selected"].Value = true;
}
else
{
this.productSpecGrid.Rows[e.RowIndex].Cells["Selected"].Value = false;
}
}
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
I suggest keeping your icons separate from FontAwesome and create and maintain your own custom library. Personally, I think it is much easier to maintain keeping FontAwesome separate if you are going to be creating your own icon library. You can then have FontAwesome loaded into your site from a CDN and never have to worry about keeping it up-to-date.
When creating your own custom icons, create each icon via Adobe Illustrator or similar software. Once your icons are created, save each individually in SVG
format on your computer.
Next, head on over to IcoMoon: http://icomoon.io , which has the best font generating software (in my opinion), and it's free. IcoMoon will allow you to import your individual svg-saved fonts into a font library, then generate your custom icon glyph library in eot
, ttf
, woff
, and svg
. One format IcoMoon does not generate is woff2
.
After generating your icon pack at IcoMoon, head over to FontSquirrel: http://fontsquirrel.com and use their font generator. Use your ttf
file generated at IcoMoon. In the newly generated icon pack created, you'll now have your icon pack in woff2
format.
Make sure the files for eot
, ttf
, svg
, woff
, and woff2
are all the same name. You are generating an icon pack from two different websites/software, and they do name their generated output differently.
You'll have CSS generated for your icon pack at both locations. But the CSS generated at IcoMoon will not include the woff2
format in your @font-face {}
declaration. Make sure to add that when you're adding your CSS to your project:
@font-face {
font-family: 'customiconpackname';
src: url('../fonts/customiconpack.eot?lchn8y');
src: url('../fonts/customiconpack.eot?lchn8y#iefix') format('embedded-opentype'),
url('../fonts/customiconpack.ttf?lchn8y') format('truetype'),
url('../fonts/customiconpack.woff2?lchn8y') format('woff'),
url('../fonts/customiconpack.woff?lchn8y') format('woff'),
url('../fonts/customiconpack.svg?lchn8y#customiconpack') format('svg');
font-weight: normal;
font-style: normal;
}
Keep in mind that you can get the glyph unicode values of each icon in your icon pack using the IcoMoon software. These values can be helpful in assigning your icons via CSS, as in (assuming we're using the font-family
declared in the example @font-face {...}
above):
selector:after {
font-family: 'customiconpackname';
content: '\e953';
}
You can also get the glyph unicode value e953
if you open the font-pack-generated svg
file in a text editor. E.g.:
<glyph unicode="" glyph-name="eye" ... />
You need to set the backgroundColor of the cell's contentView to your color. If you use accessories (such as disclosure arrows, etc), they'll show up as white, so you may need to roll custom versions of those.