Set the following CSS properties to the image:
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
You could use feature detection to see if browser is IE10 or greater like so:
var isIE = false;
if (window.navigator.msPointerEnabled) {
isIE = true;
}
Only true if > IE9
Since Service
is a Context
, the variable context must be this
:
DataBaseManager dbm = Utils.getDataManager(this);
For Kotlin developers
(activity as YourActivityClassName).methodName()
For Java developers
((YourActivityClassName) getActivity()).methodName();
Example for postgres:
string sql = "SELECT * FROM SomeTable WHERE id = ANY(@ids)"
var results = conn.Query(sql, new { ids = new[] { 1, 2, 3, 4, 5 }});
Yes. But place your "test" after the comma if you want the column...
> A <- matrix(sample(1:12,12,T),ncol=4)
> rownames(A) <- letters[1:3]
> colnames(A) <- letters[11:14]
> A[,"l"]
a b c
6 10 1
see also help(Extract)
If you look in the source code of the JDK, you can see that for unix systems the property is read at compile time from the paths.h or hard coded. For windows the function GetTempPathW
from win32 returns the tmpdir
name.
For posix systems you might expect the standard TMPDIR
to work, but that is not the case. You can confirm that TMPDIR
is not used by running TMPDIR=/mytmp java -XshowSettings
Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.
I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.
EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/
Swing has no idea what the preferred, minimum and maximum sizes of the GoBoard should be as you have no components inside of it for it to calculate based on, so it picks a (probably wrong) default. Since you are doing custom drawing here, you should implement these methods
Dimension getPreferredSize()
Dimension getMinumumSize()
Dimension getMaximumSize()
or conversely, call the setters for these methods.
That's because you should pass a function, not a string:
function funcName() {
alert("test");
}
setInterval(funcName, 10000);
Your code has two problems:
var func = funcName();
calls the function immediately and assigns the return value."func"
is invalid even if you use the bad and deprecated eval-like syntax of setInterval. It would be setInterval("func()", 10000)
to call the function eval-like.Try this:
SCRIPT:
function winOpen()
{
window.open("yourpage.jsp");
}
HTML:
<a href="javascript:;" onclick="winOpen()">Pop Up</a>
Read https://developer.mozilla.org/en/docs/DOM/window.open for window.open
Just for another possibility to check, I came up with exactly the same problem with an incorrect port number specified in connect URL. I created a new oracle11g instance and forgot to kill the former one occupying the same port 1521, so the new instance automatically started on port 1522. Editing port number solved my problem.
A lower-specificity approach that works in most modern browsers (IE11+, and excluding some mobile Opera & IE browsers -- http://caniuse.com/#feat=pointer-events):
.btn {
/* base styles */
}
.btn[disabled]
opacity: 0.4;
cursor: default;
pointer-events: none;
}
.btn:hover {
color: red;
}
The pointer-events: none
rule will disable hover; you won't need to raise specificity with a .btn[disabled]:hover
selector to nullify the hover style.
(FYI, this is the simple HTML pointer-events, not the contentious abstracting-input-devices pointer-events)
Thanks for the pointers.
I don't know, whether this is the best approach to the problem or not, but here is how I got it to work. I referenced the Microsoft XML, v2.6 dll in my VBA, and then the following code snippet, gives me the required values
Dim objXML As MSXML2.DOMDocument
Set objXML = New MSXML2.DOMDocument
If Not objXML.loadXML(strXML) Then 'strXML is the string with XML'
Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason
End If
Dim point As IXMLDOMNode
Set point = objXML.firstChild
Debug.Print point.selectSingleNode("X").Text
Debug.Print point.selectSingleNode("Y").Text
Try EPPlus if you use Excel 2007. Supports ranges, cellstyling, charts, shapes, pictures and a lot of other stuff
The filename looks like a temporary table created by a query in MySQL. These files are often very short-lived, they're created during one specific query and cleaned up immediately afterwards.
Yet they can get very large, depending on the amount of data the query needs to process in a temp table. Or you may have multiple concurrent queries creating temp tables, and if enough of these queries run at the same time, they can exhaust disk space.
I do MySQL consulting, and I helped a customer who had intermittent disk full errors on his root partition, even though every time he looked, he had about 6GB free. After we examined his query logs, we discovered that he sometimes had four or more queries running concurrently, each creating a 1.5GB temp table in /tmp, which was on his root partition. Boom!
Solutions I gave him:
Increase the MySQL config variables tmp_table_size
and max_heap_table_size
so MySQL can create really large temp tables in memory. But it's not a good idea to allow MySQL to create 1.5GB temp tables in memory, because there's no way to limit how many of these are created concurrently. You can exhaust your memory pretty quickly this way.
Set the MySQL config variable tmpdir
to a directory on another disk partition with more space.
Figure out which of your queries is creating such big temp tables, and optimize the query. For example, use indexes to help that query reduce its scan to a smaller slice of the table. Or else archive some of the data in the tale so the query doesn't have so many rows to scan.
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)
My $.02
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options): https://jsfiddle.net/59x3m6op/1/
If you want a formula to do it then:
=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)
This will do it. Change `"WORD" To the word you want.
json_decode()
will return an object or array if second value it's true:
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
I got this line from Cool
Press Ctrl + Shift + P to open the Command Palette, then write command : Toggle Menu Bar
You can use absolute imports:
/root
/app
/config
config.py
/source
file.ipynb
# In the file.ipynb importing the config.py file
from root.app.config import config
Just include this line at the end of function and the Problem is solved easily!
document.getElementById("btnsubmit").value = "";
Well, if you are using Dojo Toolkit, it gives us a direct way to encode or decode into Base64.
Try this:
To encode an array of bytes using dojox.encoding.base64:
var str = dojox.encoding.base64.encode(myByteArray);
To decode a Base64-encoded string:
var bytes = dojox.encoding.base64.decode(str);
Excel has a very powerful feature providing for a dropdown select list in a cell, reflecting data from a named region. It'a a very easy configuration, once you have done it before. Two steps are to follow:
Create a named region,
Setup the dropdown in a cell.
There is a detailed explanation of the process HERE.
You should set android:button="@null"
instead of "null"
.
You were soo close!
I have had a lot of difficulty with this as I have a custom spinner, if I setBackground then the Drawable would stretch. My solution to this was to add a drawable to the right of the Spinner TextView. Heres a code snippet from my Custom Spinner. The trick is to Override getView and customize the Textview as you wish.
public class NoTextSpinnerArrayAdapter extends ArrayAdapter<String> {
private String text = "0";
public NoTextSpinnerArrayAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
}
public void updateText(String text){
this.text = text;
notifyDataSetChanged();
}
public String getText(){
return text;
}
@NonNull
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = view.findViewById(android.R.id.text1);
textView.setCompoundDrawablePadding(16);
textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_menu_white_24dp, 0);
textView.setGravity(Gravity.END);
textView.setText(text);
return view;
}
}
You also need to set the Spinner background to transparent:
<lifeunlocked.valueinvestingcheatsheet.views.SelectAgainSpinner
android:id="@+id/saved_tickers_spinner"
android:background="@android:color/transparent"
android:layout_width="60dp"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="248dp"
tools:layout_editor_absoluteY="16dp" />
and my custom spinner if you want it....
public class SelectAgainSpinner extends android.support.v7.widget.AppCompatSpinner {
public SelectAgainSpinner(Context context) {
super(context);
}
public SelectAgainSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SelectAgainSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setPopupBackgroundDrawable(Drawable background) {
super.setPopupBackgroundDrawable(background);
}
@Override
public void setSelection(int position, boolean animate) {
boolean sameSelected = position == getSelectedItemPosition();
super.setSelection(position, animate);
if (sameSelected) {
// Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
if (getOnItemSelectedListener() != null) {
getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
}
}
}
@Override
public void setSelection(int position) {
boolean sameSelected = position == getSelectedItemPosition();
super.setSelection(position);
if (sameSelected) {
// Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
if (getOnItemSelectedListener() != null) {
getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
}
}
}
}
Assuming your my.jar has a class1 and class2 with a main defined in each, you can just call java like this:
java my.jar class1
java my.jar class2
If you need to specify other options to java just make sure they are before the my.jar
java -classpath my.jar class1
Can I use (http://caniuse.com/#feat=datauri) shows support across the major browsers with few issues on IE.
In here if there any row affect with new insertion Then it will update on different table in the database.
DELIMITER $$
CREATE TRIGGER "give trigger name" AFTER INSERT ON "table name"
FOR EACH ROW
BEGIN
INSERT INTO "give table name you want to add the new insertion on previously given table" (id,name,age) VALUES (10,"sumith",24);
END;
$$
DELIMITER ;
You can also use the java.util.Scanner class.
private static void readFileWithScanner() {
File file = new File("path/to/your/file/file.txt");
Scanner scan = null;
try {
scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] lineArray = line.split(",");
// do something with lineArray, such as instantiate an object
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scan.close();
}
}
The difference is that, for example, a
List<HashMap<String,String>>
is a
List<? extends Map<String,String>>
but not a
List<Map<String,String>>
So:
void withWilds( List<? extends Map<String,String>> foo ){}
void noWilds( List<Map<String,String>> foo ){}
void main( String[] args ){
List<HashMap<String,String>> myMap;
withWilds( myMap ); // Works
noWilds( myMap ); // Compiler error
}
You would think a List
of HashMap
s should be a List
of Map
s, but there's a good reason why it isn't:
Suppose you could do:
List<HashMap<String,String>> hashMaps = new ArrayList<HashMap<String,String>>();
List<Map<String,String>> maps = hashMaps; // Won't compile,
// but imagine that it could
Map<String,String> aMap = Collections.singletonMap("foo","bar"); // Not a HashMap
maps.add( aMap ); // Perfectly legal (adding a Map to a List of Maps)
// But maps and hashMaps are the same object, so this should be the same as
hashMaps.add( aMap ); // Should be illegal (aMap is not a HashMap)
So this is why a List
of HashMap
s shouldn't be a List
of Map
s.
As mentioned here, uou can use matplotlib.pyplot.text
objects in order to achieve the same result:
plt.text(x=0.5, y=0.94, s="My title 1", fontsize=18, ha="center", transform=fig.transFigure)
plt.text(x=0.5, y=0.88, s= "My title 2 in different size", fontsize=12, ha="center", transform=fig.transFigure)
plt.subplots_adjust(top=0.8, wspace=0.3)
function isEmpty(val){
return !val;
}
but this solution is over-engineered, if you dont'want to modify the function later for busines-model needings, then is cleaner to use it directly in code:
if(!val)...
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
In Kotlin, using coroutines you can do the following:
CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
tv.append("Hello World")
}
}
Try it out here!
Check if it's on first. That should get rid of the warning and it'll ensure that if your code is run on older versions of PHP that magic quotes are indeed off.
Don't just remove that line of code as suggested by others unless you can be 100% sure that the code will never be run on anything before PHP 5.3.
<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
// Deactivate
set_magic_quotes_runtime(false);
}
?>
get_magic_quotes_runtime
is NOT deprecated in PHP 5.3.
Source: http://us2.php.net/get_magic_quotes_runtime/
Use strtotime(..)
:
$timestamp = strtotime($mysqltime);
echo date("Y-m-d H:i:s", $timestamp);
Also check this out (to do it in MySQL way.)
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
This prints out all the object contents recursively in json or yaml indented format:
import jsonpickle # pip install jsonpickle
import json
import yaml # pip install pyyaml
serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional
print json.dumps(json.loads(serialized), indent=4)
print yaml.dump(yaml.load(serialized), indent=4)
Right, printf
could be thought of as a more powerful version of puts
. printf
provides the ability to format variables for output using format specifiers such as %s
, %d
, %lf
, etc...
In order to apply a style on your string, you can use a command like:
echo -e '\033[1mYOUR_STRING\033[0m'
Explanation:
-e
option means that escaped (backslashed) strings will be interpretedThe possible integers are:
Android studio 4.0.1 Kotlin 1.3.72
Android Navigation architecture component.
The following code works for me:
findNavController().popBackStack()
I handle it in the following way:
<html>
<body>
<form method="post" action="/">
<input type="submit" value="Encrypt" name="Encrypt"/>
<input type="submit" value="Decrypt" name="Decrypt" />
</form>
</body>
</html>
Python Code :
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def index():
print(request.method)
if request.method == 'POST':
if request.form.get('Encrypt') == 'Encrypt':
# pass
print("Encrypted")
elif request.form.get('Decrypt') == 'Decrypt':
# pass # do something else
print("Decrypted")
else:
# pass # unknown
return render_template("index.html")
elif request.method == 'GET':
# return render_template("index.html")
print("No Post Back Call")
return render_template("index.html")
if __name__ == '__main__':
app.run()
How are you generating your data?
See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)
look ?
Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float)
.
You can also call frame.astype(float)
You don't have to serialize the body yourself. Just do
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body
If you just want POST params instead (which would still map to your model and is a lot more efficient since there's no serialization to JSON) do this:
request.AddParameter("A", "foo");
request.AddParameter("B", "bar");
This might help. No JQuery needed
<a href="../some-relative-link/file"
onclick="this.href = 'https://docs.google.com/viewer?url='+this.href; this.onclick = '';"
target="_blank">
This code does the following: Pass the relative link to Google Docs Viewer
this.href
So in your case this might work:
<a href="../some-relative-link/file"
onclick="this.href = 'javascript:'+console.log('something has stopped the link'); "
target="_blank">
I'm using Sublime portable version (for Windows) and this (placing the mousemap in SublimeText\Packages\User
folder) did not work for me.
I had to place the mousemap file in SublimeText\Data\Packages\User
folder to get it to work where SublimeText
is the installation directory for my portable version. Data\Packages\User
is where I found the keymap file as well.
What I need is a function which prints an object (obj), but only if global variable verbose is true, else it does nothing.
I want to be able to change the global parameter "verbose" at any time. Simplicity and readability to me are of paramount importance. So I would proceed as the following lines indicate:
ak@HP2000:~$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> verbose = True
>>> def vprint(obj):
... if verbose:
... print(obj)
... return
...
>>> vprint('Norm and I')
Norm and I
>>> verbose = False
>>> vprint('I and Norm')
>>>
Global variable "verbose" can be set from the parameter list, too.
Check out the java.net.URI class.
$epoch = 1483228800;
$dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00
In the examples above "r" and "Y-m-d H:i:s" are PHP date formats, other examples:
r ----- Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c ----- 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y ----- Mar/15/2017
d-m-Y ----- 15-03-2017
Y-m-d H:i:s ----- 2017-03-15 12:00:00
here is a better answer found through Git docs.
This shows what the heroku remote is:
$ git remote get-url heroku
Found it here: https://git-scm.com/docs/git-remote Also in that document is a set-url, if you need to change it.
I wanted to put
cell.backgroundColor = UIColor.colorWithRed(125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0)
but that didn't work.
So I used:
For Swift
cell.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
So this is the workaround that I found.
The idiom designed into the C language (and inherited into C++) for infinite looping is for(;;)
: the omission of a test form. The do/while
and while
loops do not have this special feature; their test expressions are mandatory.
for(;;)
does not express "loop while some condition is true that happens to always be true". It expresses "loop endlessly". No superfluous condition is present.
Therefore, the for(;;)
construct is the canonical endless loop. This is a fact.
All that is left to opinion is whether or not to write the canonical endless loop, or to choose something baroque which involves extra identifiers and constants, to build a superfluous expression.
Even if the test expression of while
were optional, which it isn't, while();
would be strange. while
what? By contrast, the answer to the question for
what? is: why, ever---for ever! As a joke some programmers of days past have defined blank macros, so they could write for(ev;e;r);
.
while(true)
is superior to while(1)
because at least it doesn't involve the kludge that 1 represents truth. However, while(true)
didn't enter into C until C99. for(;;)
exists in every version of C going back to the language described in the 1978 book K&R1, and in every dialect of C++, and even related languages. If you're coding in a code base written in C90, you have to define your own true
for while (true)
.
while(true)
reads badly. While what is true? We don't really want to see the identifier true
in code, except when we are initializing boolean variables or assigning to them. true
need not ever appear in conditional tests. Good coding style avoids cruft like this:
if (condition == true) ...
in favor of:
if (condition) ...
For this reason while (0 == 0)
is superior to while (true)
: it uses an actual condition that tests something, which turns into a sentence: "loop while zero is equal to zero." We need a predicate to go nicely with "while"; the word "true" isn't a predicate, but the relational operator ==
is.
I wrote this simple helper:
Handlebars.registerHelper('conditions', function (options) {
var data = this;
data.__check_conditions = true;
return options.fn(this);
});
Handlebars.registerHelper('next', function(conditional, options) {
if(conditional && this.__check_conditions) {
this.__check_conditions = false;
return options.fn(this);
} else {
return options.inverse(this);
}
});
It's something like Chain Of Responsibility pattern in Handlebars
Example:
{{#conditions}}
{{#next condition1}}
Hello 1!!!
{{/next}}
{{#next condition2}}
Hello 2!!!
{{/next}}
{{#next condition3}}
Hello 3!!!
{{/next}}
{{#next condition4}}
Hello 4!!!
{{/next}}
{{/conditions}}
It's not a else if but in some cases it may help you)
I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.
In a php section before the HTML section, use sprinf() to create a constant string from the variables:
$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");
Then in the HTML section you can do whatever you like, such as:
<p>$mystuff</p>
One more important difference: typedef
s cannot be forward declared. So for the typedef
option you must #include
the file containing the typedef
, meaning everything that #include
s your .h
also includes that file whether it directly needs it or not, and so on. It can definitely impact your build times on larger projects.
Without the typedef
, in some cases you can just add a forward declaration of struct Foo;
at the top of your .h
file, and only #include
the struct definition in your .cpp
file.
Potential library: https://pypi.org/project/stringcase/
Example:
import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"
Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)
You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:
NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];
states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
states_list = states.split (' ')
As usual, VBScript is available for you to use.....
Set objFS = CreateObject("Scripting.FileSystemObject")
Set wshArgs = WScript.Arguments
strFile = wshArgs(0)
WScript.Echo objFS.GetFile(strFile).Size & " bytes"
Save as filesize.vbs
and enter on the command-line:
C:\test>cscript /nologo filesize.vbs file.txt
79 bytes
Use a for
loop (in batch) to get the return result.
function GetCookieValue(name) {
var found = document.cookie.split(';').filter(c => c.trim().split("=")[0] === name);
return found.length > 0 ? found[0].split("=")[1] : null;
}
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).
By default, imshow
sets the aspect of the plot to 1, as this is often what people want for image data.
In your case, you can do something like:
import matplotlib.pyplot as plt
import numpy as np
grid = np.random.random((10,10))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))
ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')
ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')
ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')
plt.tight_layout()
plt.show()
The way without re-inserting all entries into the new map should be the fastest it won't because HashMap.clone
internally performs rehash as well.
Map<String, Column> newColumnMap = originalColumnMap.clone();
newColumnMap.replaceAll((s, c) -> new Column(c));
Ok, so you've found a solution already. Just wanted to share what has been useful to me so many times;
I have created setpy2
alias which helps me switch python.
alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"
Execute setpy2
before you run npm install
. The switch stays in effect until you quit the terminal, afterwards python
is set back to system default.
You can make use of this technique for any other command/tool as well.
fileExists()
is a method of FileSystemObject
, not a global scope function.
You also have an issue with the delete, DeleteFile()
is also a method of FileSystemObject
.
Furthermore, it seems you are moving the file and then attempting to deal with the overwrite issue, which is out of order. First you must detect the name collision, so you can choose the rename the file or delete the collision first. I am assuming for some reason you want to keep deleting the new files until you get to the last one, which seemed implied in your question.
So you could use the block:
if NOT fso.FileExists(newname) Then
file.move fso.buildpath(OUT_PATH, newname)
else
fso.DeleteFile newname
file.move fso.buildpath(OUT_PATH, newname)
end if
Also be careful that your string comparison with the =
sign is case sensitive. Use strCmp
with vbText
compare option for case insensitive string comparison.
Close nodejs app
running in another shell.
Restart the terminal and run the program again.
Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port
and run the app.
To find the PID of the application that is using port:8000
$ fuser 8000/tcp
8000/tcp: 16708
Here PID is 16708 Now kill the process using the kill [PID]
command
$ kill 16708
If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.
bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config
...then run bundle again.
Note: check the version first using the following.
ls /Applications/Postgres.app/Contents/Versions/
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.
How to call procedure? Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');
i mentioned in the below where i have mentioned the custom filter also , how to call these filter which is having two parameters
countryApp.filter('reverse', function() {
return function(input, uppercase) {
var out = '';
for (var i = 0; i < input.length; i++) {
out = input.charAt(i) + out;
}
if (uppercase) {
out = out.toUpperCase();
}
return out;
}
});
and from the html using the template we can call that filter like below
<h1>{{inputString| reverse:true }}</h1>
here if you see , the first parameter is inputString and second parameter is true which is combined with "reverse' using the : symbol
I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6
Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2()
function is marginally faster than isAlphanumeric()
. One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric() {
for(int i = 0; i < reps; i++)
isAlphanumeric("ab4r3rgf"+i);
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
Like Cheeso said:
You don't need the directory on your path. You could put it on your path, but you don't NEED to do that. If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg:
%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\regasm.exe MyAssembly.dll
You need to populate the empty indexes with nulls.
while (arraylist.size() < position)
{
arraylist.add(null);
}
arraylist.add(position, object);
For those who are having a hard time finding the "merge buttons".
The little lightbulp icon with merge options only shows up if you click precisely on the "merge conflict marker"
<<<<<<<
Steps (in VS Code 1.29.x):
Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.
--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.
--abort Cancel the operation and return to the pre-sequence state.
use help to see the original doc with more details, $ git help cherry-pick
I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.
You can call more than one target goal with maven. mvn clean install
calls clean
first, then install
. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.
clean
removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean
, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).
we call it target in ant and goal in maven
Just came across this question as it was linked in a recent question on SO.
Shameless plug of an answer: Use cSplit
from my "splitstackshape" package:
df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
library(splitstackshape)
cSplit(df, "FOO", "|")
# ID FOO_1 FOO_2
# 1 11 a b
# 2 12 b c
# 3 13 x y
This particular function also handles splitting multiple columns, even if each column has a different delimiter:
df <- data.frame(ID=11:13,
FOO=c('a|b','b|c','x|y'),
BAR = c("A*B", "B*C", "C*D"))
cSplit(df, c("FOO", "BAR"), c("|", "*"))
# ID FOO_1 FOO_2 BAR_1 BAR_2
# 1 11 a b A B
# 2 12 b c B C
# 3 13 x y C D
Essentially, it's a fancy convenience wrapper for using A base R approach could be:read.table(text = some_character_vector, sep = some_sep)
and binding that output to the original data.frame
. In other words, another
df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
cbind(df, read.table(text = as.character(df$FOO), sep = "|"))
ID FOO V1 V2
1 11 a|b a b
2 12 b|c b c
3 13 x|y x y
I found colnames()
argument easier
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/row%2Bcolnames
select some column from the data frame
df <- data.frame(df[, c( "hhid","b1005", "b1012_imp", "b3004a")])
and rename the selected column in order,
colnames(df) <- c("hhid", "income", "cost", "credit")
check the names and the values to be sure
names(df);head(df)
Since the third version of Swift you can do the following:
let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)
simialr to what Sunkas advised.
Data transfer object (DTO) describes “an object that carries data between processes” (Wikipedia) or an “object that is used to encapsulate data, and send it from one subsystem of an application to another” (Stack Overflow answer).
return n
from main
is equivalent to exit(n)
.
The valid returned is the rest of your program. It's meaning is OS dependent. On unix, 0 means normal termination and non-zero indicates that so form of error forced your program to terminate without fulfilling its intended purpose.
It's unusual that your example returns 0 (normal termination) when it seems to have run out of memory.
For those looking to control the space between a dynamic number of columns, try:
<div class="row no-gutters">
<div class="col">
<div class="inner">
<!-- content here -->
</div>
</div>
<div class="col">
<div class="inner">
<!-- content here -->
</div>
</div>
<!-- etc. -->
</div>
CSS:
.col:not(:last-child) .inner {
margin: 2px; // Or whatever you want your spacing to be
}
Since you cannot set value=""
within your first option
, you'll need to create your own rule using the built-in addMethod()
method.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
year: {
selectcheck: true
}
}
});
jQuery.validator.addMethod('selectcheck', function (value) {
return (value != '0');
}, "year required");
});
HTML:
<select name="year">
<option value="0">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
Working Demo: http://jsfiddle.net/tPRNd/
Original Answer: (Only if you can set value=""
within the first option
)
To properly validate a select
element with the jQuery Validate plugin simply requires that the first option
contains value=""
. So remove the 0
from value="0"
and it's fixed.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
year: {
required: true,
}
}
});
});
HTML:
<select name="year">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
Nothing helped me so I downloaded the simulators for my deployment Target.
Download the simulators for your deployment Target
You can check Deployment target :
Hope it helps
Some of the links provided are only settings for Windows 2003's version of "Scheduled Tasks"
In Windows Server 2008 the "Tasks" setup only has a box with options for "5 Minutes, 10 minutes, 15 minutes, 30 mins, and 1 hour" (screen shot: http://i46.tinypic.com/2gwx7r8.jpg)... where the Window 2003 was a "enter whatever number you want" textbox.
I thought doing an "Export" and editing the XML from: PT30M to PT2M
and importing that as a new task would "trick" Tasks into repeating every 2 mins, but it didn't like that
My workaround for getting a task to run every 2 mins in Windows 2008 was to (ugggh) setup 30 different "triggers" for my task repeating every hour but staring at :00, :02, :04, :06 and so on and so on.... took me 8-10 mins to setup but I only had to do it once :-)
Reason for error:
The query from p in dc.BlogPosts where p.BlogPostID == ID select p
returns a sequence.
Single()
tries to retrieve an element from the sequence returned in step1.
As per the exception - The sequence returned in step1 contains no elements.
Single() tries to retrieve an element from the sequence returned in step1 which contains no elements.
Since Single()
is not able to fetch a single element from the sequence returned in step1, it throws an error.
Fix:
Make sure the query (from p in dc.BlogPosts where p.BlogPostID == ID select p)
returns a sequence with at least one element.
TL;DR: Use the utility method Iterables.size(Iterable)
of the great Guava library.
Of your two code snippets, you should use the first one, because the second one will remove all elements from values
, so it is empty afterwards. Changing a data structure for a simple query like its size is very unexpected.
For performance, this depends on your data structure. If it is for example in fact an ArrayList
, removing elements from the beginning (what your second method is doing) is very slow (calculating the size becomes O(n*n) instead of O(n) as it should be).
In general, if there is the chance that values
is actually a Collection
and not only an Iterable
, check this and call size()
in case:
if (values instanceof Collection<?>) {
return ((Collection<?>)values).size();
}
// use Iterator here...
The call to size()
will usually be much faster than counting the number of elements, and this trick is exactly what Iterables.size(Iterable)
of Guava does for you.
After more exploration and testing, it appears that this issue was being caused by debugging the plugin and using breakpoints. SVN/Subclipse apparently didn't like having breakpoints midway through their execution and as a result this lock files were being created. As soon as I started just running the plugin, this issue disappeared.
Simple and not time consuming answer with an example relevant to the question asked Follow this example:
user = [{"name": "Dough", "age": 55},
{"name": "Ben", "age": 44},
{"name": "Citrus", "age": 33},
{"name": "Abdullah", "age":22},
]
print(sorted(user, key=lambda el: el["name"]))
print(sorted(user, key= lambda y: y["age"]))
Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code
print(sorted(user, key=lambda el: el["name"]))
Results to:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Ben', 'age': 44},
{'name': 'Citrus', 'age': 33},
{'name': 'Dough', 'age': 55}]
sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.
The second print code
print(sorted(user, key= lambda y: y["age"]))
Result:
[{'name': 'Abdullah', 'age': 22},
{'name': 'Citrus', 'age': 33},
{'name': 'Ben', 'age': 44},
{'name': 'Dough', 'age': 55}]
sorts by age, and hence the list returns by ascending order of age.
Try this code for better understanding.
Since each registry runs as a container the container ID has an associated log file ID-json.log this log file contains the vars.name=[image] and vars.reference=[tag]. A script can be used to extrapolate and print these. This is perhaps one method to list images pushed to registry V2-2.0.1.
Try changing it to "subdomain -> subdomain.hosttwo.com"
The CNAME
is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the CNAME
alias.
As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?
the above approach didn't work for me on Android Studio 3.0. It still shows the background. I just made an empty background file
<?xml version="1.0" encoding="utf-8"?>
<vector
android:height="108dp"
android:width="108dp"
android:viewportHeight="108"
android:viewportWidth="108"
xmlns:android="http://schemas.android.com/apk/res/android">
</vector>
This worked except the full bleed layers
Submit your tasks into the Runner and then wait calling the method waitTillDone() like this:
Runner runner = Runner.runner(2);
for (DataTable singleTable : uniquePhrases) {
runner.run(new ComputeDTask(singleTable));
}
// blocks until all tasks are finished (or failed)
runner.waitTillDone();
runner.shutdown();
To use it add this gradle/maven dependency: 'com.github.matejtymes:javafixes:1.0'
For more details look here: https://github.com/MatejTymes/JavaFixes or here: http://matejtymes.blogspot.com/2016/04/executor-that-notifies-you-when-task.html
For JDK 1.3 or earlier :
-Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006
For JDK 1.4
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006
For newer JDK :
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6006
Please change the port number based on your needs.
From java technotes
From 5.0 onwards the -agentlib:jdwp option is used to load and specify options to the JDWP agent. For releases prior to 5.0, the -Xdebug and -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the VM rather than the older JVMDI interface)
One more thing to note, from JVM Tool interface documentation:
JVM TI was introduced at JDK 5.0. JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI) which, as of JDK 6, are no longer provided.
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
Go to your project target in Xcode > General > Set "Requires full screen" (under Hide status bar) to true.
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
The includes
(formerly called contains
and include
) method compares objects by reference (or more precisely, with ===
). Because the two object literals of {"b": 2}
in your example represent different instances, they are not equal. Notice:
({"b": 2} === {"b": 2})
> false
However, this will work because there is only one instance of {"b": 2}
:
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
On the other hand, the where
(deprecated in v4) and find
methods compare objects by their properties, so they don't require reference equality. As an alternative to includes
, you might want to try some
(also aliased as any
):
_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true
As already Jon said, a static variable, also referred to as a class variable, is a variable which exists across instances of a class.
I found an example of this here:
public class StaticVariable
{
static int noOfInstances;
StaticVariable()
{
noOfInstances++;
}
public static void main(String[] args)
{
StaticVariable sv1 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
StaticVariable sv2 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
System.out.println("No. of instances for st2 : " + sv2.noOfInstances);
StaticVariable sv3 = new StaticVariable();
System.out.println("No. of instances for sv1 : " + sv1.noOfInstances);
System.out.println("No. of instances for sv2 : " + sv2.noOfInstances);
System.out.println("No. of instances for sv3 : " + sv3.noOfInstances);
}
}
Output of the program is given below:
As we can see in this example each object has its own copy of class variable.
C:\java>java StaticVariable
No. of instances for sv1 : 1
No. of instances for sv1 : 2
No. of instances for st2 : 2
No. of instances for sv1 : 3
No. of instances for sv2 : 3
No. of instances for sv3 : 3
In SQL Server Management Studio Express:
According to the line debug1: Authentications that can continue: publickey,gssapi-with-mic
, ssh password authentication is disabled and apparently you are not using public key authentication.
Login to your server using console and open /etc/ssh/sshd_config
file with an editor with root user and look for line PasswordAuthentication
then set it's value to yes and finally restart sshd service.
Ajax.ActionLink only sends an ajax request to the server. What happens ahead really depends upon type of data returned and what your client side script does with it. You may send a partial view for ajax call or json, xml etc. Ajax.ActionLink however have different callbacks and parameters that allow you to write js code on different events. You can do something before request is sent or onComplete
. similarly you have an onSuccess callback. This is where you put your JS code for manipulating result returned by server. You may simply put it back in UpdateTargetID or you can do fancy stuff with this result using jQuery or some other JS library.
this is php code I used, reply is usually like this:
2 packets transmitted, 2 received, 0% packet loss, time 1089ms
So I used code like this:
$ping_how_many = 2; $ping_result = shell_exec('ping -c '.$ping_how_many.' bing.com'); if( !preg_match('/'.$ping_how_many.' received/',$ping_result) ){ echo 'Bad ping result'. PHP_EOL; // goto next1; }
Even if you install the Oracle JDK, your $JAVA_HOME
variable should refer to the path of the JRE that is inside the JDK root. You can refer to my other answer to a similar question for more details.
.SILENT:
Type " .SILENT: " in the beginning of your script without colons.
Its due to a conflict.
Clear all keys from ssh-agent
ssh-add -d ~/.ssh/id_rsa
ssh-add -d ~/.ssh/github
Add the github ssh key
ssh-add ~/.ssh/github
It should work now.
If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):
mokey 0 /home/jj33 > nslookup example.ad Server: 172.16.2.10 Address: 172.16.2.10#53 Non-authoritative answer: Name: example.ad Address: 172.16.6.2 Name: example.ad Address: 172.16.141.160 Name: example.ad Address: 172.16.7.9 Name: example.ad Address: 172.19.1.14 Name: example.ad Address: 172.19.1.3 Name: example.ad Address: 172.19.1.11 Name: example.ad Address: 172.16.3.2
Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.
I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.
Your variable size
is declared as: float size;
You can't use a floating point variable as the size of an array - it needs to be an integer value.
You could cast it to convert to an integer:
float *temp = new float[(int)size];
Your other problem is likely because you're writing outside of the bounds of the array:
float *temp = new float[size];
//Getting input from the user
for (int x = 1; x <= size; x++){
cout << "Enter temperature " << x << ": ";
// cin >> temp[x];
// This should be:
cin >> temp[x - 1];
}
Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.
You could use the map and reduce functions
const arr = [{x:1},{x:2},{x:4}];
const sum = arr.map(n => n.x).reduce((a, b) => a + b, 0);
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
Set step
attribute to any float number, e.g. 0.01 and you are good to go.
If you're array structure will always be multi-dimensional in that exact fashion, then we can iterate through the elements like such:
$fh = fopen('somefile.csv', 'w') or die('Cannot open the file');
for( $i=0; $i<count($arr); $i++ ){
$str = implode( ',', $arr[$i] );
fwrite( $fh, $str );
fwrite( $fh, "\n" );
}
fclose($fh);
That's one way to do it ... you could do it manually but this way is quicker and easier to understand and read.
Then you would manage your headers something what complex857 is doing to spit out the file. You could then delete the file using unlink() if you no longer needed it, or you could leave it on the server if you wished.
public class Main {
public static void main(String[] args) throws Exception{
int N = 100;
PrintingThread oddNumberThread = new PrintingThread(N - 1);
PrintingThread evenNumberThread = new PrintingThread(N);
oddNumberThread.start();
// make sure that even thread only start after odd thread
while (!evenNumberThread.isAlive()) {
if(oddNumberThread.isAlive()) {
evenNumberThread.start();
} else {
Thread.sleep(100);
}
}
}
}
class PrintingThread extends Thread {
private static final Object object = new Object(); // lock for both threads
final int N;
// N determines whether given thread is even or odd
PrintingThread(int N) {
this.N = N;
}
@Override
public void run() {
synchronized (object) {
int start = N % 2 == 0 ? 2 : 1; // if N is odd start from 1 else start from 0
for (int i = start; i <= N; i = i + 2) {
System.out.println(i);
try {
object.notify(); // will notify waiting thread
object.wait(); // will make current thread wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
CSS
html {
height:100%;
}
body {
min-height:100%; position:relative;
}
.footer {
background-color: rgb(200,200,200);
height: 115px;
position:absolute; bottom:0px;
}
.footer-ghost { height:115px; }
HTML
<div class="header">...</div>
<div class="content">...</div>
<div class="footer"></div>
<div class="footer-ghost"></div>
In my case I used another solution.
As the project doesn't require CommonJS and it must have ES3 compatibility (modules not supported) all you need is just remove all export and import statements from your code, because your tsconfig doesn't contain
"module": "commonjs"
But use import and export statements in your referenced files
import { Utils } from "./utils"
export interface Actions {}
Final generated code will always have(at least for TypeScript 3.0) such lines
"use strict";
exports.__esModule = true;
var utils_1 = require("./utils");
....
utils_1.Utils.doSomething();
Collapse all : CTRL + SHIFT + /
Expand all code blocks : CTRL + *
When the branch is no remote branch you can push your local branch direct to the remote.
git checkout master
git push origin master
or when you have a dev branch
git checkout dev
git push origin dev
or when the remote branch exists
git branch dev -t origin/dev
There are some other posibilites to push a remote branch.
Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.
Use return
statement at end of function to return value.
e.g.:
Return None value.
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Use return statement
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
When you are using GET Method the contract must be this.
[WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<User> Get();
with this we have a json without the boot parameter
Aldo Flores @alduar http://alduar.blogspot.com
From my experience I would advise great caution with using DoEvents in .NET. I experienced some very strange results when using DoEvents in a TabControl containing DataGridViews. On the other hand, if all you're dealing with is a small form with a progress bar then it might be OK.
The bottom line is: if you are going to use DoEvents, then you need to test it thoroughly before deploying your application.
Following code works..
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(0);
}
});
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
day = selectedDay;
month = selectedMonth;
year = selectedYear;
datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
You may pass "true" or "" to the checked property of input checkbox. The empty quotes ("") will be understood as false and the item will be unchecked.
let checked = variable === value ? "true" : "";
<input
className="form-check-input"
type="checkbox"
value={variable}
id={variable}
name={variable}
checked={checked}
/>
<label className="form-check-label">{variable}</label>
This is a quirk of the C grammar. A label (Cleanup:
) is not allowed to appear immediately before a declaration (such as char *str ...;
), only before a statement (printf(...);
). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.
You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:
int main (void)
{
char *str;
printf("Hello ");
goto Cleanup;
Cleanup:
str = "World\n";
printf("%s\n", str);
return 0;
}
If you're looking for an alternative to reflections I'd like to recommend Panda Utilities - AnnotationsScanner. It's a Guava-free (Guava has ~3MB, Panda Utilities has ~200kb) scanner based on the reflections library source code.
It's also dedicated for future-based searches. If you'd like to scan multiple times included sources or even provide an API, which allows someone scanning current classpath, AnnotationsScannerProcess
caches all fetched ClassFiles
, so it's really fast.
Simple example of AnnotationsScanner
usage:
AnnotationsScanner scanner = AnnotationsScanner.createScanner()
.includeSources(ExampleApplication.class)
.build();
AnnotationsScannerProcess process = scanner.createWorker()
.addDefaultProjectFilters("net.dzikoysk")
.fetch();
Set<Class<?>> classes = process.createSelector()
.selectTypesAnnotatedWith(AnnotationTest.class);
Improving on the answer by musiphil, you can write a standard deviation function without the temporary vector diff
, just using a single inner_product
call with the C++11 lambda capabilities:
double stddev(std::vector<double> const & func)
{
double mean = std::accumulate(func.begin(), func.end(), 0.0) / func.size();
double sq_sum = std::inner_product(func.begin(), func.end(), func.begin(), 0.0,
[](double const & x, double const & y) { return x + y; },
[mean](double const & x, double const & y) { return (x - mean)*(y - mean); });
return std::sqrt(sq_sum / func.size());
}
I suspect doing the subtraction multiple times is cheaper than using up additional intermediate storage, and I think it is more readable, but I haven't tested the performance yet.
Pylint message control is documented in the Pylint manual:
Is it possible to locally disable a particular message?
Yes, this feature has been added in Pylint 0.11. This may be done by adding
# pylint: disable=some-message,another-one
at the desired block level or at the end of the desired line of code.
You can use the message code or the symbolic names.
For example,
def test():
# Disable all the no-member violations in this function
# pylint: disable=no-member
...
global VAR # pylint: disable=global-statement
The manual also has further examples.
There is a wiki that documents all Pylint messages and their codes.
This is a one-liner but uses four atomic commands:
head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
The issue you are having is common and not explained well in the documentation. Normal devices do not include the sqlite3 database binary which is why you are getting an error. the Android Emeulator, OSX, Linux (if installed) and Windows (after installed) have the binary so you can open a database locally on your machine.
The workaround is to copy the Database from your device to your local machine. This can be accomplished with ADB but requires a number of steps.
Before you start you will need some information:
<package name>
, for example, com.example.application
<local path>
to place your database, eg. ~/Desktop
or %userprofile%\Desktop
Next you will need to understand what terminal each command gets written to the first character in the examples below does not get typed but lets you know what shell we are in:
>
= you OS command prompt$
= ADB shell command Prompt!
= ADB shell as admin command prompt%
Next enter the following commands from Terminal or Command (don't enter first character or text in ()
)
> adb shell
$ su
! cp /data/data/<package name>/Databases/<database name> /sdcard
! exit
$ exit
> adb pull /sdcard/<database name> <local path>
> sqlite3 <local db path>
% .dump
% .exit (to exit sqldb)
This is a really round about way of copying the database to your local machine and locally reading the database. There are SO and other resources explaining how to install the sqlite3 binary onto your device from an emulator but for one time access this process works.
If you need to access the database interactively I would suggest running your app in an emulator (that already had sqlite3) or installing sqlite onto your devices /xbin path.
You can add the tag as a property for the Fragment
arguments. It will be automatically restored if the fragment is destroyed and then recreated by the OS.
Example:-
final Bundle args = new Bundle();
args.putString("TAG", "my tag");
fragment.setArguments(args);
Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."
Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...
Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as int
s that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h>
only require zero or non-zero, not necessarily zero or one.
If you cast that to bool
, zero will convert to false, and non-zero to true (as you'd expect).
Use a lambda to pass the entry data to the command function if you have more actions to carry out, like this (I've tried to make it generic, so just adapt):
event1 = Entry(master)
button1 = Button(master, text="OK", command=lambda: test_event(event1.get()))
def test_event(event_text):
if not event_text:
print("Nothing entered")
else:
print(str(event_text))
# do stuff
This will pass the information in the event to the button function. There may be more Pythonesque ways of writing this, but it works for me.
After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals
and then a bit farther down res.locals
held the answers I needed.
I discovered for myself that the function app.locals
takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals
, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.
So for my case in my app.js
what I did was add:
app.locals({
site: {
title: 'ExpressBootstrapEJS',
description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
},
author: {
name: 'Cory Gross',
contact: '[email protected]'
}
});
Then all of these variables are accessible in my views as site.title
, site.description
, author.name
, author.contact
.
I could also define local variables for each response to a request with res.locals
, or simply pass variables like the page's title in as the options
parameter in the render
call.
EDIT: This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals
for each response and then call next
. This middleware function will need to be placed above any other middleware which needs to use these locals.
EDIT: Another difference between declaring locals via app.locals
and res.locals
is that with app.locals
the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals
in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals
unless the value depends on the request req
variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals
.
e can also select rows based on values of a column that are not in a list or any iterable. We will create boolean variable just like before, but now we will negate the boolean variable by placing ~ in the front.
For example
list = [1, 0]
df[df.col1.isin(list)]
Try this one:
(function($) {
var i = 0;
var someBackground = $(".someBackground");
var someColors = [ "yellow", "red", "blue", "pink" ];
someBackground.css('backgroundColor', someColors[0]);
window.setInterval(function() {
i = i == someColors.length ? 0 : i;
someBackground.animate({backgroundColor: someColors[i]}, 3000);
i++;
}, 30);
})(jQuery);
you can preview example here: http://jquerydemo.com/demo/jquery-animate-background-color.aspx
If function Fiber really turns async function sleep into sync
Yes. Inside the fiber, the function waits before logging ok
. Fibers do not make async functions synchronous, but allow to write synchronous-looking code that uses async functions and then will run asynchronously inside a Fiber
.
From time to time I find the need to encapsulate an async function into a sync function in order to avoid massive global re-factoring.
You cannot. It is impossible to make asynchronous code synchronous. You will need to anticipate that in your global code, and write it in async style from the beginning. Whether you wrap the global code in a fiber, use promises, promise generators, or simple callbacks depends on your preferences.
My objective is to minimize impact on the caller when data acquisition method is changed from sync to async
Both promises and fibers can do that.
You mention already having a background image on body
.
You could set that background image on html
, and the new one on body
. This will of course depend upon your layout, but you wouldn't need to use your footer for it.
The substr()
function will probably help you here:
$str = substr($str, 1);
Strings are indexed starting from 0, and this functions second parameter takes the cutstart. So make that 1, and the first char is gone.
What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.
You are trying to read the value of your checkbox before it is loaded. The script runs before the checkbox exists. You need to call your script when the page loads:
<body onload="dosomething()">
Example:
http://jsfiddle.net/jtbowden/6dx6A/
You are also missing a semi-colon after your first assignment.
You say in a comment you want to get "15.09.2016".
For this, use Date
and DateFormatter
:
let date = Date()
let formatter = DateFormatter()
Give the format you want to the formatter:
formatter.dateFormat = "dd.MM.yyyy"
Get the result string:
let result = formatter.string(from: date)
Set your label:
label.text = result
Result:
15.09.2016
You can get around the problem without switching to classic mode and still use Application_Start
public class Global : HttpApplication
{
private static HttpRequest initialRequest;
static Global()
{
initialRequest = HttpContext.Current.Request;
}
void Application_Start(object sender, EventArgs e)
{
//access the initial request here
}
For some reason, the static type is created with a request in its HTTPContext, allowing you to store it and reuse it immediately in the Application_Start event
When you say "doesn't work", how do you know it doesn't work?
You might try to figure out if the file actually exists by adding:
while [ ! -f /tmp/list.txt ]
do
sleep 2 # or less like 0.2
done
ls -l /tmp/list.txt
You might also make sure that you're using a Bash (or related) shell by typing 'echo $SHELL'. I think that CSH and TCSH use a slightly different semantic for this loop.
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
You just have to change to a Custom format - right click and select format and at the bottom of the list is custom.
0.00##\%;[Red](0.00##\%)
The first part of custom format is your defined format you posted. Everything after the semicolon is for negative numbers. [RED] tells Excel to make the negative numbers red and the () make sure that negative number is in parentheses.
Go to
Tools->Options->Text Editor->C# (or All Languages)->General
and enable Auto List Members
and Parameter Information
in right hand side pane.
In Windows 7 on GitHub 2.5.3.0 I found it in C:\Users(user)\AppData\Local\GitHub\PortableGit_(numbers)\mingw32\bin\git.exe
thanks to dir /s git.exe
The approach recommended by the ASP.Net Core team is to use the new policy design which is fully documented here. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a "policy" (e.g. [Authorize( Policy = "YouNeedToBe18ToDoThis")]
where the policy is registered in the application's Startup.cs to execute some block of code (i.e. ensure the user has an age claim where the age is 18 or older).
The policy design is a great addition to the framework and the ASP.Net Security Core team should be commended for its introduction. That said, it isn't well-suited for all cases. The shortcoming of this approach is that it fails to provide a convenient solution for the most common need of simply asserting that a given controller or action requires a given claim type. In the case where an application may have hundreds of discrete permissions governing CRUD operations on individual REST resources ("CanCreateOrder", "CanReadOrder", "CanUpdateOrder", "CanDeleteOrder", etc.), the new approach either requires repetitive one-to-one mappings between a policy name and a claim name (e.g. options.AddPolicy("CanUpdateOrder", policy => policy.RequireClaim(MyClaimTypes.Permission, "CanUpdateOrder));
), or writing some code to perform these registrations at run time (e.g. read all claim types from a database and perform the aforementioned call in a loop). The problem with this approach for the majority of cases is that it's unnecessary overhead.
While the ASP.Net Core Security team recommends never creating your own solution, in some cases this may be the most prudent option with which to start.
The following is an implementation which uses the IAuthorizationFilter to provide a simple way to express a claim requirement for a given controller or action:
public class ClaimRequirementAttribute : TypeFilterAttribute
{
public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter))
{
Arguments = new object[] {new Claim(claimType, claimValue) };
}
}
public class ClaimRequirementFilter : IAuthorizationFilter
{
readonly Claim _claim;
public ClaimRequirementFilter(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
if (!hasClaim)
{
context.Result = new ForbidResult();
}
}
}
[Route("api/resource")]
public class MyController : Controller
{
[ClaimRequirement(MyClaimTypes.Permission, "CanReadResource")]
[HttpGet]
public IActionResult GetResource()
{
return Ok();
}
}
If you want to just shift everything down you can use:
Rows(1).Insert shift:=xlShiftDown
Similarly to shift everything over:
Columns(1).Insert shift:=xlShiftRight
The CSS property that can be used is:
pointer-events:none
!IMPORTANT Keep in mind that this property is not supported by Opera Mini and IE 10 and below (inclusive). Another solution is needed for these browsers.
jQuery METHOD If you want to disable it via script and not CSS property, these can help you out: If you're using jQuery versions 1.4.3+:
$('selector').click(false);
If not:
$('selector').click(function(){return false;});
You can re-enable clicks with pointer-events: auto;
(Documentation)
Note that pointer-events
overrides the cursor
property, so if you want the cursor to be something other than the standard , your css should be place after pointer-events
.
document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';
Yo could also set labels = FALSE
inside axis(...)
and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it
lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
Detailed explanation here
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
I would avoid using Require.js. Apps I've seen that do this wind up a mess of multiple types of module pattern architecture. AMD, Revealing, different flavors of IIFE, etc. There are other ways to load on demand like the loadOnDemand Angular mod. Adding other stuff just fills your code full of cruft and creates a low signal to noise ratio and makes your code hard to read.
Neither of the answers here helped me. The problem was: I was using the slim build of jQuery, which had some things removed, ajax being one of them.
The solution: Just download the regular (compressed or not) version of jQuery here and include it in your project.
I created a Eclipse plugin, which can count the lines of source code. It support Kotlin, Java, Java Script, JSP, XML, C/C++, C#, and many other file types.
Please take a look at it. Any feedback would be appreciated!
Another use case is when using the SQL Server 2016+ functionality of AT TIME ZONE
The below statement will return a date converted to GMT
SELECT
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE 'GMT Standard Time')))
If you want to pass the time zone as a variable, say:
SELECT
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE @TimeZone)))
then that variable needs to be of the type sysname
(declaring it as varchar
will cause an error).
Use Java 8's never-too-late-to-join-in-the-fun class: java.util.Base64
new String(Base64.getEncoder().encode(bytes));
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
You could try to create your own color palette using the RColorBrewer
package
my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)
and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette
instead of the redgreen()
I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.
Actually I would like to comment, but I am not authorised yet. That is why that pretend to be next answer while it is not.
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
I would like to continue that path. That works smoothly when one has picture one can simple insert. In my case that is slightly more complex: I have to map several pictures it. So far the only workable way to do this I found is as follows
import upperBody from './upperBody.png';
import lowerBody from './lowerBody.png';
import aesthetics from './aesthetics.png';
let obj={upperBody:upperBody, lowerBody:lowerBody, aesthetics:aesthetics, agility:agility, endurance:endurance}
{Object.keys(skills).map((skill) => {
return ( <img className = 'icon-size' src={obj[skill]}/>
So, my question is whether are there simplier ways to process these images? Needless to say that in more general case number of files that must be literally imported could be huge and number of keys in object as well. (Object in that code is involved clearly to refer by names -its keys) In my case require-related procedures have not worked - loaders generated errors of strange kind during installation and shown no mark of working; and require by itself has not worked neither.
It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split()
can do the correct tokenization for args (I'm using Blender's example of the call):
import shlex
from subprocess import Popen, PIPE
command = shlex.split('swfdump /tmp/filename.swf/ -d')
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
Delete any or specific file type(for example ".bak") from a path. See demo code below -
class Program
{
static void Main(string[] args)
{
// Specify the starting folder on the command line, or in
TraverseTree(ConfigurationManager.AppSettings["folderPath"]);
// Specify the starting folder on the command line, or in
// Visual Studio in the Project > Properties > Debug pane.
//TraverseTree(args[0]);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void TraverseTree(string root)
{
if (string.IsNullOrWhiteSpace(root))
return;
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root))
{
return;
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
IEnumerable<FileInfo> files = null;
try
{
//get only .bak file
var directory = new DirectoryInfo(currentDir);
DateTime date = DateTime.Now.AddDays(-15);
files = directory.GetFiles("*.bak").Where(file => file.CreationTime <= date);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (FileInfo file in files)
{
try
{
// Perform whatever action is required in your scenario.
file.Delete();
Console.WriteLine("{0}: {1}, {2} was successfully deleted.", file.Name, file.Length, file.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
dirs.Push(str);
}
}
}
for more reference - https://msdn.microsoft.com/en-us/library/bb513869.aspx
this should work in T-SQL
ALTER TABLE Countries ADD
HasPhotoInReadyStorage bit,
HasPhotoInWorkStorage bit,
HasPhotoInMaterialStorage bit,
HasText bit GO
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx
I recommend you this repository, https://github.com/DonJayamanne/gitHistoryVSCode
Git History
It does exactly what you need and has these features:
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
More accurately anything that is not 0
is true.
So 1
is true, but so is 2
, 3
... etc.
class MyClass():
def __init__(self, a, b):
self.value1 = a
self.value2 = b
def __call__(self):
return [self.value1, self.value2]
Testing:
>>> x = MyClass('foo','bar')
>>> x()
['foo', 'bar']
Deleting directly from file system is not safe. You can run the below script to delete all builds from all jobs ( recursively ).
def numberOfBuildsToKeep = 10
Jenkins.instance.getAllItems(AbstractItem.class).each {
if( it.class.toString() != "class com.cloudbees.hudson.plugins.folder.Folder" && it.class.toString() != "class org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject") {
println it.name
builds = it.getBuilds()
for(int i = numberOfBuildsToKeep; i < builds.size(); i++) {
builds.get(i).delete()
println "Deleted" + builds.get(i)
}
}
}
You don't need a regex for this. Use tr:
"some text\nandsomemore".tr("\n","")
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
forEach()
can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.
For example ArrayList.forEach(action)
may be simply implemented as
for(int i=0; i<size; i++)
action.accept(elements[i])
as opposed to the for-each loop which requires a lot of scaffolding
Iterator iter = list.iterator();
while(iter.hasNext())
Object next = iter.next();
do something with `next`
However, we also need to account for two overhead costs by using forEach()
, one is making the lambda object, the other is invoking the lambda method. They are probably not significant.
see also http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/ for comparing internal/external iterations for different use cases.
Above tools extract the jar. Also there are certain other tools and commands to extract the jar. But AFAIK you cant get the java code in case code has been obfuscated.
I agree with Robert Siemer and Michaël Witrant. If it's not working, try to debug with strace
strace adb devices
In my case it helps to kill all instances and remove socket file /tmp/ADB_PORT
(the default is /tmp/5037
).
There is a workaround for 'virtual template method' if set of types for the template method is known in advance.
To show the idea, in the example below only two types are used (int
and double
).
There, a 'virtual' template method (Base::Method
) calls corresponding virtual method (one of Base::VMethod
) which, in turn, calls template method implementation (Impl::TMethod
).
One only needs to implement template method TMethod
in derived implementations (AImpl
, BImpl
) and use Derived<*Impl>
.
class Base
{
public:
virtual ~Base()
{
}
template <typename T>
T Method(T t)
{
return VMethod(t);
}
private:
virtual int VMethod(int t) = 0;
virtual double VMethod(double t) = 0;
};
template <class Impl>
class Derived : public Impl
{
public:
template <class... TArgs>
Derived(TArgs&&... args)
: Impl(std::forward<TArgs>(args)...)
{
}
private:
int VMethod(int t) final
{
return Impl::TMethod(t);
}
double VMethod(double t) final
{
return Impl::TMethod(t);
}
};
class AImpl : public Base
{
protected:
AImpl(int p)
: i(p)
{
}
template <typename T>
T TMethod(T t)
{
return t - i;
}
private:
int i;
};
using A = Derived<AImpl>;
class BImpl : public Base
{
protected:
BImpl(int p)
: i(p)
{
}
template <typename T>
T TMethod(T t)
{
return t + i;
}
private:
int i;
};
using B = Derived<BImpl>;
int main(int argc, const char* argv[])
{
A a(1);
B b(1);
Base* base = nullptr;
base = &a;
std::cout << base->Method(1) << std::endl;
std::cout << base->Method(2.0) << std::endl;
base = &b;
std::cout << base->Method(1) << std::endl;
std::cout << base->Method(2.0) << std::endl;
}
Output:
0
1
2
3
NB:
Base::Method
is actually surplus for real code (VMethod
can be made public and used directly).
I added it so it looks like as an actual 'virtual' template method.
If using maven, just add to your pom.xml:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
Of course, you need to check the current version.
As the time passes you should embrace a more functional approach in which you should avoid data mutations and write small, single responsibility functions. With the ECMAScript 6 standard, you can enjoy functional programming paradigm in JavaScript with the provided map
, filter
and reduce
methods. You don't need another lodash, underscore or what else to do most basic things.
Down below I have included some proposed solutions to this problem in order to show how this problem can be solved using different language features:
Using ES6 map:
const replace = predicate => replacement => element =>_x000D_
predicate(element) ? replacement : element_x000D_
_x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = arr.map(replace (predicate) (replacement))_x000D_
console.log(result)
_x000D_
Recursive version - equivalent of mapping:
Requires destructuring and array spread.
const replace = predicate => replacement =>_x000D_
{_x000D_
const traverse = ([head, ...tail]) =>_x000D_
head_x000D_
? [predicate(head) ? replacement : head, ...tail]_x000D_
: []_x000D_
return traverse_x000D_
}_x000D_
_x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = replace (predicate) (replacement) (arr)_x000D_
console.log(result)
_x000D_
When the final array's order is not important you can use an object
as a HashMap data structure. Very handy if you already have keyed collection as an object
- otherwise you have to change your representation first.
Requires object rest spread, computed property names and Object.entries.
const replace = key => ({id, ...values}) => hashMap =>_x000D_
({_x000D_
...hashMap, //original HashMap_x000D_
[key]: undefined, //delete the replaced value_x000D_
[id]: values //assign replacement_x000D_
})_x000D_
_x000D_
// HashMap <-> array conversion_x000D_
const toHashMapById = array =>_x000D_
array.reduce(_x000D_
(acc, { id, ...values }) => _x000D_
({ ...acc, [id]: values })_x000D_
, {})_x000D_
_x000D_
const toArrayById = hashMap =>_x000D_
Object.entries(hashMap)_x000D_
.filter( // filter out undefined values_x000D_
([_, value]) => value _x000D_
) _x000D_
.map(_x000D_
([id, values]) => ({ id, ...values })_x000D_
)_x000D_
_x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const replaceKey = 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
// Create a HashMap from the array, treating id properties as keys_x000D_
const hashMap = toHashMapById(arr)_x000D_
console.log(hashMap)_x000D_
_x000D_
// Result of replacement - notice an undefined value for replaced key_x000D_
const resultHashMap = replace (replaceKey) (replacement) (hashMap)_x000D_
console.log(resultHashMap)_x000D_
_x000D_
// Final result of conversion from the HashMap to an array_x000D_
const result = toArrayById (resultHashMap)_x000D_
console.log(result)
_x000D_
You can still use this with XHTML 1.0 Transitional and HTML 4.01 Transitional if you like. The only other way (best way, in my opinion) is with margins:
<div style="width:200px;margin:auto;">
<p>Hello World</p>
</div>
Your HTML should define the element, not govern its presentation.
If you want to create object (like in javascript) with dynamic properties, without receiving a warning of undefined property.
class stdClass {
public function __construct(array $arguments = array()) {
if (!empty($arguments)) {
foreach ($arguments as $property => $argument) {
if(is_numeric($property)):
$this->{$argument} = null;
else:
$this->{$property} = $argument;
endif;
}
}
}
public function __call($method, $arguments) {
$arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
if (isset($this->{$method}) && is_callable($this->{$method})) {
return call_user_func_array($this->{$method}, $arguments);
} else {
throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
}
}
public function __get($name){
if(property_exists($this, $name)):
return $this->{$name};
else:
return $this->{$name} = null;
endif;
}
public function __set($name, $value) {
$this->{$name} = $value;
}
}
$obj1 = new stdClass(['property1','property2'=>'value']); //assign default property
echo $obj1->property1;//null
echo $obj1->property2;//value
$obj2 = new stdClass();//without properties set
echo $obj2->property1;//null
There may be two causes:
It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.
You have not install pandas (pip install pandas
) in the python path.
As everyone else says, you can't from a simple programmatic way.
Consider these examples:
President "George Herbert Walker Bush" (First Middle Middle Last)
Presidential assassin "John Wilkes Booth" (First Middle Last)
Guitarist "Eddie Van Halen" (First Last Last)
And his mom probably calls him Edward Lodewijk Van Halen (First Middle Last Last)
Famed castaway "Mary Ann Summers" (First First Last)
New Mexico GOP chairman "Fernando C de Baca" (First Last Last Last)
To create sets you can use a varargs factory method instead of double-brace initialisation:
public static Set<T> setOf(T ... elements) {
return new HashSet<T>(Arrays.asList(elements));
}
The Google Collections library has lots of convenience methods like this, as well as loads of other useful functionality.
As for the idiom's obscurity, I encounter it and use it in production code all the time. I'd be more concerned about programmers who get confused by the idiom being allowed to write production code.
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)
You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.
UNAME := $(shell uname -m)
all:
$(info Checking if custom header is needed)
ifeq ($(UNAME), x86_64)
... do some things to build unistd_32.h
endif
@make -C $(KDIR) M=$(PWD) modules
So you want unistd_32.h built (maybe) before you invoke the second make
, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:
ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif
all:
@make -C $(KDIR) M=$(PWD) modules
unistd_32.h:
... do some things to build unistd_32.h
Now for building unistd_32.h
:
F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else
F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
ifeq ($(F2_EXISTS), 1)
$(info Copying custom header)
$(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
else
$(error asm/unistd_32.h and asm-386/unistd.h does not exist)
endif
endif
You are trying to build unistd.h
from unistd_32.h
; the only trick is that unistd_32.h
could be in either of two places. The simplest way to clean this up is to use a vpath
directive:
vpath unistd.h /usr/include/asm /usr/include/asm-i386
unistd_32.h: unistd.h
sed -e 's/__NR_/__NR32_/g' $< > $@
Actually, I did not want to be dependent of anything else but Python (Cairo, Ink.., etc.)
My requirements were to be as simple as possible, at most, a simple pip install "savior"
would suffice, that's why any of those above didn't suit for me.
I came through this (going further than Stackoverflow on the research). https://www.tutorialexample.com/best-practice-to-python-convert-svg-to-png-with-svglib-python-tutorial/
Looks good, so far. So I share it in case anyone in the same situation.
Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.
<div class="modal-backdrop"></div>
Made a small demo: http://jsfiddle.net/PfBnq/
You can simply use the ID attribute to the form and attach the <textarea>
tag to the form like this:
<form name="commentform" action="#" method="post" target="_blank" id="1321">
<textarea name="forcom" cols="40" rows="5" form="1321" maxlength="188">
Enter your comment here...
</textarea>
<input type="submit" value="OK">
<input type="reset" value="Clear">
</form>
This function work fine for me...just pass url string in function:
void watch_video(String url)
{
Intent yt_play = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
Intent chooser = Intent.createChooser(yt_play , "Open With");
if (yt_play .resolveActivity(getPackageManager()) != null) {
startActivity(chooser);
}
}
actually I walked the same path a couple of month ago. there is no perfect answer to the question (that was asked here a couple of time) but there is one more sophisticated then the sqrt(r-r) etc answer and more easy to implent directly with RGB without moving to all kind of alternate color spaces. I found this formula here which is a low cost approximation of the quite complicated real formula (by the CIE which is the W3C of color, since this is a not finished quest, you can find older and simpler color difference equations there). good luck
Edit: For posterity, here's the relevant C code:
typedef struct {
unsigned char r, g, b;
} RGB;
double ColourDistance(RGB e1, RGB e2)
{
long rmean = ( (long)e1.r + (long)e2.r ) / 2;
long r = (long)e1.r - (long)e2.r;
long g = (long)e1.g - (long)e2.g;
long b = (long)e1.b - (long)e2.b;
return sqrt((((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8));
}
Oracle support Mathematical Subtract -
operator on Data datatype. You may directly put in select clause following statement:
to_char (s.last_upd – s.created, ‘999999D99')
Check the EXAMPLE for more visibility.
In case you need the output in termes of hours, then the below might help;
Select to_number(substr(numtodsinterval([END_TIME]-[START_TIME]),’day’,2,9))*24 +
to_number(substr(numtodsinterval([END_TIME]-[START_TIME],’day’),12,2))
||':’||to_number(substr(numtodsinterval([END_TIME]-[START_TIME],’day’),15,2))
from [TABLE_NAME];