You can use stristr()
or strpos()
. Both return false if nothing is found.
Lot's of similar answers but no explanations...
The error is thrown because the private key file permissions are too open. It is a security risk.
Change the permissions on the private key file to be minimal (read only by owner)
chown <unix-name> <private-key-file>
chmod 400 <private-key-file>
If you are using downloading data using url...may need to use
var result = client.DownloadData(url);
There is also list.append
from the rlist
(link to the documentation)
require(rlist)
LL <- list(a="Tom", b="Dick")
list.append(LL,d="Pam",f=c("Joe","Ann"))
It's very simple and efficient.
You can use nunique
in pandas:
df.hID.nunique()
# 5
The ? : operator in Java
In Java you might write:
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:
<a href="#" onClick="(function(e){
console.log(e);
alert('Hey i am calling');
return false;
})(arguments[0]);return false;">click here</a>
It's most likely that your NPM version is old, i recently had this on a developer machine at work, type:
npm -v
If it's anything less than the current stable version, and you can just update your Node.js install from here https://nodejs.org/en/ :)
htmlentities — Convert all applicable characters to HTML entities.
htmlspecialchars — Convert special characters to HTML entities.
The translations performed translation characters on the below:
You can check the following code for more information about what's htmlentities and htmlspecialchars:
Check out C# 3.0's Collection Initializers.
var list = new List<string> { "test1", "test2", "test3" };
If you use LibreOffice from your program via cli .net integration like me, I got the same error. I use the older version of LibreOffice on the production environment on my PC I installed a newer version that was in conflict. Just uninstall LibreOffice. I found the solution here .NET CLI: Could not load file or assembly 'cli_cppuhelper'
Yahoo is the simplest option to get preliminary free data. The link described in eckesicle's answer could be easily used in a python code, but you first need all the tickers. I'd use the NYSE for this example, but this can be used for different exchanges as well.
I used this wiki page to download all company tickers with the following script (I'm not a very talented Pythonist, sorry if this code isn't very efficient):
import string
import urllib2
from bs4 import BeautifulSoup
global f
def download_page(url):
aurl = urllib2.urlopen(url)
soup = BeautifulSoup(aurl.read())
print url
for row in soup('table')[1]('tr'):
tds = row('td')
if (len(tds) > 0):
f.write(tds[1].string + '\n')
f = open('stock_names.txt', 'w')
url_part1 = 'http://en.wikipedia.org/wiki/Companies_listed_on_the_New_York_Stock_Exchange_'
url = url_part1 + '(0-9)'
download_page(url)
for letter in string.uppercase[:26]:
url_part2 = letter
url = url_part1 + '(' + letter + ')'
download_page(url)
f.close()
For downloading each ticker I used another quite similar script:
import string
import urllib2
from bs4 import BeautifulSoup
global f
url_part1 = 'http://ichart.finance.yahoo.com/table.csv?s='
url_part2 = '&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv'
print "Starting"
f = open('stock_names.txt', 'r')
file_content = f.readlines()
count = 1;
print "About %d tickers will be downloaded" % len(file_content)
for ticker in file_content:
ticker = ticker.strip()
url = url_part1 + ticker + url_part2
try:
# This will cause exception on a 404
response = urllib2.urlopen(url)
print "Downloading ticker %s (%d out of %d)" % (ticker, count, len(file_content))
count = count + 1
history_file = open('C:\\Users\\Nitay\\Desktop\\Historical Data\\' + ticker + '.csv', 'w')
history_file.write(response.read())
history_file.close()
except Exception, e:
pass
f.close()
Notice that the major downside to this method is that different data is available for different companies - Companies that don't have data existing in the requested dates (newly listed) will get you a 404 page.
Also keep in mind that this method is only good for preliminary data - If you really want to test your algorithm you should pay a bit and use a trusted data supplier like CSIData or others
This can be achieved by doing
(a2 & a1) == a2
This creates the intersection of both arrays, returning all elements from a2
which are also in a1
. If the result is the same as a2
, you can be sure you have all elements included in a1
.
This approach only works if all elements in a2
are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).
Although it's 8+ years late, in reply to @Amc_rtty, to get dynamically generated IDs from (my) HTML, I used the index of the php loop to increment the button IDs. I concatenated the same indices to the ID of the input element, hence I ended up with id="tableview1" and button id="1" and so on.
$tableView .= "<td><input type='hidden' value='http://".$_SERVER['HTTP_HOST']."/sql/update.php?id=".$mysql_rows[0]."&table=".$theTable."'id='tableview".$mysql_rows[0]."'><button type='button' onclick='loadDoc(event)' id='".$mysql_rows[0]."'>Edit</button></td>";
In the javascript, I stored the button click in a variable and added it to the element.
function loadDoc(e) {
var btn = e.target.id;
var xhttp = new XMLHttpRequest();
var page = document.getElementById("tableview"+btn).value;
//other Ajax stuff
}
From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):
child::*
selects all element children of the context node
child::text()
selects all text node children of the context node
child::node()
selects all the children of the context node, whatever their node type
So I guess your answer is:
$doc/PRESENTEDIN/X/child::node()
And if you want a flatten array of all nested nodes:
$doc/PRESENTEDIN/X/descendant::node()
Your logic is backwards.
SELECT
*
FROM
`test_table`
WHERE
start_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)
AND end_date NOT BETWEEN CAST('2009-12-15' AS DATE) and CAST('2010-01-02' AS DATE)
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
You can also open a new tab calling to an action method with parameter like this:
var reportDate = $("#inputDateId").val();
var url = '@Url.Action("PrintIndex", "Callers", new {dateRequested = "findme"})';
window.open(window.location.href = url.replace('findme', reportDate), '_blank');
You should clean the project , or restart Eclipse.
As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.
As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.
If what you want is the total number of records in the table appended to each row you can do something like
SELECT *
FROM my_table
CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
FROM MY_TABLE)
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start(). The result is a new instance of class Thread, which is called join().
Go into your project.
install Gradle.
https://docs.gradle.org/current/userguide/installation.html
On a mac: brew install gradle
Then gradle build --stacktrace
Print service
import { Injectable } from '@angular/core';
@Injectable()
export class PrintingService {
public print(printEl: HTMLElement) {
let printContainer: HTMLElement = document.querySelector('#print-container');
if (!printContainer) {
printContainer = document.createElement('div');
printContainer.id = 'print-container';
}
printContainer.innerHTML = '';
let elementCopy = printEl.cloneNode(true);
printContainer.appendChild(elementCopy);
document.body.appendChild(printContainer);
window.print();
}
}
?omponent that I want to print
@Component({
selector: 'app-component',
templateUrl: './component.component.html',
styleUrls: ['./component.component.css'],
encapsulation: ViewEncapsulation.None
})
export class MyComponent {
@ViewChild('printEl') printEl: ElementRef;
constructor(private printingService: PrintingService) {}
public print(): void {
this.printingService.print(this.printEl.nativeElement);
}
}
Not the best choice, but works.
The problem is that jQuery doesn't trigger the native click
event for <a>
elements so that navigation doesn't happen (the normal behavior of an <a>
), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
To trigger it manually, try:
var a = $("<a>")
.attr("href", "http://i.stack.imgur.com/L8rHf.png")
.attr("download", "img.png")
.appendTo("body");
a[0].click();
a.remove();
DEMO: http://jsfiddle.net/HTggQ/
Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
You can store a reference id to any setInterval or setTimeout. Like this:
var loop = setInterval(func, 30);
// some time later clear the interval
clearInterval(loop);
To do this without a "global" variable you can add a local variable to the function itself. Ex:
$(window).resize(function() {
clearTimeout(this.id);
this.id = setTimeout(doneResizing, 500);
});
function doneResizing(){
$("body").append("<br/>done!");
}
In using toolbar you should extends AppCompatActivity and
import android.support.v7.widget.Toolbar
I'm using following markup and had encoutered the same problem:
<ul class="nav">
<li><a href="abc.html">abc</a></li>
<li><a href="def.html">def</a></li>
</ul>
Here I have used the following logic:
$(".nav > li").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
// this section only processes if the .nav > li itself is clicked.
alert("you clicked .nav > li, but not it's children");
});
In terms of the exact question, I can see that working as follows:
$(".example").click(function(e){
if(e.target != this) return; // only continue if the target itself has been clicked
$(".example").fadeOut("fast");
});
or of course the other way around:
$(".example").click(function(e){
if(e.target == this){ // only if the target itself has been clicked
$(".example").fadeOut("fast");
}
});
Hope that helps.
Make sure your device is not connected as a media device.
in java you can inherit from one (abstract) class to "provide" functionality and you can implement many interfaces to "ensure" functionality
As the Jquery replaceWith() code was too bulky, tricky and complicated, here's my own solution. =)
The best way is to use outerHTML property, but it is not crossbrowsered yet, so I did some trick, weird enough, but simple.
Here is the code
var str = '<a href="http://www.com">item to replace</a>'; //it can be anything
var Obj = document.getElementById('TargetObject'); //any element to be fully replaced
if(Obj.outerHTML) { //if outerHTML is supported
Obj.outerHTML=str; ///it's simple replacement of whole element with contents of str var
}
else { //if outerHTML is not supported, there is a weird but crossbrowsered trick
var tmpObj=document.createElement("div");
tmpObj.innerHTML='<!--THIS DATA SHOULD BE REPLACED-->';
ObjParent=Obj.parentNode; //Okey, element should be parented
ObjParent.replaceChild(tmpObj,Obj); //here we placing our temporary data instead of our target, so we can find it then and replace it into whatever we want to replace to
ObjParent.innerHTML=ObjParent.innerHTML.replace('<div><!--THIS DATA SHOULD BE REPLACED--></div>',str);
}
That's all
How about this?
var people = [
{
name: 'a75',
item1: false,
item2: false
},
{
name: 'z32',
item1: true,
item2: false
},
{
name: 'e77',
item1: false,
item2: false
}];
function sort_by_key(array, key)
{
return array.sort(function(a, b)
{
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
people = sort_by_key(people, 'name');
This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?
And here is a jsFiddle: http://jsfiddle.net/6Dgbu/
BrenBarn is correct. The error means you tried to do something like None[5]
. In the backtrace, it says self.imageDef=self.values[2]
, which means that your self.values
is None
.
You should go through all the functions that update self.values
and make sure you account for all the corner cases.
Try the following command:
git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
By using git rev-parse
will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.
To do the same with remote branches (change origin
with your remote name), try:
git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)
In case you've multiple remotes, add grep origin |
before cut
to filter only the origin
.
If above command fails, try to delete the merged remote-tracking branches first:
git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))
Then git fetch
the remote again and use the previous git push -vd
command again.
If you're using it often, consider adding as aliases into your ~/.gitconfig
file.
In case you've removed some branches by mistake, use git reflog
to find the lost commits.
Again, not a direct answer to the question, but was led here by a web search. Ended up exposing the inner function without using return, etc. by simply assigning it to a global variable.
var fname;
function outer() {
function inner() {
console.log("hi");
}
fname = inner;
}
Now just
fname();
The answer depends on what you mean by "close app". In android's terms its either about an "activity", or a group of activities in a temporal/ancestral order called "task".
End activity: just call finish()
End task:
This will end the entire "task"
the documentation has this blurb https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
Here's why you saw the menu with the code you listed in your onClick
method:
You were creating an Intent with the constructor that takes a string for the action parameter of the Intent
's IntentFilter
. You passed "android.intent.action.MAIN"
as the argument to that constructor, which specifies that the Intent
can be satisfied by any Activity
with an IntentFilter including <action="android.intent.action.MAIN">
.
When you called startActivity
with that Intent
, you effectively told the Android OS to go find an Activity
(in any app installed on the system) that specifies the android.intent.action.MAIN
action. When there are multiple Activities that qualify (and there are in this case since every app will have a main Activity
with an IntentFilter
including the "android.intent.action.MAIN"
action), the OS presents a menu to let the user choose which app to use.
As to the question of how to get back to your main activity, as with most things, it depends on the specifics of your app. While the accepted answer probably worked in your case, I don't think it's the best solution, and it's probably encouraging you to use a non-idiomatic UI in your Android app. If your Button
's onClick()
method contains only a call to finish()
then you should most likely remove the Button
from the UI and just let the user push the hardware/software back button, which has the same functionality and is idiomatic for Android. (You'll often see back Buttons used to emulate the behavior of an iOS UINavigationController navigationBar which is discouraged in Android apps).
If your main activity launches a stack of Activities and you want to provide an easy way to get back to the main activity without repeatedly pressing the back button, then you want to call startActivity
after setting the flag Intent.FLAG_ACTIVITY_CLEAR_TOP
which will close all the Activities in the call stack which are above your main activity and bring your main activity to the top of the call stack. See below (assuming your main activity subclass is called MainActivity:
btnReturn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
)};
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
Welcome to hell.
You can just pass a datetime64 object to pandas.Timestamp
:
In [16]: Timestamp(numpy.datetime64('2012-05-01T01:00:00.000000'))
Out[16]: <Timestamp: 2012-05-01 01:00:00>
I noticed that this doesn't work right though in NumPy 1.6.1:
numpy.datetime64('2012-05-01T01:00:00.000000+0100')
Also, pandas.to_datetime
can be used (this is off of the dev version, haven't checked v0.9.1):
In [24]: pandas.to_datetime('2012-05-01T01:00:00.000000+0100')
Out[24]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))
I found this solution to work for me. Just call a javascript function like this:
action="javascript:myFunction();"
Then you have the html5 validation... really simple :-)
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
Try to not use setInterval
.
You can resend request to server after successful response with timeout.
jQuery:
sendRequest(); //call function
function sendRequest(){
$.ajax({
url: "test.php",
success:
function(result){
$('#links').text(result); //insert text of test.php into your div
setTimeout(function(){
sendRequest(); //this will send request again and again;
}, 5000);
}
});
}
Try this plugin JQuery UI Message box. He uses jQuery UI Dialog.
Nothing to add to the semantic aspects of "final".
But I'd like to add to chris green's comment that "final" might become a very important compiler optimization technique in the not so distant future. Not only in the simple case he mentioned, but also for more complex real-world class hierarchies which can be "closed" by "final", thus allowing compilers to generate more efficient dispatching code than with the usual vtable approach.
One key disadvantage of vtables is that for any such virtual object (assuming 64-bits on a typical Intel CPU) the pointer alone eats up 25% (8 of 64 bytes) of a cache line. In the kind of applications I enjoy to write, this hurts very badly. (And from my experience it is the #1 argument against C++ from a purist performance point of view, i.e. by C programmers.)
In applications which require extreme performance, which is not so unusual for C++, this might indeed become awesome, not requiring to workaround this problem manually in C style or weird Template juggling.
This technique is known as Devirtualization. A term worth remembering. :-)
There is a great recent speech by Andrei Alexandrescu which pretty well explains how you can workaround such situations today and how "final" might be part of solving similar cases "automatically" in the future (discussed with listeners):
http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly
You can -Xours
or -Xtheirs
with git merge
as well. So:
git reset --hard HEAD
)git merge -Xours
or git merge -Xtheirs
)DISCLAIMER: of course you can choose only one option, either -Xours
or -Xtheirs
, do use different strategy you should of course go file by file.
I do not know if there is a way for checkout
, but I do not honestly think it is terribly useful: selecting the strategy with the checkout command is useful if you want different solutions for different files, otherwise just go for the merge strategy approach.
There is a much simpler solution that will take a minute.
Done!
Now you are able to upload your release that you generated earlier :) Good luck!
if you need to validate decimal with dots, commas, positives and negatives try this:
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject);
Good luck.
You need to overload operator <<
for mystruct
class
Something like :-
friend ostream& operator << (ostream& os, const mystruct& m)
{
os << m.m_a <<" " << m.m_b << endl;
return os ;
}
See here
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
You can identify the next higher value with cummax()
. If you want the location of the each new higher value for example you can pass your vector of cummax()
values to the diff()
function to identify locations at which the cummax()
value changed. say we have the vector
v <- c(4,6,3,2,-5,6,8,12,16)
cummax(v) will give us the vector
4 6 6 6 6 6 8 12 16
Now, if you want to find the location of a change in cummax()
you have many options I tend to use sign(diff(cummax(v)))
. You have to adjust for the lost first element because of diff()
. The complete code for vector v
would be:
which(sign(diff(cummax(v)))==1)+1
We have a special case with MVP where the fragment needs to notify the presenter that the view has become visible, and the presenter is injected by Dagger in fragment.onAttach()
.
setUserVisibleHint()
is not enough, we've detected 3 different cases that needed to be addressed (onAttach()
is mentioned so that you know when the presenter is available):
Fragment has just been created. The system makes the following calls:
setUserVisibleHint() // before fragment's lifecycle calls, so presenter is null
onAttach()
...
onResume()
Fragment already created and home button is pressed. When restoring the app to foreground, this is called:
onResume()
Orientation change:
onAttach() // presenter available
onResume()
setUserVisibleHint()
We only want the visibility hint to get to the presenter once, so this is how we do it:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_list, container, false);
setHasOptionsMenu(true);
if (savedInstanceState != null) {
lastOrientation = savedInstanceState.getInt(STATE_LAST_ORIENTATION,
getResources().getConfiguration().orientation);
} else {
lastOrientation = getResources().getConfiguration().orientation;
}
return root;
}
@Override
public void onResume() {
super.onResume();
presenter.onResume();
int orientation = getResources().getConfiguration().orientation;
if (orientation == lastOrientation) {
if (getUserVisibleHint()) {
presenter.onViewBecomesVisible();
}
}
lastOrientation = orientation;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (presenter != null && isResumed() && isVisibleToUser) {
presenter.onViewBecomesVisible();
}
}
@Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_LAST_ORIENTATION, lastOrientation);
}
Here is a simple and more update format of getting the data:
$now = new \DateTime('now');
$month = $now->format('m');
$year = $now->format('Y');
There's a well documented answer to your question at this url:
The answer shown at that URL is kind of complicated and uses WMI (Windows Management Instrumentation) to iterate through files and folders. But if you do a lot of Windows administration, it's worth the effort to learn WMI.
I'm posting this now in case you need something right now; but I think I used to use a filesystemobject based approach, and I'll look for some example, and I'll post it later if I find it.
I hope this is helpful.
Ultimately, .keystore
and .jks
are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore
: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks
extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).
In Java, the word keystore can have either of the following meanings, depending on the context:
When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.
Java uses its KeyStore
class and related API to make use of a keystore (whether it's file based or not). JKS
is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:
.jks
for type "JKS"
,.p12
or .pfx
for type "PKCS12"
(the specification name is PKCS#12, but the #
is not used in the Java keystore type name).In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks
extension), which is frequently used for Android applications.
Problem 1 : Different applications use different scales for HSV. For example gimp uses H = 0-360, S = 0-100 and V = 0-100
. But OpenCV uses H: 0-179, S: 0-255, V: 0-255
. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255)
.
Problem 2: And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows:
cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)
Now run it. I got an output as follows:
Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid.
EDIT:
As Karl Philip told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new cv2
module, so users can compare the easiness and flexibility of new cv2
module.
import cv2
import numpy as np
img = cv2.imread('sof.jpg')
ORANGE_MIN = np.array([5, 50, 50],np.uint8)
ORANGE_MAX = np.array([15, 255, 255],np.uint8)
hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
cv2.imwrite('output2.jpg', frame_threshed)
It gives the same result as above. But code is much more simpler.
The selected answer is probably correct but it seems needlessly unclear.
I found Shomz's Fiddle to be very helpful, but again, needlessly unclear. (Edit: I now see that that Fiddle is based on the OP's Fiddle.)
Here's my version (which I've created a Fiddle for) which I think is more clear:
function downloadableCSV(rows) {
var content = "data:text/csv;charset=utf-8,";
rows.forEach(function(row, index) {
content += row.join(",") + "\n";
});
return encodeURI(content);
}
var rows = [
["name1", 2, 3],
["name2", 4, 5],
["name3", 6, 7],
["name4", 8, 9],
["name5", 10, 11]
];
$("#download").click(function() {
window.open(downloadableCSV(rows));
});
Switch to preg_replace
Docs and update the expression to use preg syntax (PCRE) instead of ereg syntax (POSIX) where there are differencesDocs (just as it says to do in the manual for ereg_replace
Docs).
This question is quite old but still turns up on Google Search. The accepted question wasn't working for me anymore and seems to be aged. The latest information about cmake is written in the cmake FAQ.
There are various ways to change the path of your compiler. One way would be
Set the appropriate
CMAKE_FOO_COMPILER
variable(s) to a valid compiler name or full path on the command-line usingcmake -D
. For example:cmake -G "Your Generator" -D CMAKE_C_COMPILER=gcc-4.2 -D CMAKE_CXX_COMPILER=g++-4.2 path/to/your/source
instead of gcc-4.2
you can write the path/to/your/compiler
like this
cmake -D CMAKE_C_COMPILER=/path/to/gcc/bin/gcc -D CMAKE_CXX_COMPILER=/path/to/gcc/bin/g++ .
<html>
tag in Elements.<!DOCTYPE html>
before the <html>
.here is my html
<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="myFunction()">
<h1 id="belong">
Welcome To My Home
</h1>
<p>
<a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
</p>
</body>
And so this is how I did something similar in javaScript
var myGlobalNameHolder ="";
function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
myGlobalNameHolder = myString;
if (myString != null) {
document.getElementById("replaceME").innerHTML =
"Hello " + myString + ". Welcome to my site";
document.getElementById("belong").innerHTML =
"A place you belong";
}
}
// create a function to pass our event too
function myFunction2(event) {
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}
Still an issue in Microsoft Office 2016 release, rather disturbing for those of us working with gene names such as MARC1, MARCH1, SEPT1 etc. The solution I've found to be the most practical after generating a ".csv" file in R, that will then be opened/shared with Excel users:
HTH
Since CKEditor v4.1, you can do this in config.js of CKEditor:
CKEDITOR.editorConfig = function( config ) {
config.extraAllowedContent = '*[id](*)'; // remove '[id]', if you don't want IDs for HTML tags
}
You can refer to the official documentation for the detailed syntax of Allowed Content Rules
You could use the __file__
attribute:
import os
import pandas as pd
df = pd.read_csv(os.path.join(os.path.dirname(__file__), "../data_folder/data.csv"))
You can also use DateTime.Now.ToString("yyyy-MM-dd")
for the date, and DateTime.Now.ToString("hh:mm:ss")
for the time.
by default <UL/>
contains default padding
therefore try adding style to padding:0px
in css class or inline css
I found a solution on the MSDN forums. The sample code below will remove all Click
events from button1
.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
button1.Click += button1_Click2;
button2.Click += button2_Click;
}
private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Hello");
private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World");
private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1);
private void RemoveClickEvent(Button b)
{
FieldInfo f1 = typeof(Control).GetField("EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
object obj = f1.GetValue(b);
PropertyInfo pi = b.GetType().GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
list.RemoveHandler(obj, list[obj]);
}
}
html, body {
height:100%;
}
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
For MonoTouch C# developers use:
NSLocale.PreferredLanguages.FirstOrDefault() ?? "en"
Note: I know this was an iOS question, but as I am a MonoTouch developer, the answer on this page led me in the right direction and I thought I'd share the results.
Empty just check is the refered variable/array has an value if you check the php doc(empty) you'll see this things are considered emtpy
* "" (an empty string) * 0 (0 as an integer) * "0" (0 as a string) * NULL * FALSE * array() (an empty array) * var $var; (a variable declared, but without a value in a class)
while isset check if the variable isset and not null which can also be found in the php doc(isset)
You can use momentjs duration object
Example:
const diff = moment.duration(Date.now() - new Date(2010, 1, 1))
console.log(`${diff.years()} years ${diff.months()} months ${diff.days()} days ${diff.hours()} hours ${diff.minutes()} minutes and ${diff.seconds()} seconds`)
just want to add TFS MSBuild does not support special characters on folders i.e. "@"
i had experienced in the past where one of our project folders named as External@Project1
we created a TFS Build definition to run a custom msbuild file then the workspace folder is not getting any contents at the External@Project1 folder during workspace get latest. It seems that tfs get is failing but does not show any error.
after some trial and error and renaming the folder to _Project1. voila we got files on the the folder (_Project1).
Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.
POST https://instagram.com/api/v1/media/upload/
Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php
As an alternative to the PROGRA~2 method (which is not working for example in IntelliJ IDEA), you can create a symbolic link.
It can be named, for example, prg
to Program Files
(run mklink /?
from the command line to learn how to do it). Then run the emulator as C:\prg\Android\android-sdk\tools\emulator.exe
. Also change the path to SDK/emulator in your IDE.
One liner:
new File(uri.getPath).getName
Complete code (in a scala REPL):
import java.io.File
import java.net.URI
val uri = new URI("http://example.org/file.txt?whatever")
new File(uri.getPath).getName
res18: String = file.txt
Note: URI#gePath
is already intelligent enough to strip off query parameters and the protocol's scheme. Examples:
new URI("http://example.org/hey/file.txt?whatever").getPath
res20: String = /hey/file.txt
new URI("hdfs:///hey/file.txt").getPath
res21: String = /hey/file.txt
new URI("file:///hey/file.txt").getPath
res22: String = /hey/file.txt
Use !empty
instead of isset
.
isset return true for $_POST
because $_POST
array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
Just rebooting a AWS instance works for me to clear the error "shell request failed on channel 0"
I know this post specifically asks for sorting a TreeMap by values, but for those of us that don't really care about implementation but do want a solution that keeps the collection sorted as elements are added, I would appreciate feedback on this TreeSet-based solution. For one, elements are not easily retrieved by key, but for the use case I had at hand (finding the n keys with the lowest values), this was not a requirement.
TreeSet<Map.Entry<Integer, Double>> set = new TreeSet<>(new Comparator<Map.Entry<Integer, Double>>()
{
@Override
public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2)
{
int valueComparison = o1.getValue().compareTo(o2.getValue());
return valueComparison == 0 ? o1.getKey().compareTo(o2.getKey()) : valueComparison;
}
});
int key = 5;
double value = 1.0;
set.add(new AbstractMap.SimpleEntry<>(key, value));
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
The simplest thing I did is to set focus on another view in onCreate:
myView.setFocusableInTouchMode(true);
myView.requestFocus();
This stopped the soft keyboard coming up and there was no cursor flashing in the EditText.
For apache-tomcat-8.5.28 version just do this,
catalina.bat jpda start
As the default settings already configured for us in catalina.bat as
if not "%JPDA_OPTS%" == "" goto gotJpdaOpts set JPDA_OPTS=-agentlib:jdwp=transport=%JPDA_TRANSPORT%,address=%JPDA_ADDRESS%,server=y,suspend=%JPDA_SUSPEND%
So no need of any other config. And when you execute command catalina.bat jpda start, you can see debug port 8000 is opened.
This might help you.
<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>
<script>
function save(){
$('#myinput').val('1');
$('#form').submit();
}
</script>
If you have already defined your view in layout(xml) file and only want to change the weight pro grammatically, then then creating new LayoutParams overwrites other params defined in you xml file.
So first you should use "getLayoutParams" and then setLayoutParams
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams();
params.weight = 4f;
mButton.setLayoutParams(params);
This is an old thread but I stumbled onto second highest answer (custom listeners) while looking for a solution using Angular. While the solution works, angular has a better built in way to resolve this using @Output
and event emitters. Going off of the example in custom listener answer:
ChildComponent.html
<button (click)="increment(1)">Increment</button>
ChildComponent.ts
import {EventEmitter, Output } from '@angular/core';
@Output() myEmitter: EventEmitter<number> = new EventEmitter<number>();
private myValue: number = 0;
public increment(n: number){
this.myValue += n;
// Send a change event to the emitter
this.myEmitter.emit(this.myValue);
}
ParentComponent.html
<child-component (myEmitter)="monitorChanges($event)"></child-component>
<br/>
<label>{{n}}</label>
ParentComponent.ts
public n: number = 0;
public monitorChanges(n: number){
this.n = n;
console.log(n);
}
This will now update n
on parent each time the child button is clicked. Working stackblitz
Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.
Example #
// tsconfig.json_x000D_
_x000D_
{_x000D_
"compilerOptions": {_x000D_
"module": "commonjs",_x000D_
"resolveJsonModule": true,_x000D_
"esModuleInterop": true_x000D_
}_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true; // OK_x000D_
settings.dry === 2; // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
"repo": "TypeScript",_x000D_
"dry": false,_x000D_
"debug": false_x000D_
}
_x000D_
cat | git log --author="authorName" > author_commits_details.txt
This gives your commits in text format.
Try to use flexbox model. It is easy and short to write.
Live Jsfiddle
CSS:
#wrapper {
display: flex;
border: 1px solid black;
}
#first {
border: 1px solid red;
}
#second {
border: 1px solid green;
}
default direction is row. So, it aligns next to each other inside the #wrapper. But it is not supported IE9 or less than that versions
With tensorflow version >3.2 you may use this command:
x1 = tf.Variable(5)
y1 = tf.Variable(3)
z1 = x1 + y1
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
init.run()
print(sess.run(z1))
The output: 8 will be displayed.
Try this:
//Force array
$dataArr = is_array($dataArr) ? $dataArr : array($dataArr);
foreach ($dataArr as $val) {
echo $val;
}
;)
I appreciate this is an old post, but it may be useful for people to know that the Azure Migration Wizard (available on Codeplex - can't link to is as Codeplex is at the moment I'm typing this) will do this easily.
All depends on the app you're trying to build. Use Window
s if you're building a dialog based app. Use Page
s if you're building a navigation based app. UserControl
s will be useful regardless of the direction you go as you can use them in both Windows and Pages.
A good place to start exploring is here: http://windowsclient.net/learn
Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.
So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:
int *gnabber(){
static int foo[] = {1,2,3}
return foo;
}
The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'
@kangax (IE 9 preview)
Array.prototype.slice can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.
Example:
Array.prototype.slice.call(document.childNodes);
1.<a href="index.jsp?p=products">Products</a>
when user clicks on Products link,you can directly call products.jsp.
I mean u can maintain name of the JSP file same as parameter Value.
<%
if(request.getParameter("p")!=null)
{
String contextPath="includes/";
String p = request.getParameter("p");
p=p+".jsp";
p=contextPath+p;
%>
<%@include file="<%=p%>" %>
<%
}
%>
or
2.you can maintain external resource file with key,value pairs. like below
products : products.jsp
customer : customers.jsp
you can programatically retrieve the name of JSP file from properies file.
this way you can easily change the name of JSP file
Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec
Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec
, as I have ~/bin
in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...
Launch it from the root of your project, where you can see src and target dirs.
The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)
$ mvnexec
1) org.jmeld.ui.JMeldComponent
2) org.jmeld.ui.text.FileDocument
3) org.jmeld.JMeld
4) org.jmeld.util.UIDefaultsPrint
5) org.jmeld.util.PrintProperties
6) org.jmeld.util.file.DirectoryDiff
7) org.jmeld.util.file.VersionControlDiff
8) org.jmeld.vc.svn.InfoCmd
9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#?
If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P
)
By default it compiles project every run. but you can avoid that using mvnexec -B
It allows to search only in test classes -M
or --no-main
, or only in main classes -T
or --no-test
. also has a filter by name option -f <whatever>
Hope this could save you some time, for me it does.
As others have said, CGFloat is a float on 32-bit systems and a double on 64-bit systems. However, the decision to do that was inherited from OS X, where it was made based on the performance characteristics of early PowerPC CPUs. In other words, you should not think that float is for 32-bit CPUs and double is for 64-bit CPUs. (I believe, Apple's ARM processors were able to process doubles long before they went 64-bit.) The main performance hit of using doubles is that they use twice the memory and therefore might be slower if you are doing a lot of floating point operations.
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name
A.B
designates a submodule namedB
in a package namedA
....
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring
, from unintentionally hiding valid modules that occur later on the module search path.
You need to set it up to something like this:
man
|- __init__.py
|- Mans
|- __init__.py
|- man1.py
|- MansTest
|- __init.__.py
|- SoftLib
|- Soft
|- __init__.py
|- SoftWork
|- __init__.py
|- manModules.py
|- Unittests
|- __init__.py
|- man1test.py
SECOND, for the "ModuleNotFoundError: No module named 'Soft'
" error caused by from ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py to sys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path
directly, you can also modify PYTHONPATH
:
sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
THIRD, for from ...MansTest.SoftLib import Soft
which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.
With that said, here's how I got it to work.
man1.py:
from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH
def foo():
print("called foo in man1.py")
print("foo call module1 from manModules: " + module1())
man1test.py
# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1
man1.foo()
manModules.py
def module1():
return "module1 in manModules"
Terminal output:
$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
...
from ...Mans import man1
File "/temp/man/Mans/man1.py", line 2, in <module>
from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'
$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).
Same as suggested by others, just mentioning the cleaner way of doing it:
int max = decMax[0];
for(int i=1;i<decMax.length;i++)
max = Math.max(decMax[i],max);
System.out.println("The Maximum value is : " + max);
This is the mysql function using the space technique (tested with mysql 5.0 + 5.5):
CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32))
RETURNS INTEGER DETERMINISTIC
RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );
if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):
count before dedupe:
df.count()
do the de-dupe (convert the column you are de-duping to string type):
from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))
df.drop_duplicates(subset=['colName']).count()
can use a sorted groupby to check to see that duplicates have been removed:
df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)
Per the docs, you can catch the appropriate exception type (ClientErrorResponseException
for 4xx errors) and call its getResponse()
method to get the response object, then call getBody()
on that:
use Guzzle\Http\Exception\ClientErrorResponseException;
...
try {
$response = $request->send();
} catch (ClientErrorResponseException $exception) {
$responseBody = $exception->getResponse()->getBody(true);
}
Passing true
to the getBody
function indicates that you want to get the response body as a string. Otherwise you will get it as instance of class Guzzle\Http\EntityBody
.
Same answer like @Jim F answer but ES6 syntax , so, less instructions :
const rgb2hex = (rgb) => {
if (rgb.search("rgb") === -1) return rgb;
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
};
CONVERT
takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn
to an integer instead of the column content.
SELECT convert (int, N'A.my_NvarcharColumn') FROM A;
should instead be
SELECT convert (int, A.my_NvarcharColumn) FROM A;
Simple SQLfiddle here.
Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?
Use a normal for-loop with range(start, stop, step)
(where start
and step
are optional arguments).
For example, looping through an array starting at index 1:
for i in range(1, len(arr)):
print(arr[i])
Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0
The definitive answer (covering changes to jQuery api at version 1.6) has been given by Gnarf
You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.
In simple words java donot provide such an API. You need to iterate through loop and using fill method you can fill 2D array with one loop.
int row = 5;
int col = 6;
int cache[][]=new int[row][col];
for(int i=0;i<=row;i++){
Arrays.fill(cache[i]);
}
Alternatively, you could set the .AcceptButton property of your form. Enter will automcatically create a click event.
this.AcceptButton = this.buttonSearch;
This works well for coping entire records.
UPDATE your_table
SET new_field = sourse_field
in addition to what Kirk said I want to tell you that just "playing around" won't help you to learn asp.net, and there is a lot of free and very good tutorials .
take a look on the asp.net official site tutorials and on 4GuysFromRolla site
Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...
I put file.txt
in c:\temp\
and I put c:\temp\
on the classpath.
There is only one case where there is a difference between the two call.
class J {
public static void main(String[] a) {
// as "absolute"
// ok
System.err.println(J.class.getResourceAsStream("/file.txt") != null);
// pop
System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null);
// as relative
// ok
System.err.println(J.class.getResourceAsStream("./file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null);
// no path
// ok
System.err.println(J.class.getResourceAsStream("file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null);
}
}
If you are insisting to use the window.location.origin
You can put this in top of your code before reading the origin
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
PS: For the record, it was actually the original question. It was already edited :)
Running:
npm install
from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).
You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.
To prevent this, just create a symlink to the relocated node_modules from your app dir:
ln -s ../node_modules node_modules
Edit 2020: This does not work any more. It seems so, that the browser vendors patched this out. Because the most browsers rely on chromium, it might be in its core.
Old answer: You can also hook mouseenter (this event is fired after page reload, when the mousecursor is inside the page). Extending Corrupted's code should do the trick:
var x = null;_x000D_
var y = null;_x000D_
_x000D_
document.addEventListener('mousemove', onMouseUpdate, false);_x000D_
document.addEventListener('mouseenter', onMouseUpdate, false);_x000D_
_x000D_
function onMouseUpdate(e) {_x000D_
x = e.pageX;_x000D_
y = e.pageY;_x000D_
console.log(x, y);_x000D_
}_x000D_
_x000D_
function getMouseX() {_x000D_
return x;_x000D_
}_x000D_
_x000D_
function getMouseY() {_x000D_
return y;_x000D_
}
_x000D_
You can also set x and y to null on mouseleave-event. So you can check if the user is on your page with it's cursor.
If you're willing and able to employ a little jquery, you can simply do this:
$('.someDiv').css([".radius", ".opacity"]);
If you have a javascript that already processes the page or you can enclose it somewhere in <script> tags. If so, wrap the above in the document ready function:
$(document).ready( function() {
$('.someDiv').css([".radius", ".opacity"]);
}
I recently came across this while updating a wordpress plugin. The them has been changed which used a lot of "!important" directives across the css. I had to use jquery to force my styles because of the genius decision to declare !important on several tags.
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
Often i reach for the abbreviation html tag in this situation.
<abbr title="Hover">Text</abbr>
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
if explode is used together with foreach to build a new string you can simulate explode by using a while loop like this:
CREATE FUNCTION explode_and_loop(sep VARCHAR(),inputstring VARCHAR()) RETURNS VARCHAR()
BEGIN
DECLARE part,returnstring VARCHAR();
DECLARE cnt,partsCnt INT();
SET returnstring = '';
SET partsCnt = ((LENGTH(inputstring ) - LENGTH(REPLACE(inputstring,sep,''))) DIV LENGTH(sep);
SET cnt = 0;
WHILE cnt <= partsCnt DO
SET cnt = cnt + 1;
SET part = SUBSTRING_INDEX(SUBSTRING_INDEX(inputstring ,sep,cnt),sep,-1);
-- DO SOMETHING with the part eg make html:
SET returnstring = CONCAT(returnstring,'<li>',part,'</li>')
END WHILE;
RETURN returnstring;
END
this example will return a html list of the parts. (required variable legths have to be added)
I solved it this way, I opened the .sql file in a Notepad and clicked CTRL + H to find and replace the string "utf8mb4_0900_ai_ci" and replaced it with "utf8mb4_general_ci".
Consider the outcome of the tool 'stat':
File: `infolog.txt'
Size: 694 Blocks: 8 IO Block: 4096 regular file
Device: 801h/2049d Inode: 11635578 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ fdr) Gid: ( 1000/ fdr)
Access: 2009-01-01 22:04:15.000000000 -0800
Modify: 2009-01-01 22:05:05.000000000 -0800
Change: 2009-01-01 22:05:05.000000000 -0800
You can see here the three dates for Access/modify/change. There is no created date. You can only really be sure when the file contents were modified (the "modify" field) or its inode changed (the "change" field).
Examples of when both fields get updated:
"Modify" will be updated if someone concatenated extra information to the end of the file.
"Change" will be updated if someone changed permissions via chmod.
First of all, your code works and that's a valid way of creating a function in JavaScript (jQuery aside), but because you are declaring a function inside another function (an anonymous one in this case) "MyBlah" will not be accessible from the global scope.
Here's an example:
$(document).ready( function () {
var MyBlah = function($blah) { alert($blah); };
MyBlah("Hello this works") // Inside the anonymous function we are cool.
});
MyBlah("Oops") //This throws a JavaScript error (MyBlah is not a function)
This is (sometimes) a desirable behavior since we do not pollute the global namespace, so if your function does not need to be called from other part of your code, this is the way to go.
Declaring it outside the anonymous function places it in the global namespace, and it's accessible from everywhere.
Lastly, the $ at the beginning of the variable name is not needed, and sometimes used as a jQuery convention when the variable is an instance of the jQuery object itself (not necessarily in this case).
Maybe what you need is creating a jQuery plugin, this is very very easy and useful as well since it will allow you to do something like this:
$('div#message').myBlah("hello")
See also: http://www.re-cycledair.com/creating-jquery-plugins
Also you can do like this:
<select class="form-control postType" ng-model="selectedProd">
<option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>
where "selectedProd" will be selected product.
Table structure...very basic:
create table tabla(ID int, Stuff varchar (50));
insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');
Query:
SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla
Or, try this:
SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla
Working on SQLServer 2008
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.
Instead, use sos (second-order sections) output of filter design.
from scipy.signal import butter, sosfilt, sosfreqz
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='band', output='sos')
return sos
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, data)
return y
Also, you can plot frequency response by changing
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
to
sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)
To safely encrypt large files (>600MB) with openssl smime
you'll have to split each file into small chunks:
# Splits large file into 500MB pieces
split -b 500M -d -a 4 INPUT_FILE_NAME input.part.
# Encrypts each piece
find -maxdepth 1 -type f -name 'input.part.*' | sort | xargs -I % openssl smime -encrypt -binary -aes-256-cbc -in % -out %.enc -outform DER PUBLIC_PEM_FILE
For the sake of information, here is how to decrypt and put all pieces together:
# Decrypts each piece
find -maxdepth 1 -type f -name 'input.part.*.enc' | sort | xargs -I % openssl smime -decrypt -in % -binary -inform DEM -inkey PRIVATE_PEM_FILE -out %.dec
# Puts all together again
find -maxdepth 1 -type f -name 'input.part.*.dec' | sort | xargs cat > RESTORED_FILE_NAME
I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.
Here's an example that finds div elements whose className contains atag
:
//div[contains(@class, 'atag')]
Here's an example that finds div elements whose className contains atag
and btag
:
//div[contains(@class, 'atag') and contains(@class ,'btag')]
However, it will also find partial matches like class="catag bobtag"
.
If you don't want partial matches, see bobince's answer below.
The shortest way (will print "not same" because String comparison is case sensitive):
def compareString = {
it == "india" ? "same" : "not same"
}
compareString("India")
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC
You have to add the python executable in your SYSTEM PATH, do the following, My Computer > Properties > Advanced System Settings > Environment Variables
> Then under system variables I create a new Variable called "PythonPath". In this variable I have "C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-foolder-on-the-path"
.
As mentioned by nicholas.hauschild injecting Spring context is not a good idea. In your case, @Scope("request") is enough to fix it. But let say you need several instances of LoginAction
in controller method. In this case, I would recommend to create the bean of Supplier (Spring 4 solution):
@Bean
public Supplier<LoginAction> loginActionSupplier(LoginAction loginAction){
return () -> loginAction;
}
Then inject it into controller:
@Controller
public class HomeController {
@Autowired
private Supplier<LoginAction> loginActionSupplier;
Something like this
string find = "item_manuf_id = 'some value'";
DataRow[] foundRows = table.Select(find);
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
You may want to take a different approach: Instead of changing the css dynamically, predefine your styles in CSS the way you want them. Then use JQuery to add and remove styles from within Javascript. (see code from Ajmal)
This is very easy to implement. You can use:
window.location.href = "http://www.example.com/";
This will remember the history of the previous page. So one can go back by clicking on the browser's back button.
Or:
window.location.replace("http://www.example.com/");
This method does not remember the history of the previous page. The back button becomes disabled in this case.
There is a ruby gem for it - SocialShares
Currently it supports following social networks:
Usage:
:000 > url = 'http://www.apple.com/'
=> "http://www.apple.com/"
:000 > SocialShares.facebook url
=> 394927
:000 > SocialShares.google url
=> 28289
:000 > SocialShares.twitter url
=> 1164675
:000 > SocialShares.all url
=> {:vkontakte=>44, :facebook=>399027, :google=>28346, :twitter=>1836, :mail_ru=>37, :odnoklassniki=>1, :reddit=>2361, :linkedin=>nil, :pinterest=>21011, :stumbleupon=>43035}
:000 > SocialShares.selected url, %w(facebook google linkedin)
=> {:facebook=>394927, :google=>28289, :linkedin=>nil}
:000 > SocialShares.total url, %w(facebook google)
=> 423216
:000 > SocialShares.has_any? url, %w(twitter linkedin)
=> true
In ASP.net MVC, you can use a FileContentResult
and the File
method:
public FileContentResult DownloadManifest() {
byte[] csvData = getCsvData();
return File(csvData, "text/csv", "filename.csv");
}
To start the shell-script 'file.sh':
sh file.sh
bash file.sh
Another option is set executable permission using chmod command:
chmod +x file.sh
Now run .sh file as follows:
./file.sh
Additionally, for our Android friends (API Level 8):
import android.util.Base64
...
Base64.encodeToString(bytes, Base64.DEFAULT);
Just use the table name:
SELECT myTable.*, otherTable.foo, otherTable.bar...
That would select all columns from myTable
and columns foo
and bar
from otherTable
.
Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:
var str,
el = document.getElementById("myUrl");
if ("textContent" in el)
str = encodeURIComponent(el.textContent);
else
str = encodeURIComponent(el.innerText);
If that isn't the case, you can use the replace() method to replace the HTML entity:
encodeURIComponent(str.replace(/&/g, "&"));
Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.
The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.
You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
The <scope>
element can take 6 values: compile, provided, runtime, test, system and import.
This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.
compile
This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
provided
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
runtime
This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
test
This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.
system
This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
import (only available in Maven 2.0.9 or later)
This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.
To answer the second part of your question:
How can we use it for running test?
Note that the test
scope allows to use dependencies only for the test phase.
Read the documentation for full details.
The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file
The file is in the res folder and is named (applicationName).rc
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID ) ICON "res\\filename.ico"
Here is the implementation of custom filter, which will filter the data using array of values.It will support multiple key object with both array and single value of keys. As mentioned inangularJS API AngularJS filter Doc supports multiple key filter with single value, but below custom filter will support same feature as angularJS and also supports array of values and combination of both array and single value of keys.Please find the code snippet below,
myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
var filterObj = {
data:items,
filteredData:[],
applyFilter : function(obj,key){
var fData = [];
if (this.filteredData.length == 0)
this.filteredData = this.data;
if (obj){
var fObj = {};
if (!angular.isArray(obj)){
fObj[key] = obj;
fData = fData.concat($filter('filter')(this.filteredData,fObj));
} else if (angular.isArray(obj)){
if (obj.length > 0){
for (var i=0;i<obj.length;i++){
if (angular.isDefined(obj[i])){
fObj[key] = obj[i];
fData = fData.concat($filter('filter')(this.filteredData,fObj));
}
}
}
}
if (fData.length > 0){
this.filteredData = fData;
}
}
}
};
if (keyObj){
angular.forEach(keyObj,function(obj,key){
filterObj.applyFilter(obj,key);
});
}
return filterObj.filteredData;
}
}]);
Usage:
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}
Here is a fiddle example with implementation of above "filterMutiple" custom filter. :::Fiddle Example:::
It was working for me when I used padding like:
<div style="padding-top :200px;page-break-inside:avoid;">
<div>My content</div>
</div>
First, here's some sample data:
set.seed(1)
dat <- data.frame(one = rnorm(15),
two = sample(LETTERS, 15),
three = rnorm(15),
four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 NA
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA NA
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Here's our replacement:
dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 0.0000000
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA 0.0000000
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0
I got this error while trying to use the &&
operator inside single brackets like [ ... && ... ]
. I had to switch to [[ ... && ... ]]
.
Have you considered using BigDecimal
instead of String
to hold your numbers?
git reset
is specifically about updating the index, moving the HEAD.git checkout
is about updating the working tree (to the index or the specified tree). It will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD).git restore
, not necessarily git checkout
) By comparison, since svn has no index, only a working tree, svn checkout
will copy a given revision on a separate directory.
The closer equivalent for git checkout
would:
svn update
(if you are in the same branch, meaning the same SVN URL)svn switch
(if you checkout for instance the same branch, but from another SVN repo URL)All those three working tree modifications (svn checkout
, update
, switch
) have only one command in git: git checkout
.
But since git has also the notion of index (that "staging area" between the repo and the working tree), you also have git reset
.
Thinkeye mentions in the comments the article "Reset Demystified ".
For instance, if we have two branches, '
master
' and 'develop
' pointing at different commits, and we're currently on 'develop
' (so HEAD points to it) and we rungit reset master
, 'develop
' itself will now point to the same commit that 'master
' does.On the other hand, if we instead run
git checkout master
, 'develop
' will not move,HEAD
itself will.HEAD
will now point to 'master
'.So, in both cases we're moving
HEAD
to point to commitA
, but how we do so is very different.reset
will move the branchHEAD
points to, checkout movesHEAD
itself to point to another branch.
On those points, though:
LarsH adds in the comments:
The first paragraph of this answer, though, is misleading: "
git checkout
... will update the HEAD only if you checkout a branch (if not, you end up with a detached HEAD)".
Not true:git checkout
will update the HEAD even if you checkout a commit that's not a branch (and yes, you end up with a detached HEAD, but it still got updated).git checkout a839e8f updates HEAD to point to commit a839e8f.
De Novo concurs in the comments:
@LarsH is correct.
The second bullet has a misconception about what HEAD is in will update the HEAD only if you checkout a branch.
HEAD goes wherever you are, like a shadow.
Checking out some non-branch ref (e.g., a tag), or a commit directly, will move HEAD. Detached head doesn't mean you've detached from the HEAD, it means the head is detached from a branch ref, which you can see from, e.g.,git log --pretty=format:"%d" -1
.
- Attached head states will start with
(HEAD ->
,- detached will still show
(HEAD
, but will not have an arrow to a branch ref.
You are using the pointer newFile
without allocating space for it.
struct stasher_file *newFile = malloc(sizeof(stasher_file));
Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Please install openssl from below link:
https://code.google.com/p/openssl-for-windows/downloads/list
then set the variables below:
OPENSSL_ROOT_DIR=D:/softwares/visualStudio/openssl-0.9.8k_WIN32
OPENSSL_INCLUDE_DIR=D:/softwares/visualStudio/openssl-0.9.8k_WIN32/include
OPENSSL_LIBRARIES=D:/softwares/visualStudio/openssl-0.9.8k_WIN32/lib
I have an example I would like to share
$File = "C:\Foo.txt"
#retrieves the Systems current Date and Time in a DateTime Format
$today = Get-Date
#subtracts 12 hours from the date to ensure the file has been written to recently
$today = $today.AddHours(-12)
#gets the last time the $file was written in a DateTime Format
$lastWriteTime = (Get-Item $File).LastWriteTime
#If $File doesn't exist we will loop indefinetely until it does exist.
# also loops until the $File that exists was written to in the last twelve hours
while((!(Test-Path $File)) -or ($lastWriteTime -lt $today))
{
#if a file exists then the write time is wrong so update it
if (Test-Path $File)
{
$lastWriteTime = (Get-Item $File).LastWriteTime
}
#Sleep for 5 minutes
$time = Get-Date
Write-Host "Sleep" $time
Start-Sleep -s 300;
}
<init-param>
will be used if you want to initialize some parameter for a particular servlet. When request come to servlet first its init
method will be called then doGet/doPost
whereas if you want to initialize some variable for whole application you will need to use <context-param>
. Every servlet will have access to the context variable.
To translate your *nix style command script to windows/command batch style it would go like this:
SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"
mkdir on windows doens't have a -p parameter : from the MKDIR /? help:
MKDIR creates any intermediate directories in the path, if needed.
which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide
There are essentially two problems to solve when dealing with
environment variables in OS X. The first is when invoking programs
from Spotlight (the magnifying glass icon on the right side of the Mac
menu/status bar) and the second when invoking programs from the Dock.
Invoking programs from a Terminal application/utility is trivial
because it reads the environment from the standard shell locations
(~/.profile
, ~/.bash_profile
, ~/.bashrc
, etc.)
When invoking programs from the Dock, use ~/.MacOSX/environment.plist
where the <dict>
element contains a sequence of
<key>KEY</key><string>theValue</string>
elements.
When invoking programs from Spotlight, ensure that launchd has been setup with all the key/value settings you require.
To solve both problems simultaneously, I use a login item (set via the
System Preferences tool) on my User account. The login item is a bash script that
invokes an Emacs lisp function although one can of course use their
favorite scripting tool to accomplish the same thing. This approach
has the added benefit that it works at any time and does not require a
reboot, i.e. one can edit ~/.profile
, run the login item in some shell and have the changes visible for newly invoked programs, from either the Dock or Spotlight.
Details:
Login item: ~/bin/macosx-startup
#!/bin/bash
bash -l -c "/Applications/Emacs.app/Contents/MacOS/Emacs --batch -l ~/lib/emacs/elisp/macosx/environment-support.el -f generate-environment"
Emacs lisp function: ~/lib/emacs/elisp/macosx/envionment-support.el
;;; Provide support for the environment on Mac OS X
(defun generate-environment ()
"Dump the current environment into the ~/.MacOSX/environment.plist file."
;; The system environment is found in the global variable:
;; 'initial-environment' as a list of "KEY=VALUE" pairs.
(let ((list initial-environment)
pair start command key value)
;; clear out the current environment settings
(find-file "~/.MacOSX/environment.plist")
(goto-char (point-min))
(setq start (search-forward "<dict>\n"))
(search-forward "</dict>")
(beginning-of-line)
(delete-region start (point))
(while list
(setq pair (split-string (car list) "=")
list (cdr list))
(setq key (nth 0 pair)
value (nth 1 pair))
(insert " <key>" key "</key>\n")
(insert " <string>" value "</string>\n")
;; Enable this variable in launchd
(setq command (format "launchctl setenv %s \"%s\"" key value))
(shell-command command))
;; Save the buffer.
(save-buffer)))
NOTE: This solution is an amalgam of those coming before I added mine, particularly that offered by Matt Curtis, but I have deliberately tried to keep my ~/.bash_profile
content platform independent and put the setting of the launchd
environment (a Mac only facility) into a separate script.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
src={"/images/resto.png"}
Using of src attribute in this way means, your image will be loaded from the absolute path "/images/resto.png" for your site. Images directory should be located at the root of your site. Example: http://www.example.com/images/resto.png
var data = [
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
];
for(var i = 0, len = data.length; i < length; i++) {
var temp = '<tr><td>' + data[i].id + '</td>';
temp+= '<td>' + data[i].name+ '</td>';
temp+= '<td>' + data[i].category + '</td>';
temp+= '<td>' + data[i].color + '</td></tr>';
$('table tbody').append(temp));
}
To be explicit, you can also use --local
to use current repository config file:
git config --local user.name "John Doe"
Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:
I had this problem myself. Most of the information I could find online was related to people having this problem with an ASP.NET web application. I was creating a Win Forms stand alone app so most of the advice wasn't helpful for me.
Turns out that the problem was that my project was set to use the ".NET 4 Framework Client Profile" as the target framework and the System.Web.Extensions reference was not in the list for adding. I changed the target to ".NET 4 Framework" and then the reference was available by the normal methods.
Here is what worked for me step by step:
After reading all these answers here in order to symbolicate a crash log (and finally succeeding) I think there are some points missing here that are really important in order to determine why the invocation of symbolicatecrash does not produce a symbolicated output.
There are 3 assets that have to fit together when symbolicating a crash log:
example.crash
), either exported from XCode's organizer or received from iTunes Connect..app
package (i.e. example.app
) that itself contains the app binary belonging to the crash log. If you have an .ipa
package (i.e. example.ipa
) then you can extract the .app
package by unzipping the .ipa
package (i.e. unzip example.ipa
). Afterwards the .app
package resides in the extracted Payload/
folder..dSYM
package containing the debug symbols (i.e. example.app.dSYM
)Before starting symbolication you should check if all those artifacts match, which means that the crash log belongs to the binary you have and that the debug symbols are the ones produced during the build of that binary.
Each binary is referred by a UUID that can be seen in the crash log file:
...
Binary Images:
0xe1000 - 0x1f0fff +example armv7 <aa5e633efda8346cab92b01320043dc3> /var/mobile/Applications/9FB5D11F-42C0-42CA-A336-4B99FF97708F/example.app/example
0x2febf000 - 0x2fedffff dyld armv7s <4047d926f58e36b98da92ab7a93a8aaf> /usr/lib/dyld
...
In this extract the crash log belongs to an app binary image named example.app/example with UUID aa5e633efda8346cab92b01320043dc3
.
You can check the UUID of the binary package you have with dwarfdump:
dwarfdump --uuid example.app/example
UUID: AA5E633E-FDA8-346C-AB92-B01320043DC3 (armv7) example.app/example
Afterwards you should check if the debug symbols you have also belong to that binary:
dwarfdump --uuid example.app.dSYM
UUID: AA5E633E-FDA8-346C-AB92-B01320043DC3 (armv7) example.app.dSYM/Contents/Resources/DWARF/example
In this example all assets fit together and you should be able to symbolicate your stacktrace.
Proceeding to the symbolicatecrash
script:
In Xcode 8.3 you should be able to invoke the script via
/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash -v example.crash 2> symbolicate.log
If it is not there you may run a find . -name symbolicatecrash
in your Xcode.app directory to find it.
As you can see there are no more parameters given. So the script has to find your application binary and debug symbols by running a spotlight search. It searches the debug symbols with a specific index called com_apple_xcode_dsym_uuids
. You can do this search yourself:
mdfind 'com_apple_xcode_dsym_uuids = *'
resp.
mdfind "com_apple_xcode_dsym_uuids == AA5E633E-FDA8-346C-AB92-B01320043DC3"
The first spotlight invocation gives you all indexed dSYM packages and the second one gives you the .dSYM
packages with a specific UUID. If spotlight does not find your .dSYM
package then symbolicatecrash
will neither. If you do all this stuff e.g. in a subfolder of your ~/Desktop
spotlight should be able to find everything.
If symbolicatecrash
finds your .dSYM
package there should be a line like the following in symbolicate.log
:
@dsym_paths = ( <SOME_PATH>/example.app.dSYM/Contents/Resources/DWARF/example )
For finding your .app
package a spotlight search like the following is invoked by symbolicatecrash
:
mdfind "kMDItemContentType == com.apple.application-bundle && (kMDItemAlternateNames == 'example.app' || kMDItemDisplayName == 'example' || kMDItemDisplayName == 'example.app')"
If symbolicatecrash
finds your .app
package there should be the following extract in symbolicate.log
:
Number of symbols in <SOME_PATH>/example.app/example: 2209 + 19675 = 21884
Found executable <SOME_PATH>/example.app/example
-- MATCH
If all those resources are found by symbolicatecrash
it should print out the symbolicated version of your crash log.
If not you can pass in your dSYM and .app files directly.
symbolicatecrash -v --dsym <SOME_PATH>/<App_URI>.app.dSYM/<APP_NAME>.app.dsym <CRASHFILE> <SOME_OTHER_PATH>/<APP_NAME>.app/<APP_NAME> > symbolicate.log
Note: The symbolicated backtrace will be output to terminal, not symbolicate.log
.
Comments are not an official standard, although some parsers support C++-style comments. One that I use is JsonCpp. In the examples there is this one:
// Configuration options
{
// Default encoding for text
"encoding" : "UTF-8",
// Plug-ins loaded at start-up
"plug-ins" : [
"python",
"c++",
"ruby"
],
// Tab indent size
"indent" : { "length" : 3, "use_space": true }
}
jsonlint does not validate this. So comments are a parser specific extension and not standard.
Another parser is JSON5.
An alternative to JSON TOML.
A further alternative is jsonc.
The latest version of nlohmann/json has optional support for ignoring comments on parsing.
Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.
Figured it out.
Put a new column to the left of column1 and copy+paste the following formula
=B2=B3
=B3=B4
=B4=B5
... all the way to the bottom (assume column B here is column1 in the original question).
This formula evaluates whether or not the next row is a new value in column1. Deopending on the result, you will have TRUE or FALSE. Copy and Paste these results as values and then swap "FALSE" for nil and "TRUE" for 0.5
Then add that column full of only 0.5's to the column1 which will yield the following table:
newcolumn0 | column1 ("B") | column2 | column3
-----------------------------------------------------
| 1 | small | blue
| 1 | small | orange
1.5 | 1 | small | yellow
| 2 | med | yellow
2.5 | 2 | med | blue
3.5 | 3 | large | green
| 4 | large | green
4.5 | 4 | small | pink
Lastly, copy and paste the values from newcolumn0 right below the values in column1 and then sort the table by column1 and you should have a blank row in between each distinct whole number in column1, with the table something like this:
newcolumn0 | column1 ("B") | column2 | column3
---------------------------------------------------------------
| 1 | small | blue
| 1 | small | orange
1.5 | 1.5 | |
| 1 | small | yellow
| 2 | med | yellow
| 2 | med | blue
2.5 | 2.5 | |
| 3 | large | green
3.5 | 3.5 | |
| 4 | large | green
| 4 | small | pink
4.5 | 4.5 | |
=IF(B3=B2,A2,A2+1)
and copy+paste this formula for the rest of column 2It's simple. Do this, in your Manifest
file.
<activity
android:name="Your app name"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.
If you want to understand more deeply, you can head over to the source below:-
The following code is perfectly fine and the right way (most exact, concise, and clear) to check if an object is null
:
object obj = null;
//...
if (obj == null)
{
// Do something
}
String.IsNullOrEmpty
is a method existing for convenience so that you don't have to write the comparison code yourself:
private bool IsNullOrEmpty(string input)
{
return input == null || input == string.Empty;
}
Additionally, there is a String.IsNullOrWhiteSpace
method checking for null
and whitespace characters, such as spaces, tabs etc.
Shallow copy:
Some members of the copy may reference the same objects as the original:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(copy.pi)
{ }
};
Here, the pi
member of the original and copied X
object will both point to the same int
.
Deep copy:
All members of the original are cloned (recursively, if necessary). There are no shared objects:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(new int(*copy.pi)) // <-- note this line in particular!
{ }
};
Here, the pi
member of the original and copied X
object will point to different int
objects, but both of these have the same value.
The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.
Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.
Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:
The implicitly defined copy constructor for class
X
performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.
The page to do this is at https://developers.facebook.com/tools/debug/ and has changed slightly since some of the other answers.
Paste your URL in there and hit "Debug". Then hit the "Fetch new scrape information" button under the URL text field and you should be all set. It'll pull the fresh meta tags from your page, but they'll still cache so keep in mind you'll need to do this whenever you change them. This is really critical if you are playing with the meta tags to get FB Shared URLs to format the way you want them to inside of facebook.
Below is an example of multiple figures that I used recently in Latex. You need to call these packages
\usepackage{graphicx}
\usepackage{subfig})
\begin{figure}[H]%
\centering
\subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%
\subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%
\subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
\hfill
\subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%
\subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%
\caption{Multiple figures in latex.}%
\label{fig:MFL}%
\end{figure}
It's good to know that
but also know that
math.log
takes an optional second argument which allows you to specify the base:
In [22]: import math
In [23]: math.log?
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form: <built-in function log>
Namespace: Interactive
Docstring:
log(x[, base]) -> the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
In [25]: math.log(8,2)
Out[25]: 3.0
Yes this is good. Tutorials are not always consize and neat. Not only that, creating local variables is waste of space and inefficient
This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.
For Windows
I had the same problem, I tried to reinstall and didn't worked for me.
Remove "C:\Program Files(x86)\nodejs"
from your system enviorment PATH
and thats it!
If you don't want to display popup for all event you can add conditions like
window.onbeforeunload = confirmExit;
function confirmExit() {
if (isAnyTaskInProgress) {
return "Some task is in progress. Are you sure, you want to close?";
}
}
This works fine for me
These guys have an API that will give the results. It's also free to use.
Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.
Use typeof(Book).GetProperties()
to get an array of PropertyInfo
instances. Then use GetCustomAttributes()
on each PropertyInfo
to see if any of them have the Author
Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.
Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):
public static Dictionary<string, string> GetAuthors()
{
Dictionary<string, string> _dict = new Dictionary<string, string>();
PropertyInfo[] props = typeof(Book).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
AuthorAttribute authAttr = attr as AuthorAttribute;
if (authAttr != null)
{
string propName = prop.Name;
string auth = authAttr.Name;
_dict.Add(propName, auth);
}
}
}
return _dict;
}
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
Yes, when you invoke e.extractAll(foo)
, Python munges that into extractAll(e, foo)
.
From http://docs.python.org/tutorial/classes.html
the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
Emphasis added.
ExecuteNonQuery():
ExecuteReader():
ExecuteScalar():
Reference URL:
http://nareshkamuni.blogspot.in/2012/05/what-is-difference-between.html
I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception x
and y
, but not when they mean row and column (sometimes respectively)).
public static int intValue(long value) {
int valueInt = (int)value;
if (valueInt != value) {
throw new IllegalArgumentException(
"The long value "+value+" is not within range of the int type"
);
}
return valueInt;
}
However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases IllegalArgumentException
is almost certainly the wrong exception to be throwing as far as client code is concerned.
you can use the left_on and right_on options as follows:
pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)
pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')
This can be done by using a pointer, and allocating memory on the heap using malloc
.
Note that there is no way to later ask how big that memory block is. You have to keep track of the array size yourself.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
/* declare a pointer do an integer */
int *data;
/* we also have to keep track of how big our array is - I use 50 as an example*/
const int datacount = 50;
data = malloc(sizeof(int) * datacount); /* allocate memory for 50 int's */
if (!data) { /* If data == 0 after the call to malloc, allocation failed for some reason */
perror("Error allocating memory");
abort();
}
/* at this point, we know that data points to a valid block of memory.
Remember, however, that this memory is not initialized in any way -- it contains garbage.
Let's start by clearing it. */
memset(data, 0, sizeof(int)*datacount);
/* now our array contains all zeroes. */
data[0] = 1;
data[2] = 15;
data[49] = 66; /* the last element in our array, since we start counting from 0 */
/* Loop through the array, printing out the values (mostly zeroes, but even so) */
for(int i = 0; i < datacount; ++i) {
printf("Element %d: %d\n", i, data[i]);
}
}
That's it. What follows is a more involved explanation of why this works :)
I don't know how well you know C pointers, but array access in C (like array[2]
) is actually a shorthand for accessing memory via a pointer. To access the memory pointed to by data
, you write *data
. This is known as dereferencing the pointer. Since data
is of type int *
, then *data
is of type int
. Now to an important piece of information: (data + 2)
means "add the byte size of 2 ints to the adress pointed to by data
".
An array in C is just a sequence of values in adjacent memory. array[1]
is just next to array[0]
. So when we allocate a big block of memory and want to use it as an array, we need an easy way of getting the direct adress to every element inside. Luckily, C lets us use the array notation on pointers as well. data[0]
means the same thing as *(data+0)
, namely "access the memory pointed to by data
". data[2]
means *(data+2)
, and accesses the third int
in the memory block.
Edit
This answer is now deprecated. See the answer by apsillers.
Since this is for a Chrome extension, you might as well use the standard DOM event - DOMSubtreeModified
. See the support for this event across browsers. It has been supported in Chrome since 1.0.
$("#someDiv").bind("DOMSubtreeModified", function() {
alert("tree changed");
});
See a working example here.
This is v. easy, have been doing work on this for the past few weeks.
You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.
Open the terminal, and run this command:
java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg
That should output a JPEG of the SVG file. Really easy. You can even just place it in a loop and convert loads of SVGs,
import os
svgs = ('test1.svg', 'test2.svg', 'etc.svg')
for svg in svgs:
os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg')
A C++14 version of the answer provided by R. Martinho Fernandes would be:
#include <type_traits>
template <typename E>
constexpr auto to_underlying(E e) noexcept
{
return static_cast<std::underlying_type_t<E>>(e);
}
As with the previous answer, this will work with any kind of enum and underlying type. I have added the noexcept
keyword as it will never throw an exception.
Update
This also appears in Effective Modern C++ by Scott Meyers. See item 10 (it is detailed in the final pages of the item within my copy of the book).
In case someone else runs accross this and wants to just disable all path variable changing for all users.
Access your sudoers file by using the command:visudo
. You should see the following line somewhere:
Defaults env_reset
which you should add the following on the next line
Defaults !secure_path
secure_path is enabled by default. This option specifies what to make $PATH when sudoing. The exclamation mark disables the feature.
I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.
eg: http://[email protected]/myresource/myid
This way it can also be passed as headers with basic-auth.
According to uber-JAR Documentation Approaches: There are three common methods for constructing an uber-JAR:
Unshaded Unpack all JAR files, then repack them into a single JAR. Tools: Maven Assembly Plugin, Classworlds Uberjar
Shaded Same as unshaded, but rename (i.e., "shade") all packages of all dependencies. Tools: Maven Shade Plugin
JAR of JARs The final JAR file contains the other JAR files embedded within. Tools: Eclipse JAR File Exporter, One-JAR.
The settings are changed for PyCharm 5+.
Go to File > Invalidate caches/restart and click Invalidate and Restart to apply changes and restart PyCharm.
TextWatcher maritalStatusTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
try {
if (charSequence.length()==0){
topMaritalStatus.setVisibility(View.GONE);
}else{
topMaritalStatus.setVisibility(View.VISIBLE);
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
};
What about using ideviceinfo to get these values? Should be able to install it using brew install ideviceinfo
Then run:
PRODUCT_NAME=$(ideviceinfo --udid $DEVICE_UDID --key ProductName)
PRODUCT_TYPE=$(ideviceinfo --udid $DEVICE_UDID --key ProductType)
PRODUCT_VERSION=$(ideviceinfo --udid $DEVICE_UDID --key ProductVersion)