I've improved Josh's answer. I've noticed that dig
only shows entries already present in the queried nameserver's cache, so it's better to pull an authoritative nameserver from the SOA (rather than rely on the default nameserver). I've also disabled the filtering of wildcard IPs because usually I'm usually more interested in the correctness of the setup.
The new script takes a -x
argument for expanded output and a -s NS
argument to choose a specific nameserver: dig -x example.com
#!/bin/bash
set -e; set -u
COMMON_SUBDOMAINS="www mail mx a.mx smtp pop imap blog en ftp ssh login"
EXTENDED=""
while :; do case "$1" in
--) shift; break ;;
-x) EXTENDED=y; shift ;;
-s) NS="$2"; shift 2 ;;
*) break ;;
esac; done
DOM="$1"; shift
TYPE="${1:-any}"
test "${NS:-}" || NS=$(dig +short SOA "$DOM" | awk '{print $1}')
test "$NS" && NS="@$NS"
if test "$EXTENDED"; then
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
wild_ips=$(dig +short "$NS" "*.$DOM" "$TYPE" | tr '\n' '|')
wild_ips="${wild_ips%|}"
for sub in $COMMON_SUBDOMAINS; do
dig +nocmd $NS "$sub.$DOM" +noall +answer "$TYPE"
done | cat #grep -vE "${wild_ips}"
dig +nocmd $NS "*.$DOM" +noall +answer "$TYPE"
else
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
fi
What is the difference between c++ and visaul c++?
Visual C++ is an IDE. There's also C++Builder from Embarcadero. (Used to be Borland.) There are also a few other C++ IDE's.
I know that c++ has the portability and all so if you know c++ how is it related to visual c++?
C++ is as portable as the libraries that you use in your C++ application. VC++ has some specialized libraries to use with Windows, so if you use those libraries in your C++ application, you're stuck with Windows. But a simple "Hello, World" application that just uses the console as output can be compiled on Windows, Linux, VMS, AS/400, Smartphones, FreeBSD, MS-DOS, CP80 and almost any other system for which you can find a C++ compiler. Injteresting fact: at http://nethack.org/ you can download the C sourcecode for an almost antique game, where you have to walk through a bunch of mazes, kick some monsters around, find treasures and steal some valuable amulet and bring that amulet back out. (It's also a game where you can encounter your characters from previous, failed attempts to get that amulet. :-) The sourcecode of NetHack is a fine example of how portable C (C++) code can be.
Is visual c++ mostly for online apps?
No. But it can be used for online apps. Actually, C# is used more often for server-side web applications while C++ (VC++) is used for all kinds of (server) components that your application will be depending upon.
Would visual basic be better for desktop applications?
Or Embarcadero Delphi. Delphi and Basic are languages that are easier to learn than C++ and both have very good IDE's to develop GUI applications with. Unfortunately, Visual Basic is now running on .NET only, while there are still many developers who need to create WIN32 applications. Those developers often have to choose between Delphi or C++ or else convince management to move to .NET development.
Most importantly you need to mount the drive
net use z: \\yourserver\sharename
Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:
"When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.
Then run your batch script with the following changes
copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"
import json
d = json.loads(j)
print d['glossary']['title']
If you are looking for "how to press the Enter key from the keyboard in Selenium WebDriver (Java)",then below code will definitely help you.
// Assign a keyboard object
Keyboard keyboard = ((HasInputDevices) driver).getKeyboard();
// Enter a key
keyboard.pressKey(Keys.ENTER);
One way assuming filtered data in A1 downwards;
dim Rng as Range
set Rng = Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
...
for each cell in Rng
...
nothing new but still want to share my method:
+(NSString*) getDateStringFromSrcFormat:(NSString *) srcFormat destFormat:(NSString *)
destFormat scrString:(NSString *) srcString
{
NSString *dateString = srcString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setDateFormat:@"MM-dd-yyyy"];
[dateFormatter setDateFormat:srcFormat];
NSDate *date = [dateFormatter dateFromString:dateString];
// Convert date object into desired format
//[dateFormatter setDateFormat:@"yyyy-MM-dd"];
[dateFormatter setDateFormat:destFormat];
NSString *newDateString = [dateFormatter stringFromDate:date];
return newDateString;
}
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
It's worth noting that the QuerySet.values_list()
method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet
, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.
Somewhat irritatingly, though, this object has a custom __repr__
method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.
The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
my_list = list(self.get_queryset().values_list('code', flat=True))
...then you can convert it to JSON with...
json_data = json.dumps(my_list)
You'll also have to place the resulting JSON data in an HttpResponse
object, which, apparently, should have a Content-Type
of application/json
, with...
response = HttpResponse(json_data, content_type='application/json')
...which you can then return from your function.
Rob's solution is the right one--use @require
with the jQuery library and be sure to reinstall your script so the directive gets processed.
One thing I think is worth adding is that you can use jQuery normally once you have included it in your script, except for AJAX methods. By default jQuery looks for XMLHttpRequest, which doesn't exist in the Greasemonkey context. I wrote about a workaround where you create a wrapper for GM_xmlhttpRequest (the Greasemonkey version of XHR) and use jQuery's ajaxSetup()
to specify your wrapped version as the default. Once you do this, you can use $.get
and $.post
as usual.
You may also have problems with jQuery's $.getJSON
because it loads JSONP using <script>
tags. This leads to errors because jQuery defines the callback function in the scope of the Greasemonkey window, and the loaded scripts looks for the callback in the scope of the main window. Your best bet is to use $.get
instead and parse the result with JSON.parse()
.
The following worked for me:
/* function to save JSON to file from browser
* adapted from http://bgrins.github.io/devtools-snippets/#console-save
* @param {Object} data -- json object to save
* @param {String} file -- file name to save to
*/
function saveJSON(data, filename){
if(!data) {
console.error('No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
and then to call it like so
saveJSON(myJsonObject, "saved_data.json");
I would do something like this
DEMO in JsBin: http://jsbin.com/ofiqur/1/
<a href="#" id="showmenu">Click Here</a>
<div class="menu">
<ul>
<li><a href="#">Button 1</a></li>
<li><a href="#">Button 2</a></li>
<li><a href="#">Button 3</a></li>
</ul>
</div>
and in jQuery as simple as
var min = "-100px", // remember to set in css the same value
max = "0px";
$(function() {
$("#showmenu").click(function() {
if($(".menu").css("marginLeft") == min) // is it left?
$(".menu").animate({ marginLeft: max }); // move right
else
$(".menu").animate({ marginLeft: min }); // move left
});
});
I integrate the @mattmc3 aswer. If you want to convert a xlsx file you should use this connection string (the string provided by matt works for xls formats, not xlsx):
var cnnStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO\"", excelFilePath);
or try this (from http://drupal.org/node/870058)
Download wkhtmltopdf. Or better install it with a package manager:
sudo apt-get install wkhtmltopdf
Extract it and move it to /usr/local/bin/
wkhtmltopdf
so that now you have an executable at /usr/local/bin/wkhtmltopdf
sudo chmod a+x /usr/local/bin/wkhtmltopdf
Install required support packages.
sudo apt-get install openssl build-essential xorg libssl-dev
Check to see if it works: run
/usr/local/bin/wkhtmltopdf http://www.google.com test.pdf
If it works, then you are done. If you get the error "Cannot connect to X server" then continue to number 7.
We need to run it headless on a 'virtual' x server. We will do this with a package called xvfb.
sudo apt-get install xvfb
We need to write a little shell script to wrap wkhtmltopdf in xvfb. Make a file called wkhtmltopdf.sh
and add the following:
xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf "$@"
Move this shell script to /usr/local/bin
, and set permissions:
sudo chmod a+x /usr/local/bin/wkhtmltopdf.sh
Check to see if it works once again: run
/usr/local/bin/wkhtmltopdf.sh http://www.google.com test.pdf
Note that http://www.google.com may throw an error like "A finished ResourceObject received a loading finished signal. This might be an indication of an iframe taking to long to load." You may want to test with a simpler page like http://www.example.com
.
To serve from file system
I added spring.resources.static-location=file:../frontend/build
in application.properties
index.html
is present in the build
folder
Use can also add absolute path
spring.resources.static-location=file:/User/XYZ/Desktop/frontend/build
I think similarly you can try adding Dropbox folder path.
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().
std::string mystring;
mystring = "This is a test!"; // Assign C string to std:string directly
std::cout << mystring << '\n';
If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY
is not "V_ARRAY"
, then you are using different types; even if they are declared identically (e.g. both are table of number
) this will not work.
You're hitting this data type compatibility restriction:
You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.
You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.
You can access the first element adding the following code to the highlight
function
$(this).find(".selected td:first").html()
Working Code:JSFIDDLE
dir /b *.jpg >file.bat
This will give you lines such as:
Vacation2010 001.jpg
Vacation2010 002.jpg
Vacation2010 003.jpg
Edit file.bat in your favorite Windows text-editor, doing the equivalent of:
s/Vacation2010(.+)/rename "&" "December \1"/
That's a regex; many editors support them, but none that come default with Windows (as far as I know). You can also get a command line tool such as sed or perl which can take the exact syntax I have above, after escaping for the command line.
The resulting lines will look like:
rename "Vacation2010 001.jpg" "December 001.jpg"
rename "Vacation2010 002.jpg" "December 002.jpg"
rename "Vacation2010 003.jpg" "December 003.jpg"
You may recognize these lines as rename commands, one per file from the original listing. ;) Run that batch file in cmd.exe.
This is something that worked for me, although it smells a bit wrong:
var iframe = ...
var doc = iframe.contentDocument;
var i = doc.createElement('input');
i.style.display = 'none';
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);
hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.
findIndex
retrieves only the first index which matches callback output. You can implement your own findIndexes
by extending Array , then casting your arrays to the new structure .
class EnhancedArray extends Array {_x000D_
findIndexes(where) {_x000D_
return this.reduce((a, e, i) => (where(e, i) ? a.concat(i) : a), []);_x000D_
}_x000D_
}_x000D_
/*----Working with simple data structure (array of numbers) ---*/_x000D_
_x000D_
//existing array_x000D_
let myArray = [1, 3, 5, 5, 4, 5];_x000D_
_x000D_
//cast it :_x000D_
myArray = new EnhancedArray(...myArray);_x000D_
_x000D_
//run_x000D_
console.log(_x000D_
myArray.findIndexes((e) => e===5)_x000D_
)_x000D_
/*----Working with Array of complex items structure-*/_x000D_
_x000D_
let arr = [{name: 'Ahmed'}, {name: 'Rami'}, {name: 'Abdennour'}];_x000D_
_x000D_
arr= new EnhancedArray(...arr);_x000D_
_x000D_
_x000D_
console.log(_x000D_
arr.findIndexes((o) => o.name.startsWith('A'))_x000D_
)
_x000D_
If you run the GWT compiler with the -localWorkers flag, the compiler will compile multiple permutations in parallel. This lets you use all the cores of a multi-core machine, for example -localWorkers 2 will tell the compiler to do compile two permutations in parallel. You won't get order of magnitudes differences (not everything in the compiler is parallelizable) but it is still a noticable speedup if you are compiling multiple permutations.
If you're willing to use the trunk version of GWT, you'll be able to use hosted mode for any browser (out of process hosted mode), which alleviates most of the current issues with hosted mode. That seems to be where the GWT is going - always develop with hosted mode, since compiles aren't likely to get magnitudes faster.
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. -- jQuery.each() | jQuery API Documentation
I'm using following code (in C#) to change the color of the NavigationBar:
NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.Default);
NavigationController.NavigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.LandscapePhone);
NavigationController.NavigationBar.BackgroundColor = UIColor.Green;
The trick is that you need to get rid of the default background image and then the color will appear.
If a function does not return anything, e.g.:
def test():
pass
it has an implicit return value of None
.
Thus, as your pick*
methods do not return anything, e.g.:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
the lines that call them, e.g.:
word = pickEasy()
set word
to None
, so wordInput
in getInput
is None
. This means that:
if guess in wordInput:
is the equivalent of:
if guess in None:
and None
is an instance of NoneType
which does not provide iterator/iteration functionality, so you get that type error.
The fix is to add the return type:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
Can't post comments yet, but @Cristi S's answer works a treat for me.
In my scenario, I needed to keep only the most recent 3 records in Lowest_Offers for all product_ids.
Need to rework his SQL to delete - thought that this would be ok, but syntax is wrong.
DELETE from (
SELECT product_id, id, date_checked,
ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY date_checked DESC) rn
FROM lowest_offers
) tmp WHERE > 3;
for Z score, we can stick to documentation instead of using 'apply' function
from scipy.stats import zscore
df_zscore = zscore(cols as array, axis=1)
In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.
Here is an example I have just written to demonstrate how you could do it using deferreds/promises.
Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.
Hope this helps!
$(function(){
function1().done(function(){
// function1 is done, we can now call function2
console.log('function1 is done!');
function2().done(function(){
//function2 is done
console.log('function2 is done!');
});
});
});
function function1(){
var dfrd1 = $.Deferred();
var dfrd2= $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function1 is done!');
dfrd1.resolve();
}, 1000);
setTimeout(function(){
// doing more async stuff
console.log('task 2 in function1 is done!');
dfrd2.resolve();
}, 750);
return $.when(dfrd1, dfrd2).done(function(){
console.log('both tasks in function1 are done');
// Both asyncs tasks are done
}).promise();
}
function function2(){
var dfrd1 = $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function2 is done!');
dfrd1.resolve();
}, 2000);
return dfrd1.promise();
}
If you don't want to touch your current table too much you can make a fake pinned column in front of the table.
The example shows one way of doing it without JS
table {_x000D_
border-collapse: collapse;_x000D_
border-spacing: 0;_x000D_
border: 1px solid #ddd;_x000D_
min-width: 600px;_x000D_
}_x000D_
_x000D_
.labels {_x000D_
display:flex;_x000D_
flex-direction: column_x000D_
}_x000D_
_x000D_
.overflow {_x000D_
overflow-x: scroll;_x000D_
min width: 400px;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
.label {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
white-space:nowrap;_x000D_
padding: 10px;_x000D_
flex: 1;_x000D_
border-bottom: 1px solid #ddd;_x000D_
border-right: 2px solid #ddd;_x000D_
}_x000D_
_x000D_
.label:last-of-type {_x000D_
overflow-x: scroll;_x000D_
border-bottom: 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
border: 1px solid #ddd;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
display:flex;_x000D_
max-width: 600px;_x000D_
padding: 0;_x000D_
border: 5px solid #ddd;_x000D_
}
_x000D_
<div class="flex">_x000D_
<div class="labels">_x000D_
<span class="label">Label 1</span>_x000D_
<span class="label">Lorem ipsum dolor sit amet.</span>_x000D_
<span class="label">Lorem ipsum dolor.</span>_x000D_
</div>_x000D_
<div class="overflow">_x000D_
<table>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL
my_value := regexp_replace(my_value, '[[:space:]]*','');
Maybe you find this simpler
select * from (
select ssn, sum(time) from downloads
group by ssn
order by sum(time) desc
) where rownum <= 10 --top 10 downloaders
Regards
K
There is a simple check for a user being root.
The [[ stuff ]]
syntax is the standard way of running a check in bash.
error() {
printf '\E[31m'; echo "$@"; printf '\E[0m'
}
if [[ $EUID -eq 0 ]]; then
error "Do not run this as the root user"
exit 1
fi
This also assumes that you want to exit with a 1 if you fail. The error
function is some flair that sets output text to red (not needed, but pretty classy if you ask me).
The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.
What you want to do is use Page.RegisterStartupScript(key, script) :
See here for more details: http://msdn.microsoft.com/en-us/library/aa478975.aspx
What you basically do is build your javascript string, pass it to that method and give it a unique id( in case you try to register it twice on a page.)
EDIT: This is what you call trigger happy. Feel free to down it. :)
A fast-forward update is where the only changes one one side are after the most recent commit on the other side, so there doesn't need to be any merging. This is saying that you need to merge your changes before you can push.
When you say:
#include <cstring>
the g++ compiler should put the <string.h>
declarations it itself includes into the std::
AND the global namespaces. It looks for some reason as if it is not doing that. Try replacing one instance of strcpy
with std::strcpy
and see if that fixes the problem.
Since AngularJS 1.3 you can use aliases:
item in items | filter:x as results
and somewhere:
<span>Total {{results.length}} result(s).</span>
From docs:
You can also provide an optional alias expression which will then store the intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message when a filter is active on the repeater, but the filtered result set is empty.
For example: item in items | filter:x as results will store the fragment of the repeated items as results, but only after the items have been processed through the filter.
Try this piece of code:
$first = $string[0];
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') {
$v='starts with vowel';
}
else {
$v='does not start with vowel';
}
This might be helpful,
const data = {_x000D_
email: "[email protected]",_x000D_
username: "me"_x000D_
};_x000D_
_x000D_
const options = {_x000D_
headers: {_x000D_
'Content-Type': 'application/json',_x000D_
}_x000D_
};_x000D_
_x000D_
axios.post('http://path', data, options)_x000D_
.then((res) => {_x000D_
console.log("RESPONSE ==== : ", res);_x000D_
})_x000D_
.catch((err) => {_x000D_
console.log("ERROR: ====", err);_x000D_
})
_x000D_
Blockquote
Blockquote
This is the best one I've found.
make sure you have mapped the y: drive, or copy all the files to local dir c:/local
c:/local> copy *.* c:/newfile.txt
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
I wanted to clone an open source project so I could submit some pull requests. The problem was that I didn't have permissions from the owner of the project. No matter, since my intention was to submit a PR, here is a viable alternative:
My solution:
Quite easy to combine all files in a directory and merge them
import glob
import csv
# Open result file
with open('output.txt','wb') as fout:
wout = csv.writer(fout,delimiter=',')
interesting_files = glob.glob("*.csv")
h = True
for filename in interesting_files:
print 'Processing',filename
# Open and process file
with open(filename,'rb') as fin:
if h:
h = False
else:
fin.next()#skip header
for line in csv.reader(fin,delimiter=','):
wout.writerow(line)
Correctness of Dijkstra's algorithm:
We have 2 sets of vertices at any step of the algorithm. Set A consists of the vertices to which we have computed the shortest paths. Set B consists of the remaining vertices.
Inductive Hypothesis: At each step we will assume that all previous iterations are correct.
Inductive Step: When we add a vertex V to the set A and set the distance to be dist[V], we must prove that this distance is optimal. If this is not optimal then there must be some other path to the vertex V that is of shorter length.
Suppose this some other path goes through some vertex X.
Now, since dist[V] <= dist[X] , therefore any other path to V will be atleast dist[V] length, unless the graph has negative edge lengths.
Thus for dijkstra's algorithm to work, the edge weights must be non negative.
Sometimes all it takes to get a EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
is a missing return
statement.
It certainly was my case.
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
All the answers above are correct, but I think this is the easiest example possible:
public class ExampleActivity extends Activity {
private Handler handler;
private ProgressBar progress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
handler = new Handler();
}
public void clickAButton(View view) {
// Do something that takes a while
Runnable runnable = new Runnable() {
@Override
public void run() {
handler.post(new Runnable() { // This thread runs in the UI
@Override
public void run() {
progress.setProgress("anything"); // Update the UI
}
});
}
};
new Thread(runnable).start();
}
}
What this does is update a progress bar in the UI thread from a completely different thread passed through the post() method of the handler declared in the activity.
Hope it helps!
There are several tools which can import Excel to SQL Server.
I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...
I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.
try some thing like blow:
SString otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
wr.writeBytes(jsonParam.toString());
wr.flush();
wr.close();
References :
white-space: nowrap
is the correct solution but it will prevent any break in a line. If you only want to prevent line breaks between two elements it gets a bit more complicated:
<p>
<span class="text">Some text</span>
<span class="icon"></span>
</p>
To prevent breaks between the spans but to allow breaks between "Some" and "text" can be done by:
p {
white-space: nowrap;
}
.text {
white-space: normal;
}
That's good enough for Firefox. In Chrome you additionally need to replace the whitespace between the spans with an
. (Removing the whitespace doesn't work.)
function isArray(value) {
if (value) {
if (typeof value === 'object') {
return (Object.prototype.toString.call(value) == '[object Array]')
}
}
return false;
}
var ar = ["ff","tt"]
alert(isArray(ar))
Actually there only a handful of solutions to track and compare changes in macro code - most of those were named here already. I have been browsing the web and came across this new tool worth mentioning:
XLTools Version Control for VBA macros
You could try in this way.
SOAPMessage msg = messageContext.getMessage();
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
String strMsg = new String(out.toByteArray());
(from i in list
select new { i.category_id, i.category_name })
.Distinct()
.OrderBy(i => i.category_name);
Edit php.ini
Find this line:
max_execution_time
Change its value to 300:
max_execution_time = 300
300 means 5 minutes of execution time for the http request.
UTC
is definitely a valid timezone. It is simply an abbreviation for Coordinated Universal Time. In addition, remember that date_default_timezone_set
accepts one of the following values:
$timezones=array(
"America/Adak",
"America/Argentina/Buenos_Aires",
"America/Argentina/La_Rioja",
"America/Argentina/San_Luis",
"America/Atikokan",
"America/Belem",
"America/Boise",
"America/Caracas",
"America/Chihuahua",
"America/Cuiaba",
"America/Denver",
"America/El_Salvador",
"America/Godthab",
"America/Guatemala",
"America/Hermosillo",
"America/Indiana/Tell_City",
"America/Inuvik",
"America/Kentucky/Louisville",
"America/Lima",
"America/Managua",
"America/Mazatlan",
"America/Mexico_City",
"America/Montreal",
"America/Nome",
"America/Ojinaga",
"America/Port-au-Prince",
"America/Rainy_River",
"America/Rio_Branco",
"America/Santo_Domingo",
"America/St_Barthelemy",
"America/St_Vincent",
"America/Tijuana",
"America/Whitehorse",
"America/Anchorage",
"America/Argentina/Catamarca",
"America/Argentina/Mendoza",
"America/Argentina/Tucuman",
"America/Atka",
"America/Belize",
"America/Buenos_Aires",
"America/Catamarca",
"America/Coral_Harbour",
"America/Curacao",
"America/Detroit",
"America/Ensenada",
"America/Goose_Bay",
"America/Guayaquil",
"America/Indiana/Indianapolis",
"America/Indiana/Vevay",
"America/Iqaluit",
"America/Kentucky/Monticello",
"America/Los_Angeles",
"America/Manaus",
"America/Mendoza",
"America/Miquelon",
"America/Montserrat",
"America/Noronha",
"America/Panama",
"America/Port_of_Spain",
"America/Rankin_Inlet",
"America/Rosario",
"America/Sao_Paulo",
"America/St_Johns",
"America/Swift_Current",
"America/Toronto",
"America/Winnipeg",
"America/Anguilla",
"America/Argentina/ComodRivadavia",
"America/Argentina/Rio_Gallegos",
"America/Argentina/Ushuaia",
"America/Bahia",
"America/Blanc-Sablon",
"America/Cambridge_Bay",
"America/Cayenne",
"America/Cordoba",
"America/Danmarkshavn",
"America/Dominica",
"America/Fort_Wayne",
"America/Grand_Turk",
"America/Guyana",
"America/Indiana/Knox",
"America/Indiana/Vincennes",
"America/Jamaica",
"America/Knox_IN",
"America/Louisville",
"America/Marigot",
"America/Menominee",
"America/Moncton",
"America/Nassau",
"America/North_Dakota/Beulah",
"America/Pangnirtung",
"America/Porto_Acre",
"America/Recife",
"America/Santa_Isabel",
"America/Scoresbysund",
"America/St_Kitts",
"America/Tegucigalpa",
"America/Tortola",
"America/Yakutat",
"America/Antigua",
"America/Argentina/Cordoba",
"America/Argentina/Salta",
"America/Aruba",
"America/Bahia_Banderas",
"America/Boa_Vista",
"America/Campo_Grande",
"America/Cayman",
"America/Costa_Rica",
"America/Dawson",
"America/Edmonton",
"America/Fortaleza",
"America/Grenada",
"America/Halifax",
"America/Indiana/Marengo",
"America/Indiana/Winamac",
"America/Jujuy",
"America/Kralendijk",
"America/Lower_Princes",
"America/Martinique",
"America/Merida",
"America/Monterrey",
"America/New_York",
"America/North_Dakota/Center",
"America/Paramaribo",
"America/Porto_Velho",
"America/Regina",
"America/Santarem",
"America/Shiprock",
"America/St_Lucia",
"America/Thule",
"America/Vancouver",
"America/Yellowknife",
"America/Araguaina",
"America/Argentina/Jujuy",
"America/Argentina/San_Juan",
"America/Asuncion",
"America/Barbados",
"America/Bogota",
"America/Cancun",
"America/Chicago",
"America/Creston",
"America/Dawson_Creek",
"America/Eirunepe",
"America/Glace_Bay",
"America/Guadeloupe",
"America/Havana",
"America/Indiana/Petersburg",
"America/Indianapolis",
"America/Juneau",
"America/La_Paz",
"America/Maceio",
"America/Matamoros",
"America/Metlakatla",
"America/Montevideo",
"America/Nipigon",
"America/North_Dakota/New_Salem",
"America/Phoenix",
"America/Puerto_Rico",
"America/Resolute",
"America/Santiago",
"America/Sitka",
"America/St_Thomas",
"America/Thunder_Bay",
"America/Virgin",
"Indian/Antananarivo",
"Indian/Kerguelen",
"Indian/Reunion",
"Australia/ACT",
"Australia/Currie",
"Australia/Lindeman",
"Australia/Perth",
"Australia/Victoria",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Chisinau",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Madrid",
"Europe/Moscow",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Tallinn",
"Europe/Vatican",
"Europe/Zagreb",
"Pacific/Apia",
"Pacific/Efate",
"Pacific/Galapagos",
"Pacific/Johnston",
"Pacific/Marquesas",
"Pacific/Noumea",
"Pacific/Ponape",
"Pacific/Tahiti",
"Pacific/Wallis",
"Indian/Chagos",
"Indian/Mahe",
"Australia/Adelaide",
"Australia/Darwin",
"Australia/Lord_Howe",
"Australia/Queensland",
"Australia/West",
"Europe/Andorra",
"Europe/Bratislava",
"Europe/Copenhagen",
"Europe/Isle_of_Man",
"Europe/Lisbon",
"Europe/Malta",
"Europe/Nicosia",
"Europe/Riga",
"Europe/Simferopol",
"Europe/Tirane",
"Europe/Vienna",
"Europe/Zaporozhye",
"Pacific/Auckland",
"Pacific/Enderbury",
"Pacific/Gambier",
"Pacific/Kiritimati",
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Port_Moresby",
"Pacific/Tarawa",
"Pacific/Yap",
"Africa/Abidjan",
"Africa/Asmera",
"Africa/Blantyre",
"Africa/Ceuta",
"Africa/Douala",
"Africa/Johannesburg",
"Africa/Kinshasa",
"Africa/Lubumbashi",
"Africa/Mbabane",
"Africa/Niamey",
"Africa/Timbuktu",
"Africa/Accra",
"Africa/Bamako",
"Africa/Brazzaville",
"Africa/Conakry",
"Africa/El_Aaiun",
"Africa/Juba",
"Africa/Lagos",
"Africa/Lusaka",
"Africa/Mogadishu",
"Africa/Nouakchott",
"Africa/Tripoli",
"Africa/Addis_Ababa",
"Africa/Bangui",
"Africa/Bujumbura",
"Africa/Dakar",
"Africa/Freetown",
"Africa/Kampala",
"Africa/Libreville",
"Africa/Malabo",
"Africa/Monrovia",
"Africa/Ouagadougou",
"Africa/Tunis",
"Africa/Algiers",
"Africa/Banjul",
"Africa/Cairo",
"Africa/Dar_es_Salaam",
"Africa/Gaborone",
"Africa/Khartoum",
"Africa/Lome",
"Africa/Maputo",
"Africa/Nairobi",
"Africa/Porto-Novo",
"Africa/Windhoek",
"Africa/Asmara",
"Africa/Bissau",
"Africa/Casablanca",
"Africa/Djibouti",
"Africa/Harare",
"Africa/Kigali",
"Africa/Luanda",
"Africa/Maseru",
"Africa/Ndjamena",
"Africa/Sao_Tome",
"Atlantic/Azores",
"Atlantic/Faroe",
"Atlantic/St_Helena",
"Atlantic/Bermuda",
"Atlantic/Jan_Mayen",
"Atlantic/Stanley",
"Atlantic/Canary",
"Atlantic/Madeira",
"Atlantic/Cape_Verde",
"Atlantic/Reykjavik",
"Atlantic/Faeroe",
"Atlantic/South_Georgia",
"Asia/Aden",
"Asia/Aqtobe",
"Asia/Baku",
"Asia/Calcutta",
"Asia/Dacca",
"Asia/Dushanbe",
"Asia/Hong_Kong",
"Asia/Jayapura",
"Asia/Kashgar",
"Asia/Kuala_Lumpur",
"Asia/Magadan",
"Asia/Novokuznetsk",
"Asia/Pontianak",
"Asia/Riyadh",
"Asia/Shanghai",
"Asia/Tehran",
"Asia/Ujung_Pandang",
"Asia/Vladivostok",
"Asia/Almaty",
"Asia/Ashgabat",
"Asia/Bangkok",
"Asia/Choibalsan",
"Asia/Damascus",
"Asia/Gaza",
"Asia/Hovd",
"Asia/Jerusalem",
"Asia/Kathmandu",
"Asia/Kuching",
"Asia/Makassar",
"Asia/Novosibirsk",
"Asia/Pyongyang",
"Asia/Saigon",
"Asia/Singapore",
"Asia/Tel_Aviv",
"Asia/Ulaanbaatar",
"Asia/Yakutsk",
"Asia/Amman",
"Asia/Ashkhabad",
"Asia/Beirut",
"Asia/Chongqing",
"Asia/Dhaka",
"Asia/Harbin",
"Asia/Irkutsk",
"Asia/Kabul",
"Asia/Katmandu",
"Asia/Kuwait",
"Asia/Manila",
"Asia/Omsk",
"Asia/Qatar",
"Asia/Sakhalin",
"Asia/Taipei",
"Asia/Thimbu",
"Asia/Ulan_Bator",
"Asia/Yekaterinburg",
"Asia/Anadyr",
"Asia/Baghdad",
"Asia/Bishkek",
"Asia/Chungking",
"Asia/Dili",
"Asia/Hebron",
"Asia/Istanbul",
"Asia/Kamchatka",
"Asia/Kolkata",
"Asia/Macao",
"Asia/Muscat",
"Asia/Oral",
"Asia/Qyzylorda",
"Asia/Samarkand",
"Asia/Tashkent",
"Asia/Thimphu",
"Asia/Urumqi",
"Asia/Yerevan",
"Asia/Aqtau",
"Asia/Bahrain",
"Asia/Brunei",
"Asia/Colombo",
"Asia/Dubai",
"Asia/Ho_Chi_Minh",
"Asia/Jakarta",
"Asia/Karachi",
"Asia/Krasnoyarsk",
"Asia/Macau",
"Asia/Nicosia",
"Asia/Phnom_Penh",
"Asia/Rangoon",
"Asia/Seoul",
"Asia/Tbilisi",
"Asia/Tokyo",
"Asia/Vientiane",
"Australia/Canberra",
"Australia/LHI",
"Australia/NSW",
"Australia/Tasmania",
"Australia/Broken_Hill",
"Australia/Hobart",
"Australia/North",
"Australia/Sydney",
"Pacific/Chuuk",
"Pacific/Fiji",
"Pacific/Guam",
"Pacific/Kwajalein",
"Pacific/Niue",
"Pacific/Pitcairn",
"Pacific/Saipan",
"Pacific/Truk",
"Pacific/Chatham",
"Pacific/Fakaofo",
"Pacific/Guadalcanal",
"Pacific/Kosrae",
"Pacific/Nauru",
"Pacific/Palau",
"Pacific/Rarotonga",
"Pacific/Tongatapu",
"Pacific/Easter",
"Pacific/Funafuti",
"Pacific/Honolulu",
"Pacific/Majuro",
"Pacific/Norfolk",
"Pacific/Pohnpei",
"Pacific/Samoa",
"Pacific/Wake",
"Antarctica/Casey",
"Antarctica/McMurdo",
"Antarctica/Vostok",
"Antarctica/Davis",
"Antarctica/Palmer",
"Antarctica/DumontDUrville",
"Antarctica/Rothera",
"Antarctica/Macquarie",
"Antarctica/South_Pole",
"Antarctica/Mawson",
"Antarctica/Syowa",
"Arctic/Longyearbyen",
"Europe/Athens",
"Europe/Brussels",
"Europe/Dublin",
"Europe/Istanbul",
"Europe/Ljubljana",
"Europe/Mariehamn",
"Europe/Oslo",
"Europe/Rome",
"Europe/Skopje",
"Europe/Tiraspol",
"Europe/Vilnius",
"Europe/Zurich",
"Europe/Belfast",
"Europe/Bucharest",
"Europe/Gibraltar",
"Europe/Jersey",
"Europe/London",
"Europe/Minsk",
"Europe/Paris",
"Europe/Samara",
"Europe/Sofia",
"Europe/Uzhgorod",
"Europe/Volgograd",
"Europe/Belgrade",
"Europe/Budapest",
"Europe/Guernsey",
"Europe/Kaliningrad",
"Europe/Luxembourg",
"Europe/Monaco",
"Europe/Podgorica",
"Europe/San_Marino",
"Europe/Stockholm",
"Europe/Vaduz",
"Europe/Warsaw",
"Indian/Cocos",
"Indian/Mauritius",
"Indian/Christmas",
"Indian/Maldives",
"Indian/Comoro",
"Indian/Mayotte",
"Australia/Brisbane",
"Australia/Eucla",
"Australia/Melbourne",
"Australia/South",
"Australia/Yancowinna",
);
Timezones in PHP at http://www.php.net/manual/en/timezones.php
Hi sorry the code for the second one should be:
private static void getAll(CarList c1) {
ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{
System.out.println(item.getMake()
+ " "
+ item.getReg()
);
}
}
I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:
CarList c1; c1 = new CarList();
everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.
POJO (plain old Java object): POJOs are ordinary Java objects, with no restriction other than those forced by the Java Language.
Serialization: It is used to save state of an object and send it across a network. It converts the state of an object into a byte stream. We can recreate a Java object from the byte stream by process called deserialization.
Make your class implement java.io.Serializable interface. And use writeObject() method of ObjectOutputStream class to achive Serialization.
JavaBean class: It is a special POJO which have some restriction (or convention).
Many frameworks - like Spring - use JavaBean objects.
Git pull is actually a combo tool: it runs git fetch (getting the changes) and git merge (merging them with your current copy)
Are you sure you are on the correct branch?
If you need to remove white spaces at the end then here is a solution: https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/
const stringQ1 = (string)=>{_x000D_
//remove white space at the end _x000D_
const arrString = string.split("")_x000D_
for(let i = arrString.length -1 ; i>=0 ; i--){_x000D_
let char = arrString[i];_x000D_
_x000D_
if(char.indexOf(" ") >=0){_x000D_
arrString.splice(i,1)_x000D_
}else{_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
let start =0;_x000D_
let end = arrString.length -1;_x000D_
_x000D_
_x000D_
//add %20_x000D_
while(start < end){_x000D_
if(arrString[start].indexOf(' ') >=0){_x000D_
arrString[start] ="%20"_x000D_
_x000D_
}_x000D_
_x000D_
start++;_x000D_
}_x000D_
_x000D_
return arrString.join('');_x000D_
}_x000D_
_x000D_
console.log(stringQ1("Mr John Smith "))
_x000D_
Normally when you don't use __block, the block will copy(retain) the variable, so even if you modify the variable, the block has access to the old object.
NSString* str = @"hello";
void (^theBlock)() = ^void() {
NSLog(@"%@", str);
};
str = @"how are you";
theBlock(); //prints @"hello"
In these 2 cases you need __block:
1.If you want to modify the variable inside the block and expect it to be visible outside:
__block NSString* str = @"hello";
void (^theBlock)() = ^void() {
str = @"how are you";
};
theBlock();
NSLog(@"%@", str); //prints "how are you"
2.If you want to modify the variable after you have declared the block and you expect the block to see the change:
__block NSString* str = @"hello";
void (^theBlock)() = ^void() {
NSLog(@"%@", str);
};
str = @"how are you";
theBlock(); //prints "how are you"
With labels this works fine at least:
@"H:|-15-[first(==second)]-[second(==third)]-[third(==first)]-15-|
If the first has the same width as the second, and second the third, and third the first, then they will all get the same width... You can do it both horizontally (H) and vertically (V).
Just for anyone trying to do this automatically, you can use that extension method to ignore non existing properties on the destination type :
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
&& x.DestinationType.Equals(destinationType));
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
to be used as follow :
Mapper.CreateMap<SourceType, DestinationType>().IgnoreAllNonExisting();
thanks to Can Gencer for the tip :)
source : http://cangencer.wordpress.com/2011/06/08/auto-ignore-non-existing-properties-with-automapper/
Following can be used as a common method to return different arguments on different method calls. Only thing we need to do is we need to pass an array with order in which objects should be retrieved in each call.
@SafeVarargs
public static <Mock> Answer<Mock> getAnswerForSubsequentCalls(final Mock... mockArr) {
return new Answer<Mock>() {
private int count=0, size=mockArr.length;
public Mock answer(InvocationOnMock invocation) throws throwable {
Mock mock = null;
for(; count<size && mock==null; count++){
mock = mockArr[count];
}
return mock;
}
}
}
Ex. getAnswerForSubsequentCalls(mock1, mock3, mock2);
will return mock1 object on first call, mock3 object on second call and mock2 object on third call.
Should be used like when(something()).doAnswer(getAnswerForSubsequentCalls(mock1, mock3, mock2));
This is almost similar to when(something()).thenReturn(mock1, mock3, mock2);
It should suffice to say whether bcrypt or SHA-512 (in the context of an appropriate algorithm like PBKDF2) is good enough. And the answer is yes, either algorithm is secure enough that a breach will occur through an implementation flaw, not cryptanalysis.
If you insist on knowing which is "better", SHA-512 has had in-depth reviews by NIST and others. It's good, but flaws have been recognized that, while not exploitable now, have led to the the SHA-3 competition for new hash algorithms. Also, keep in mind that the study of hash algorithms is "newer" than that of ciphers, and cryptographers are still learning about them.
Even though bcrypt as a whole hasn't had as much scrutiny as Blowfish itself, I believe that being based on a cipher with a well-understood structure gives it some inherent security that hash-based authentication lacks. Also, it is easier to use common GPUs as a tool for attacking SHA-2–based hashes; because of its memory requirements, optimizing bcrypt requires more specialized hardware like FPGA with some on-board RAM.
Note: bcrypt is an algorithm that uses Blowfish internally. It is not an encryption algorithm itself. It is used to irreversibly obscure passwords, just as hash functions are used to do a "one-way hash".
Cryptographic hash algorithms are designed to be impossible to reverse. In other words, given only the output of a hash function, it should take "forever" to find a message that will produce the same hash output. In fact, it should be computationally infeasible to find any two messages that produce the same hash value. Unlike a cipher, hash functions aren't parameterized with a key; the same input will always produce the same output.
If someone provides a password that hashes to the value stored in the password table, they are authenticated. In particular, because of the irreversibility of the hash function, it's assumed that the user isn't an attacker that got hold of the hash and reversed it to find a working password.
Now consider bcrypt. It uses Blowfish to encrypt a magic string, using a key "derived" from the password. Later, when a user enters a password, the key is derived again, and if the ciphertext produced by encrypting with that key matches the stored ciphertext, the user is authenticated. The ciphertext is stored in the "password" table, but the derived key is never stored.
In order to break the cryptography here, an attacker would have to recover the key from the ciphertext. This is called a "known-plaintext" attack, since the attack knows the magic string that has been encrypted, but not the key used. Blowfish has been studied extensively, and no attacks are yet known that would allow an attacker to find the key with a single known plaintext.
So, just like irreversible algorithms based cryptographic digests, bcrypt produces an irreversible output, from a password, salt, and cost factor. Its strength lies in Blowfish's resistance to known plaintext attacks, which is analogous to a "first pre-image attack" on a digest algorithm. Since it can be used in place of a hash algorithm to protect passwords, bcrypt is confusingly referred to as a "hash" algorithm itself.
Assuming that rainbow tables have been thwarted by proper use of salt, any truly irreversible function reduces the attacker to trial-and-error. And the rate that the attacker can make trials is determined by the speed of that irreversible "hash" algorithm. If a single iteration of a hash function is used, an attacker can make millions of trials per second using equipment that costs on the order of $1000, testing all passwords up to 8 characters long in a few months.
If however, the digest output is "fed back" thousands of times, it will take hundreds of years to test the same set of passwords on that hardware. Bcrypt achieves the same "key strengthening" effect by iterating inside its key derivation routine, and a proper hash-based method like PBKDF2 does the same thing; in this respect, the two methods are similar.
So, my recommendation of bcrypt stems from the assumptions 1) that a Blowfish has had a similar level of scrutiny as the SHA-2 family of hash functions, and 2) that cryptanalytic methods for ciphers are better developed than those for hash functions.
Keep it simple.
func NowAsUnixMilli() int64 {
return time.Now().UnixNano() / 1e6
}
std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; }
else {
while(str.at(0) == ' ') { str.erase(0, 1);}
while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
return str ;
}
}
While you do the following, technically speaking:
<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
//reference to the button that triggered the function:
$event.target
};
This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.
You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796
You can use the following. They all wrap the window
object into a jQuery object.
$(window).load(function () {
topInViewport($("#mydivname"))
});
$(window).resize(function () {
topInViewport($("#mydivname"))
});
$(window).scroll(function () {
topInViewport($("#mydivname"))
});
Or bind to them all using on
:
$(window).on("load resize scroll",function(e){
topInViewport($("#mydivname"))
});
For Delete files from the public folders, we can use the File::delete
function into the Laravel. For use File
need to use File
into the controller OR We can use \File
. This consider the root of the file.
// Delete a single file
File::delete($filename);
For delete Multiple files
// Delete multiple files
File::delete($file1, $file2, $file3);
Delete an array of Files
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
Well if you want to make a semi-obfuscated code you make code like this:
import base64
import zlib
def run(code): exec(zlib.decompress(base64.b16decode(code)))
def enc(code): return base64.b16encode(zlib.compress(code))
and make a file like this (using the above code):
f = open('something.py','w')
f.write("code=" + enc("""
print("test program")
print(raw_input("> "))"""))
f.close()
file "something.py":
code = '789CE352008282A2CCBC120DA592D4E212203B3FBD28315749930B215394581E9F9957500A5463A7A0A4A90900ADFB0FF9'
just import "something.py" and run run(something.code)
to run the code in the file.
One trick is to make the code hard to read by design: never document anything, if you must, just give the output of a function, not how it works. Make variable names very broad, movie references, or opposites example: btmnsfavclr = 16777215
where as "btmnsfavclr
" means "Batman's Favorite Color" and the value is 16777215
or the decimal form of "ffffff
" or white. Remember to mix different styles of naming to keep those pesky people of of your code. Also, use tips on this site: Top 11 Tips to Develop Unmaintainable Code.
If you work in PyCharm
, check the Environmental variables
for your Django server
. You should specify the proper module.settings
file
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
Use map.panTo();
does not do anything if the point is in the current view. Use map.setView()
instead.
I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/
mymap.setView(point, 11, { animation: true });
BAD: https://jsfiddle.net/nstudor/Lgahv905/
mymap.panTo(point);
mymap.setZoom(11);
Just found this version of 3d noise for GPU, alledgedly it is the fastest one available:
#ifndef __noise_hlsl_
#define __noise_hlsl_
// hash based 3d value noise
// function taken from https://www.shadertoy.com/view/XslGRr
// Created by inigo quilez - iq/2013
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
// ported from GLSL to HLSL
float hash( float n )
{
return frac(sin(n)*43758.5453);
}
float noise( float3 x )
{
// The noise function returns a value in the range -1.0f -> 1.0f
float3 p = floor(x);
float3 f = frac(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0 + 113.0*p.z;
return lerp(lerp(lerp( hash(n+0.0), hash(n+1.0),f.x),
lerp( hash(n+57.0), hash(n+58.0),f.x),f.y),
lerp(lerp( hash(n+113.0), hash(n+114.0),f.x),
lerp( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z);
}
#endif
For Python 2.7:
As it says here,
You don't need to download
Tkinter
- it's an integral part of all Python distributions (except binary distributions for platforms that don't support Tcl/Tk).
In my case, on Windows, what helped was reinstalling the Python distribution. A long time ago, I had unchecked the "Tcl/Tk" installation feature. After reinstalling, all works fine and I can import _tkinter
and import Tkinter
.
Last version of jupyter notebook accepts copy/paste of image natively
Use this code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
conn.Open();
MessageBox.Show("Connection Open !");
conn.Close();
I've tried different cases and only when owner was set to nginx (chown -R nginx:nginx "/var/www/myfolder"
) - it started to work as expected.
You have to use bracket notation:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}
.
There is also Mappa - http://mappatool.com/.
It only supports polygons, but they are definitely the hardest parts :)
Including numbers but not whitespace:
"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").toCharArray();
=> S, t, a, c, k, M, e, 1, 2, 3, H, e, p, p, a, 1, o, e, u
Without numbers and whitespace:
"Stack Me 123 Heppa1 oeu".replaceAll("[^a-z^A-Z]","").toCharArray()
=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u
It looks like you are calling next even if the scanner no longer has a next element to provide... throwing the exception.
while(!file.next().equals(treasure)){
file.next();
}
Should be something like
boolean foundTreasure = false;
while(file.hasNext()){
if(file.next().equals(treasure)){
foundTreasure = true;
break; // found treasure, if you need to use it, assign to variable beforehand
}
}
// out here, either we never found treasure at all, or the last element we looked as was treasure... act accordingly
Once you used
stmt->execute();
You MAY close it to use another query.
stmt->close();
This problem was hunting me for hours. Hopefully, it will fix yours.
For limit 1
use methods FirstOrDefault()
or First()
.
Example
var y = (from x in q select x).FirstOrDefault();
This should answer that question, and then some.
The second line, if (obj.GetType() == typeof(ClassA)) {}
, is faster, for those that don't want to read the article.
(Be aware that they don't do the same thing)
The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)
Example
ALTER TABLE 0_value_addition_setup ADD UNIQUE (`value_code`)
If anyone is coming here looking to do this with Font Awesome Icons (like I was) view here: https://fontawesome.com/how-to-use/on-the-web/styling/icons-in-a-list
<ul class="fa-ul">
<li><i class="fa-li fa fa-check-square"></i>List icons</li>
<li><i class="fa-li fa fa-check-square"></i>can be used</li>
<li><i class="fa-li fa fa-spinner fa-spin"></i>as bullets</li>
<li><i class="fa-li fa fa-square"></i>in lists</li>
</ul>
The fa-ul
and fa-li
classes easily replace default bullets in unordered lists.
This is the most stable (and easy) way to do it, and it works in all modern browsers:
.fullscreen {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
overflow: auto;_x000D_
background: lime; /* Just to visualize the extent */_x000D_
_x000D_
}
_x000D_
<div class="fullscreen">_x000D_
Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa._x000D_
</div>
_x000D_
Tested to work in Firefox, Chrome, Opera, Vivaldi, IE7+ (based on emulation in IE11).
Change *.cs to .cs in the excludefileslist.txt
You need to create a git repo locally, add your project files to that repo, commit them to the local repo, and then sync that repo to your repo on github. You can find good instructions on how to do the latter bit on github, and the former should be easy to do with the software you've downloaded.
If people are using shared Linux hosting with cPanel (Godaddy, Reseller club, Hostgator or any Shared Hosting), try the following:
Under Software and Services tab -> Select PHP Version -> PHP Selectors | Extentions
Tick all MySQL related extensions, save it and you are done. Please check the attached image.
Use argument "--query-compute-apps="
nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv
for further help, please follow
nvidia-smi --help-query-compute-app
Well if you are new to C# with cmd-line exp. you can use online sites like "https://curl.olsh.me/" or search curl to C# converter will returns site that could do that for you.
or if you are using postman you can use Generate Code Snippet only problem with Postman code generator is the dependency on RestSharp library.
Anyone who has this error, especially on Azure, try adding "tcp:" to the db-server-name in your connection string in your application. This forces the sql client to communicate with the db using tcp. I'm assuming the connection is UDP by default and there can be intermittent connection issues
An alternate solution of @kender
import os
os.path.dirname(os.path.normpath(yourpath))
where yourpath
is the path you want the parent for.
But this solution is not perfect, since it will not handle the case where yourpath
is an empty string, or a dot.
This other solution will handle more nicely this corner case:
import os
os.path.normpath(os.path.join(yourpath, os.pardir))
Here the outputs for every case that can find (Input path is relative):
os.path.dirname(os.path.normpath('a/b/')) => 'a'
os.path.normpath(os.path.join('a/b/', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/b')) => 'a'
os.path.normpath(os.path.join('a/b', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/')) => ''
os.path.normpath(os.path.join('a/', os.pardir)) => '.'
os.path.dirname(os.path.normpath('a')) => ''
os.path.normpath(os.path.join('a', os.pardir)) => '.'
os.path.dirname(os.path.normpath('.')) => ''
os.path.normpath(os.path.join('.', os.pardir)) => '..'
os.path.dirname(os.path.normpath('')) => ''
os.path.normpath(os.path.join('', os.pardir)) => '..'
os.path.dirname(os.path.normpath('..')) => ''
os.path.normpath(os.path.join('..', os.pardir)) => '../..'
Input path is absolute (Linux path):
os.path.dirname(os.path.normpath('/a/b')) => '/a'
os.path.normpath(os.path.join('/a/b', os.pardir)) => '/a'
os.path.dirname(os.path.normpath('/a')) => '/'
os.path.normpath(os.path.join('/a', os.pardir)) => '/'
os.path.dirname(os.path.normpath('/')) => '/'
os.path.normpath(os.path.join('/', os.pardir)) => '/'
For Kotlin, if you want to be sure that the format is "Aaaaaaaaa" you can use :
myString.toLowerCase(Locale.getDefault()).capitalize()
It doesn't work for me either when there are multiple foreign key tables.
I found that code that works and does everything you try (delete all tables from your database):
DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_SCHEMA + '].[' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + '];'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec sp_executesql @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO
You can find the post here. It is the post by Groker.
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = @"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)
Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:
var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'Ajax.ashx',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
Things to notice:
JSON.stringify
method to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include json2.jscontentType
property in order to indicate to the server the intent of sending a JSON requestdataType: 'json'
property is used for the response type you expect from the server. jQuery is intelligent enough to guess it from the server Content-Type
response header. So if you have a web server which respects more or less the HTTP protocol and responds with Content-Type: application/json
to your request jQuery will automatically parse the response into a javascript object into the success
callback so that you don't need to specify the dataType
property.Things to be careful about:
arr
is not an array. It is a javascript object with properties (City
and Age
). Arrays are denoted with []
in javascript. For example [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]
is an array of 2 objects.By omitting all parts of the head, the loop can also become infinite:
for (;;) {}
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
Guava's ComparisonChain:
Collections.sort(list, new Comparator<ActiveAlarm>(){
@Override
public int compare(ActiveAlarm a1, ActiveAlarm a2) {
return ComparisonChain.start()
.compare(a1.timestarted, a2.timestarted)
//...
.compare(a1.timeEnded, a1.timeEnded).result();
}});
If you don't need to worry about scientific or other expressions of numbers and are only working with strings that could be numbers with or without a period:
Function
def is_float(s):
result = False
if s.count(".") == 1:
if s.replace(".", "").isdigit():
result = True
return result
Lambda version
is_float = lambda x: x.replace('.','',1).isdigit() and "." in x
Example
if is_float(some_string):
some_string = float(some_string)
elif some_string.isdigit():
some_string = int(some_string)
else:
print "Does not convert to int or float."
This way you aren't accidentally converting what should be an int, into a float.
#include <windows.h>
#include <map>
#include <string>
#include <stdio.h>
#include <string.h>
#include <tr1/stdint.h>
using namespace std;
void printerr(DWORD dwerror) {
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwerror,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
// Process any inserts in lpMsgBuf.
// ...
// Display the string.
if (isOut) {
fprintf(fout, "%s\n", lpMsgBuf);
} else {
printf("%s\n", lpMsgBuf);
}
// Free the buffer.
LocalFree(lpMsgBuf);
}
bool regreadSZ(string& hkey, string& subkey, string& value, string& returnvalue, string& regValueType) {
char s[128000];
map<string,HKEY> keys;
keys["HKEY_CLASSES_ROOT"]=HKEY_CLASSES_ROOT;
keys["HKEY_CURRENT_CONFIG"]=HKEY_CURRENT_CONFIG; //DID NOT SURVIVE?
keys["HKEY_CURRENT_USER"]=HKEY_CURRENT_USER;
keys["HKEY_LOCAL_MACHINE"]=HKEY_LOCAL_MACHINE;
keys["HKEY_USERS"]=HKEY_USERS;
HKEY mykey;
map<string,DWORD> valuetypes;
valuetypes["REG_SZ"]=REG_SZ;
valuetypes["REG_EXPAND_SZ"]=REG_EXPAND_SZ;
valuetypes["REG_MULTI_SZ"]=REG_MULTI_SZ; //probably can't use this.
LONG retval=RegOpenKeyEx(
keys[hkey], // handle to open key
subkey.c_str(), // subkey name
0, // reserved
KEY_READ, // security access mask
&mykey // handle to open key
);
if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
DWORD slen=128000;
DWORD valuetype = valuetypes[regValueType];
retval=RegQueryValueEx(
mykey, // handle to key
value.c_str(), // value name
NULL, // reserved
(LPDWORD) &valuetype, // type buffer
(LPBYTE)s, // data buffer
(LPDWORD) &slen // size of data buffer
);
switch(retval) {
case ERROR_SUCCESS:
//if (isOut) {
// fprintf(fout,"RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
//} else {
// printf("RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
//}
break;
case ERROR_MORE_DATA:
//what do I do now? data buffer is too small.
if (isOut) {
fprintf(fout,"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
} else {
printf("RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
}
return false;
case ERROR_FILE_NOT_FOUND:
if (isOut) {
fprintf(fout,"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
} else {
printf("RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
}
return false;
default:
if (isOut) {
fprintf(fout,"RegQueryValueEx():unknown error type 0x%lx.\n", retval);
} else {
printf("RegQueryValueEx():unknown error type 0x%lx.\n", retval);
}
return false;
}
retval=RegCloseKey(mykey);
if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
returnvalue = s;
return true;
}
I had same issue as I had missed adding composeEnhancers. Once this is setup then you can take a look into action creators. You get this error when this is not setup as well.
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(thunk))
);
You should only need to do one of:
inline
(or inline-block
)float
left or rightYou should be able to adjust the height
, padding
, or margin
properties of the smaller heading to compensate for its positioning. I recommend setting both headings to have the same height
.
See this live jsFiddle for an example.
(code of the jsFiddle):
CSS
h2 {
font-size: 50px;
}
h3 {
font-size: 30px;
}
h2, h3 {
width: 50%;
height: 60px;
margin: 0;
padding: 0;
display: inline;
}?
HTML
<h2>Big Heading</h2>
<h3>Small(er) Heading</h3>
<hr />?
I personally use import because, we can import the required methods, members by using import.
import {foo, bar} from "dep";
FileName: dep.js
export foo function(){};
export const bar = 22
Credit goes to Paul Shan. More info.
I have a bash script that calls a small python routine to display a message window. As I need to use killall to stop the python script I can't use the above method as it would then mean running killall python which could take out other python programmes so I use
pythonprog.py "$argument"
& # The & returns control straight to the bash script so must be outside the backticks. The preview of this message is showing it without "`" either side of the command for some reason.
As long as the python script will run from the cli by name rather than python pythonprog.py this works within the script. If you need more than one argument just use a space between each one within the quotes.
Add this below code(<handler>
) on your web.config within <system.webServer>
:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
I've pushed django-pdb
to PyPI.
It's a simple app that means you don't need to edit your source code every time you want to break into pdb.
Installation is just...
pip install django-pdb
'django_pdb'
to your INSTALLED_APPS
You can now run: manage.py runserver --pdb
to break into pdb at the start of every view...
bash: manage.py runserver --pdb
Validating models...
0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}
> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)
And run: manage.py test --pdb
to break into pdb on test failures/errors...
bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
one_plus_one = four
NameError: global name 'four' is not defined
======================================================================
> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)
The project's hosted on GitHub, contributions are welcome of course.
$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);
you can change LIMIT 1 to LIMIT any number you want
This will show you the last INSERTED row first.
For own property :
var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount"))
{
//will execute
}
Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)
const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi)
console.log("Yoshi can skulk");
if (!("sneak" in yoshi))
console.log("Yoshi cannot sneak");
if (!("creep" in yoshi))
console.log("Yoshi cannot creep");
Object.setPrototypeOf(yoshi, hattori);
if ("sneak" in yoshi)
console.log("Yoshi can now sneak");
if (!("creep" in hattori))
console.log("Hattori cannot creep");
Object.setPrototypeOf(hattori, kuma);
if ("creep" in hattori)
console.log("Hattori can now creep");
if ("creep" in yoshi)
console.log("Yoshi can also creep");
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...
var loan = { amount: 150 };
loan.installment = undefined;
if("installment" in loan) // correct
{
// will execute
}
if(typeof loan["installment"] !== "undefined") // incorrect
{
// will not execute
}
The answers above are very good I'm sure. But for dim-wits, like me, I recommend Snagit 10. You can give an image a border in any width, style, and color before inserting it into your webpage. They do a full working program on 30 day trial.
I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.
Wrap up content like below,
var params = {
"IDs": IDs,
"ID2s": IDs2,
"id": 1
};
In my case I had already json'd the arrays and passed the result to the function
var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());
Then call the XMLHttpRequest POST and stringify the object
var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
var blob = new Blob([this.response], { type: "application/octet-stream" });
saveAs(blob, "filename.zip");
}
};
ajax.send(JSON.stringify(params));
Then have a model like this
public class MyModel
{
public int[] IDs { get; set; }
public int[] ID2s { get; set; }
public int id { get; set; }
}
Then pass in Action like
public async Task<IActionResult> MyAction([FromBody] MyModel model)
Use this add-on if your returning a file
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
You may try the following:
System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);
I hope these functions will help you.
$('#your-select').multiSelect('select', String|Array);
$('#your-select').multiSelect('deselect', String|Array);
$('#your-select').multiSelect('select_all');
$('#your-select').multiSelect('deselect_all');
$('#your-select').multiSelect('refresh');
Reference by this site Reference
The other answers are great but I thought I'd take a different tact.
If all you are really looking for is to slow down a specific file in linux:
rm slowfile; mkfifo slowfile; perl -e 'select STDOUT; $| = 1; while(<>) {print $_; sleep(1) if (($ii++ % 5) == 0); }' myfile > slowfile &
node myprog slowfile
This will sleep 1 sec every five lines. The node program will go as slow as the writer. If it is doing other things they will continue at normal speed.
The mkfifo creates a first-in-first-out pipe. It's what makes this work. The perl line will write as fast as you want. The $|=1 says don't buffer the output.
If you want to pass an app-instance to others in Node-Typescript :
Option 1:
With the help of import
(when importing)
//routes.ts
import { Application } from "express";
import { categoryRoute } from './routes/admin/category.route'
import { courseRoute } from './routes/admin/course.route';
const routing = (app: Application) => {
app.use('/api/admin/category', categoryRoute)
app.use('/api/admin/course', courseRoute)
}
export { routing }
Then import it and pass app:
import express, { Application } from 'express';
const app: Application = express();
import('./routes').then(m => m.routing(app))
Option 2: With the help of class
// index.ts
import express, { Application } from 'express';
import { Routes } from './routes';
const app: Application = express();
const rotues = new Routes(app)
...
Here we will access the app in the constructor of Routes Class
// routes.ts
import { Application } from 'express'
import { categoryRoute } from '../routes/admin/category.route'
import { courseRoute } from '../routes/admin/course.route';
class Routes {
constructor(private app: Application) {
this.apply();
}
private apply(): void {
this.app.use('/api/admin/category', categoryRoute)
this.app.use('/api/admin/course', courseRoute)
}
}
export { Routes }
The META-INF folder is the home for the MANIFEST.MF file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.
Use __new__
to return value from a class.
As others suggest __repr__
,__str__
or even __init__
(somehow) CAN give you what you want, But __new__
will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.
Read this answer for more insights into __str__
and __repr__
https://stackoverflow.com/a/19331543/4985585
class MyClass():
def __new__(cls):
return list() #or anything you want
>>> MyClass()
[] #Returns a true list not a repr or string
let a: number[] = [];
a.push(1);
a.push(2);
a.push(3);
let index: number = a.findIndex(a => a === 1);
if (index != -1) {
a.splice(index, 1);
}
console.log(a);
I wrote a very tiny plugin called "once" which do that. Execute off and on in element.
$.fn.once = function(a, b) {
return this.each(function() {
$(this).off(a).on(a,b);
});
};
And simply:
$(element).once('click', function(){
});
Here comes a powershell code I write to list size and file count for all folders under current directory. Feel free to re-use or modify per your need.
$FolderList = Get-ChildItem -Directory
foreach ($folder in $FolderList)
{
set-location $folder.FullName
$size = Get-ChildItem -Recurse | Measure-Object -Sum Length
$info = $folder.FullName + " FileCount: " + $size.Count.ToString() + " Size: " + [math]::Round(($size.Sum / 1GB),4).ToString() + " GB"
write-host $info
}
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE
instead of xhr.readyState === 4
The problem is that Internet Explorer uses different state names so it's better to use state values.
For those who could not fix the problem with the other solutions here, the following fix worked for me:
Go to your "DATA" folder in your SQL Server installation, right click, properties, security tab, and add full control permissions for the "NETWORK SERVICE" user.
http://decoding.wordpress.com/2008/08/25/sql-server-2005-expess-how-to-fix-error-3417/
(The above link is for SQL 2005, but this fixed a SQL 2008 R2 installation for me).
Some additional info: This problem showed up for me after replacing a secondary hard drive (which the SQL installation was on). I copied all the files, and restored the original drive letter to the new hard disk. However, the security permissions were not copied over. I think next time I will use a better method of copying data.
Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.
you need littler (pronounced 'little r')
Dirk will be by in about 15 minutes to elaborate ;)
Give the first div float: left;
and a fixed width, and give the second div width: 100%;
and float: left;
. That should do the trick. If you want to place items below it you need a clear: both;
on the item you want to place below it.
You should use Modernizr, it will add a class to the body tag.
also:
function getIeVersion()
{
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
else if (navigator.appName == 'Netscape')
{
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
Note that IE11 is still is in preview, and the user agent may change before release.
The User-agent string for IE 11 is currently this one :
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko
Which means your can simply test, for versions 11.xx,
var isIE11 = !!navigator.userAgent.match(/Trident.*rv 11\./)
I think I have come up with a quite shorter solution.. Hope it helps someone.
cbind.na<-function(df1, df2){
#Collect all unique rownames
total.rownames<-union(x = rownames(x = df1),y = rownames(x=df2))
#Create a new dataframe with rownames
df<-data.frame(row.names = total.rownames)
#Get absent rownames for both of the dataframe
absent.names.1<-setdiff(x = rownames(df1),y = rownames(df))
absent.names.2<-setdiff(x = rownames(df2),y = rownames(df))
#Fill absents with NAs
df1.fixed<-data.frame(row.names = absent.names.1,matrix(data = NA,nrow = length(absent.names.1),ncol=ncol(df1)))
colnames(df1.fixed)<-colnames(df1)
df1<-rbind(df1,df1.fixed)
df2.fixed<-data.frame(row.names = absent.names.2,matrix(data = NA,nrow = length(absent.names.2),ncol=ncol(df2)))
colnames(df2.fixed)<-colnames(df2)
df2<-rbind(df2,df2.fixed)
#Finally cbind into new dataframe
df<-cbind(df,df1[rownames(df),],df2[rownames(df),])
return(df)
}
if anyone else need the solution
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed(); return true;
}
return super.onOptionsItemSelected(item);
}
If the array keys in your PHP array are not consecutive numbers, json_encode()
must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.
Use array_values()
on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:
// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
2 => array("Afghanistan", 32, 13),
4 => array("Albania", 32, 12)
);
// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]
#y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.
For completeness, it is also a rather important (and relatively new) method in statistics that uses resampling / simulation to infer population properties from a sample. It has its own lengthy Wikipedia article on bootstrapping (statistics).
This issue was with me also. Simple trick for it.
@NgModule({
imports: [
.....
],
declarations: [
......
],
providers: [...],
bootstrap: [...]
})
use it as in above order.first imports then declarations.It worked for me.
You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.
Try HashSet:
The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...
The capacity of a HashSet(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object.
The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary(Of TKey, TValue) or Hashtable collections. In simple terms, the HashSet(Of T) class can be thought of as a Dictionary(Of TKey, TValue) collection without values.
A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...
.md is markdown
. README.md
is used to generate the html
summary you see at the bottom of projects. Github has their own flavor of Markdown.
Order of Preference: If you have two files named README
and README.md
, the file named README.md
is preferred, and it will be used to generate github's html
summary.
FWIW, Stack Overflow uses local Markdown modifications as well (also see Stack Overflow's C# Markdown Processor)
df.index.rename('new name', inplace=True)
Is the only one that does the job for me (pandas 0.22.0).
Without the inplace=True, the name of the index is not set in my case.
oracleserviceorcl
service. (From services in Task Manager)ORACLE_SID
variable with orcl
value. (In environment variables)Install Git from https://git-scm.com/download/win
Open Visual Studio Code and press and hold Ctrl + ` to open the terminal.
Open the command palette using Ctrl + Shift + P.
Type - Select Default Shell
Select Git Bash from the options
Click on the + icon in the terminal window
The new terminal now will be a Git Bash terminal. Give it a few seconds to load Git Bash
You can now toggle between the different terminals as well from the dropdown in terminal.
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
In my case, I found that a computed column had been added to the "included columns" of an index. Later, when an item in that table was updated, the merge
statement failed with that message. The merge was in a trigger, so this was hard to track down! Removing the computed column from the index fixed it.
To split vertically:
?+\ Mac
command: workbench.action.splitEditor
To split orthogonal (ie. horizontally in this case):
?+k+?+\ Mac
command: workbench.action.splitEditorOrthogonal
The answer is nice, but it introduces one problem. Whenever you assign onload
or onerror
directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.
Let me rewrite the answer a little bit.
function testImage(url) {
var tester = new Image();
tester.addEventListener('load', imageFound);
tester.addEventListener('error', imageNotFound);
tester.src = url;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.
function testImage(url) {
// Define the promise
const imgPromise = new Promise(function imgPromise(resolve, reject) {
// Create the image
const imgElement = new Image();
// When image is loaded, resolve the promise
imgElement.addEventListener('load', function imgOnLoad() {
resolve(this);
});
// When there's an error during load, reject the promise
imgElement.addEventListener('error', function imgOnError() {
reject();
})
// Assign URL
imgElement.src = url;
});
return imgPromise;
}
testImage("http://foo.com/bar.jpg").then(
function fulfilled(img) {
console.log('That image is found and loaded', img);
},
function rejected() {
console.log('That image was not found');
}
);
If its a Java
version problem, you can edit the eclipse.ini
file and assign the compatible version to the application through adding these lines:
windows example:
-vm
C:\jdk1.7.0_21\bin\javaw.exe
for more information: https://wiki.eclipse.org/Eclipse.ini
To blank it:
myObject["myVar"]=null;
To remove it:
delete myObject["myVar"]
as you can see in duplicate answers
If you have a hidden field like this
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>
Now you can use your value like this
$(this).parent().find('input[type=hidden]').val()
@Jacob already showed you how to use the Gaussian filter in Matlab, so I won't repeat that.
I would choose filter size to be about 3*sigma in each direction (round to odd integer). Thus, the filter decays to nearly zero at the edges, and you won't get discontinuities in the filtered image.
The choice of sigma depends a lot on what you want to do. Gaussian smoothing is low-pass filtering, which means that it suppresses high-frequency detail (noise, but also edges), while preserving the low-frequency parts of the image (i.e. those that don't vary so much). In other words, the filter blurs everything that is smaller than the filter.
If you're looking to suppress noise in an image in order to enhance the detection of small features, for example, I suggest to choose a sigma that makes the Gaussian just slightly smaller than the feature.
Just for the next guy searching for a micropython solution, this works purely based on os (listdir, remove, rmdir). It is neither complete (especially in errorhandling) nor fancy, it will however work in most circumstances.
def deltree(target):
print("deltree", target)
for d in os.listdir(target):
try:
deltree(target + '/' + d)
except OSError:
os.remove(target + '/' + d)
os.rmdir(target)
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol()); //http
System.out.println("authority = " + aURL.getAuthority()); //example.com:80
System.out.println("host = " + aURL.getHost()); //example.com
System.out.println("port = " + aURL.getPort()); //80
System.out.println("path = " + aURL.getPath()); // /docs/books/tutorial/index.html
System.out.println("query = " + aURL.getQuery()); //name=networking
System.out.println("filename = " + aURL.getFile()); ///docs/books/tutorial/index.html?name=networking
System.out.println("ref = " + aURL.getRef()); //DOWNLOADING
}
}
@K Scott Piel wrote a great answer here, but I want to add one important point.
Note that the stdout
stream is usually line-buffered, so to ensure the output is actually printed and not just left sitting in the buffer waiting to be written you must flush the buffer by either ending your printf
statement with a \n
Ex:
printf("hello world\n");
or
printf("hello world");
printf("\n");
or similar, OR you must call fflush(stdout);
after your printf
call.
Ex:
printf("hello world");
fflush(stdout);
Read more here: Why does printf not flush after the call unless a newline is in the format string?
Using Eclipe Oxygen command + Shift + c on macOSx Sierra will add/remove comments out multiple lines of code
$('#my_select').bind('mousedown', function (event) {_x000D_
event.preventDefault();_x000D_
event.stopImmediatePropagation();_x000D_
});
_x000D_
FrameLayout
is not the better way to do this:
Use RelativeLayout
instead.
You can position the elements anywhere you like.
The element that comes after, has the higher z-index than the previous one (i.e. it comes over the previous one).
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
app:srcCompat="@drawable/ic_information"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a text."
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_margin="8dp"
android:padding="5dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#A000"
android:textColor="@android:color/white"/>
</RelativeLayout>
Explicit access to module level variables by accessing them explicity on the module
In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).
Think of it like self for the current module instead of the current instance !
# db.py
import sys
# this is a pointer to the module object instance itself.
this = sys.modules[__name__]
# we can explicitly make assignments on it
this.db_name = None
def initialize_db(name):
if (this.db_name is None):
# also in local function scope. no scope specifier like global is needed
this.db_name = name
# also the name remains free for local use
db_name = "Locally scoped db_name variable. Doesn't do anything here."
else:
msg = "Database is already initialized to {0}."
raise RuntimeError(msg.format(this.db_name))
As modules are cached and therefore import only once, you can import db.py
as often on as many clients as you want, manipulating the same, universal state:
# client_a.py
import db
db.initialize_db('mongo')
# client_b.py
import db
if (db.db_name == 'mongo'):
db.db_name = None # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value
# that "db.db_name" has at import time of "client_c".
if (db_name == 'mongo'): # checking is fine if "db.db_name" doesn't change
db_name = None # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.
As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.
First of all, tf.train.GradientDescentOptimizer
is designed to use a constant learning rate for all variables in all steps. TensorFlow also provides out-of-the-box adaptive optimizers including the tf.train.AdagradOptimizer
and the tf.train.AdamOptimizer
, and these can be used as drop-in replacements.
However, if you want to control the learning rate with otherwise-vanilla gradient descent, you can take advantage of the fact that the learning_rate
argument to the tf.train.GradientDescentOptimizer
constructor can be a Tensor
object. This allows you to compute a different value for the learning rate in each step, for example:
learning_rate = tf.placeholder(tf.float32, shape=[])
# ...
train_step = tf.train.GradientDescentOptimizer(
learning_rate=learning_rate).minimize(mse)
sess = tf.Session()
# Feed different values for learning rate to each training step.
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.01})
sess.run(train_step, feed_dict={learning_rate: 0.01})
Alternatively, you could create a scalar tf.Variable
that holds the learning rate, and assign it each time you want to change the learning rate.
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})
To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:
JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);
And if you have an image:
JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);
But, I believe you want to make the label such that there are only 2 words on 1 line.
In that case try this:
String urText="<html>You can<br>use basic HTML<br>in Swing<br> components,"
+"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);
Yes it can mean so, or it can be a simple iterator. For example: Example as iterator:
a=set(['1','2','3'])
for x in a:
print ('This set contains the value ' + x)
Similarly as a check:
a=set('ILovePython')
if 'I' in a:
print ('There is an "I" in here')
edited: edited to include sets rather than lists and strings
This means that Table A can have one or more records relating to a single record in Table B.
If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:
ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id)
fk_b
: Name of the foreign key constraint, must be unique to the databaseb_id
: Name of column in Table A you are creating the foreign key relationship onb
: Name of table, in this case bid
: Name of column in Table BThe following code demonstrates if you need to produce the same items. You can also specify how many samples you want to extract.
The sample
method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.
import random as random
random.seed(0) # don't use seed function, if you want different results in each run
print(random.sample(foo,3)) # 3 is the number of sample you want to retrieve
Output:['d', 'e', 'a']
I would prefer to use neither in most cases. The problem with properties is that they make the class less transparent. Especially, this is an issue if you were to raise an exception from a setter. For example, if you have an Account.email property:
class Account(object):
@property
def email(self):
return self._email
@email.setter
def email(self, value):
if '@' not in value:
raise ValueError('Invalid email address.')
self._email = value
then the user of the class does not expect that assigning a value to the property could cause an exception:
a = Account()
a.email = 'badaddress'
--> ValueError: Invalid email address.
As a result, the exception may go unhandled, and either propagate too high in the call chain to be handled properly, or result in a very unhelpful traceback being presented to the program user (which is sadly too common in the world of python and java).
I would also avoid using getters and setters:
Instead of properties and getters/setters I prefer doing the complex logic in well defined places such as in a validation method:
class Account(object):
...
def validate(self):
if '@' not in self.email:
raise ValueError('Invalid email address.')
or a similiar Account.save method.
Note that I am not trying to say that there are no cases when properties are useful, only that you may be better off if you can make your classes simple and transparent enough that you don't need them.
I was facing the same issue. I renamed my php folder from php7_winxxxx
to just php and it worked fine. It looked like composer was checking the location to the php_openssl module in c:/php/ext
.
You may also need to add c:/php
to the PATH
in environment variable
Just in case you are looking for a way to trim and keep the LAST 10 characters of a string.
s = s.substring(Math.max(s.length(),10) - 10);
I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.
Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.
One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.
Needed to do a reverse on $.each so i used Vinay idea:
//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});
worked nicely, thanks
You don't need (shouldn't use) a function as far as I can tell. The stored procedure will return tabular data from any SELECT statements you include that return tabular data.
A stored proc does not use RETURN statements.
CREATE PROCEDURE name
AS
SELECT stuff INTO #temptbl1
.......
SELECT columns FROM #temptbln
Just to add to other comments - it would be worth while to disable scrolling up whilst at the top of the page. If the user accidentally scrolls up whilst already at the top they would have to scroll down twice to start
if(scrolled != 0){
$("#upClick").on("click" ,function(){
scrolled=scrolled-300;
$(".cover").animate({
scrollTop: scrolled
});
});
}
You should definitely encapsulate this logic into a method.
There is no benefit to repeating identical code multiple times.
Also, if you place the logic in a method and it changes, you only need to modify your code in one place.
Whether or not you want to use a 3rd party library is an entirely different decision.
Try:
public class ImageComponent extends JComponent {
private final BufferedImage img;
public ImageComponent(URL url) throws IOException {
img = ImageIO.read(url);
setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
}
public static void main(String[] args) throws Exception {
final URL kitten = new URL("https://placekitten.com/g/200/300");
final ImageComponent image = new ImageComponent(kitten);
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(image));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:
api.com/users?id=id1,id2,id3,id4,id5
Like this:
>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'
This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4]
removes the same 4 characters from the end of the string:
>>>mystr[:-4]
'abcdefgh'
For more information on slicing see this Stack Overflow answer.
Open the source tab in 'Developer Tools', click on a line number in a script that is running, this will create a breakpoint and the debugger will break there.
nasm -f bin -o 2_hello 2_hello.asm
Another way would be to define an interface IThing and then implement it in both classes here's the snipet:
public interface IThing
{
void Move();
}
public class ThingA : IThing
{
public void Move()
{
Hop();
}
public void Hop(){
//Implementation of Hop
}
}
public class ThingA : IThing
{
public void Move()
{
Skip();
}
public void Skip(){
//Implementation of Skip
}
}
public class Foo
{
static void Main(String[] args)
{
}
private void Foo(IThing a)
{
a.Move();
}
}
Interesting. The consensus from most of these answers seems to be that the redundant break
statement is unnecessary clutter. On the other hand, I read the break
statement in a switch as the 'closing' of a case. case
blocks that don't end in a break
tend to jump out at me as potential fall though bugs.
I know that that's not how it is when there's a return
instead of a break
, but that's how my eyes 'read' the case blocks in a switch, so I personally would prefer that each case
be paired with a break
. But many compilers do complain about the break
after a return
being superfluous/unreachable, and apparently I seem to be in the minority anyway.
So get rid of the break
following a return
.
NB: all of this is ignoring whether violating the single entry/exit rule is a good idea or not. As far as that goes, I have an opinion that unfortunately changes depending on the circumstances...
I tested this and it works fine for me:
from PIL import Image
im = Image.open('image.jpg')
im.show()
I believe there is still no ideal solution that would correctly preserve all whitespace characters and is fast enough, so I'll post my answer. Using ${foo:$i:1}
works, but is very slow, which is especially noticeable with large strings, as I will show below.
My idea is an expansion of a method proposed by Six, which involves read -n1
, with some changes to keep all characters and work correctly for any string:
while IFS='' read -r -d '' -n 1 char; do
# do something with $char
done < <(printf %s "$string")
How it works:
IFS=''
- Redefining internal field separator to empty string prevents stripping of spaces and tabs. Doing it on a same line as read
means that it will not affect other shell commands.-r
- Means "raw", which prevents read
from treating \
at the end of the line as a special line concatenation character.-d ''
- Passing empty string as a delimiter prevents read
from stripping newline characters. Actually means that null byte is used as a delimiter. -d ''
is equal to -d $'\0'
.-n 1
- Means that one character at a time will be read.printf %s "$string"
- Using printf
instead of echo -n
is safer, because echo
treats -n
and -e
as options. If you pass "-e" as a string, echo
will not print anything.< <(...)
- Passing string to the loop using process substitution. If you use here-strings instead (done <<< "$string"
), an extra newline character is appended at the end. Also, passing string through a pipe (printf %s "$string" | while ...
) would make the loop run in a subshell, which means all variable operations are local within the loop.Now, let's test the performance with a huge string.
I used the following file as a source:
https://www.kernel.org/doc/Documentation/kbuild/makefiles.txt
The following script was called through time
command:
#!/bin/bash
# Saving contents of the file into a variable named `string'.
# This is for test purposes only. In real code, you should use
# `done < "filename"' construct if you wish to read from a file.
# Using `string="$(cat makefiles.txt)"' would strip trailing newlines.
IFS='' read -r -d '' string < makefiles.txt
while IFS='' read -r -d '' -n 1 char; do
# remake the string by adding one character at a time
new_string+="$char"
done < <(printf %s "$string")
# confirm that new string is identical to the original
diff -u makefiles.txt <(printf %s "$new_string")
And the result is:
$ time ./test.sh
real 0m1.161s
user 0m1.036s
sys 0m0.116s
As we can see, it is quite fast.
Next, I replaced the loop with one that uses parameter expansion:
for (( i=0 ; i<${#string}; i++ )); do
new_string+="${string:$i:1}"
done
The output shows exactly how bad the performance loss is:
$ time ./test.sh
real 2m38.540s
user 2m34.916s
sys 0m3.576s
The exact numbers may very on different systems, but the overall picture should be similar.
In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]:
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
@Amber gave correct answer! Just one more addition, if you do not know the exact path of the file you can use wildcards! This worked for me.
git log --all -- **/thefile.*
I followed @Viktor Kerkez's answer and have had mixed success. I found that sometimes this recipe of
conda skeleton pypi PACKAGE
conda build PACKAGE
would look like everything worked but I could not successfully import PACKAGE. Recently I asked about this on the Anaconda user group and heard from @Travis Oliphant himself on the best way to use conda to build and manage packages that do not ship with Anaconda. You can read this thread here, but I'll describe the approach below to hopefully make the answers to the OP's question more complete...
Example: I am going to install the excellent prettyplotlib package on Windows using conda 2.2.5.
1a) conda build --build-recipe prettyplotlib
You'll see the build messages all look good until the final TEST section of the build. I saw this error
File "C:\Anaconda\conda-bld\test-tmp_dir\run_test.py", line 23 import None SyntaxError: cannot assign to None TESTS FAILED: prettyplotlib-0.1.3-py27_0
1b) Go into /conda-recipes/prettyplotlib and edit the meta.yaml file. Presently, the packages being set up like in step 1a result in yaml files that have an error in the test
section. For example, here is how mine looked for prettyplotlib
test: # Python imports imports:
-
- prettyplotlib
- prettyplotlib
Edit this section to remove the blank line preceded by the - and also remove the redundant prettyplotlib line. At the time of this writing I have found that I need to edit most meta.yaml files like this for external packages I am installing with conda, meaning that there is a blank import line causing the error along with a redundant import of the given package.
1c) Rerun the command from 1a, which should complete with out error this time. At the end of the build you'll be asked if you want to upload the build to binstar. I entered No and then saw this message:
If you want to upload this package to binstar.org later, type:
$ binstar upload C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2
That tar.bz2 file is the build that you now need to actually install.
2) conda install C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2
Following these steps I have successfully used conda to install a number of packages that do not come with Anaconda. Previously, I had installed some of these using pip, so I did pip uninstall PACKAGE
prior to installing PACKAGE with conda. Using conda, I can now manage (almost) all of my packages with a single approach rather than having a mix of stuff installed with conda, pip, easy_install, and python setup.py install.
For context, I think this recent blog post by @Travis Oliphant will be helpful for people like me who do not appreciate everything that goes into robust Python packaging but certainly appreciate when stuff "just works". conda seems like a great way forward...
The answers above and on this question either didn't work for me with Selenium 3.14 and Firefox 68.9 on Linux, or are unnecessarily complex. I needed to use a WPAD configuration, sometimes behind a proxy (on a VPN), and sometimes not. After studying the code a bit, I came up with:
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
proxy = Proxy({'proxyAutoconfigUrl': 'http://wpad/wpad.dat'})
profile = FirefoxProfile()
profile.set_proxy(proxy)
driver = webdriver.Firefox(firefox_profile=profile)
The Proxy initialization sets proxyType to ProxyType.PAC (autoconfiguration from a URL) as a side-effect.
It also worked with Firefox's autodetect, using:
from selenium.webdriver.common.proxy import ProxyType
proxy = Proxy({'proxyType': ProxyType.AUTODETECT})
But I don't think this would work with both internal URLs (not proxied) and external (proxied) the way WPAD does. Similar proxy settings should work for manual configuration as well. The possible proxy settings can be seen in the code here.
Note that directly passing the Proxy object as proxy=proxy
to the driver does NOT work--it's accepted but ignored (there should be a deprecation warning, but in my case I think Behave is swallowing it).
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str
is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str
which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.
I guess ssh
is the best secured way for this, for example :
ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"
where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.
Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain
if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config
. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.
Some extra docs over the source project main pages :
ssh and ssh-agent
man ssh
http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring
keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/
Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:
Using collections.defaultdict
:
import collections
dict_x = collections.defaultdict(list)
...
dict_x[key].append(value)
Pros: Probably best performance. Cons: Not available in Python 2.4.x.
Using dict().setdefault()
:
dict_x = {}
...
dict_x.setdefault(key, []).append(value)
Cons: Inefficient creation of unused list()
s.
Using try ... except
:
dict_x = {}
...
try:
values = dict_x[key]
except KeyError:
values = dict_x[key] = []
values.append(value)
Or:
try:
dict_x[key].append(value)
except KeyError:
dict_x[key] = [value]
I know this is an old question, but I thought I'd add my two cents anyway:
It depends on what the link is going to do, but usually, I would be pointing the link at a url that could possibly be displaying/doing the same thing, for example, if you're making a little about box pop up:
<a id="about" href="/about">About</a>
Then with jQuery
$('#about').click(function(e) {
$('#aboutbox').show();
e.preventDefault();
});
This way, very old browsers (or browsers with JavaScript disabled) can still navigate to a separate about page, but more importantly, Google will also pick this up and crawl the contents of the about page.
To make it more generic of keeping both columns in df1
and df2
:
import pyspark.sql.functions as F
# Keep all columns in either df1 or df2
def outter_union(df1, df2):
# Add missing columns to df1
left_df = df1
for column in set(df2.columns) - set(df1.columns):
left_df = left_df.withColumn(column, F.lit(None))
# Add missing columns to df2
right_df = df2
for column in set(df1.columns) - set(df2.columns):
right_df = right_df.withColumn(column, F.lit(None))
# Make sure columns are ordered the same
return left_df.union(right_df.select(left_df.columns))
what @eldarerathis said is correct in all aspects, the wake lock is the right way of keeping the device from going to sleep.
I don't know waht you app needs to do but it is really important that you think on how architect your app so that you don't force the phone to stay awake for more that you need, or the battery life will suffer enormously.
I would point you to this really good example on how to use AlarmManager
to fire events and wake up the phone and (your app) to perform what you need to do and then go to sleep again: Alarm Manager (source: commonsware.com)
See this question for the why (taken from the comments).
If you really need to do something like this, you may want an abstract base class rather than an interface.
I was looking at the same statistics problems. The approach you are thinking it is good and it will work. (Answer to the sorting has been given)
But in case you are interested in algorithm performance, I think there are a couple of algorithms that have better performance than just sorting the array, one (QuickSelect) is indicated by @bruce-feist's answer and is very well explained.
[Java implementation: https://discuss.leetcode.com/topic/14611/java-quick-select ]
But there is a variation of this algorithm named median of medians, you can find a good explanation on this link: http://austinrochford.com/posts/2013-10-28-median-of-medians.html
Java implementation of this: - https://stackoverflow.com/a/27719796/957979
Here's a good one:
Set line-height
equal to whatever the height
is; works like a charm!
E.g:
li {
height: 30px;
line-height: 30px;
}
In my case adding sudo before npm install solved gulp command not found problem
sudo npm install