Gold Noise
// Gold Noise ©2015 [email protected]
// - based on the Golden Ratio
// - uniform normalized distribution
// - fastest static noise generator function (also runs at low precision)
float PHI = 1.61803398874989484820459; // F = Golden Ratio
float gold_noise(in vec2 xy, in float seed){
return fract(tan(distance(xy*PHI, xy)*seed)*xy.x);
}
See Gold Noise in your browser right now!
This function has improved random distribution over the current function in @appas' answer as of Sept 9, 2017:
The @appas function is also incomplete, given there is no seed supplied (uv is not a seed - same for every frame), and does not work with low precision chipsets. Gold Noise runs at low precision by default (much faster).
c
can be used on lists (and not only on vectors):
# you have
l1 = list(2, 3)
l2 = list(4)
# you want
list(2, 3, 4)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
# you can do
c(l1, l2)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
If you have a list of lists, you can do it (perhaps) more comfortably with do.call
, eg:
do.call(c, list(l1, l2))
Since GDB 7.5 you can use these native Convenience Functions:
$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)
Seems quite less problematic than having to execute a "foreign" strcmp()
on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.
Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running
show configuration
inside GDB and searching for--with-python
. This little oneliner does the trick, too:$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python' --with-python=/usr (relocatable)
For your demo case, the usage would be
break <where> if $_streq(x, "hello")
or, if your breakpoint already exists and you just want to add the condition to it
condition <breakpoint number> $_streq(x, "hello")
$_streq
only matches the whole string, so if you want something more cunning you should use $_regex
, which supports the Python regular expression syntax.
async() => {
let body = await model.find().or([
{ name: 'something'},
{ nickname: 'somethang'}
]).exec();
console.log(body);
}
/* Gives an array of the searched query!
returns [] if not found */
Configuration files are application-scoped and not assembly-scoped. So you'll need to put your library's configuration sections in every application's configuration file that is using your library.
That said, it is not a good practice to get configuration from the application's configuration file, specially the appSettings
section, in a class library. If your library needs parameters, they should probably be passed as method arguments in constructors, factory methods, etc. by whoever is calling your library. This prevents calling applications from accidentally reusing configuration entries that were expected by the class library.
That said, XML configuration files are extremely handy, so the best compromise that I've found is using custom configuration sections. You get to put your library's configuration in an XML file that is automatically read and parsed by the framework and you avoid potential accidents.
You can learn more about custom configuration sections on MSDN and also Phil Haack has a nice article on them.
Run the command INFO
. The version will be the first item displayed.
The advantage of this over redis-server --version is that sometimes you don't have access to the server (e.g. when it's provided to you on the cloud), in which case INFO
is your only option.
Humm!
did you try LOCK_TIMEOUT
Note down what it was orginally before running the query
set it for your query
after running your query set it back to original value
SET LOCK_TIMEOUT 1800;
SELECT @@LOCK_TIMEOUT AS [Lock Timeout];
I stumbled upon this problem again. But this time it occurred for a different reason. I had copied files into the repo to overwrite the previous versions. Now I can see the files are modified but diff doesn't return the diffs.
For example, I have a mainpage.xaml file.
In File Explorer I pasted a new mainpage.xaml file over the one in my current repo.
I did the work on another machine and just pasted the file here.
The file shows modified, but when I run git diff, it will not show the changes. It's probably because the fileinfo on the file has changed and git knows that it isn't really the same file. Interesting.
You can see that when I run diff on the file it shows nothing, just returns the prompt.
I use these templates
template <typename T> string toStr(T tmp)
{
ostringstream out;
out << tmp;
return out.str();
}
template <typename T> T strTo(string tmp)
{
T output;
istringstream in(tmp);
in >> output;
return output;
}
You can use ramda
library.
Learning ramda
also helps you to work with immutable objects easily.
var obj = {
a:{
b: {
c:[100,101,{
d: 1000
}]
}
}
};
var lens = R.lensPath('a.b.c.2.d'.split('.'));
var result = R.view(lens, obj);
I presume you are talking about filling zeros of some existing mat? How about this? :)
mat *= 0;
As short as the question:
SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID
The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.
Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.
Netty also provides a nice query string parser called QueryStringDecoder
.
In one line of code, it can parse the URL in the question.
I like because it doesn't require catching or throwing java.net.MalformedURLException
.
In one line:
Map<String, List<String>> parameters = new QueryStringDecoder(url).parameters();
See javadocs here: https://netty.io/4.1/api/io/netty/handler/codec/http/QueryStringDecoder.html
Here is a short, self contained, correct example:
import io.netty.handler.codec.http.QueryStringDecoder;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
public class UrlParse {
public static void main(String... args) {
String url = "https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback";
QueryStringDecoder decoder = new QueryStringDecoder(url);
Map<String, List<String>> parameters = decoder.parameters();
print(parameters);
}
private static void print(final Map<String, List<String>> parameters) {
System.out.println("NAME VALUE");
System.out.println("------------------------");
parameters.forEach((key, values) ->
values.forEach(val ->
System.out.println(StringUtils.rightPad(key, 19) + val)));
}
}
which generates
NAME VALUE
------------------------
client_id SS
response_type code
scope N_FULL
access_type offline
redirect_uri http://localhost/Callback
If what you want is a way to turn your class into kind of a list without subclassing list
, then just make a method that returns a list:
def MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def get_list(self):
return [self.value1, self.value2...]
>>>print MyClass().get_list()
[1, 2...]
If you meant that print MyClass()
will print a list, just override __repr__
:
class MyClass():
def __init__(self):
self.value1 = 1
self.value2 = 2
def __repr__(self):
return repr([self.value1, self.value2])
EDIT:
I see you meant how to make objects compare. For that, you override the __cmp__
method.
class MyClass():
def __cmp__(self, other):
return cmp(self.get_list(), other.get_list())
If your jQuery page isn't being loaded from http://localhost:54473
then this issue is probably because you're trying to make cross-domain request.
Update 1 Take a look at this blog post.
Update 2 If this is indeed the problem (and I suspect it is), you might want to check out JSONP as a solution. Here are a few links that might help you get started:
How about:
echo "hello" >> <filename>
Using the >>
operator will append data at the end of the file, while using the >
will overwrite the contents of the file if already existing.
You could also use printf
in the same way:
printf "hello" >> <filename>
Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last >
all data in the file will be destroyed. You can change this behavior by setting the noclobber
variable in your .bashrc
:
set -o noclobber
Now when you try to do echo "hello" > file.txt
you will get a warning saying cannot overwrite existing file
.
To force writing to the file you must now use the special syntax:
echo "hello" >| <filename>
You should also know that by default echo
adds a trailing new-line character which can be suppressed by using the -n
flag:
echo -n "hello" >> <filename>
References
Adding more to the answers already present. If you know the file in which you might have made do this:
git log --follow -p -S 'search-string' <file-path>
--follow: lists the history of a file
Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.
Therefore, you can not use this variation
> sitemap: /sitemap.xml
Recommended syntax is
Sitemap: https://www.yourdomain.com/sitemap.xml
Note:
Your second for loop should have j++ instead of i++
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
GROUP BY grade.gradeId
ORDER BY exam.date
It's canonical to use references for this; precedence: ostream::operator<<
. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.
Try this solution which worked fine for me.
Basically it's to reinstall/upgrade to latest version of mysql from brew, and then installing mysqlclient
or MySQL-Python
from global pip3
instead of virtualenv pip3
.
Then accessing the virtualenv
and successfully install mysqlclient
or MySQL-Python
.
auto-alignment shortcut key Ctrl
+Shift
+F
to change the shortcut keys Goto Window > Preferences > Java > Editor > Save Actions
I would like to run an automation test in different environments.
So I add this to command maven command:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"
Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095
I think I got it. I have to use org.w3c.dom.Element
explicitly. I had a different Element field too.
If you have a table called memos that has two columns id
and text
you should be able to do like this:
INSERT INTO memos(id,text)
SELECT 5, 'text to insert'
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
If a record already contains a row where text
is equal to 'text to insert' and id
is equal to 5, then the insert operation will be ignored.
I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.
I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer
below.
Even more simple, pass the $event
object to ng-click
to access the event properties. As an example:
<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>
Within your clickEvent() = function(obj) {}
function you can access the data
value like this:
var dataValue = obj.target.attributes.data.value;
Which would return exampleData
.
Here's a full jsFiddle.
The main concept of partial view is returning the HTML code rather than going to the partial view it self.
[HttpGet]
public ActionResult Calendar(int year)
{
var dates = new List<DateTime>() { /* values based on year */ };
HolidayViewModel model = new HolidayViewModel {
Dates = dates
};
return PartialView("HolidayPartialView", model);
}
this action return the HTML code of the partial view ("HolidayPartialView").
To refresh partial view replace the existing item with the new filtered item using the jQuery below.
$.ajax({
url: "/Holiday/Calendar",
type: "GET",
data: { year: ((val * 1) + 1) }
})
.done(function(partialViewResult) {
$("#refTable").html(partialViewResult);
});
Others have covered performance profiling, but with regards to memory profiling I'm currently evaluating both the Scitech .NET Memory Profiler 3.1 and ANTS Memory Profiler 5.1 (current versions as of September 2009). I tried the JetBrains one a year or two ago and it wasn't as good as ANTS (for memory profiling) so I haven't bothered this time. From reading the web sites it looks like it doesn't have the same memory profiling features as the other two.
Both ANTS and the Scitech memory profiler have features that the other doesn't, so which is best will depend upon your preferences. Generally speaking, the Scitech one provides more detailed information while the ANTS one is really incredible at identifying the leaking object. Overall, I prefer the ANTS one because it is so quick at identifying possible leaks.
Here are the main the pros and cons of each from my experience:
Common Features of ANTS and Scitech .NET Memory Profiler
ANTS
Scitech .NET Memory Profiler
By way of summary, I think ANTS helps you find what's leaking faster while Scitech provides a bit more detail about your overall application memory performance and individual objects once you know what to look at (eg. stack trace on creation). If the stack trace and tracking of undisposed disposable objects was added to ANTS I wouldn't see the need to use anything else.
These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.
function isURL(str) {
var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
var url = new RegExp(urlRegex, 'i');
return str.length < 2083 && url.test(str);
}
I know the OP specifically mentioned jQuery but I wanted to put an answer here to introduce people to the helpful Underscore library if they are not aware of it already.
By leveraging the keys
method in the Underscore library, you can simply do the following:
_.keys(foo) #=> ["alfa", "beta"]
Plus, there's a plethora of other useful functions that are worth perusing.
From firefox's official release notes on V35:
Using
-moz-appearance
with thenone
value on a combobox now remove the dropdown button (bug 649849).
So now in order to hide the default arrow - it's as easy as adding the following rules on our select element:
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
select {_x000D_
margin: 50px;_x000D_
border: 1px solid #111;_x000D_
background: transparent;_x000D_
width: 150px;_x000D_
padding: 5px;_x000D_
font-size: 16px;_x000D_
border: 1px solid #ccc;_x000D_
height: 34px;_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
}
_x000D_
<select>_x000D_
<option>Apples</option>_x000D_
<option selected>Pineapples</option>_x000D_
<option>Chocklate</option>_x000D_
<option>Pancakes</option>_x000D_
</select>
_x000D_
Precision of a number is the number of digits.
Scale of a number is the number of digits after the decimal point.
What is generally implied when setting precision and scale on field definition is that they represent maximum values.
Example, a decimal field defined with precision=5
and scale=2
would allow the following values:
123.45
(p=5,s=2)12.34
(p=4,s=2)12345
(p=5,s=0)123.4
(p=4,s=1)0
(p=0,s=0)The following values are not allowed or would cause a data loss:
12.345
(p=5,s=3) => could be truncated into 12.35
(p=4,s=2)1234.56
(p=6,s=2) => could be truncated into 1234.6
(p=5,s=1)123.456
(p=6,s=3) => could be truncated into 123.46
(p=5,s=2)123450
(p=6,s=0) => out of rangeNote that the range is generally defined by the precision: |value| < 10^p
...
Michael Krelin's answer is close is not entirely safe, since it can be wrong in rare situations. The problem is that intervals in PostgreSQL do not have context with regards to things like daylight savings. Intervals store things internally as months, days, and seconds. Months aren't an issue in this case since subtracting two timestamps just use days and seconds but 'days' can be a problem.
If your subtraction involves daylight savings change-overs, a particular day might be considered 23 or 25 hours respectively. The interval will take that into account, which is useful for knowing the amount of days that passed in the symbolic sense but it would give an incorrect number of the actual hours that passed. Epoch on the interval will just multiply all days by 24 hours.
For example, if a full 'short' day passes and an additional hour of the next day, the interval will be recorded as one day and one hour. Which converted to epoch/3600 is 25 hours. But in reality 23 hours + 1 hour should be a total of 24 hours.
So the safer method is:
(EXTRACT(EPOCH FROM current_timestamp) - EXTRACT(EPOCH FROM somedate))/3600
As Michael mentioned in his follow-up comment, you'll also probably want to use floor() or round() to get the result as an integer value.
$pdf->Output()
takes a second parameter $dest
, which accepts a single character. The default, $dest='I'
opens the PDF in the browser.
Use F
to save to file
$pdf->Output('/path/to/file.pdf', 'F')
Please check you pom.xml for the below tags
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
it should point the required jdk version
import java.io.IOException;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
/**
* @author Kiran
*
*/
public class MyLogger {
public MyLogger() {
}
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
Appender fh = null;
try {
fh = new FileAppender(new SimpleLayout(), "MyLogFile.log");
logger.addAppender(fh);
fh.setLayout(new SimpleLayout());
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
}
You could use regex as this will give you the string if it matches the requirements. The code would be something like:
const address = "1345 albany street, Bellevue WA 42344";
const regex = /[1-9][0-9]* [a-zA-Z]+ [a-zA-Z]+/;
const matchedResult = address.match(regex);
console.log(matchedResult[0]); // This will give you 1345 albany street.
So to break the code down. [1-9][0-9]*
basically means the first number cannot be a zero and has to be a number between 1-9
and the next number can be any number from 0-9
and can occur zero or more times as sometimes the number is just one digit and then it matches a space. [a-zA-Z]
basically matches all capital letters to small letters and has to occur one or more times and this is repeated.
Just discovered this:
SELECT * FROM OPENROWSET(BULK N'<PATH_TO_FILE>', SINGLE_CLOB) AS Contents
It'll pull in the contents of the file as varchar(max). Replace SINGLE_CLOB
with:
SINGLE_NCLOB
for nvarchar(max)
SINGLE_BLOB
for varbinary(max)
Thanks to http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/ for this!
Use this library: http://imageresizing.net
Have a read of this article by the library author: 20 Image Sizing Pitfalls with .NET
Use itertools.chain:
itertools.chain(*iterables)
:Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
from itertools import chain
A = [[1,2], [3,4]]
print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))
The output is:
[1, 2, 3, 4]
[1, 2, 3, 4]
There are already several answers however none of them mention the best (and easiest) way to do this, which is using spawn
and the { stdio: 'inherit' }
option. It seems to produce the most accurate output, for example when displaying the progress information from a git clone
.
Simply do this:
var spawn = require('child_process').spawn;
spawn('coffee', ['-cw', 'my_file.coffee'], { stdio: 'inherit' });
Credit to @MorganTouvereyQuilling for pointing this out in this comment.
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
This works for both float
and double
:
double NAN = 0.0/0.0;
double POS_INF = 1.0 /0.0;
double NEG_INF = -1.0/0.0;
Edit: As someone already said, the old IEEE standard said that such values should raise traps. But the new compilers almost always switch the traps off and return the given values because trapping interferes with error handling.
Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated.
However, I came across this article which demonstrates the use of PSTools from SysInternals (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic:
psexec -i -s cmd.exe
PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem.
Many thanks to those who offered help.
The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.
Create it at the following location <your home folder>/.m2/settings.xml
e.g. C:\Users\YourUserName\.m2\settings.xml
on Windows or /home/YourUserName/.m2/settings.xml
on Linux
Here's an empty skeleton you can use:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>
If you use Eclipse to edit it, it will give you auto-completion when editing it.
And here's the Maven settings.xml Reference page
hi i got the same problem.. add 0.71 to excel cell width value and give that value to the
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
eg: A Column width = 3.71 (excel value)
give column width = 4.42
will give the output file with same cell width.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(4.42);
hope this help
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
You can also make sure you are the sudo user and you have READ/WRITE access on the directory you are working. I had a similar problem on OS X, and I got it fixed just by entering in sudo mode.
Assuming you want a default button checked.
<div class="row">
<h1>Radio Group #2</h1>
<label for="year" class="control-label input-group">Year</label>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" name="year" value="2011">2011
</label>
<label class="btn btn-default">
<input type="radio" name="year" value="2012">2012
</label>
<label class="btn btn-default active">
<input type="radio" name="year" value="2013" checked="">2013
</label>
</div>
</div>
Add the active
class to the button (label
tag) you want defaulted and checked=""
to its input
tag so it gets submitted in the form by default.
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
In real world or project we have requirement in advance and needs to create variable and methods inside the class , On the basis of requirement we needs to decide whether we needs to create
=>2. Static Keyword we will used with variable which going to same for particular class throughout for all objects, e.g in selenium : we decalre webDriver as static=> so we do not need to create webdriver again and again for every test case= Static Webdriver driver(but parallel execution it will cause problem but thats another case); then, Real world scenario=>If India is class then, flag, money would be same every indian so we might take as static. Anatoher example: utility method we always declare as static b'cos it will be used in different test cases. Static stored in CMA( PreGen space)=PreGen (Fixed memory)changed to Metaspace after Java8 as now its growing dynamically
In my case, It was from Stored Producers. I was removed a field from table and forgotten to remove it from my SP.
If you want to kill the process(es) or cmd.exe carrying a particular title(s).
import csv, os
import subprocess
# ## Find the command prompt windows.
# ## Collect the details of the command prompt windows and assign them.
tasks = csv.DictReader(subprocess.check_output('tasklist /fi "imagename eq cmd.exe" /v /fo csv').splitlines(), delimiter=',', quotechar='"')
# ## The cmds with titles to be closed.
titles= ["Ploter", "scanFolder"]
# ## Find the PIDs of the cmds with the above titles.
PIDList = []
for line in tasks:
for title in titles:
if title in line['Window Title']:
print line['Window Title']
PIDList.append(line['PID'])
# ## Kill the CMDs carrying the PIDs in PIDList
for id in PIDList:
os.system('taskkill /pid ' + id )
Hope it helps. Their might be numerous better solutions to mine.
in my case, I Edit my gradle.properties
:
note: if u enable the minifyEnabled true
:
remove this line :
android.enableR8=true
and add this lines in ur build.gradle
, android
block :
dexOptions {
incremental = true
preDexLibraries = false
javaMaxHeapSize "4g" // 2g should be also OK
}
hope this help some one :)
Regex.Matches(input, "true").Count
As @StahlRat already answered. I would like to add another method for it. There is extension pack for Python Default idle editor Python Extensions Package.
Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.
More info here:
From the docs:
urllib.quote(string[, safe])
Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'
That means passing '' for safe will solve your first issue:
>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'
About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:
>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller
By the way have a look at urlencode
The same, except replace urllib.quote
with urllib.parse.quote
.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
Use lapply
function after creating your function normally.
lapply(x="your input", fun="insert your function name")
lapply
gives a list so use unlist
function to take them out of the function
unlist(lapply(a,w))
For Windows, I did recently this:
// +build windows
package main
import (
"syscall"
"unsafe"
)
var (
modrpcrt4 = syscall.NewLazyDLL("rpcrt4.dll")
procUuidCreate = modrpcrt4.NewProc("UuidCreate")
)
const (
RPC_S_OK = 0
)
func NewUuid() ([]byte, error) {
var uuid [16]byte
rc, _, e := syscall.Syscall(procUuidCreate.Addr(), 1,
uintptr(unsafe.Pointer(&uuid[0])), 0, 0)
if int(rc) != RPC_S_OK {
if e != 0 {
return nil, error(e)
} else {
return nil, syscall.EINVAL
}
}
return uuid[:], nil
}
Just do something like below:
function isNotDefined(value) {
return typeof value === "undefined";
}
and call it like:
isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false
Check all the key and values in info.plist file. if any key is missing then it will cause this issue. AppIcon and other thing written in info.plist file must be prefect then u will not able to get this issue.
package com.dataload;
public class insertCSV
{
public static void main(String args[])
{
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationcontext.xml");
// retrieve configured instance
JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
Job job = context.getBean("job", Job.class);
JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
}
}
I was able to install composer on HostGator's shared hosting. Logged in to SSH with Putty, right after login you should be in your home directory, which is usually /home/username, where username is your username obviously. Then ran the curl command posted by @niutech above. This downloaded the composer to my home directory and it's now accessible and working well.
This may or may not help anyone, but I had a page I could not get to center correctly no matter what Css tricks I tried so I wrote a JQuery file call Center Page:
The problem occurred with zoom level of the browser, the page would shift based upon if you were 100%, 125%, 150%, etc.
The code below is in a JQuery file called centerpage.js.
From my page I had to link to JQuery and this file to get it work, even though my master page already had a link to JQuery.
<title>Home Page.</title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/centerpage.js"></script>
centerpage.js
:
// centering page element
function centerPage() {
// get body element
var body = document.body;
// if the body element exists
if (body != null) {
// get the clientWidth
var clientWidth = body.clientWidth;
// request data for centering
var windowWidth = document.documentElement.clientWidth;
var left = (windowWidth - bodyWidth) / 2;
// this is a hack, but it works for me a better method is to determine the
// scale but for now it works for my needs
if (left > 84) {
// the zoom level is most likely around 150 or higher
$('#MainBody').removeClass('body').addClass('body150');
} else if (left < 100) {
// the zoom level is most likely around 110 - 140
$('#MainBody').removeClass('body').addClass('body125');
}
}
}
// CONTROLLING EVENTS IN jQuery
$(document).ready(function() {
// center the page
centerPage();
});
Also if you want to center a panel:
// centering panel
function centerPanel($panelControl) {
// if the panel control exists
if ($panelControl && $panelControl.length) {
// request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var panelHeight = $panelControl.height();
var panelWidth = $panelControl.width();
// centering
$panelControl.css({
'position': 'absolute',
'top': (windowHeight - panelHeight) / 2,
'left': (windowWidth - panelWidth) / 2
});
// only need force for IE6
$('#backgroundPanel').css('height', windowHeight);
}
}
Google mentioned that all js files rendered but in real, I've lost my title and another meta tags which had been provided by Reactjs on this website and actually lost my position on Google! I've searched a lot but it seems that all pages must have pre-rendered or using SSR(Server Side Rendering) to have their SEO-friendly protocole!
It expands to Reactjs, Angularjs , etc.
For short, Every page that has view page source on browser is indexed by all robots, if it's not probably Google can index but others skip indexing!
With a non-US keyboard layout the default shortcut Ctrl+/ (Win/Linux) does not work.
I managed to change it into Ctrl+1 as per Robert's comment by writing
[
{
"keys": ["ctrl+1"],
"command": "toggle_comment",
"args": { "block": false }
}
,
{ "keys": ["ctrl+shift+1"],
"command": "toggle_comment",
"args": { "block": true }
}
]
to Preferences -> Key Bindings
(on the right half, the user keymap).
Note that there should be only one set of brackets ('[]
') at the right side; if you had there something already, copy paste this between the brackets and keep only the outermost brackets.
Based on an earlier reply by @dmckee
make | tee makelog.txt
This gives you real-time scrolling output while compiling, and simultaneously write to the makelog.txt file.
On OSX and VSCode 1.50.0 all I had to do was to close and restart VSCode and the problem went away.
255 is used because it's the largest number of characters that can be counted with an 8-bit number. It maximizes the use of the 8-bit count, without frivolously requiring another whole byte to count the characters above 255.
When used this way, VarChar only uses the number of bytes + 1 to store your text, so you might as well set it to 255, unless you want a hard limit (like 50) on the number of characters in the field.
Do the following change to the jquery.validationengine-en.js
file and update the dd/mm/yyyy inline validation by including leap year:
"date": {
// Check if date is valid by leap year
"func": function (field) {
//var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
//var year = match[1];
//var month = match[2]*1;
//var day = match[3]*1;
var year = match[3];
var month = match[2]*1;
var day = match[1]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in DD-MM-YYYY format"
Technically yes. But only on certain instances. If for example you have the code page up and you hit git checkout, and you realize that you accidently checked out the wrong page or something. Go to the page and click undo. (for me, command + z), and it will go back to exactly where you were before you hit the good old git checkout.
This will not work if your page has been closed, and then you hit git checkout. It only works if the actual code page is open
This is a perfect use-case for DISTINCT ON
- a Postgres specific extension of the standard DISTINCT
:
SELECT DISTINCT ON (category)
id -- , category, date -- any other column (expression) from the same row
FROM tbl
ORDER BY category, date DESC;
Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST
:
DISTINCT ON
is simple and fast. Detailed explanation in this related answer:
For big tables with many rows per category
consider an alternative approach:
sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just
echo "c1, c2, ... " >> file
cat testfile.csv >> file
?
I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.
That said, please try the following filter and see if you're getting the entries that you think you should be getting:
dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7
You can use .css()
to get the value of "visibility":
if( ! ( $("#singlechatpanel-1").css('visibility') === "hidden")){
}
Tabview: lightweight python curses command line CSV file viewer (and also other tabular Python data, like a list of lists) is here on Github
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror
from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null
it will remove the onerror then try to get the alternate image.
NEW I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
If you are using Sass/Scss, then follow this,
Do npm install
npm install bootstrap --save
and add import
statement to your sass/scss file,
@import '~bootstrap/dist/css/bootstrap.css'
You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding. There is no magical event.cancelled=false;
As requested
$('form').submit( function(ev){
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
(N-1) + (N-2) +...+ 2 + 1
is a sum of N-1 items. Now reorder the items so, that after the first comes the last, then the second, then the second to last, i.e. (N-1) + 1 + (N-2) + 2 +..
. The way the items are ordered now you can see that each of those pairs is equal to N (N-1+1 is N, N-2+2 is N). Since there are N-1 items, there are (N-1)/2 such pairs. So you're adding N (N-1)/2 times, so the total value is N*(N-1)/2
.
pip list --outdated
You will get the list of outdated packages.pip install [package] --upgrade
It will upgrade the [package]
and uninstall the previous version.To update pip:
py -m pip install --upgrade pip
Again, this will uninstall the previous version of pip and will install the latest version of pip.
There's no particular single naming convention, but I've seen that for private members.
There is an unnecessary hashtag; change the code to this:
var e = document.getElementById("ticket_category_clone").value;
In my case, I was downloading a library with sample code of keycloak implementation by mattorg from GITHUB: https://github.com/mattmorg55/Owin.Security.Keycloak/tree/dev/samples
The solution was quite easy, as I used .Net Framework 4.6.1, but the project begged me in the beginning to use 4.6.2. Although I downloaded it, it was first actively chosen, when restartet all instances of Visual Studion (or better close all instances). The project was manipulated to 4.6.1 (although I wished not and chose so).
So after I chose the configuration again to choose .Net Framework 4.6.1 the error vanished immediately.
This is the easiest solution possible. The following code can be used directly for creating a custom section header.
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
SectionHeaderTableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:@"sectionHeader"];
//For creating a drop menu of rows from the section
//==THIS IS JUST AN EXAMPLE. YOU CAN REMOVE THIS IF-ELSE.==
if (![self.sectionCollapsedArray[section] boolValue])
{
headerView.imageView.image = [UIImage imageNamed:@"up_icon"];
}
else
{
headerView.imageView.image = [UIImage imageNamed:@"drop_icon"];
}
//For button action inside the custom cell
headerView.dropButton.tag = section;
[headerView.dropButton addTarget:self action:@selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside];
//For removing long touch gestures.
for (UIGestureRecognizer *recognizer in headerView.contentView.gestureRecognizers)
{
[headerView.contentView removeGestureRecognizer:recognizer];
[headerView removeGestureRecognizer:recognizer];
}
return headerView.contentView;
}
NOTE: SectionHeaderTableViewCell is a custom UITableViewCell created in Storyboard.
SELECT DISTINCT a.StoreID
FROM tableName a
LEFT JOIN tableName b
ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE b.StoreID IS NULL
OUTPUT
+---------+
¦ STOREID ¦
¦---------¦
¦ 3 ¦
+---------+
I have a library that is doing exactly you need.
Some time ago I had wrote simple and fast enough library for work with CSV files. You can find it by the following link: https://github.com/ukushu/DataExporter
It works with CSV like with 2 dimensions array. Exactly like you need.
As example, in case of you need all of values of 3rd row only you need is to write:
Csv csv = new Csv();
csv.FileOpen("c:\\file1.csv");
var allValuesOf3rdRow = csv.Rows[2];
or to read 2nd cell of
var value = csv.Rows[2][1];
Help -> About Eclipse Platform
For Eclipse Mars - you can check Eclipse -> About Eclipse
or Help -> Installation Details
, then you should see the version:
Using the FM
format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.
. You can use rtrim
to get rid of that:
select to_char(a, '99D90'),
to_char(a, '90D90'),
to_char(a, 'FM90D99'),
rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
select 50 a from dual
union all select 50.57 from dual
union all select 5.57 from dual
union all select 0.35 from dual
union all select 0.4 from dual
)
order by a;
TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
.35 0.35 0.35 0.35
.40 0.40 0.4 0.4
5.57 5.57 5.57 5.57
50.00 50.00 50. 50
50.57 50.57 50.57 50.57
Note that I'm using to_char(0, 'D')
to generate the character to trim, to match the decimal separator - so it looks for the same character, ,
or .
, as the first to_char
adds.
The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad
, which starts to make it look a bit complicated:
...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...
TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
.35 0.35 0.35 0.35 0.35
.40 0.40 0.4 0.4 0.4
5.57 5.57 5.57 5.57 5.57
50.00 50.00 50. 50 50
50.57 50.57 50.57 50.57 50.57
As per PHP Documentation,
Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.
So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.
Following Libraries are not thread safe. They are not recommended for use in a multi-threaded environment.
select to_char(sysdate, 'DD-fmMONTH-YYYY') "Date" from Dual;
The above query result will be as given below.
01-APRIL-2019
I faced this issue as well. And finally got resolved by getting guidance from this MSDN Blog.
Update
Actually you need to add the certificate in git's certificates file curl-ca-bundel.cert that resides in Git\bin directory.
Steps
Finally check the status. Please note that backup curl-ca-bundle.crt file before editing to remain on safe side.
select * from [Table_Name] limit 5
One consideration is that FTP can use non-standard ports, which can make getting though firewalls difficult (especially if you're using SSL). HTTP is typically on a known port, so this is rarely a problem.
If you do decide to use FTP, make sure you read about Active and Passive FTP.
In terms of performance, at the end of the day they're both spewing files directly down TCP connections so should be about the same.
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (url.equals("your url")) {
Intent intent = new Intent(view.getContext(), TransferAllDoneActivity.class);
startActivity(intent);
}
}
As many mentioned the recursive approach, this is the function you can pass the searched name and the property to begin with to:
public static void loopAttributes(PropertyInfo prop, string targetAttribute, object tempObject)
{
foreach (PropertyInfo nestedProp in prop.PropertyType.GetProperties())
{
if(nestedProp.Name == targetAttribute)
{
//found the matching attribute
}
loopAttributes(nestedProp, targetAttribute, prop.GetValue(tempObject);
}
}
//in the main function
foreach (PropertyInfo prop in rootObject.GetType().GetProperties())
{
loopAttributes(prop, targetAttribute, rootObject);
}
To install SOAP in PHP-7 run following in your Ubuntu terminal:
sudo apt-get install php7.0-soap
To install SOAP in PHP-7.1 run following in your Ubuntu terminal:
sudo apt-get install php7.1-soap
To install SOAP in PHP-7.2 run following in your Ubuntu terminal:
sudo apt-get install php7.2-soap
To install SOAP in PHP-7.3 run following in your Ubuntu terminal:
sudo apt-get install php7.3-soap
place something like this in your script file json-content.js
var mainjson = { your json data}
then call it from script tag
<script src="json-content.js"></script>
then you can use it in next script
<script>
console.log(mainjson)
</script>
for Angular 6+ and >=RC.6
.html
<form [formGroup]="formGroup">
<input type="text" formControlName="myName">
</form>
.ts
public formGroup: FormGroup;
this.formGroup.value.myName
should also work.
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
I'm posting an answer from another thread because it's what worked well for me, the trick is to add support for both architectures :
Posting this because I could not find a direct answer and had to look at a couple of different posts to get what I wanted done...
I was able to use the x86 Accelerated (HAXM) emulator by simply adding this to my Module's build.gradle script Inside android{} block:
splits {
abi {
enable true
reset()
include 'x86', 'armeabi-v7a'
universalApk true
}
}
Run (build)... Now there will be a (yourapp)-x86-debug.apk in your output folder. I'm sure there's a way to automate installing upon Run but I just start my preferred HAXM emulator and use command line:
adb install (yourapp)-x86-debug.apk
If you plot in IPython console (where you can't use %matplotlib inline
) instead of Jupyter notebook, and don't want to run plt.show()
repeatedly, you can start IPython console with ipython --pylab
:
$ ipython --pylab
Python 3.6.6 |Anaconda custom (64-bit)| (default, Jun 28 2018, 17:14:51)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.0.1 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg
In [1]: import seaborn as sns
In [2]: tips = sns.load_dataset("tips")
In [3]: sns.relplot(x="total_bill", y="tip", data=tips) # you can see the plot now
rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber
Run a select to make sure it is what you want
SELECT t1.value AS NEWVALUEFROMTABLE1,t2.value AS OLDVALUETABLE2,*
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID
Update
UPDATE Table2
SET Value = t1.Value
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID
Also, consider using BEGIN TRAN
so you can roll it back if needed, but make sure you COMMIT
it when you are satisfied.
You should be able to run:
svn add *
It may complain about the files that are already under version control, but it will also add the new ones.
You may want to think about whether or not you really want to add these generated files to version control, though. They could be considered derived artifacts, sort of like the compiled code, and thus shouldn't be added. Of course, this is up to you, but its something to think about.
Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);
A completely alternative solution is to not use the MVC HandleErrorAttribute
, and instead rely on ASP.Net error handling, which Elmah is designed to work with.
You need to remove the default global HandleErrorAttribute
from App_Start\FilterConfig (or Global.asax), and then set up an error page in your Web.config:
<customErrors mode="RemoteOnly" defaultRedirect="~/error/" />
Note, this can be an MVC routed URL, so the above would redirect to the ErrorController.Index
action when an error occurs.
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
you could try:
<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>
<div>
<div ng-view=""></div>
</div>
You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.
The github repo will be created as a new project in android studio.
With neuraxle, you can easily solve this :
p = Pipeline([
# expected outputs shape: (n, 1)
OutputTransformerWrapper(NumpyRavel()),
# expected outputs shape: (n, )
RandomForestRegressor(**RF_tuned_parameters)
])
p, outputs = p.fit_transform(data_inputs, expected_outputs)
Neuraxle is a sklearn-like framework for hyperparameter tuning and AutoML in deep learning projects !
Simple version:
for /F "delims==, tokens=4" %a IN ('ping -n 2 127.0.0.1 ^| findstr /R "^Packets: Sent =.$"') DO (
if %a EQU 2 (
echo Success
) ELSE (
echo FAIL
)
)
But sometimes first ping just fail and second one work (or vice versa) right? So we want to get success when at least one ICMP reply has been returned successfully:
for /F "delims==, tokens=4" %a IN ('ping -n 2 192.168.1.1 ^| findstr /R "^Packets: Sent =.$"') DO (
if %a EQU 2 (
echo Success
) ELSE (
if %a EQU 1 (
echo Success
) ELSE (
echo FAIL
)
)
)
Have a look at qtlcharts. It allows you to create interactive correlation matrices:
library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)
It's more impressive when you correlate more variables, like in the package's vignette:
Similar to that discussed below for IntelliJ 13 & 14, but with an extra level in the Settings/Preferences panel: Settings > Build, Execution, Deployment > Compiler > Java Compiler.
In IntelliJ 13 and 14, check the Settings > Compiler > Java Compiler UI to ensure you're not targeting a different bytecode version in your module.
I've had this sort of problem.....
The solve: cmd
/ powershell
run as ADMINISTRATOR! I always forget.
Notice: In powershell
, you need to put .\
for example:
.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall
Result: Removing the apache2.4
service The Apache2.4
service has been removed successfully.
I am not aware of any pure shell XML parsing tool. So you will most likely need a tool written in an other language.
My XML::Twig Perl module comes with such a tool: xml_grep
, where you would probably write what you want as xml_grep -t '/html/head/title' xhtmlfile.xhtml > titleOfXHTMLPage.txt
(the -t
option gives you the result as text instead of xml)
public static void main(String[] args) {
Season.add("Frühling");
Season.add("Sommer");
Season.add("Herbst");
Season.add("WINTER");
for (String s : Season) {
if(!s.equals("Sommer")) {
System.out.println(s);
continue;
}
Season.remove("Frühling");
}
}
Ternary Operator example:
int a = (i == 0) ? 10 : 5;
You can't do assignment with if/else like this:
// invalid:
int a = if (i == 0) 10; else 5;
This is a good reason to use the ternary operator. If you don't have an assignment:
(i == 0) ? foo () : bar ();
an if/else isn't that much more code:
if (i == 0) foo (); else bar ();
In performance critical cases: measure it. Measure it with the target machine, the target JVM, with typical data, if there is a bottleneck. Else go for readability.
Embedded in context, the short form is sometimes very handy:
System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ());
CSS
If this doesn't work:
.modal-backdrop {
background-color: red;
}
try this:
.modal {
background-color: red !important;
}
HorizontialListView can't work when the data in the adapter is involved in another thread. Everything runs 100% on UI thread.This is a big problem in multithread. I think using HorizontialListView is not the best solution for your problem.HorzListView is a better way.You just replace your previous Gallery with HorzListView.You neednot modify the code about the adapter.Then everything goes the way you hope.See https://stackoverflow.com/a/12339708/1525777 about HorzListView.
Try to use the WEEKDAY()
function.
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
While you can use a virtualenv
, you don't need to. The trick is passing the PEP370 --user
argument to the setup.py
script. With the latest version of pip
, one way to do it is:
pip install --user mercurial
This should result in the hg
script being installed in $HOME/.local/bin/hg
and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/
.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user
installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local
to $HOME/Library/Python
. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg
were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg
and $HOME/Library/Python/x.y/lib/python/site-packages
.
Look at these to build a solution more or less from scratch:
You always have the option of calling external tools from Java using the exec()
and similar methods. For instance, you could use wget
, or cURL
.
Then if you want to go into more fully-fledged stuff, thankfully the need for automated web-testing as given us very practical tools for this. Look at:
Some other libs are purposefully written with web-scraping in mind:
Java is a language, but also a platform, with many other languages running on it. Some of which integrate great syntactic sugar or libraries to easily build scrapers.
Check out:
If you know of a great library for Ruby (JRuby, with an article on scraping with JRuby and HtmlUnit) or Python (Jython) or you prefer these languages, then give their JVM ports a chance.
Some other similar questions:
Another way that works for me is,
<command> |& tee <outputFile>
as shown in gnu bash manual
Example:
ls |& tee files.txt
If ‘|&’ is used, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.
For more information, refer redirection
A complex filter condition is better in performance perspective, but the best performance will show old fashion for loop with a standard if clause
is the best option. The difference on a small array 10 elements difference might ~ 2 times, for a large array the difference is not that big.
You can take a look on my GitHub project, where I did performance tests for multiple array iteration options
For small array 10 element throughput ops/s: For medium 10,000 elements throughput ops/s: For large array 1,000,000 elements throughput ops/s:
NOTE: tests runs on
UPDATE: Java 11 has some progress on the performance, but the dynamics stay the same
file_exists checks whether a file exist in the specified path or not.
Syntax:
file_exists ( string $filename )
Returns TRUE
if the file or directory specified by filename exists; FALSE
otherwise.
$filename = BASE_DIR."images/a/test.jpg";
if (file_exists($filename)){
echo "File exist.";
}else{
echo "File does not exist.";
}
Another alternative method you can use getimagesize(), it will return 0(zero) if file/directory is not available in the specified path.
if (@getimagesize($filename)) {...}
What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.
If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.
EDIT
I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.
It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc()
call, etc.) so those warnings would not be very useful due to the false positive frequency.
The
setInterval()
method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
var intervalId = setInterval(function() {
alert("Interval reached every 5s")
}, 5000);
// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);
See more @ setInterval() @ MDN Web Docs
If you're using RHEL, CentOS, Oracle Linux, etc. You can use yum to install tkinter module
yum install tkinter
What type of LayoutManager are you using for the panel you're adding the JTextField to?
Different layout managers approach sizing elements on them in different ways, some respect SetPreferredSize(), while others will scale the compoenents to fit their container.
See: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
ps. this has nothing to do with eclipse, its java.
I recommend to use bellow formula suggested on Apache:
MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)
Find my script here which is running on Rhel 6.7. you can made change according to your OS.
#!/bin/bash
echo "HostName=`hostname`"
#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit
Using Sieve of Eratosthenes logic, I am able to achieve the same results with much faster speed.
My code demo VS accepted answer.
Comparing the count
,
my code takes significantly lesser iteration to finish the job. Checkout the results for different N
values in the end.
Why this code performs better than already accepted ones:
- the even numbers are not checked even once throughout the process.
- both inner and outer loops are checking only within possible limits. No extraneous checks.
Code:
int N = 1000; //Print primes number from 1 to N
vector<bool> primes(N, true);
for(int i = 3; i*i < N; i += 2){ //Jump of 2
for(int j = 3; j*i < N; j+=2){ //Again, jump of 2
primes[j*i] = false;
}
}
if(N >= 2) cout << "2 ";
for(int i = 3; i < N; i+=2){ //Again, jump of 2
if(primes[i] == true) cout << i << " ";
}
For N = 1000
, my code takes 1166 iterations, accepted answer takes 5287 (4.5 times slower)
For N = 10000
, my code takes 14637 iterations, accepted answer takes 117526 (8 times slower)
For N = 100000
, my code takes 175491 iterations, accepted answer takes 2745693 (15.6 times slower)
handle.exe http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx
THis has helped me sooooo many times....
Here's your problem:
if(imgArray[i] == img)
You're comparing an array element to a DOM object.
Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014
Just be sure to be using correct instance and connect each other
Just pay attention in Stored procs must be recompiled
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
To get the value of the selected item of a listbox then use the following.
For Single Column ListBox:
ListBox1.List(ListBox1.ListIndex)
For Multi Column ListBox:
ListBox1.Column(column_number, ListBox1.ListIndex)
This avoids looping and is extremely more efficient.
The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files
SET xyz=%~1
Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).
But, This simple tilde syntax will not work for other variables that were not passed in as parameters
For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.
@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%
If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows
@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%
For my WPF application i've defined global app id and use semaphore to handle it.
public partial class App : Application
{
private const string AppId = "c1d3cdb1-51ad-4c3a-bdb2-686f7dd10155";
//Passing name associates this sempahore system wide with this name
private readonly Semaphore instancesAllowed = new Semaphore(1, 1, AppId);
private bool WasRunning { set; get; }
private void OnExit(object sender, ExitEventArgs e)
{
//Decrement the count if app was running
if (this.WasRunning)
{
this.instancesAllowed.Release();
}
}
private void OnStartup(object sender, StartupEventArgs e)
{
//See if application is already running on the system
if (this.instancesAllowed.WaitOne(1000))
{
new MainWindow().Show();
this.WasRunning = true;
return;
}
//Display
MessageBox.Show("An instance is already running");
//Exit out otherwise
this.Shutdown();
}
}
$date = date('Y-m-d H:i:s'); with the type: 'datetime' worked very good for me as i wanted to print whole date and timestamp..
$date = date('Y-m-d H:i:s'); $stmtc->bindParam(2,$date);
int(limit)
returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit
:
if 'limit' in user_data :
limit = int(user_data['limit'])
With either string concatenation or string interpolation (via template literals).
Here with JavaScript template literal:
function geoPreview() {
var lat = document.getElementById("lat").value;
var long = document.getElementById("long").value;
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${lat}&lon=${long}&setLatLon=Set`;
}
Both parameters are unused and can be removed.
Join strings with the +
operator:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=" + elemA + "&lon=" + elemB + "&setLatLon=Set";
For more concise code, use JavaScript template literals to replace expressions with their string representations.
Template literals are enclosed by ``
and placeholders surrounded with ${}
:
window.location.href = `http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat=${elemA}&lon=${elemB}&setLatLon=Set`;
Template literals are available since ECMAScript 2015 (ES6).
Make sure the function is in the same DB schema as the table.
One more Swift 3.0 solution to remove duplicates from an array. This solution improves on many other solutions already proposed by:
Given the integer array:
let numberArray = [10, 1, 2, 3, 2, 1, 15, 4, 5, 6, 7, 3, 2, 12, 2, 5, 5, 6, 10, 7, 8, 3, 3, 45, 5, 15, 6, 7, 8, 7]
Functional code:
func orderedSet<T: Hashable>(array: Array<T>) -> Array<T> {
var unique = Set<T>()
return array.filter { element in
return unique.insert(element).inserted
}
}
orderedSet(array: numberArray) // [10, 1, 2, 3, 15, 4, 5, 6, 7, 12, 8, 45]
Array extension code:
extension Array where Element:Hashable {
var orderedSet: Array {
var unique = Set<Element>()
return filter { element in
return unique.insert(element).inserted
}
}
}
numberArray.orderedSet // [10, 1, 2, 3, 15, 4, 5, 6, 7, 12, 8, 45]
This code takes advantage of the result returned by the insert
operation on Set
, which executes on O(1)
, and returns a tuple indicating if the item was inserted or if it already existed in the set.
If the item was in the set, filter
will exclude it from the final result.
If you don't mind the set to be sorted then you may be interested to take a look at the indexed-tree-map project.
The enhanced TreeSet/TreeMap provides access to elements by index or getting the index of an element. And the implementation is based on updating node weights in the RB tree. So no iteration or backing up by a list here.
i personally have
alias ..='source ~/.bashrc'
in my bashrc, so that i can just use ".." to reload it.
After displaying the first 1000 records, you can page through them by clicking on the icon beside "Fetch rows:" in the header of the result grid.
You can use dirname
:
os.path.dirname(path)
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
And given the full path, then you can split normally to get the last portion of the path. For example, by using basename
:
os.path.basename(path)
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').
All together:
>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'
In my case I fixed this issue like below:-
First I removed (apache) C:\Users\myuserId\.m2\repository\org\apache
I added below dependencies in my pom.xml
file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
I have changed the default socket by adding below lines in resource file ..\yourprojectfolder\src\main\resourcesand\application.properties
(I manually created this file)
server.port=8099
[email protected]@
for that I have added below block in my pom.xml
under <build>
section.
<build>
.
.
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
.
.
</build>
My final pom.xml
file look like
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bhaiti</groupId>
<artifactId>spring-boot-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-rest</name>
<description>Welcome project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
How about not using strings at all...
This should work for any number of digits...
int[] nums = {1, 0, 2, 2, 1};
int retval = 0;
for (int digit : nums)
{
retval *= 10;
retval += digit;
}
System.out.println("Return value is: " + retval);
To prevent the flex items from shrinking, set the flex shrink factor to 0
:
The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.
.boxcontainer .box {
flex-shrink: 0;
}
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
width: 200px;_x000D_
background-color: #EEEEEE;_x000D_
border: 2px solid #DDDDDD;_x000D_
padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
position: relative;_x000D_
left: 0;_x000D_
border: 2px solid #BDC3C7;_x000D_
transition: all 0.4s ease;_x000D_
display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
width: 100%;_x000D_
padding: 1rem;_x000D_
flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
<div class="boxcontainer">_x000D_
<div class="box">_x000D_
First bunch of content._x000D_
</div>_x000D_
<div class="box">_x000D_
Second load of content._x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="9"
android:orientation="horizontal" >
<ImageView
android:id="@+id/ring_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/ring_oss" />
<ImageView
android:id="@+id/maila_oss"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
<EditText
android:id="@+id/edittxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/maila_oss" />
</LinearLayout>
This works:
myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");
The following JavaScript will open a new browser window, 450px wide by 300px high with scrollbars:
window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");
You can add this to a link like so:
<a href='#' onclick='javascript:window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");' title='Pop Up'>Pop Up</a>
Python 3 built-in exceptions have the strerror
field:
except ValueError as err:
err.strerror = "New error message"
raise err
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
Use List<Integer> list = new ArrayList<Integer>();
geopoint = {'latitude':41.123,'longitude':71.091}
# working examples.
print(f'{geopoint["latitude"]} {geopoint["longitude"]}') # from above answer
print('{geopoint[latitude]} {geopoint[longitude]}'.format(geopoint=geopoint)) # alternate for format method (including dict name in string).
print('%(latitude)s %(longitude)s'%geopoint) # thanks @tcll
Here is a JS Function to this:
This function is needed because Chrome doesn't accept a base64 encoded string as value for applicationServerKey in pushManager.subscribe yet https://bugs.chromium.org/p/chromium/issues/detail?id=802280
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
var myobj = {"A":["Abe"], "B":["Bob"]};
var keysArray = Object.keys(myobj);
var valuesArray = Object.keys(myobj).map(function(k) {
return String(myobj[k]);
});
var mydata = valuesArray[keysArray.indexOf("A")]; // Abe
I used the logic suggested by Andrew which is very effective. And this is my version:
$('body').on('keydown', 'input, select', function(e) {
if (e.key === "Enter") {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
KeyboardEvent's keycode (i.e: e.keycode
) depreciation notice :- https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
If you also want to name the constraint, use this:
ALTER TABLE myTable
ADD CONSTRAINT constraintName
UNIQUE (columnName);
You can use
string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
Old question, but here's a fairly clean way to create a nullable parameter:
new SqlParameter("@note", (object) request.Body ?? DBNull.Value);
If request.Body has a value, then it's value is used. If it's null, then DbNull.Value is used.
<audio controls autoplay loop>
<source src="path/your_song.mp3" type="audio/ogg">
<embed src="path/your_song.mp3" autostart="true" loop="true" hidden="true">
</audio>
[ps. replace the "path/your_song.mp3" with the folder and the song title eg. "music/samplemusic.mp3" or "media/bgmusic.mp3" etc.
Sadly, mod_evasive
won't work as expected when used in non-prefork configurations (recent apache setups are mainly MPM)
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...
I managed to do it with CSS display: table-*
. I haven't tested with more than 3 blocks though.
The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.
This explains the "strange results".
"Better" results can be obtained using the expressions below:
//*[text() = 'qwerty']
The above selects every element in the document that has at least one text-node child with value 'qwerty'.
//*[text() = 'qwerty' and not(text()[2])]
The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
Double d = scan.nextDouble();
String newStr = "";
Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
while( charScanner.hasNext() ) {
String c = charScanner.next();
if (c.equalsIgnoreCase("\r")) {
break;
}
else {
newStr += c;
}
}
System.out.println("String: " + newStr);
System.out.println("Int: " + i);
System.out.println("Double: " + d);
This code works fine
Abstraction is a means of hiding details in order to simplify an interface.
So, using a car as an example, all of the controls in a car are abstractions. This allows you to operate a vehicle without understanding the underlying details of the steering, acceleration, or deceleration systems.
A good abstraction is one that standardizes an interface broadly, across multiple instances of a similar problem. A great abstraction can change an industry.
The modern steering wheel, brake pedal, and gas pedal are all examples of great abstractions. Car steering initially looked more like bicycle steering. And both brakes and throttles were operated by hand. But the abstractions we use today were so powerful, they swept the industry.
--
Encapsulation is a means of hiding details in order to protect them from outside manipulation.
Encapsulation is what prevents the driver from manipulating the way the car drives — from the stiffness of the steering, suspension, and braking, to the characteristics of the throttle, and transmission. Most cars do not provide interfaces for changing any of these things. This encapsulation ensures that the vehicle will operate as the manufacturer intended.
Some cars offer a small number of driving modes — like luxury, sport, and economy — which allow the driver to change several of these attributes together at once. By providing driving modes, the manufacturer is allowing the driver some control over the experience while preventing them from selecting a combination of attributes that would render the vehicle less enjoyable or unsafe. In this way, the manufacturer is hiding the details to prevent unsafe manipulations. This is encapsulation.
You can't according to the PHP manual:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
But you can work around it by also setting $_COOKIE
when you call setcookie()
:
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
Based on @markhellewell answer I created a couple of alias functions that will do it for you. Just add these to your shell startup file
#list available jdks
alias jdks="/usr/libexec/java_home -V"
# jdk version switching - e.g. `jdk 6` will switch to version 1.6
function jdk() {
echo "Switching java version";
export JAVA_HOME=`/usr/libexec/java_home -v 1.$1`;
java -version;
}
https://gist.github.com/Noyabronok/0a90e1f3c52d1aaa941013d3caa8d0e4
(Updated 2018-03-17)
The problem, as you've spotted, is that String.Contains
does not perform a word-boundary check, so Contains("float")
will return true
for both "foo float bar" (correct) and "unfloating" (which is incorrect).
The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b
. So the regex you want is simply: \bfloat\b
.
A downside to using a Regex
instance is that they can be slow to run if you don't use the .Compiled
option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.
Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split
).
Suppose you just want to look for elements with a single, design-time specified class-name:
class Program {
private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );
private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
}
}
If you need to choose a single class-name at runtime then you can build a regex:
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {
Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}
If you have multiple class-names and you want to match all of them, you could create an array of Regex
objects and ensure they're all matching, or combine them into a single Regex
using lookarounds, but this results in horrendously complicated expressions - so using a Regex[]
is probably better:
using System.Linq;
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {
Regex[] exprs = new Regex[ classNames.Length ];
for( Int32 i = 0; i < exprs.Length; i++ ) {
exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
}
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e =>
e.Name == "div" &&
exprs.All( r =>
r.IsMatch( e.GetAttributeValue("class", "") )
)
);
}
The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex
may be faster in some circumstances - always profile your code first, kids!)
This method below: CheapClassListContains
provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch
:
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e =>
e.Name == "div" &&
CheapClassListContains(
e.GetAttributeValue("class", ""),
className,
StringComparison.Ordinal
)
);
}
/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
if( String.Equals( haystack, needle, comparison ) ) return true;
Int32 idx = 0;
while( idx + needle.Length <= haystack.Length )
{
idx = haystack.IndexOf( needle, idx, comparison );
if( idx == -1 ) return false;
Int32 end = idx + needle.Length;
// Needle must be enclosed in whitespace or be at the start/end of string
Boolean validStart = idx == 0 || Char.IsWhiteSpace( haystack[idx - 1] );
Boolean validEnd = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
if( validStart && validEnd ) return true;
idx++;
}
return false;
}
HtmlAgilityPack is somewhat stagnated doesn't support .querySelector
and .querySelectorAll
, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll
, so you can use it like so:
private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {
return doc.QuerySelectorAll( "div.float" );
}
With runtime-defined classes:
private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {
String selector = "div." + String.Join( ".", classNames );
return doc.QuerySelectorAll( selector );
}
template<typename T>
string str(T begin, T end)
{
stringstream ss;
bool first = true;
for (; begin != end; begin++)
{
if (!first)
ss << ", ";
ss << *begin;
first = false;
}
return ss.str();
}
This is the str function that can make integers turn into a string and not into a char for what the integer represents. Also works for doubles.
Consider using Android's uiautomator, with adb shell uiautomator [...] or directly using the .jar that comes with the SDK.
git format-patch --full-index --binary --stdout range... | git am -3
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
We can easily do that in css3. We have to simply use @import statement. The following video easily describes the way how to do that. so go ahead and watch it out.
It's new feature in iOS11 and Swift 4.
Trailing Swipe :
@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
print("index path of delete: \(indexPath)")
completionHandler(true)
}
let rename = UIContextualAction(style: .normal, title: "Edit") { (action, sourceView, completionHandler) in
print("index path of edit: \(indexPath)")
completionHandler(true)
}
let swipeActionConfig = UISwipeActionsConfiguration(actions: [rename, delete])
swipeActionConfig.performsFirstActionWithFullSwipe = false
return swipeActionConfig
}
Try using background-size
but using TWO ARGUMENTS One for the width and the other one for the height
background-image:url('../images/bg.png');
background-repeat:no-repeat;
background-size: 100% 100%; // Here the first argument will be the width
// and the second will be the height.
background-position:center;
In a constants.h
file you can add these define statements:
#define IS_IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
#define IS_IPHONE UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone
#define IS_WIDESCREEN (fabs((double)[[UIScreen mainScreen] bounds].size.height - (double)568) < DBL_EPSILON)
#define IS_IPHONE_5 (!IS_IPAD && IS_WIDESCREEN)
So I know that this post is pretty old, but I figured I may as well add a function that has helped me over the years. Why not just remake the explode function using split as mentioned above? Well here it is:
function explode(str,begin,end)
{
t=str.split(begin);
t=t[1].split(end);
return t[0];
}
This function works well if you are trying to get the values between two values. For instance:
data='[value]insertdataherethatyouwanttoget[/value]';
If you were interested in getting the information from between the two [values] "tags", you could use the function like the following.
out=explode(data,'[value]','[/value]');
//Variable out would display the string: insertdataherethatyouwanttoget
But let's say you don't have those handy "tags" like the example above displayed. No matter.
out=explode(data,'insert','wanttoget');
//Now out would display the string: dataherethatyou
Wana see it in action? Click here.
There are multiple schemas for "JUnit" and "xUnit" results.
model/xsd
)Please note that there are several versions of the schema in use by the Jenkins xunit-plugin (the current latest version is junit-10.xsd
which adds support for Erlang/OTP Junit format).
Some testing frameworks as well as "xUnit"-style reporting plugins also use their own secret sauce to generate "xUnit"-style reports, those may not use a particular schema (please read: they try to but the tools may not validate against any one schema). Python unittests in Jenkins? gives a quick comparison of several of these libraries and slight differences between the xml reports generated.
I had this same issue. I was doing
arr = []
arr.append["HI"]
So using [
was causing error. It should be arr.append("HI")
If this is what you are looking for -
To find all the multiples between a given number and a limit
def find_multiples(integer, limit):
return list(range(integer,limit+1, integer))
This should return -
Test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])
In bootstrap 4 the outline is no longer used, but the box-shadow. If it is your case, just do the following:
.btn:focus {
box-shadow: none;
}
You can just share the contact with your bot and, via /getUpdates, you get the "contact" object
see nditer
import numpy as np
Y = np.array([3,4,5,6])
for y in np.nditer(Y, op_flags=['readwrite']):
y += 3
Y == np.array([6, 7, 8, 9])
y = 3
would not work, usey *= 0
andy += 3
instead.
current_dir=$PWD;cd /path/to/your/command/dir;special command ARGS;cd $current_dir;
current_dir
equal to your pwd
cd
to where you need to run your commandcd
back to our variable current_dir
Another Solution by @apieceofbart
pushd && YOUR COMMAND && popd
Put the image — let's say it's width is 140px — inside of a link:
<a><img src='image link' style='width: 140px'></a>
Next, put the caption in a and give it a width less than your image, while centering it:
<a>
<img src='image link' style='width: 140px'>
<div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>
Next, in the link tag, style the link so that it no longer looks like a link. You can give it any color you want, but just remove any text decoration your links may carry.
<a style='text-decoration: none; color: orange;'>
<img src='image link' style='width: 140px'>
<div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>
I wrapped the image with it's caption in a link so that no text could push the caption out of the way: The caption is tied to the picture by the link. Here's an example: http://www.alphaeducational.com/p/okay.html
Recent versions of Cordova have the version number in www/cordova.js.
I was able to use this site to easily download and install curl on my Windows machine. It took all of 30 seconds. I'm using Windows 7 (w/ Admin privelages), so I downloaded curl-7.37.0-win64.msi from http://curl.haxx.se/download.html.
Also, don't forget to restart your console/terminal after you install curl, otherwise you will get the same error messages.
Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.
Example:
class Typetester {
void printType(byte x) {
System.out.println(x + " is an byte");
}
void printType(int x) {
System.out.println(x + " is an int");
}
void printType(float x) {
System.out.println(x + " is an float");
}
void printType(double x) {
System.out.println(x + " is an double");
}
void printType(char x) {
System.out.println(x + " is an char");
}
}
then:
Typetester t = new Typetester();
t.printType( yourVariable );