JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects.
JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads.
Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place. Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser.
Core dump is a os level memory usage of objects. It has more informaiton than a head dump. core dump is not created when we kill a process purposely.
Then, in your javascript:
var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);
Now you can look at the console, click on the statement and see what is inside blah
In Jboss you can perform the following
nohup $JBOSS_HOME/bin/run.sh -c yourinstancename $JBOSS_OPTS >> console-$(date +%Y%m%d).out 2>&1 < /dev/null &
kill -3 <java_pid>
This will redirect your output/threadump to the file console specified in the above command.
OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go
$ homebrew install mdbtools
Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.
$ ./to_mysql.sh myfile.mdb > myfile.sql
(which btw contains more than 1 table)
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
There is a command line option for logging. The output is saved to screenlog.n file, where n is a number of the screen. From man pages of screen:
‘-L’ Tell screen to turn on automatic output logging for the windows.
Here's a short and simple python program to print out the table names and the column names for those tables (python 2. python 3 follows).
import sqlite3
db_filename = 'database.sqlite'
newline_indent = '\n '
db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()
result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(zip(*result)[0])
print "\ntables are:"+newline_indent+newline_indent.join(table_names)
for table_name in table_names:
result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
column_names = zip(*result)[1]
print ("\ncolumn names for %s:" % table_name)+newline_indent+(newline_indent.join(column_names))
db.close()
print "\nexiting."
(EDIT: I have been getting periodic vote-ups on this, so here is the python3 version for people who are finding this answer)
import sqlite3
db_filename = 'database.sqlite'
newline_indent = '\n '
db=sqlite3.connect(db_filename)
db.text_factory = str
cur = db.cursor()
result = cur.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall()
table_names = sorted(list(zip(*result))[0])
print ("\ntables are:"+newline_indent+newline_indent.join(table_names))
for table_name in table_names:
result = cur.execute("PRAGMA table_info('%s')" % table_name).fetchall()
column_names = list(zip(*result))[1]
print (("\ncolumn names for %s:" % table_name)
+newline_indent
+(newline_indent.join(column_names)))
db.close()
print ("\nexiting.")
You can now use BaseEncoding in guava
to accomplish this.
BaseEncoding.base16().decode(string);
To reverse it use
BaseEncoding.base16().encode(bytes);
Combining the advice from MartinP and user664833, I was also able to get it to work. Caveat is that entering psql from the pgAdmin GUI tool via choosing Plugins...PSQL Console sets the credentials and permission level for the psql session, so you must have Admin or CRUD permissions on the table and maybe also Admin on the DB (do not know for sure on that). The command then in the psql console would take this form:
postgres=# \i driveletter:/folder_path/backupfilename.backup
where postgres=# is the psql prompt, not part of the command.
The .backup file will include the commands used to create the table, so you may also get things like "ALTER TABLE ..." commands in the file that get executed but reported as errors. I suppose you can always delete these commands before running the restore but you're probably better safe than sorry to keep them in there, as these will not likely cause the restore of data to fail. But always check to be sure the data you wanted to resore actually got there. (Sorry if this seems like patronizing advice to anyone, but it's an oversight that can happen to anyone no matter how long they have been at this stuff -- a moment's distraction from a colleague, a phone call, etc., and it's easy to forget this step. I have done it myself using other databases earlier in my career and wondered "Gee, why am I not seeing any data back from this query?" Answer was the data never actually got restored, and I just wasted 2 hours trying to hunt down suspected possible bugs that didn't exist.)
From the Mongo documentation:
The mongoexport utility takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output
Read more here: http://www.mongodb.org/display/DOCS/mongoexport
If you need exact '/' delimiters, for example: 09/20/2013 rather than 09.20.2013, use escape sequence '/':
Dim regDate As Date = Date.Now()
Dim strDate As String = regDate.ToString("MM\/dd\/yyyy")
It's not so difficult.
You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.
Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.
This is pretty simple stuff.
No, Java doesn't have that ability.
It does have System.nanoTime(), but that just gives an offset from some previously known time. So whilst you can't take the absolute number from this, you can use it to measure nanosecond (or higher) precision.
Note that the JavaDoc says that whilst this provides nanosecond precision, that doesn't mean nanosecond accuracy. So take some suitably large modulus of the return value.
In Bootstrap 3 I've added a table-no-border class
.table-no-border>thead>tr>th,
.table-no-border>tbody>tr>th,
.table-no-border>tfoot>tr>th,
.table-no-border>thead>tr>td,
.table-no-border>tbody>tr>td,
.table-no-border>tfoot>tr>td {
border-top: none;
}
I think if you have something that structured and complex, you might consider something other than a single drop-down box.
(function(f){
if(document.readyState != "loading") f();
else document.addEventListener("DOMContentLoaded", f);
})(function(){
console.log("The Document is ready");
});
You can use Controls attribute
<video id="sampleMovie" src="HTML5Sample.mov" controls></video>
I've just learned of a handy packaging tool called fpm recently. Stumbling upon this question I thought I might give it a try. Turns out, after reading @OrwellHindenberg's answer, it's easy to package maven into an RPM with fpm.
yum install -y gcc make rpm-build ruby-devel rubygems
gem install fpm
create a project directory and layout the directory structure of the package
mkdir maven-build
cd maven-build
mkdir -p etc/profile.d opt
create a file that we'll install to /etc/profile.d/maven.sh
, we'll store this under the newly created etc/profile.d directory as maven.sh, with the following contents
export M3_HOME=/opt/apache-maven-3.1.0
export M3=$M3_HOME/bin
export PATH=$M3:$PATH
download and unpack the latest maven in the opt directory
wget http://www.eng.lsu.edu/mirrors/apache/maven/maven-3/3.1.0/binaries/apache-maven-3.1.0-bin.tar.gz
tar -xzf apache-maven-3.1.0-bin.tar.gz -C opt
finally, build the RPM
fpm -n maven-3.1.0 -s dir -t rpm etc opt
Now you can install maven through rpm
$ rpm -Uvh maven-3.1.0-1.0-1.x86_64.rpm
Preparing... ########################################### [100%]
1:maven-3.1.0 ########################################### [100%]
and viola
$ which mvn
/opt/apache-maven-3.1.0/bin/mvn
not quite yum but closer to home ;)
SQLite doesn't support removing or modifying columns, apparently. But do remember that column data types aren't rigid in SQLite, either.
See also:
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Because comparaison method have to be done based on type int (x==y) or class Integer (x.equals(y)) with right operator
public class Example {
public static void main(String[] args) {
int[] arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};
for(int j=1; j<arr.length-1; j++)
if((arr[j-1]!=arr[j]) && (arr[j]!=arr[j+1]))
System.out.println("int>"+arr[j]);
Integer[] I_arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};
for(int j=1; j<I_arr.length-1; j++)
if((!I_arr[j-1].equals(I_arr[j])) && (!I_arr[j].equals(I_arr[j+1])))
System.out.println("Interger>"+I_arr[j]);
}
}
Try this:
class Flonetwork(Object):
def __init__(self,adj = {},flow={}):
self.adj = adj
self.flow = flow
The return value (aka exit code) is a value in the range 0 to 255 inclusive. It's used to indicate success or failure, not to return information. Any value outside this range will be wrapped.
To return information, like your number, use
echo "$value"
To print additional information that you don't want captured, use
echo "my irrelevant info" >&2
Finally, to capture it, use what you did:
result=$(password_formula)
In other words:
echo "enter: "
read input
password_formula()
{
length=${#input}
last_two=${input:length-2:length}
first=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $2}'`
second=`echo $last_two| sed -e 's/\(.\)/\1 /g'|awk '{print $1}'`
let sum=$first+$second
sum_len=${#sum}
echo $second >&2
echo $sum >&2
if [ $sum -gt 9 ]
then
sum=${sum:1}
fi
value=$second$sum$first
echo $value
}
result=$(password_formula)
echo "The value is $result"
TypeScript isn't giving you a gun to shoot yourself in the foot with.
The iterator variable is a string because it is a string, full stop. Observe:
var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';
for(var key in obj) {
console.log('Type: ' + typeof key);
console.log(key + ' => ' + obj[key]);
}
How many key/value pairs are in obj
now? 6, more or less? No, 3, and all of the keys are strings:
Type: string
0 => zero point zero
Type: string
[object Object] => this obj;
Type: string
undefined => the literal string "undefined"
public ActionResult Index()
{
List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();
var orderlist = (from a in db.OrderMasters
join b in db.Customers on a.CustomerId equals b.Id
join c in db.CustomerAddresses on b.Id equals c.CustomerId
where a.Status == "Pending"
select new
{
Customername = b.Customername,
Phone = b.Phone,
OrderId = a.OrderId,
OrderDate = a.OrderDate,
NoOfItems = a.NoOfItems,
Order_amt = a.Order_amt,
dis_amt = a.Dis_amt,
net_amt = a.Net_amt,
status=a.Status,
address = c.address,
City = c.City,
State = c.State,
Pin = c.Pin
}) ;
foreach (var item in orderlist)
{
CustomerOrder_Result clr = new CustomerOrder_Result();
clr.Customername=item.Customername;
clr.Phone = item.Phone;
clr.OrderId = item.OrderId;
clr.OrderDate = item.OrderDate;
clr.NoOfItems = item.NoOfItems;
clr.Order_amt = item.Order_amt;
clr.net_amt = item.net_amt;
clr.address = item.address;
clr.City = item.City;
clr.State = item.State;
clr.Pin = item.Pin;
clr.status = item.status;
obj.Add(clr);
}
virtualenv
permission problems might occur when you create the virtualenv
as sudo
and then operate without sudo
in the virtualenv
.
As found out in your question's comment, the solution here is to create the virtualenv
without sudo
to be able to work (esp. write) in it without sudo
.
just switch your current logged-in user to the root and login without password mysql -uroot
You have to check to ensure editTransactionRow is not null and pay_id is not null.
Try this one.
cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);
Hope that helps. :)
A matrix is really just a vector with a dim
attribute (for the dimensions). So you can add dimensions to vec
using the dim()
function and vec
will then be a matrix:
vec <- 1:49
dim(vec) <- c(7, 7) ## (rows, cols)
vec
> vec <- 1:49
> dim(vec) <- c(7, 7) ## (rows, cols)
> vec
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 8 15 22 29 36 43
[2,] 2 9 16 23 30 37 44
[3,] 3 10 17 24 31 38 45
[4,] 4 11 18 25 32 39 46
[5,] 5 12 19 26 33 40 47
[6,] 6 13 20 27 34 41 48
[7,] 7 14 21 28 35 42 49
For Angular9+, according to this, you can use:
.mat-select-panel {
background: red;
....
}
mat-select-content
as class name for the select list content. For its styling I would suggest four options.
1. Use ::ng-deep:
Use the /deep/ shadow-piercing descendant combinator to force a style down through the child component tree into all the child component views. The /deep/ combinator works to any depth of nested components, and it applies to both the view children and content children of the component. Use /deep/, >>> and ::ng-deep only with emulated view encapsulation. Emulated is the default and most commonly used view encapsulation. For more information, see the Controlling view encapsulation section. The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
CSS:
::ng-deep .mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
2. Use ViewEncapsulation
... component CSS styles are encapsulated into the component's view and don't affect the rest of the application. To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes: .... None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.
None value is what you will need to break the encapsulation and set material style from your component. So can set on the component's selector:
Typscript:
import {ViewEncapsulation } from '@angular/core';
....
@Component({
....
encapsulation: ViewEncapsulation.None
})
CSS
.mat-select-content{
width:2000px;
background-color: red;
font-size: 10px;
}
3. Set class style in style.css
This time you have to 'force' styles with !important
too.
style.css
.mat-select-content{
width:2000px !important;
background-color: red !important;
font-size: 10px !important;
}
4. Use inline style
<mat-option style="width:2000px; background-color: red; font-size: 10px;" ...>
+-------------------------------------+--------------------------------------------------------------------------------------------------+
| Runnable | Callable<T> |
+-------------------------------------+--------------------------------------------------------------------------------------------------+
| Introduced in Java 1.0 of java.lang | Introduced in Java 1.5 of java.util.concurrent library |
| Runnable cannot be parametrized | Callable is a parametrized type whose type parameter indicates the return type of its run method |
| Runnable has run() method | Callable has call() method |
| Runnable.run() returns void | Callable.call() returns a value of Type T |
| Can not throw Checked Exceptions | Can throw Checked Exceptions |
+-------------------------------------+--------------------------------------------------------------------------------------------------+
The designers of Java felt a need of extending the capabilities of the Runnable
interface, but they didn't want to affect the uses of the Runnable
interface and probably that was the reason why they went for having a separate interface named Callable
in Java 1.5 than changing the already existing Runnable
interface which has been a part of Java since Java 1.0. source
I was struggling and Found this Easy and Effective way from IntelliJ IDEA
suggestion
<select id="country" formControlName="country" >
<option [defaultSelected]=true [value]="default" >{{default}}</option>
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
And On your ts file assign the values
countries = ['USA', 'UK', 'Canada'];
default = 'UK'
Just make sure your formControlName accepts string, because you already assigned it as a string.
In your case I use: val dm = ListBuffer[String]()
and val dk = ListBuffer[Map[String,anyRef]]()
You can use the MsiEnumProductsEx and MsiGetProductInfoEx methods to enumerate all the installed applications on your system and match the data to your application
or you can
SELECT
String_to_array(CASE
WHEN <condition 1> THEN a1||','||b1
WHEN <condition 2> THEN a2||','||b2
ELSE a3||','||b3
END, ',') K
FROM <table>
str1 = "test123.00";
str2 = "yes50.00";
intStr1 = str1.replace(/[A-Za-z$-]/g, "");
intStr2 = str2.replace(/[A-Za-z$-]/g, "");
total = parseInt(intStr1)+parseInt(intStr2);
alert(total);
working Jsfiddle
Here's the answer if you're using south and you want to default to the date you add the field to the database:
Choose option 2 then: datetime.datetime.now()
Looks like this:
$ ./manage.py schemamigration myapp --auto
? The field 'User.created_date' does not have a default specified, yet is NOT NULL.
? Since you are adding this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> datetime.datetime.now()
+ Added field created_date on myapp.User
git stash list
to list your stashed changes.
git stash show
to see what n
is in the below commands.
git stash apply
to apply the most recent stash.
git stash apply stash@{n}
to apply an older stash.
https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning
After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.
Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)
link: http://bugs.mysql.com/bug.php?id=72533
Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.
Regards SB
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
So the difference are :
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
Edit:
Remove the wrong example.
@RequestMapping(value = "/get-image",method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage() throws IOException {
RandomAccessFile f = new RandomAccessFile("/home/vivex/apache-tomcat-7.0.59/tmpFiles/1.jpg", "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);
}
Worked For Me.
OK guys I finally overcame this problem. Here is the solution:
Download gradle-1.6-bin.zip
for offline use.
Paste it in the C:\Users\username\.gradle
directory.
Open Android Studio and click on the "Create New Project" option and you will not get this error any more while offline.
You might get some other errors like this:
Don't worry, just ignore it. Your project has been created.
So now click on "Import Project" and go to the path C:\Users\username\AndroidStudioProjects
and open your project and you are done.
LIMIT is usually applied as the last operation, so the result will first be sorted and then limited to 20. In fact, sorting will stop as soon as first 20 sorted results are found.
My 5 cents (because it appears more straightforward/simpler and sufficient for short lists):
public static T Median<T>(this IEnumerable<T> items)
{
var i = (int)Math.Ceiling((double)(items.Count() - 1) / 2);
if (i >= 0)
{
var values = items.ToList();
values.Sort();
return values[i];
}
return default(T);
}
P.S. using "higher median" as described by ShitalShah.
I think I found the proper way to do it...
// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);
// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');
// Optional: clear its old contents
//elem.innerHTML = '';
// Append the text node into it:
elem.appendChild(text_node);
First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.
We need to Update the GoogleMapHelper to fix the issue
Need to add the below script in setCenterMap function
google.maps.event.trigger({$id}, \"resize\");
And need the include below code in JavaScript
google.maps.event.addListenerOnce({$id}, 'idle', function(){
setCenterMap(new google.maps.LatLng({$this->defaultLatitude},
{$this->defaultLongitude}));
});
Add an extra apostrophe '
to the MessageFormat
pattern String
to ensure the '
character is displayed
String text =
java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
^
An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc
A single quote itself must be represented by doubled single quotes '' throughout a String.
The String
You\\'re
is equivalent to adding a backslash character to the String
so the only difference will be that You\re
will be produced rather than Youre
. (before double quote solution ''
applied)
You can create with javascript some css-rules
, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
from subprocess import Popen
Popen('python filename.py')
You can dynamically populate a list via AJAX using the excellent Select2 plugin. From my answer to "Is there a way to dynamically ajax add elements through jquery chosen plugin?":
Take a look at the neat Select2 plugin, which is based on Chosen itself and supports remote data sources (aka AJAX data) and infinite scrolling.
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
I've used this...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="JavaScript">
function fullScreen(theURL) {
window.open(theURL, '', 'fullscreen=yes, scrollbars=auto');
}
// End -->
</script>
</head>
<body>
<h1 style="text-align: center;">
Open In Full Screen
</h1>
<div style="text-align: center;"><br>
<a href="javascript:void(0);" onclick="fullScreen('http://google.com');">
Open Full Screen Window
</a>
</div>
</body>
</html>
Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.
As example you could create your own bundle:
bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
"~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
"~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
"~/Resources/Core/Javascripts/jquery.validate.min.js",
"~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
"~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
"~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))
And render it like this:
@Scripts.Render("~/bundles/mybundle")
One more advantage of @Scripts.Render("~/bundles/mybundle")
over the native <script src="~/bundles/mybundle" />
is that @Scripts.Render()
will respect the web.config
debug setting:
<system.web>
<compilation debug="true|false" />
If debug="true"
then it will instead render individual script tags for each source script, without any minification.
For stylesheets you will have to use a StyleBundle and @Styles.Render().
Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.
if you are writing styles in styles.xml then
remove android:inputType property and add below lines
<item name="android:capitalize">words</item>
Here is code that will upload multiple images at once, into a specific folder!
The HTML:
<form method="post" enctype="multipart/form-data" id="image_upload_form" action="submit_image.php">
<input type="file" name="images" id="images" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">
</ul>
The PHP:
<?php
$errors = $_FILES["images"]["error"];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
//$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = explode("_", $name);
$imagename='';
foreach($name as $letter){
$imagename .= $letter;
}
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" . $imagename);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
And finally, the JavaSCript/Ajax:
(function () {
var input = document.getElementById("images"),
formdata = false;
function showUploadedItem (source) {
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = source;
li.appendChild(img);
list.appendChild(li);
}
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "Uploading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("images[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "submit_image.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
}());
Hope this helps
Yup. Function references are just like any other object reference, you can pass them around to your heart's content.
Here's a more concrete example:
function foo() {
console.log("Hello from foo!");
}
function caller(f) {
// Call the given function
f();
}
function indirectCaller(f) {
// Call `caller`, who will in turn call `f`
caller(f);
}
// Do it
indirectCaller(foo); // logs "Hello from foo!"
_x000D_
You can also pass in arguments for foo
:
function foo(a, b) {
console.log(a + " + " + b + " = " + (a + b));
}
function caller(f, v1, v2) {
// Call the given function
f(v1, v2);
}
function indirectCaller(f, v1, v2) {
// Call `caller`, who will in turn call `f`
caller(f, v1, v2);
}
// Do it
indirectCaller(foo, 1, 2); // logs "1 + 2 = 3"
_x000D_
Here is how I did it with data binding:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:onTouch="@{(v,e) -> true}"/>
In place of the "true" I used a boolean variable that changed based on a condition so that the recycler view would switch between being disabled and enabled.
Complementing the above answers and also "Parroting" from the Windows Dev Center documentation,
The Winsock2.h header file internally includes core elements from the Windows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for the Windows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, the Windows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents the Winsock.h from being included by the Windows.h header ..
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
Yes, you can have comments. But I will not recommend whatever reason mentioned above.
I did some investigation, and I found all JSON require methods use the JSON.parse
method. So I came to a solution: We can override or do monkey patching around JSON.parse.
Note: tested on Node.js only ;-)
var oldParse = JSON.parse;
JSON.parse = parse;
function parse(json){
json = json.replace(/\/\*.+\*\//, function(comment){
console.log("comment:", comment);
return "";
});
return oldParse(json)
}
JSON file:
{
"test": 1
/* Hello, babe */
}
For everyone using .NET Core CLI on MinGW MSYS. After installing using
dotnet tool install --global dotnet-ef
add this line to to bashrc file c:\msys64\home\username\ .bashrc (location depend on your setup)
export PATH=$PATH:/c/Users/username/.dotnet/tools
You can:
mkdir -p folder/subfolder
The -p
flag causes any parent directories to be created if necessary.
I tried to run insertion of random data into MyISAM and InnoDB tables. The result was quite shocking. MyISAM needed a few seconds less for inserting 1 million rows than InnoDB for just 10 thousand!
Tim S. was much closer to a "correct" answer then the currently accepted one. If you want to have a 100% width, variable height background image done with CSS, instead of using cover
(which will allow the image to extend out from the sides) or contain
(which does not allow the image to extend out at all), just set the CSS like so:
body {
background-image: url(img.jpg);
background-position: center top;
background-size: 100% auto;
}
This will set your background image to 100% width and allow the height to overflow. Now you can use media queries to swap out that image instead of relying on JavaScript.
EDIT: I just realized (3 months later) that you probably don't want the image to overflow; you seem to want the container element to resize based on it's background-image (to preserve it's aspect ratio), which is not possible with CSS as far as I know.
Hopefully soon you'll be able to use the new srcset attribute on the img
element. If you want to use img
elements now, the currently accepted answer is probably best.
However, you can create a responsive background-image element with a constant aspect ratio using purely CSS. To do this, you set the height
to 0 and set the padding-bottom
to a percentage of the element's own width, like so:
.foo {
height: 0;
padding: 0; /* remove any pre-existing padding, just in case */
padding-bottom: 75%; /* for a 4:3 aspect ratio */
background-image: url(foo.png);
background-position: center center;
background-size: 100%;
background-repeat: no-repeat;
}
In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value. This works because padding percentage is always calculated based on width, even if it's vertical padding.
Here is a simple solution:
import pandas as pd
# convert the timestamp column to datetime
df['timestamp'] = pd.to_datetime(df['timestamp'])
# extract hour from the timestamp column to create an time_hour column
df['time_hour'] = df['timestamp'].dt.hour
All in all, I'd say that MD5 in addition to the file name is absolutely safe. SHA-256 would just be slower and harder to handle because of its size.
You could also use something less secure than MD5 without any problem. If nobody tries to hack your file integrity this is safe, too.
I will answer this question in terms of AngularFire, Firebase's library for Angular.
Tl;dr: superpowers. :-)
AngularFire's three-way data binding. Angular binds the view and the $scope, i.e., what your users do in the view automagically updates in the local variables, and when your JavaScript updates a local variable the view automagically updates. With Firebase the cloud database also updates automagically. You don't need to write $http.get or $http.put requests, the data just updates.
Five-way data binding, and seven-way, nine-way, etc. I made a tic-tac-toe game using AngularFire. Two players can play together, with the two views updating the two $scopes and the cloud database. You could make a game with three or more players, all sharing one Firebase database.
AngularFire's OAuth2 library makes authorization easy with Facebook, GitHub, Google, Twitter, tokens, and passwords.
Double security. You can set up your Angular routes to require authorization, and set up rules in Firebase about who can read and write data.
There's no back end. You don't need to make a server with Node and Express. Running your own server can be a lot of work, require knowing about security, require that someone do something if the server goes down, etc.
Fast. If your server is in San Francisco and the client is in San Jose, fine. But for a client in Bangalore connecting to your server will be slower. Firebase is deployed around the world for fast connections everywhere.
Shorter version of previous using map()
function (works for python 2.7):
"".join(map(chr, myList))
In your Manifest file write this before </application >
<activity android:name="com.fsck.k9.activity.MessageList">
<intent-filter>
<action android:name="android.intent.action.MAIN">
</action>
</intent-filter>
</activity>
and tell me if it solves your issue :)
If your delimiter is only characters, you can use strtok
, which seems to be more fit here. Note that you must use it with a while
loop to achieve the effects.
The below way of having commands in a batch file will open new command prompt windows and the new windows will not exit automatically.
start "title" call abcd.exe param1 param2
start "title" call xyz.exe param1 param2
Look the path for example this import is not correct import Navbar from '@/components/Navbar.vue' should look like this ** import Navbar from './components/Navbar.vue'**
I looked into this once a long time ago, and you can read my little write-up on it. Here’s the Mathematica source.
By using generating functions, you can get a closed-form constant-time solution to the problem. Graham, Knuth, and Patashnik’s Concrete Mathematics is the book for this, and contains a fairly extensive discussion of the problem. Essentially you define a polynomial where the nth coefficient is the number of ways of making change for n dollars.
Pages 4-5 of the writeup show how you can use Mathematica (or any other convenient computer algebra system) to compute the answer for 10^10^6 dollars in a couple seconds in three lines of code.
(And this was long enough ago that that’s a couple of seconds on a 75Mhz Pentium...)
I took @jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
I use this class for Audio play. If your audio location is raw folder.
Call method for play:
new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
.getDetail().get(0).getAudio(),"raw", getPackageName()));
AudioPlayer.java class:
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
// mothod for raw folder (R.raw.fileName)
public void play(Context context, int rid){
stop();
mMediaPlayer = MediaPlayer.create(context, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
// mothod for other folder
public void play(Context context, String name) {
stop();
//mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
Another way to do this without adding dependencies or using datetime is to simply do some math on the attributes of the time object. It has hours, minutes, seconds, milliseconds, and a timezone. For very simple comparisons, hours and minutes should be sufficient.
d = datetime.utcnow()
t = d.time()
print t.hour,t.minute,t.second
I don't recommend doing this unless you have an incredibly simple use-case. For anything requiring timezone awareness or awareness of dates, you should be using datetime.
The forced cast suggested by other people did not work for me, throwing an exception of illegal casting.
However, this implicit cast worked fine:
Item<K>[] array = new Item[SIZE];
where Item is a class I defined containing the member:
private K value;
This way you get an array of type K (if the item only has the value) or any generic type you want defined in the class Item.
If you want to set required to true
$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',true);
});
if you want to set required to false
$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',false);
});
Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent
is the door, which needs to be closed (reset) manually. The AutoResetEvent
is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.
In my experience the pythonw.exe is faster at least with using pygame.
Non-prototype version of toHHMMSS:
function toHHMMSS(seconds) {
var sec_num = parseInt(seconds);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
As for me the solution could be a macro to make it explicitly inline and thus fast enough. It also works for any float type. It bases on the fact that the only case when a value is not equals itself is when the value is not a number.
#ifndef isnan
#define isnan(a) (a != a)
#endif
You're not far; you need to do something like this:
[WebMethod]
public static string GetProducts()
{
// instantiate a serializer
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
//optional: you can create your own custom converter
TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});
var products = context.GetProducts().ToList();
var TheJson = TheSerializer.Serialize(products);
return TheJson;
}
You can reduce this code further but I left it like that for clarity. In fact, you could even write this:
return context.GetProducts().ToList();
and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's JavaScriptSerializer
works just fine out of the box.
Yep, both and
and or
operators short-circuit -- see the docs.
You can use %x
or %X
or %p
; all of them are correct.
%x
, the address is given as lowercase, for example: a3bfbc4
%X
, the address is given as uppercase, for example: A3BFBC4
Both of these are correct.
If you use %x
or %X
it's considering six positions for the address, and if you use %p
it's considering eight positions for the address. For example:
If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:
def plot(xx, yy, good):
"""Plot data
Good parts are plotted as black, bad parts as red.
Parameters
----------
xx, yy : 1D arrays
Data to plot.
good : `numpy.ndarray`, boolean
Boolean array indicating if point is good.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
from matplotlib.colors import from_levels_and_colors
from matplotlib.collections import LineCollection
cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
points = np.array([xx, yy]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lines = LineCollection(segments, cmap=cmap, norm=norm)
lines.set_array(good.astype(int))
ax.add_collection(lines)
plt.show()
Expanding on Felix Turner s response, here is how I would use this approach with the fetch
API.
async function createFile(){
let response = await fetch('http://127.0.0.1:8080/test.jpg');
let data = await response.blob();
let metadata = {
type: 'image/jpeg'
};
let file = new File([data], "test.jpg", metadata);
// ... do something with the file or return it
}
createFile();
For Tomcat 8, I had to add the following line to catalina.properties for preventing jars scanned by Tomcat:
tomcat.util.scan.StandardJarScanFilter.jarsToSkip=jsp-api.jar,servlet-api.jar
Set step
attribute to any float number, e.g. 0.01 and you are good to go.
Try using Slivers:
Container(
child: CustomScrollView(
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate(
[
HeaderWidget("Header 1"),
HeaderWidget("Header 2"),
HeaderWidget("Header 3"),
HeaderWidget("Header 4"),
],
),
),
SliverList(
delegate: SliverChildListDelegate(
[
BodyWidget(Colors.blue),
BodyWidget(Colors.red),
BodyWidget(Colors.green),
BodyWidget(Colors.orange),
BodyWidget(Colors.blue),
BodyWidget(Colors.red),
],
),
),
SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
delegate: SliverChildListDelegate(
[
BodyWidget(Colors.blue),
BodyWidget(Colors.green),
BodyWidget(Colors.yellow),
BodyWidget(Colors.orange),
BodyWidget(Colors.blue),
BodyWidget(Colors.red),
],
),
),
],
),
),
)
Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.
bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]
DB::statement("your query")
I used it for add index to column in migration
I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default
declaration for a class, and instead append the export
tag to the class declaration. The imported class should be instead listed in the import
command of the module.
That is: instead of
class Foo {
// ...
}
export default Foo;
and the simple import Foo from './foo';
in the module that will import, one should use
export class Foo {
// ...
}
and import {Foo} from './foo'
in the importer.
The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default
can lead to problems
If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.
I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11
If you have the ID of the div, try this:
<input type='submit' onclick='$("#div_id").show()'>
You may find useful this modification of date object, which is smaller than any library and is easily extendable to support different formats:
NOTE:
CODE
Date.prototype.format = function(format) {
// set default format if function argument not provided
format = format || 'YYYY-MM-DD hh:mm';
var zeropad = function(number, length) {
number = number.toString();
length = length || 2;
while(number.length < length)
number = '0' + number;
return number;
},
// here you can define your formats
formats = {
YYYY: this.getFullYear(),
MM: zeropad(this.getMonth() + 1),
DD: zeropad(this.getDate()),
hh: zeropad(this.getHours()),
mm: zeropad(this.getMinutes())
},
pattern = '(' + Object.keys(formats).join(')|(') + ')';
return format.replace(new RegExp(pattern, 'g'), function(match) {
return formats[match];
});
};
USE
var now = new Date;
console.log(now.format());
// outputs: 2015-02-09 11:47
var yesterday = new Date('2015-02-08');
console.log(yesterday.format('hh:mm YYYY/MM/DD'));
// outputs: 00:00 2015/02/08
On your adapter's getItemViewType
check if the adapter has 0 elements and return a different viewType if so.
Then on your onCreateViewHolder
check if the viewType is the one you returned earlier and inflate a diferent view. In this case a layout file with that TextView
EDIT
If this is still not working then you might want to set the size of the view programatically like this:
Point size = new Point();
((WindowManager)itemView.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(size);
And then when you inflate your view call:
inflatedView.getLayoutParams().height = size.y;
inflatedView.getLayoutParams().width = size.x;
Cookies are your best bet. Look for the jquery cookie plugin.
Cookies are designed for this sort of situation -- you want to keep some information about this client on client side. Just be aware that cookies are passed back and forth on every web request so you can't store large amounts of data in there. But just a simple answer to a question should be fine.
I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:
<ul> {% for page in site.pages %} {% if page.title != 'index' %} <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li> {% endif %} {% endfor %} </ul>
There is some confusion when using pip install
in Windows. The instructions talk about a specific folder which has youtube-dl.exe
. There is no such folder if you use pip install
.
The solution is to:
bin
folder (there are three exe files) in any folder which is a path
in Windows. I personally use Ananconda, so I placed them in /Anaconda/Scripts
, but you could place it in any folder and add that folder to the path.I know this is an old question, but for those perusing the web like me, here's another solution:
Use replace()
on the commas and create a set of characters to determine the end of a row. I just add --
to end of the internal arrays. That way you don't have to run a for
function.
Here's a JSFiddle: https://jsfiddle.net/0rpb22pt/2/
First, you have to get a table inside your HTML and give it an id:
<table id="thisTable"><tr><td>Click me</td></tr></table>
Here's your array edited for this method:
thisArray=[["row 1, cell 1__", "row 2, cell 2--"], ["row 2, cell 1__", "row 2, cell 2"]];
Notice the added --
at the end of each array.
Because you also have commas inside of arrays, you have to differentiate them somehow so you don't end up messing up your table- adding __
after cells (besides the last one in a row) works. If you didn't have commas in your cell, this step wouldn't be necessary though.
Now here's your function:
function tryit(){
document
.getElementById("thisTable")
.innerHTML="<tr><td>"+String(thisArray)
.replace(/--,/g,"</td></tr><tr><td>")
.replace(/__,/g,"</td><td>");
}
It works like this:
innerHTML
. document.getElementById("thisTable").innerHTML
"<tr><td>"
thisArray
as a String()
. +String(thisArray)
--
that ends up before a new row with the closing and opening of data and row. .replace(/--,/g,"</td></tr><tr><td>")
__
: .replace(/__,/g,"</td><td>")
. Normally you'd just do .replace(/,/g,"</td><td>")
.As long as you don't mind adding some stray characters into your array, it takes up a lot less code and is simple to implement.
Adding to Julia Passynkova's answer
To set validation error in component:
formData.form.controls['email'].setErrors({'incorrect': true});
To unset validation error in component:
formData.form.controls['email'].setErrors(null);
Be careful with unsetting the errors using null
as this will overwrite all errors. If you want to keep some around you may have to check for the existence of other errors first:
if (isIncorrectOnlyError){
formData.form.controls['email'].setErrors(null);
}
I found this today. It really helped me. http://www.propra.nl/playground/css_filters/
All you need is to add this to your css style.:
div {-webkit-filter: brightness(57%)}
Override the equals method in your class and use Collection#equals() method to check for equality.
Add this to the iframe, this worked for me:
onload="this.height=this.contentWindow.document.body.scrollHeight;"
And if you use jQuery try this code:
onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"
The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.
For instance:
echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7
Will result in output of:
2 3.4
-d sets the delimiter
-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7
.
See the MDN docs for the available values for border-style
:
- none : No border, sets width to 0. This is the default value.
Apart from those choices, there is no way to influence the standard border's style.
If the possibilities there are not to your liking, you could use CSS3's border-image
but note that browser support for this is still very spotty (EDIT: browser support is good as of 2020).
According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/
function setMapOnAll(map1) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map1);
}
}
Next create another function to take away all these markers
function clearMarker(){
setMapOnAll(null);
}
Then create this final function to erase all the markers when ever this function is called upon.
function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to
}
Hope that helped good luck
If you need more fine-grade control, you can also go the fork
pipe
exec
route. This will allow your application to retrieve the data outputted from the shell script.
import os
dir="/path/to/dir"
[x[0]+"/"+f for x in os.walk(dir) for f in x[2] if f.endswith(".jpg")]
This will give you a list of jpg files with their full path. You can replace x[0]+"/"+f
with f
for just filenames. You can also replace f.endswith(".jpg")
with whatever string condition you wish.
If you want to check for local files first do:
@font-face {
font-family: 'Green Sans Web';
src:
local('Green Web'),
local('GreenWeb-Regular'),
url('GreenWeb.ttf');
}
There is a more elaborate description of what to do here.
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
Im under the impression that theres no way to do this, it would be nice though.
You can achieve a similar result by having a Alarm_last_set_time recorded somewhere, and having a On_boot_starter BroadcastReciever:BOOT_COMPLETED kinda thing.
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
Context
can be your current Activity
.
You can add comments in Vim's configuration file by either:
" brief descriptiion of command
or:
"" commended command
Taken from here
In the terminal, I typed:
/usr/local/mysql/bin/mysql -u root -p
I was then prompted to enter the temporary password that was given to me upon completion of the installation.
I find this to be the most straightforward and working:
df = pd.DataFrame({
'one thing':[1,2,3,4],
'second thing':[0.1,0.2,1,2],
'other thing':['a','e','i','o']})
df = df[['one thing','second thing', 'other thing']]
Through Xml you can do easily as type following code in xml (editText)...
android:digits="abcdefghijklmnopqrstuvwxyz"
only characters will be accepted...
First, disabling the index during the deletion would be helpful.
Try with a MERGE INTO statement :
1) create a temp table with IDs and an additional column from TABLE1 and test with the following
MERGE INTO table1 src
USING (SELECT id,col1
FROM test_merge_delete) tgt
ON (src.id = tgt.id)
WHEN MATCHED THEN
UPDATE
SET src.col1 = tgt.col1
DELETE
WHERE src.id = tgt.id
As of (dplyr 1.0.0) we can use across()
For all columns:
dat <- dat %>%
mutate(across(everything(), ~ifelse(.=="", NA, as.character(.))))
For individual columns:
dat <- dat %>%
mutate(across(c("Age","Gender"), ~ifelse(.=="", NA, as.character(.))))
As of (dplyr 0.8.0 above) the way this should be written has changed. Before it was, funs()
in .funs (funs(name = f(.))
. Instead of funs
, now we use list (list(name = ~f(.)))
Note that there is also a much simpler way to list the column names ! (both the name of the column and column index work)
dat <- dat %>%
mutate_at(.vars = c("Age","Gender"),
.funs = list(~ifelse(.=="", NA, as.character(.))))
Original Answer:
You can also use mutate_at
in dplyr
dat <- dat %>%
mutate_at(vars(colnames(.)),
.funs = funs(ifelse(.=="", NA, as.character(.))))
Select individual columns to change:
dat <- dat %>%
mutate_at(vars(colnames(.)[names(.) %in% c("Age","Gender")]),
.funs = funs(ifelse(.=="", NA, as.character(.))))
A combination of what NailItDown and Victor said. The preferred/easiest way is to use your Global.Asax to store the error and then redirect to your custom error page.
Global.asax:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError();
Application["TheException"] = ex; //store the error for later
Server.ClearError(); //clear the error so we can continue onwards
Response.Redirect("~/myErrorPage.aspx"); //direct user to error page
}
In addition, you need to set up your web.config:
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="~/myErrorPage.aspx">
</customErrors>
</system.web>
And finally, do whatever you need to with the exception you've stored in your error page:
protected void Page_Load(object sender, EventArgs e)
{
// ... do stuff ...
//we caught an exception in our Global.asax, do stuff with it.
Exception caughtException = (Exception)Application["TheException"];
//... do stuff ...
}
$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
I found this on https://css-tricks.com/snippets/php/change-month-number-to-month-name/ and it worked perfectly.
The trunc()
function truncates a date to the specified time period; so trunc(sysdate,'mm')
would return the beginning of the current month. You can then use the add_months()
function to get the beginning of the previous month, something like this:
select count(distinct switch_id)
from [email protected]
where dealer_name = 'XXXX'
and creation_date >= add_months(trunc(sysdate,'mm'),-1)
and creation_date < trunc(sysdate, 'mm')
As a little side not you're not explicitly converting to a date in your original query. Always do this, either using a date literal, e.g. DATE 2012-08-31
, or the to_date()
function, for example to_date('2012-08-31','YYYY-MM-DD')
. If you don't then you are bound to get this wrong at some point.
You would not use sysdate - 15
as this would provide the date 15 days before the current date, which does not seem to be what you are after. It would also include a time component as you are not using trunc()
.
Just as a little demonstration of what trunc(<date>,'mm')
does:
select sysdate
, case when trunc(sysdate,'mm') > to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
then 1 end as gt
, case when trunc(sysdate,'mm') < to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
then 1 end as lt
, case when trunc(sysdate,'mm') = to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
then 1 end as eq
from dual
;
SYSDATE GT LT EQ
----------------- ---------- ---------- ----------
20120911 19:58:51 1
In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:
sys.stderr.write("Usage: " + sys.argv[0])
or
sys.stderr.write("Usage: %s" % sys.argv[0])
Also, you may want to consider using the following syntax of print
(for Python earlier than 3.x):
print >>sys.stderr, "Usage:", sys.argv[0]
Using print
arguably makes the code easier to read. Python automatically adds a space between arguments to the print
statement, so there will be one space after the colon in the above example.
In Python 3.x, you would use the print
function:
print("Usage:", sys.argv[0], file=sys.stderr)
Finally, in Python 2.6 and later you can use .format
:
print >>sys.stderr, "Usage: {0}".format(sys.argv[0])
All the previous reviews were tested by me, but there was no solution. But I did not give up.
SOLUTION
Uncomment the following lines in my NGINX configuration
[/etc/nginx/site-avaible/{sitename}.conf]
The same code should follow in the site-enable folder
#fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name;
And comment this:
fastcgi_param SCRIPT_FILENAME / www / {namesite} / public_html $ fastcgi_script_name;
I changed several times from the original:
#fastcgi_pass unix: /var/php-nginx/9882989289032.sock;
Going back to this:
#fastcgi_pass 127.0.0.1:9007;
And finally I found what worked ...
fastcgi_pass localhost: 8004;
I also recommend these lines...
#fastcgi_index index.php;
#include fastcgi_params;
And even the FastCGI timeout (only to improve performance)
fastcgi_read_timeout 3000;
During the process, I checked the NGINX log for all modifications. (This is very important because it shows the wrong parameter.) In my case it is like this, but it depends on the configuration:
error_log/var/log/nginx/{site}_error_log;
Test the NGINX Configuration
nginx -t
Attention this is one of the options ... Well on the same server, what did not work on this site works on others ... So keep in mind that the settings depends on the platform.
In this case it was for Joomla CMS.
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
Yes you can, for example:
[textField setKeyboardType:UIKeyboardTypeNumberPad];
Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:
g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)
I ran into this because I made a copy-and-paste of ngBoilerplate into my project on a Mac without Finder showing hidden files. So .bower was not copied with the rest of ngBoilerplate. Thus bower moved resources to bower_components (defult) instead of vendor (as configured) and my app didn't get angular. Probably a corner case, but it might help someone here.
I found a new way to do it without interfaces. You only need to add the below code to the Fragment’s onCreate() method:
//overriding the fragment's oncreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//calling onBackPressedDispatcher and adding call back
requireActivity().onBackPressedDispatcher.addCallback(this) {
//do stuff here
}
}
As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread
, as now the sleep functions are public:
Static Public Members
QThread * currentThread()
Qt::HANDLE currentThreadId()
int idealThreadCount()
void msleep(unsigned long msecs)
void sleep(unsigned long secs)
void usleep(unsigned long usecs)
void yieldCurrentThread()
cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members
1.mysql_set_charset('utf8');
// set this line on top of your page in which you are using json.
latin1_swedish_ci
". Whenever you insert an image it just takes the width that the image has originally. You can add any other html element next to it and you will see that it will allow it. That makes image an "inline" element.
I suppose that you want to show your enum values to the user, therefore, you want them to have some friendly name.
Here's my suggestion:
Use an enum type pattern. Although it takes some effort to implement, it is really worth it.
public class MyEnum
{
public static readonly MyEnum Enum1=new MyEnum("This will work",1);
public static readonly MyEnum Enum2=new MyEnum("This.will.work.either",2);
public static readonly MyEnum[] All=new []{Enum1,Enum2};
private MyEnum(string name,int value)
{
Name=name;
Value=value;
}
public string Name{get;set;}
public int Value{get;set;}
public override string ToString()
{
return Name;
}
}
A very nice example that uses :after
and :before
to do the trick is in Styling Select Box with CSS3 | CSSDeck
Boost has something to help: the Boost.Iterator library.
More precisely this page: boost::iterator_adaptor.
What's very interesting is the Tutorial Example which shows a complete implementation, from scratch, for a custom type.
template <class Value> class node_iter : public boost::iterator_adaptor< node_iter<Value> // Derived , Value* // Base , boost::use_default // Value , boost::forward_traversal_tag // CategoryOrTraversal > { private: struct enabler {}; // a private type avoids misuse public: node_iter() : node_iter::iterator_adaptor_(0) {} explicit node_iter(Value* p) : node_iter::iterator_adaptor_(p) {} // iterator convertible to const_iterator, not vice-versa template <class OtherValue> node_iter( node_iter<OtherValue> const& other , typename boost::enable_if< boost::is_convertible<OtherValue*,Value*> , enabler >::type = enabler() ) : node_iter::iterator_adaptor_(other.base()) {} private: friend class boost::iterator_core_access; void increment() { this->base_reference() = this->base()->next(); } };
The main point, as has been cited already, is to use a single template implementation and typedef
it.
That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.
The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.
But, I'll take a stab. The original sentence is this:
All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.
X here is a category. Endofunctors are functors from a category to itself (which is usually all Functor
s as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.
And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:
* -> *
with a Functor
instance)join
in Haskell)return
in Haskell)With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.
Use include_once();
- with this, your codes will be included only one time.
Below Steps worked for me:
1). right click on source task.
2). click on "Show Advanced editor". advanced edit option for source task in ssis
3). Go to "Input and Output Properties" tab.
4). select the output column for which you are getting the error.
5). Its data type will be "String[DT_STR]".
6). Change that data type to "Unicode String[DT_WSTR]". Changing the data type to unicode string
7). save and close. Hope this helps!
Yes you can,
In your pom.xml, add the tomcat plugin. (You can use this for both Tomcat 7 and 8):
pom.xml
<!-- Tomcat plugin -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http:// localhost:8080/manager/text</url>
<server>TomcatServer</server> *(From maven > settings.xml)*
<username>*yourtomcatusername*</username>
<password>*yourtomcatpassword*</password>
</configuration>
</plugin>
tomcat-users.xml
<tomcat-users>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<user username="admin" password="password" roles="manager-gui,manager-script" />
</tomcat-users>
settings.xml (maven > conf)
<servers>
<server>
<id>TomcatServer</id>
<username>admin</username>
<password>password</password>
</server>
</servers>
* deploy/re-deploy
mvn tomcat7:deploy OR mvn tomcat7:redeploy
Tried this on (Both Ubuntu and Windows 8/10):
* Jdk 7 & Tomcat 7
* Jdk 7 & Tomcat 8
* Jdk 8 & Tomcat 7
* Jdk 8 & Tomcat 8
* Jdk 8 & Tomcat 9
Tested on Both Jdk 7/8 & Tomcat 7/8. (Works with Tomcat 8.5 and 9)
Note:
Tomcat manager should be running or properly setup, before you can use it with maven.
Good Luck!
Great answer by mshutov & Salselvaprabu. I needed something a little bit more robust, and that checked all IPAddresses that was provided instead of checking only the first one.
I also wanted to replicate some of the parameter names and functionality than the Test-Connection function.
This new function allows you to set a Count for the number of retries, and the Delay between each try. Enjoy!
function Test-Port {
[CmdletBinding()]
Param (
[string] $ComputerName,
[int] $Port,
[int] $Delay = 1,
[int] $Count = 3
)
function Test-TcpClient ($IPAddress, $Port) {
$TcpClient = New-Object Net.Sockets.TcpClient
Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}
If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
Return $False
}
function Invoke-Test ($ComputerName, $Port) {
Try { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString }
Catch { Return $False }
[array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
If ($Results -contains $True) { Return $True } Else { Return $False }
}
for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
{
if ($i -ge $Count) {
Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
Return $false
}
Write-Warning "Port $Port not open, retrying..."
Sleep $Delay
}
Return $true
}
you can check that by either isset()
or empty()
(its check explicit isset) weather check box is checked or not
for example
<input type='checkbox' name='Mary' value='2' id='checkbox' />
here you can check by
if (isset($_POST['Mary'])) {
echo "checked!";
}
or
if (!empty($_POST['Mary'])) {
echo "checked!";
}
the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo htmlspecialchars($aDoor[$i] ). " ";
}
}
I see permutation has been suggested. In fact it can be made into one line:
>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]
array([[0, 3, 0],
[3, 1, 2]])
In case of direct @Value injection, the most elegant way is writing the key-values as an inline json (use ' and " chars to avoid cumbersome escapings) and parsing it using SPEL:
#in yaml file:
my:
map:
is: '{ "key1":"val1",
"key2":"val2" }'
in your @Component or @Bean, :
@Component
public class MyClass{
@Value("#{${my.map.is}}")
Map<String,String> myYamlMap;
}
for a more YAML convenient syntax, you can avoid the json curly braces altogether, directly typing the key value pairs
my:
map:
is: '"a":"b", "foo":"bar"'
and add the missing curly braces directly to your @Value SPEL expression:
@Value("#{{${my.map.is}}}")
Map<String,String> myYamlMap;
the value will be resolved from the yaml, the wrapping curlies will be concatenated to it, and finally the SPEL expression will resolve the string as map.
In addition to the example given in the Advanced Bash Scripting Guide referenced by Jefromi, these examples show how pipes create subshells:
$ echo $$ $BASHPID | cat -
11656 31528
$ echo $$ $BASHPID
11656 11656
$ echo $$ | while read line; do echo $line $$ $BASHPID; done
11656 11656 31497
$ while read line; do echo $line $$ $BASHPID; done <<< $$
11656 11656 11656
I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.
mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM tin3;
+----+------------+
| id | val |
+----+------------+
| 1 | 0000000012 |
| 2 | 0000000007 |
| 4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)
mysql>
mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
| 10 |
+-------------+
1 row in set (0.01 sec)
mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
| 8 |
+-------+
1 row in set (0.00 sec)
I think there are reasons to use a switch statement. If you are using xText generated Code perhaps. Or another kind of EMF generated classes.
instance.getClass().getName();
returns a String of the Class Implementation Name. i.e: org.eclipse.emf.ecore.util.EcoreUtil
instance.getClass().getSimpleName();
returns the simple represenation i.e: EcoreUtil
1.Click on Configure
2.Then Choose Project Defaults
3.Click on Project Structure
4.Set android sdk path
You will find here "C:\User\YourPcname\AppData\Local\SDK"
Note: Sometime AppData
may hidden if it will not show then enable show hidden content.
5.Apply Changes
6.Then Select Sdk From Configure
option
7.Then Android sdk manager page is open
8.In bottom you will see Install packages
option
9.Install them and enjoy.
// if you need to check if all items' MyProperty doesn't have null
if (list.All(x => x.MyProperty != null))
// do something
// or if you need to check if at least one items' property has doesn't have null
if (list.Any(x => x.MyProperty != null))
// do something
But you always have to check for null
The error message is telling you.
Try just
"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
When you enclose the string in single-quotes, this makes everything inside a valid string, including the "
chars. By removing the single-quotes, the shell will process the dbl-quotes as string "wrappers".
I would also wrap the filename variable in dbl-quotes so you can easily process files with spaces in their names, i.e.
"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
IHTH
@Maxim
try this...
pom.xml
<groupId>org.opensource</groupId>
<artifactId>base</artifactId>
<version>1.0.0.SNAPSHOT</version>
..............
<properties>
<my.version>4.0.8.8</my.version>
</properties>
<build>
<finalName>my-base-project</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<goals>
<goal>install-file</goal>
</goals>
<phase>install</phase>
<configuration>
<file>${project.build.finalName}.${project.packaging}</file>
<generatePom>false</generatePom>
<pomFile>pom.xml</pomFile>
<version>${my.version}</version>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Commnad mvn clean install
Output
[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ base ---
[INFO] Building jar: D:\dev\project\base\target\my-base-project.jar
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install (default-install) @ base ---
[INFO] Installing D:\dev\project\base\target\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.pom
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default) @ base ---
[INFO] Installing D:\dev\project\base\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
With the later spring-boot releases switching to Hikari can be done entirely in configuration. I'm using 1.5.6.RELEASE
and this approach works.
build.gradle:
compile "com.zaxxer:HikariCP:2.7.3"
application YAML
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
hikari:
idleTimeout: 60000
minimumIdle: 2
maximumPoolSize: 20
connectionTimeout: 30000
poolName: MyPoolName
connectionTestQuery: SELECT 1
Change connectionTestQuery
to suit your underlying DB. That's it, no code required.
If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete
also.
code sample:
$("img").one("load", function() {
//do stuff
}).each(function() {
if(this.complete || /*for IE 10-*/ $(this).height() > 0)
$(this).load();
});
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
Take a look at strtol(), if you're using the C standard library.
Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# instead of ax.hold(False)
self.figure.clear()
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
# ax.hold(False) # deprecated, see above
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
Slight modification to what was stated above. My Json format, which validates was
{
mycollection:{[
{
property0:value,
property1:value,
},
{
property0:value,
property1:value,
}
]
}
}
Using AlexDev's response, I did this Looping each child, creating reader from it
public partial class myModel
{
public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}
public class myModelList {
[JsonConverter(typeof(myModelConverter))]
public List<myModel> model { get; set; }
}
class myModelConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Children()) //mod here
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject); //mod here
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
The __init__
method, like other methods and functions returns None by default in the absence of a return statement, so you can write it like either of these:
class Foo:
def __init__(self):
self.value=42
class Bar:
def __init__(self):
self.value=42
return None
But, of course, adding the return None
doesn't buy you anything.
I'm not sure what you are after, but you might be interested in one of these:
class Foo:
def __init__(self):
self.value=42
def __str__(self):
return str(self.value)
f=Foo()
print f.value
print f
prints:
42
42
@JoinColumn(name="reference_column_name")
annotation can be used above that property or field of class that is being referenced from some other entity.
From a script (one that works):
CREATE DATABASE Northwind
ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind.mdf' )
LOG ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind_log.ldf')
GO
obviously update the path:
C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA
To where your .mdf and .ldf reside.
The Color
structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.
Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb
method:
Color myColor = Color.FromArgb(100, 150, 75);
In your Page_Load you will want to clear out the normal output and write your own, for example:
string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
To convert a C# object to JSON you can use a library such as Json.NET.
Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.
Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.
<div id="showhide" class="meta-info" onclick="changeclass(this);">
function changeclass(element) {
$(element).toggleClass('mynewclass');
}
Or for a slighly more jQuery way (you would run this after the DOM is loaded)
<div id="showhide" class="meta-info">
$('#showhide').click(function() {
$(this).toggleClass('mynewclass');
});
See a working example of this here: http://jsfiddle.net/S76WN/
You can do :
document.forms["loginForm"].submit()
But this won't call the onclick
action of your button, so you will need to call it by hand.
Be aware that you must use the name
of your form and not the id
to access it.
Its because the email address which is being sent is blank. see those empty brackets? that means the email address is not being put in the $address of the swiftmailer function.
The source of your confusion is evident in your comment:
The whole point of ceil/floor operations is to convert floats to integers!
The point of the ceil and floor operations is to round floating-point data to integral values. Not to do a type conversion. Users who need to get integer values can do an explicit conversion following the operation.
Note that it would not be possible to implement a round to integral value as trivially if all you had available were a ceil or float operation that returned an integer. You would need to first check that the input is within the representable integer range, then call the function; you would need to handle NaN and infinities in a separate code path.
Additionally, you must have versions of ceil and floor which return floating-point numbers if you want to conform to IEEE 754.
If you have luasocket installed:
local socket = require 'socket'
socket.sleep(0.2)
Red Hat, Fedora:
yum -y install gcc mysql-devel ruby-devel rubygems
gem install -y mysql -- --with-mysql-config=/usr/bin/mysql_config
Debian, Ubuntu:
apt-get install libmysqlclient-dev ruby-dev
gem install mysql
Arch Linux:
pacman -S libmariadbclient
gem install mysql
simple way is to login to phpmyadmin with root account , there goto mysql database and select user table , there edit root account and in host field add % wild card . and then through ssh flush privileges
FLUSH PRIVILEGES;
DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.
Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!
You can use the grid
feature for the second unused axis x2
, which is the most natural way of drawing a set of regular spaced lines.
set grid x2tics
set x2tics 10 format "" scale 0
In general, the grid is drawn at the same position as the tics on the axis. In case the position of the lines does not correspond to the tics position, gnuplot provides an additional set of tics, called x2tics
. format ""
and scale 0
hides the x2tics so you only see the grid lines.
You can style the lines as usual with linewith
, linecolor
.
you can use if() in place of decode() in mySql as follows This query will print all even id row.
mysql> select id, name from employee where id in
-> (select if(id%2=0,id,null) from employee);
You can use these two libs to download files http://danml.com/download.html https://github.com/eligrey/FileSaver.js/#filesaverjs
example
// for FileSaver
import FileSaver from 'file-saver';
export function exportRecordToExcel(record) {
return ({fetch}) => ({
type: EXPORT_RECORD_TO_EXCEL,
payload: {
promise: fetch('/records/export', {
credentials: 'same-origin',
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(function(response) {
return response.blob();
}).then(function(blob) {
FileSaver.saveAs(blob, 'nameFile.zip');
})
}
});
// for download
let download = require('./download.min');
export function exportRecordToExcel(record) {
return ({fetch}) => ({
type: EXPORT_RECORD_TO_EXCEL,
payload: {
promise: fetch('/records/export', {
credentials: 'same-origin',
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(function(response) {
return response.blob();
}).then(function(blob) {
download (blob);
})
}
});
2020 answer
Just open the url. Facebook automatically registers for deep links.
let url = URL(string:"https://www.facebook.com/TheGoodLordAbove")!
UIApplication.shared.open(url,completionHandler:nil)
this opens in the facebook app if installed, and in your default browser otherwise
My database doesn't support most of the functions above however I found that this works:
SELECT * FROM table WHERE SUBSTR(datetime_column, starting_position, number_of_strings)=required_year_and_month;
for example:
SELECT SUBSTR(created, 1,7) FROM table;
returns the year and month in the format "yyyy-mm"
There are subtleties with Swifts ===
that go beyond mere pointer arithmetics. While in Objective-C you were able to compare any two pointers (i.e. NSObject *
) with ==
this is no longer true in Swift since types play a much greater role during compilation.
A Playground will give you
1 === 2 // false
1 === 1 // true
let one = 1 // 1
1 === one // compile error: Type 'Int' does not conform to protocol 'AnyObject'
1 === (one as AnyObject) // true (surprisingly (to me at least))
With strings we will have to get used to this:
var st = "123" // "123"
var ns = (st as NSString) // "123"
st == ns // true, content equality
st === ns // compile error
ns === (st as NSString) // false, new struct
ns === (st as AnyObject) // false, new struct
(st as NSString) === (st as NSString) // false, new structs, bridging is not "free" (as in "lunch")
NSString(string:st) === NSString(string:st) // false, new structs
var st1 = NSString(string:st) // "123"
var st2 = st1 // "123"
st1 === st2 // true
var st3 = (st as NSString) // "123"
st1 === st3 // false
(st as AnyObject) === (st as AnyObject) // false
but then you can also have fun as follows:
var st4 = st // "123"
st4 == st // true
st4 += "5" // "1235"
st4 == st // false, not quite a reference, copy on write semantics
I am sure you can think of a lot more funny cases :-)
Update for Swift 3 (as suggested by the comment from Jakub Truhlár)
1===2 // Compiler error: binary operator '===' cannot be applied to two 'Int' operands
(1 as AnyObject) === (2 as AnyObject) // false
let two = 2
(2 as AnyObject) === (two as AnyObject) // false (rather unpleasant)
(2 as AnyObject) === (2 as AnyObject) // false (this makes it clear that there are new objects being generated)
This looks a little more consistent with Type 'Int' does not conform to protocol 'AnyObject'
, however we then get
type(of:(1 as AnyObject)) // _SwiftTypePreservingNSNumber.Type
but the explicit conversion makes clear that there might be something going on.
On the String-side of things NSString
will still be available as long as we import Cocoa
. Then we will have
var st = "123" // "123"
var ns = (st as NSString) // "123"
st == ns // Compile error with Fixit: 'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?
st == ns as String // true, content equality
st === ns // compile error: binary operator '===' cannot be applied to operands of type 'String' and 'NSString'
ns === (st as NSString) // false, new struct
ns === (st as AnyObject) // false, new struct
(st as NSString) === (st as NSString) // false, new structs, bridging is not "free" (as in "lunch")
NSString(string:st) === NSString(string:st) // false, new objects
var st1 = NSString(string:st) // "123"
var st2 = st1 // "123"
st1 === st2 // true
var st3 = (st as NSString) // "123"
st1 === st3 // false
(st as AnyObject) === (st as AnyObject) // false
It is still confusing to have two String classes, but dropping the implicit conversion will probably make it a little more palpable.
On a Mac, the idea.log is contained in
/Users/<user>/Library/Logs/AndroidStudio/idea.log
The new stable version (1.2) is in
/Users/<user>/Library/Logs/AndroidStudio1.2/
The new stable version (2.2) is in
/Users/<user>/Library/Logs/AndroidStudio2.2/
The new stable version (3.4) is in
/Users/<user>/Library/Logs/AndroidStudio3.4/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JQuery</title>
<script src="jquery.js" type="text/javascript"> </script>
<style type="text/css">
#box{
width: 68px;
height: 27px;
background: url(images/home1.gif);
cursor: pointer;
}
</style>
<script type="text/javascript">
$(function(){
$('#box').hover( function(){
$('#box').css('background', 'url(images/home2.gif)');
});
$('#box').mouseout( function(){
$('#box').css('background', 'url(images/home1.gif)');
});
});
</script>
</head>
<body>
<div id="box" onclick="location.href='index.php';"></div>
</body>
</html>
Try:
select concat(first_name,last_name) as "Name" from test.student
or, better:
select concat(first_name," ",last_name) as "Name" from test.student
Simple and precise (Source: Socket.IO google group):
socket.emit
allows you to emit custom events on the server and client
socket.send
sends messages which are received with the 'message'
event
The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.
Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.
It is common to get this issue. I cannot set any specific Java home in my system as I have 2 different version of Java (Java 6 and Java 7) for different environment. To resolve the issue, I included the JDK path in the run configuration when opening the build.xml file. This way, 2 different build files use 2 different Java version for build. I think there might be a better solution to this problem but at least the above approach avoid setting the JAVA_HOME variable.
For 2D matrix:
mat.rows – Number of rows in a 2D array.
mat.cols – Number of columns in a 2D array.
Or: C++: Size Mat::size() const
The method returns a matrix size: Size(cols, rows) . When the matrix is more than 2-dimensional, the returned size is (-1, -1).
For multidimensional matrix, you need to use
int thisSizes[3] = {2, 3, 4};
cv::Mat mat3D(3, thisSizes, CV_32FC1);
// mat3D.size tells the size of the matrix
// mat3D.size[0] = 2;
// mat3D.size[1] = 3;
// mat3D.size[2] = 4;
Note, here 2 for z axis, 3 for y axis, 4 for x axis. By x, y, z, it means the order of the dimensions. x index changes the fastest.
To answer "why" someone might use it, I was tempted to use it since I had the $_POST values stored after the page refresh or while going from one page to another. My sense tells me this is not a good practice, but it works nevertheless.
To get several and indepent columns, just:
> test[:,[0,2]]
you will get colums 0 and 2
Try to add this:
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava's Strings.isNullOrEmpty
This is what I would use to test if a string is either None OR Empty OR Blank:
def isBlank (myString):
if myString and myString.strip():
#myString is not None AND myString is not empty or blank
return False
#myString is None OR myString is empty or blank
return True
And, the exact opposite to test if a string is not None NOR Empty NOR Blank:
def isNotBlank (myString):
if myString and myString.strip():
#myString is not None AND myString is not empty or blank
return True
#myString is None OR myString is empty or blank
return False
More concise forms of the above code:
def isBlank (myString):
return not (myString and myString.strip())
def isNotBlank (myString):
return bool(myString and myString.strip())
Usually, if the command is an external program, you can use the OS to help you here.
command > file_output.txt
So your C code would be doing something like
exec("command > file_output.txt");
Then you can use the file_output.txt file.
Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.
const temp = [];
const t = {
name: "name",
etc: [
{
a: 0,
},
],
};
for (let i = 0; i < 3; i++) {
const bla = Object.assign({}, t);
bla.name = bla.name + i;
bla.etc[0].a = i;
temp.push(bla);
}
console.log(JSON.stringify(temp));
use the request()
helper instead. You don't have to worry about use
statements and thus this sort of problem wont happen again.
$input = request()->all();
simple
Yes, there are tons of software available to decompile a .apk file.
Recently, I had compiled an ultimate list of 47 best APK decompilers on my website. I arranged them into 4 different sections.
I hope this collection will be helpful to you.
The following was tested for IIS 8.5 and Windows 8.1.
As of IIS 7, Windows recommends restarting IIS via net stop/start
. Via the command prompt (as Administrator):
> net stop WAS
> net start W3SVC
net stop WAS
will stop W3SVC
as well. Then when starting, net start W3SVC
will start WAS
as a dependency.
I appreciate this wasn't the OP's issue, but I ran into this issue recently with a different cause. For reference, I was using the Liquibase Maven plugin (liquibase-maven-plugin:3.1.1) with SQL Server.
Anyway, I'd erroneously copied and pasted a SQL Server "use" statement into one of my scripts that switches databases, so liquibase was running and updating the DATABASECHANGELOGLOCK
, acquiring the lock in the correct database, but then switching databases to apply the changes. Not only could I NOT see my changes or liquibase audit in the correct database, but of course, when I ran liquibase again, it couldn't acquire the lock, as the lock had been released in the "wrong" database, and so was still locked in the "correct" database. I'd have expected liquibase to check the lock was still applied before releasing it, and maybe that is a bug in liquibase (I haven't checked yet), but it may well be addressed in later versions! That said, I suppose it could be considered a feature!
Quite a bit of a schoolboy error, I know, but I raise it here in case anyone runs into the same problem!
If you have a worksheet with many rows that all contain the formula, by far the easiest method is to copy a row that is without data (but it does contain formulas), and then "insert copied cells" below/above the row where you want to add. The formulas remain. In a pinch, it is OK to use a row with data. Just clear it or overwrite it after pasting.
Are you saying you can have calls like these: getData(id, parameters); getData(id, callback)?
In this case you can't obviously rely on position and you have to rely on analysing the type: getType() and then if necessary getTypeName()
Check if the parameter in question is an array or a function.
I was trying to connect Visual Studio 2013 to Visual Studio Team Services, and am behind a corporate proxy. I made VS use the default proxy settings (as specified in IE's connection settings) by adding:
<system.net>
<defaultProxy useDefaultCredentials="true" enabled="true">
<proxy usesystemdefault="True" />
</defaultProxy>
<settings>
<ipv6 enabled="true"/>
</settings>
</system.net>
to ..\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe.config (running notepad as admin and opening the file from within there)
Declare:
SET @a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (@a);
The clean solution would be to use Array.filter
:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
The problem with this is that it does not work on IE < 9. However, you can include code from a Javascript library (e.g. underscore.js) that implements this for any browser.