Just for information, i made a little tool for Windows doing the same thing than "grep -F -x -f file1 file2" (As i haven't found anything equivalent to this command on Windows)
Here it is : http://www.nerdzcore.com/?page=commonlines
Usage is "CommonLines inputFile1 inputFile2 outputFile"
Source code is also available (GPL)
What's worked for me recently is to remove all height=""
and width=""
attributes from the <svg>
tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.
Before:
<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
After:
<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
The following code works well (On FireFox, IE and Chrome) :
var display_out = "This is line 1" + "<br>" + "This is line 2";
document.getElementById("demo").innerHTML = display_out;
You can do it using jquery inputmask plugin.
HTML:
<input id="price" type="text">
Javascript:
$('#price').inputmask({
alias: 'numeric',
allowMinus: false,
digits: 2,
max: 999.99
});
Here is a YUI compressor script (Byuic) that finds all the js and css down a path and compresses /(optionally) obfuscates them. Nice to integrate into a build process.
You can also access the date via the variable %DATE%
When testing my system %DATE%
produces ddd dd/mm/yyyy
you can use substring operators to produce the format you desire
ie. running the following on MON 11/12/2018 with US regional settings
%DATE:~3,3% %DATE:~0,3% %DATE:~7,2%
Will produce an output:
11 Mon 12
the substring arguments are
%*variable*:~*startpos*,*numberofchars*%
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
You were in the correct folder if you got the ./mongod working! You now need to open another terminal, go to the same folder and type ./mongo the first terminal window serves as your server, the second is where you enter your commands!
You may find such kind of errors when you did not define the complete path of your XML file. Try this one if you are using opencv3.1.0 in raspberrypi 3: "faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')"
This works reliably for me in my main sub.
Dim defDate1 As Date, defDate2 As Date
'** Set default date range to previous month
defDate1 = CDate(Month(Now) & "/1/" & Year(Now))
defDate1 = DateAdd("m", -1, defDate1)
defDate2 = DateAdd("d", -1, DateAdd("m", 1, defDate1))
You can check the existence of a symlink and that it is not broken with:
[ -L ${my_link} ] && [ -e ${my_link} ]
So, the complete solution is:
if [ -L ${my_link} ] ; then
if [ -e ${my_link} ] ; then
echo "Good link"
else
echo "Broken link"
fi
elif [ -e ${my_link} ] ; then
echo "Not a link"
else
echo "Missing"
fi
-L
tests whether there is a symlink, broken or not. By combining with -e
you can test whether the link is valid (links to a directory or file), not just whether it exists.
This is the only syntax that worked for me
$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');
function routeToRoom(userId, passw, cb) {
var roomId = 0;
var nStore = require('nstore/lib/nstore').extend(require('nstore/lib/nstore/query')());
var users = nStore.new('data/users.db', function() {
users.find({
user: userId,
pass: passw
}, function(err, results) {
if (err) {
roomId = -1;
} else {
roomId = results.creationix.room;
}
cb(roomId);
});
});
}
routeToRoom("alex", "123", function(id) {
console.log(id);
});
You need to use callbacks. That's how asynchronous IO works. Btw sys.puts
is deprecated
You might want to look at ConcurrentDoublyLinkedList written by Doug Lea based on Paul Martin's "A Practical Lock-Free Doubly-Linked List". It does not implement the java.util.List interface, but offers most methods you would use in a List.
According to the javadoc:
A concurrent linked-list implementation of a Deque (double-ended queue). Concurrent insertion, removal, and access operations execute safely across multiple threads. Iterators are weakly consistent, returning elements reflecting the state of the deque at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations.
The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF]
protocol, and then there's the new version using Hybi formatted packets.
The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!
However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88
(better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.
Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).
I used 1.5 for the other server, so I waisted a lot of time on this.
Tricky issue.
My simple solution is this
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}
or you can open permission dialog in else like this
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION },
TAG_CODE_PERMISSION_LOCATION);
}
Use os.path.join to combine the path to the Documents
directory with the completeName
(filename?) supplied by the user.
import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
toFile = raw_input("Write what you want into the field")
file1.write(toFile)
If you want the Documents
directory to be relative to the user's home directory, you could use something like:
os.path.join(os.path.expanduser('~'),'Documents',completeName)
Others have proposed using os.path.abspath
. Note that os.path.abspath
does not resolve '~'
to the user's home directory:
In [10]: cd /tmp
/tmp
In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'
Manage multiple GitHub accounts on one Windows machine (HTTPS)
Let's say you previously use git on your machine and configure git global config file. To check it open the terminal and :
git config --global -e
It opens your editor, and you may see something like this:
[user]
email = [email protected]
name = Your_Name
...
And this is great because you can push your code to GitHub account without entering credentials every time. But what if it needs to push to repo from another account? In this case, git will reject with 403 err, and you must change your global git credentials. To make this comfortable lat set storing a repo name in a credential manager:
git config --global credential.github.com.useHttpPath true
to check it open config one more time git config --global -e you will see new config lines
[credential]
useHttpPath = true
...
The is it. Now when you first time push to any account you will see a pop-up Screenshot_1
Enter specific for this repo account credentials, and this will "bind" this account for the repo. And so in your machine, you can specify as many accounts/repos as you want.
For a more expanded explanation you can see this cool video that I found on youtube: https://youtu.be/2MGGJtTH0bQ
Inserting \n
p="${var1}\n${var2}"
echo -e "${p}"
Inserting a new line in the source code
p="${var1}
${var2}"
echo "${p}"
Using $'\n'
(only bash and zsh)
p="${var1}"$'\n'"${var2}"
echo "${p}"
\n
p="${var1}\n${var2}"
echo -e "${p}"
echo -e
interprets the two characters "\n"
as a new line.
var="a b c"
first_loop=true
for i in $var
do
p="$p\n$i" # Append
unset first_loop
done
echo -e "$p" # Use -e
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p\n$i" # After -> Append
unset first_loop
done
echo -e "$p" # Use -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p\n$i" # Append
done
echo -e "$p" # Use -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
var="a b c"
for i in $var
do
p="$p
$i" # New line directly in the source code
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p
$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p
$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
$'\n'
(less portable)bash and zsh interprets $'\n'
as a new line.
var="a b c"
for i in $var
do
p="$p"$'\n'"$i"
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p"$'\n'"$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p"$'\n'"$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
a
b
c
Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.
EDIT
for
loop in above bash snippets.You can have class something like below from which you can add 'n' number of functions or console_scripts you want to execute in parallel passion and start the execution and wait for all jobs to complete..
from multiprocessing import Process
class ProcessParallel(object):
"""
To Process the functions parallely
"""
def __init__(self, *jobs):
"""
"""
self.jobs = jobs
self.processes = []
def fork_processes(self):
"""
Creates the process objects for given function deligates
"""
for job in self.jobs:
proc = Process(target=job)
self.processes.append(proc)
def start_all(self):
"""
Starts the functions process all together.
"""
for proc in self.processes:
proc.start()
def join_all(self):
"""
Waits untill all the functions executed.
"""
for proc in self.processes:
proc.join()
def two_sum(a=2, b=2):
return a + b
def multiply(a=2, b=2):
return a * b
#How to run:
if __name__ == '__main__':
#note: two_sum, multiply can be replace with any python console scripts which
#you wanted to run parallel..
procs = ProcessParallel(two_sum, multiply)
#Add all the process in list
procs.fork_processes()
#starts process execution
procs.start_all()
#wait until all the process got executed
procs.join_all()
Simple and dynamic solution (Swift 5):
extension FileManager {
class func directoryUrl() -> URL? {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths.first
}
class func allRecordedData() -> [URL]? {
if let documentsUrl = FileManager.directoryUrl() {
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
return directoryContents.filter{ $0.pathExtension == "m4a" }
} catch {
return nil
}
}
return nil
}}
I had the same error message when trying to run a Python script -- this was not @Warpspace's intended use case (see other comments), but this was among the top hits to my search, so maybe somebody will find it useful.
In my case it was the DOS line endings (\r\n
instead of \n
) that the shebang line (#!/usr/bin/env python
) would trip over. A simple dos2unix myfile.py
fixed it.
When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.
@
string literal, pass string value, one way binding.=
string literal, pass object, 2 ways binding.&
string literal, calls external function, can pass data from directive to controller.clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
try this one
public void writeFile(String arg1,String arg2) {_x000D_
try {_x000D_
if (!dir.exists()) {_x000D_
_x000D_
if (dir.mkdirs()) {_x000D_
_x000D_
Toast.makeText(getBaseContext(), "Directory created",_x000D_
Toast.LENGTH_SHORT).show();_x000D_
} else {_x000D_
Toast.makeText(getBaseContext(),_x000D_
"Error writng file " + filename, Toast.LENGTH_LONG)_x000D_
.show();_x000D_
}_x000D_
}_x000D_
_x000D_
else {_x000D_
_x000D_
File file = new File(dir, filename);_x000D_
if (!file.exists()) {_x000D_
file.createNewFile();_x000D_
}_x000D_
_x000D_
FileWriter fileWritter = new FileWriter(file, true);_x000D_
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);_x000D_
bufferWritter.write(arg1 + "\n");_x000D_
bufferWritter.close();_x000D_
_x000D_
} catch (Exception e) {_x000D_
e.printStackTrace();_x000D_
Toast.makeText(getBaseContext(),_x000D_
"Error writng file " + e.toString(), Toast.LENGTH_LONG)_x000D_
.show();_x000D_
}_x000D_
_x000D_
}
_x000D_
Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.
$('.clickHere').click(function(){
// this is flat click. this event will be attatched
//to element if element is available in
//dom at the time when JS loaded.
// do your stuff
});
$('.clickHere').on('click', function(){
// same as first one
// do your stuff
})
$(document).on('click', '.clickHere', function(){
// this is diffrent type
// of click. The click will be registered on document when JS
// loaded and will delegate to the '.clickHere ' element. This is
// called event delegation
// do your stuff
});
$('body').on('click', '.clickHere', function(){
// This is same as 3rd
// point. Here we used body instead of document/
// do your stuff
});
$('.clickHere').off().on('click', function(){ //
// deregister event listener if any and register the event again. This
// prevents the duplicate event resistration on same element.
// do your stuff
})
Bootstrap still doesnt work with Jquery UI, for example the modal.Bootstrap has nice style but as a framework with Twitter behind isnt that good.
Object Model is concerned with the following three concepts Data Abstraction Encapsulation Inheritance The relational model used the basic concept of a relation or table. Object-relational mapping (OR mapping) products integrate object programming language capabilities with relational databases.
A more recent solution to this problem: Use the more recent sdl libs on
"https://buildbot.libsdl.org/sdl-builds/sdl-visualstudio/?C=M;O=D"
They seem to have fixed the problem, although it's only the 32 bit library (I think).
In my case clean project and rebuild works, no need to disable instant run and restart.
Try This basic code snippet:
private static Bitmap ResizeBitmap(Bitmap srcbmp, int width, int height )
{
Bitmap newimage = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(newimage))
g.DrawImage(srcbmp, 0, 0, width, height);
return newimage;
}
I kept using this all this time
Import-module .\build_functions.ps1 -Force
I do it in a way that will cast any case insensitive version of the string "false" to the boolean FALSE, but will behave using the normal php casting rules for all other strings. I think this is the best way to prevent unexpected behavior.
$test_var = 'False';
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
$result = (boolean) $test_var;
Or as a function:
function safeBool($test_var){
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
return (boolean) $test_var;
}
from your question I assume that you already have your data in hdfs.
So you don't need to LOAD DATA
, which moves the files to the default hive location /user/hive/warehouse
. You can simply define the table using the external
keyword, which leaves the files in place, but creates the table definition in the hive metastore. See here:
Create Table DDL
eg.:
create external table table_name (
id int,
myfields string
)
location '/my/location/in/hdfs';
Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:
row format delimited fields terminated by ','
This code worked for me:
if (strpos(shell_exec('/usr/local/apache/bin/apachectl -l'), 'mod_rewrite') !== false) echo "mod_rewrite enabled";
else echo "mod_rewrite disabled";
The simplest solution is to select the second cell, and press =
. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1
) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.
To read up more on different options for referencing see - This Article.
Same as accepted solution, but transfred to "dot" LINQ syntax...
private string ToQueryString(NameValueCollection nvc)
{
if (nvc == null) return String.Empty;
var queryParams =
string.Join("&", nvc.AllKeys.Select(key =>
string.Join("&", nvc.GetValues(key).Select(v => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(v))))));
return "?" + queryParams;
}
I often need to run more code per condition, by using: ( , , )
multiple code elements can execute:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );
I don't think that this is safe because e.g. the "=" character is used in raw base 64 and is also used in differentiating the parameters from the values in an HTTP GET.
You can use getTime()
method to convert the Date
to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date
with setTime()
. See here an example.
Submit form when your checkbox is checked
$(document).ready(function () {
$("#yoursubmitbuttonid").click(function(){
if( $(".yourcheckboxclass").is(":checked") )
{
$("#yourformId").submit();
}else{
alert("Please select !!!");
return false;
}
return false;
});
});
/bin/sh
may or may not invoke the same program as /bin/bash
.
sh
supports at least the features required by POSIX (assuming a correct implementation). It may support extensions as well.
bash
, the "Bourne Again Shell", implements the features required for sh plus bash-specific extensions. The full set of extensions is too long to describe here, and it varies with new releases. The differences are documented in the bash manual. Type info bash
and read the "Bash Features" section (section 6 in the current version), or read the current documentation online.
I was having the same difficulty loading my VB 6 project. Here is a sample error message: "Class MSComctlLib.ProgressBar of control prgExecution was not a loaded control class."
This problem was solved by some Microsoft Magic as follows: I opened the Project Components window in my broken project. I clicked on Browse and found the file MsComctl.ocx. I clicked on OK. VB 6 then got stuck (the application non responsive). After some time, I ended the VB 6 application using the task manager.
Then, magically, when I opened up my VB 6 project to show my programming friend what a POS this project was, all the controls were back, linked as expected. Somehow, something was registered or fixed.
use plt.figure(dpi=1200)
before all your plt.plot...
and at the end use plt.savefig(...
see: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure
and
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
Other posts have mentioned flexbox, but if more than one row of items is necessary, flexbox's space-between
property fails (see the end of the post)
To date, the only clean solution for this is with the
Basically the relevant code necessary boils down to this:
ul {
display: grid; /* (1) */
grid-template-columns: repeat(auto-fit, 120px); /* (2) */
grid-gap: 1rem; /* (3) */
justify-content: space-between; /* (4) */
align-content: flex-start; /* (5) */
}
1) Make the container element a grid container
2) Set the grid with an 'auto' amount of columns - as necessary. This is done for responsive layouts. The width of each column will be 120px. (Note the use of auto-fit
(as apposed to auto-fill
) which (for a 1-row layout) collapses empty tracks to 0 - allowing the items to expand to take up the remaining space. (check out this demo to see what I'm talking about) ).
3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.
4) and 5) - Similar to flexbox.
body {_x000D_
margin: 0;_x000D_
}_x000D_
ul {_x000D_
display: grid;_x000D_
grid-template-columns: repeat(auto-fit, 120px);_x000D_
grid-gap: 1rem;_x000D_
justify-content: space-between;_x000D_
align-content: flex-start;_x000D_
_x000D_
/* boring properties: */_x000D_
list-style: none;_x000D_
width: 90vw;_x000D_
height: 90vh;_x000D_
margin: 2vh auto;_x000D_
border: 5px solid green;_x000D_
padding: 0;_x000D_
overflow: auto;_x000D_
}_x000D_
li {_x000D_
background: tomato;_x000D_
height: 120px;_x000D_
}
_x000D_
<ul>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
</ul>
_x000D_
Currently supported by Chrome (Blink), Firefox, Safari and Edge! ... with partial support from IE (See this post by Rachel Andrew)
Flexbox's space-between
property works great for one row of items, but when applied to a flex container which wraps it's items - (with flex-wrap: wrap
) - fails, because you have no control over the alignment of the last row of items;
the last row will always be justified (usually not what you want)
To demonstrate:
body {_x000D_
margin: 0;_x000D_
}_x000D_
ul {_x000D_
_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
flex-wrap: wrap;_x000D_
align-content: flex-start;_x000D_
_x000D_
list-style: none;_x000D_
width: 90vw;_x000D_
height: 90vh;_x000D_
margin: 2vh auto;_x000D_
border: 5px solid green;_x000D_
padding: 0;_x000D_
overflow: auto;_x000D_
_x000D_
}_x000D_
li {_x000D_
background: tomato;_x000D_
width: 110px;_x000D_
height: 80px;_x000D_
margin-bottom: 1rem;_x000D_
}
_x000D_
<ul>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
</ul>
_x000D_
Codepen (Resize to see what i'm talking about)
Further reading on CSS grids:
Check your Project -> Properties -> Java Build Path has JDK
Library instead of JRE System Library
.
Go to Eclipse
installed directory, Search eclipse.ini
-> Open it
Search lines for containing any below values:
-Xms512m -Xmx512m -Xms1024m -Xmx1024m -Xms1G -Xmx1G
Just double it the memory size, Assume you have to change the
-Xms512m to -Xms1024m
Increasing the eclipse memory size will help eclipse
to gain more RAM size from your PC.
As Peter in the previous answer mentioned, all previous answers suggest grep and find.
But there is a more sophisticated way using Gnome Commander with a perfect GUI and with tons of options since 2001, and finding files is just one of them. It is a free utility as well, proven by time.
This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.
String literals like
"a"
or
"This is a string"
are put in the text or data segments of your program.
A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.
So if I have
char *s1 = "This is a string";
then s1 is a pointer to the first byte of the string.
Now, if I have
char *s2 = "This is a string";
this is also a pointer to the same first byte of that string in the text or data segment of the program.
But if I have
char *s3 = malloc( 17 );
strcpy(s3, "This is a string");
then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.
Illustrative examples:
Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:
s1 == s2 // True: we are comparing two pointers that contain the same address
but the following will evaluate to false
s1 == s3 // False: Comparing two pointers that don't hold the same address.
And although it might be tempting to have something like this:
struct Vehicle{
char *type;
// other stuff
}
if( type == "Car" )
//blah1
else if( type == "Motorcycle )
//blah2
You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.
I have tested it and it works. If I do
A.type = "Car";
then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like
if( A.type == B.type )
but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.
Solutions:
In your case, what you want to do is use strcmp(a,b) == 0
to replace a == b
In the case of my example, you should use an enum.
enum type {CAR = 0, MOTORCYCLE = 1}
The preceding thing with string was useful because you could print the type, so you might have an array like this
char *types[] = {"Car", "Motorcycle"};
And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.
Therefore it might be better to do
char *getTypeString(int type)
{
switch(type)
case CAR: return "Car";
case MOTORCYCLE: return "Motorcycle"
default: return NULL;
}
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
(as per http://java.sun.com/...ex/Pattern.html)
The backslash character ('\
') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\
matches a single backslash and { matches a left brace.
Other examples of usage :
\\ The backslash character<br>
\t The tab character ('\u0009')<br>
\n The newline (line feed) character ('\u000A')<br>
\r The carriage-return character ('\u000D')<br>
\f The form-feed character ('\u000C')<br>
\a The alert (bell) character ('\u0007')<br>
\e The escape character ('\u001B')<br>
\cx The control character corresponding to x <br>
Try this:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
zzz
is the timezone offset.
Starting with your table definition:
- UserID
- Fname
- Lname
- Email
- Password
- IV
Here are the changes:
Fname
, Lname
and Email
will be encrypted using a symmetric cipher, provided by OpenSSL,IV
field will store the initialisation vector used for encryption. The storage requirements depend on the cipher and mode used; more about this later.Password
field will be hashed using a one-way password hash,Cipher and mode
Choosing the best encryption cipher and mode is beyond the scope of this answer, but the final choice affects the size of both the encryption key and initialisation vector; for this post we will be using AES-256-CBC which has a fixed block size of 16 bytes and a key size of either 16, 24 or 32 bytes.
Encryption key
A good encryption key is a binary blob that's generated from a reliable random number generator. The following example would be recommended (>= 5.3):
$key_size = 32; // 256 bits
$encryption_key = openssl_random_pseudo_bytes($key_size, $strong);
// $strong will be true if the key is crypto safe
This can be done once or multiple times (if you wish to create a chain of encryption keys). Keep these as private as possible.
IV
The initialisation vector adds randomness to the encryption and required for CBC mode. These values should be ideally be used only once (technically once per encryption key), so an update to any part of a row should regenerate it.
A function is provided to help you generate the IV:
$iv_size = 16; // 128 bits
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
Let's encrypt the name field, using the earlier $encryption_key
and $iv
; to do this, we have to pad our data to the block size:
function pkcs7_pad($data, $size)
{
$length = $size - strlen($data) % $size;
return $data . str_repeat(chr($length), $length);
}
$name = 'Jack';
$enc_name = openssl_encrypt(
pkcs7_pad($name, 16), // padded data
'AES-256-CBC', // cipher and mode
$encryption_key, // secret key
0, // options (not used)
$iv // initialisation vector
);
The encrypted output, like the IV, is binary; storing these values in a database can be accomplished by using designated column types such as BINARY
or VARBINARY
.
The output value, like the IV, is binary; to store those values in MySQL, consider using BINARY
or VARBINARY
columns. If this is not an option, you can also convert the binary data into a textual representation using base64_encode()
or bin2hex()
, doing so requires between 33% to 100% more storage space.
Decryption of the stored values is similar:
function pkcs7_unpad($data)
{
return substr($data, 0, -ord($data[strlen($data) - 1]));
}
$row = $result->fetch(PDO::FETCH_ASSOC); // read from database result
// $enc_name = base64_decode($row['Name']);
// $enc_name = hex2bin($row['Name']);
$enc_name = $row['Name'];
// $iv = base64_decode($row['IV']);
// $iv = hex2bin($row['IV']);
$iv = $row['IV'];
$name = pkcs7_unpad(openssl_decrypt(
$enc_name,
'AES-256-CBC',
$encryption_key,
0,
$iv
));
You can further improve the integrity of the generated cipher text by appending a signature that's generated from a secret key (different from the encryption key) and the cipher text. Before the cipher text is decrypted, the signature is first verified (preferably with a constant-time comparison method).
// generate once, keep safe
$auth_key = openssl_random_pseudo_bytes(32, $strong);
// authentication
$auth = hash_hmac('sha256', $enc_name, $auth_key, true);
$auth_enc_name = $auth . $enc_name;
// verification
$auth = substr($auth_enc_name, 0, 32);
$enc_name = substr($auth_enc_name, 32);
$actual_auth = hash_hmac('sha256', $enc_name, $auth_key, true);
if (hash_equals($auth, $actual_auth)) {
// perform decryption
}
See also: hash_equals()
Storing a reversible password in your database must be avoided as much as possible; you only wish to verify the password rather than knowing its contents. If a user loses their password, it's better to allow them to reset it rather than sending them their original one (make sure that password reset can only be done for a limited time).
Applying a hash function is a one-way operation; afterwards it can be safely used for verification without revealing the original data; for passwords, a brute force method is a feasible approach to uncover it due to its relatively short length and poor password choices of many people.
Hashing algorithms such as MD5 or SHA1 were made to verify file contents against a known hash value. They're greatly optimized to make this verification as fast as possible while still being accurate. Given their relatively limited output space it was easy to build a database with known passwords and their respective hash outputs, the rainbow tables.
Adding a salt to the password before hashing it would render a rainbow table useless, but recent hardware advancements made brute force lookups a viable approach. That's why you need a hashing algorithm that's deliberately slow and simply impossible to optimize. It should also be able to increase the load for faster hardware without affecting the ability to verify existing password hashes to make it future proof.
Currently there are two popular choices available:
This answer will use an example with bcrypt.
Generation
A password hash can be generated like this:
$password = 'my password';
$random = openssl_random_pseudo_bytes(18);
$salt = sprintf('$2y$%02d$%s',
13, // 2^n cost factor
substr(strtr(base64_encode($random), '+', '.'), 0, 22)
);
$hash = crypt($password, $salt);
The salt is generated with openssl_random_pseudo_bytes()
to form a random blob of data which is then run through base64_encode()
and strtr()
to match the required alphabet of [A-Za-z0-9/.]
.
The crypt()
function performs the hashing based on the algorithm ($2y$
for Blowfish), the cost factor (a factor of 13 takes roughly 0.40s on a 3GHz machine) and the salt of 22 characters.
Validation
Once you have fetched the row containing the user information, you validate the password in this manner:
$given_password = $_POST['password']; // the submitted password
$db_hash = $row['Password']; // field with the password hash
$given_hash = crypt($given_password, $db_hash);
if (isEqual($given_hash, $db_hash)) {
// user password verified
}
// constant time string compare
function isEqual($str1, $str2)
{
$n1 = strlen($str1);
if (strlen($str2) != $n1) {
return false;
}
for ($i = 0, $diff = 0; $i != $n1; ++$i) {
$diff |= ord($str1[$i]) ^ ord($str2[$i]);
}
return !$diff;
}
To verify a password, you call crypt()
again but you pass the previously calculated hash as the salt value. The return value yields the same hash if the given password matches the hash. To verify the hash, it's often recommended to use a constant-time comparison function to avoid timing attacks.
Password hashing with PHP 5.5
PHP 5.5 introduced the password hashing functions that you can use to simplify the above method of hashing:
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 13]);
And verifying:
if (password_verify($given_password, $db_hash)) {
// password valid
}
See also: password_hash()
, password_verify()
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
Calling iterator()
on a Collection impl, probably would get a new Iterator on each call.
Thus, you can simply call iterator()
again to get a new one.
IteratorLearn.java
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
/**
* Iterator learn.
*
* @author eric
* @date 12/30/18 4:03 PM
*/
public class IteratorLearn {
@Test
public void test() {
Collection<Integer> c = new HashSet<>();
for (int i = 0; i < 10; i++) {
c.add(i);
}
Iterator it;
// iterate,
it = c.iterator();
System.out.println("\niterate:");
while (it.hasNext()) {
System.out.printf("\t%d\n", it.next());
}
Assert.assertFalse(it.hasNext());
// consume,
it = c.iterator();
System.out.println("\nconsume elements:");
it.forEachRemaining(ele -> System.out.printf("\t%d\n", ele));
Assert.assertFalse(it.hasNext());
}
}
Output:
iterate:
0
1
2
3
4
5
6
7
8
9
consume elements:
0
1
2
3
4
5
6
7
8
9
The SQLite command line utility has a .schema TABLENAME
command that shows you the create statements.
This query will list all of the tables in all of the databases and schemas (uncomment the line(s) in the WHERE
clause to filter for specific databases, schemas, or tables), with the privileges shown in order so that it's easy to see if a specific privilege is granted or not:
SELECT grantee
,table_catalog
,table_schema
,table_name
,string_agg(privilege_type, ', ' ORDER BY privilege_type) AS privileges
FROM information_schema.role_table_grants
WHERE grantee != 'postgres'
-- and table_catalog = 'somedatabase' /* uncomment line to filter database */
-- and table_schema = 'someschema' /* uncomment line to filter schema */
-- and table_name = 'sometable' /* uncomment line to filter table */
GROUP BY 1, 2, 3, 4;
Sample output:
grantee |table_catalog |table_schema |table_name |privileges |
--------|----------------|--------------|---------------|---------------|
PUBLIC |adventure_works |pg_catalog |pg_sequence |SELECT |
PUBLIC |adventure_works |pg_catalog |pg_sequences |SELECT |
PUBLIC |adventure_works |pg_catalog |pg_settings |SELECT, UPDATE |
...
Please, see oficial encode()
and decode()
documentation from codecs
library. utf-8
is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1
or utf_32
.
I just give it a shot:
In [9]: s = Series([True, True, True, False])
In [10]: s
Out[10]:
0 True
1 True
2 True
3 False
In [11]: -s
Out[11]:
0 False
1 False
2 False
3 True
There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.
Please go through the below points.
1 Query String.
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);
SecondForm.aspx.cs
TextBox1.Text = Request.QueryString["Parameter"].ToString();
This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));
SecondForm.aspx.cs
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
URL Encoding
2. Passing value through context object
Passing value through context object is another widely used method.
FirstForm.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
SecondForm.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);
Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.
3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add("onclick", "return PostPage();");
}
And we create a javascript function to post the form.
SecondForm.aspx.cs
function PostPage()
{
document.Form1.action = "SecondForm.aspx";
document.Form1.method = "POST";
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false
4. Another method is by adding PostBackURL property of control for cross page post back
In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
<asp:Button id=buttonPassValue style=”Z-INDEX: 102" runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1");
TextBox1.Text = textBoxTemp.Text;
As you have noticed, this is also a simple and clean implementation of passing value between pages.
Reference: MICROSOFT MSDN WEBSITE
HAPPY CODING!
Convert dictionary into JSON (string)
import json
mydict = { "name" : "Don",
"surname" : "Mandol",
"age" : 43}
result = json.dumps(mydict)
print(result[0:20])
will get you:
{"name": "Don", "sur
Convert string into dictionary
back_to_mydict = json.loads(result)
Run it under a different user name, using "runas" or by scheduling it under a different user in Windows Scheduled Tasks.
This will work too:
$('<li>').text('hello').appendTo('#mylist');
It feels more like a jquery way with the chained function calls.
I would use a library to create your JSON String
for you. Some options are:
This will make dealing with escaping much easier. An example (using org.json
) would be:
JSONObject obj = new JSONObject();
obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);
// etc.
final String json = obj.toString(); // <-- JSON string
If someone finds this question like me, here are my performance tests of proposed methods:
Python 2.7.8
In [1]: %timeit ([1]*1000000).insert(0, 0)
100 loops, best of 3: 4.62 ms per loop
In [2]: %timeit ([1]*1000000)[0:0] = [0]
100 loops, best of 3: 4.55 ms per loop
In [3]: %timeit [0] + [1]*1000000
100 loops, best of 3: 8.04 ms per loop
As you can see, insert
and slice assignment are as almost twice as fast than explicit adding and are very close in results. As Raymond Hettinger noted insert
is more common option and I, personally prefer this way to prepend to list.
You can use
change config to cookie & type your password in ' ' in password like bellow
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'your password';
Then save & type on browser localhost/phpmyadmin/
Enter your given password & enjoy
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);
use below simple code, no need to use any library
String list = "your_json_string";
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);
std based
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
#include <openssl/sha.h>
string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
int main() {
cout << sha256("1234567890_1") << endl;
cout << sha256("1234567890_2") << endl;
cout << sha256("1234567890_3") << endl;
cout << sha256("1234567890_4") << endl;
return 0;
}
Another option besides awk is nl which allows for options -v
for setting starting value and -n <lf,rf,rz>
for left, right and right with leading zeros justified. You can also include -s
for a field separator such as -s ","
for comma separation between line numbers and your data.
In a Unix environment, this can be done as
cat <infile> | ...other stuff... | nl -v 0 -n rz
or simply
nl -v 0 -n rz <infile>
Example:
echo "Here
are
some
words" > words.txt
cat words.txt | nl -v 0 -n rz
Out:
000000 Here
000001 are
000002 some
000003 words
In case that you are using ruby 2.0 or 2.2 (thanks @patrick-davey) or 2.3 (thanks @juanitofatas).
sudo apt-get install ruby-dev
sudo apt-get install ruby2.0-dev
sudo apt-get install ruby2.2-dev
sudo apt-get install ruby2.3-dev
And you get the pattern here...
Although the question is a bit old, here is a new library, which is worth mentioning, that can do extra tasks.
In some cases, you don't want only to remove stop words. Rather, you would want to find the stopwords in the text data and store it in a list so that you can find the noise in the data and make it more interactive.
The library is called 'textfeatures'
. You can use it as follows:
! pip install textfeatures
import textfeatures as tf
import pandas as pd
For example, suppose you have the following set of strings:
texts = [
"blue car and blue window",
"black crow in the window",
"i see my reflection in the window"]
df = pd.DataFrame(texts) # Convert to a dataframe
df.columns = ['text'] # give a name to the column
df
Now, call the stopwords() function and pass the parameters you want:
tf.stopwords(df,"text","stopwords") # extract stop words
df[["text","stopwords"]].head() # give names to columns
The result is going to be:
text stopwords
0 blue car and blue window [and]
1 black crow in the window [in, the]
2 i see my reflection in the window [i, my, in, the]
As you can see, the last column has the stop words included in that docoument (record).
This code works perfectly:
import sqlalchemy
Maybe you installed the package in another version of the interpreter?
Also, like Shawley pointed out, you need to have the flask extension installed in order for it to be accessible.
From the RFC 4648:
Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.
So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.
But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:
^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
=AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
=AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
=$A:$H
.Results should be similar to the following.
¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. ""
).
Install as npm install font-awesome --save-dev
In your development less file, you can either import the whole font awesome less using @import "node_modules/font-awesome/less/font-awesome.less"
, or look in that file and import just the components that you need. I think this is the minimum for basic icons:
/* adjust path as needed */
@fa_path: "../node_modules/font-awesome/less";
@import "@{fa_path}/variables.less";
@import "@{fa_path}/mixins.less";
@import "@{fa_path}/path.less";
@import "@{fa_path}/core.less";
@import "@{fa_path}/icons.less";
As a note, you still aren't going to save that many bytes by doing this. Either way, you're going to end up including between 2-3k lines of unminified CSS.
You'll also need to serve the fonts themselves from a folder called/fonts/
in your public directory. You could just copy them there with a simple gulp task, for example:
gulp.task('fonts', function() {
return gulp.src('node_modules/font-awesome/fonts/*')
.pipe(gulp.dest('public/fonts'))
})
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
This is how I do it.
import os
for x in os.listdir(os.getcwd()):
if os.path.isdir(x):
print(x)
I solved a similar issue by just deleting the .git
folder from my project and reintegrating with version control through IntelliJ.
Note: The .git
folder is hidden. You can view it in the terminal with ls -a
, and then remove it using rm -rf .git
.
bool breakInnerLoop=false
for(int i=0;i<=10;i++)
{
for(int J=0;i<=10;i++)
{
if(i<=j)
{
breakInnerLoop=true;
break;
}
}
if(breakInnerLoop)
{
continue
}
}
You might be looking for Promise.race
(native I/O racing solution, not threads)
Assuming you (or others searching this question) want to race threads to avoid failure and avoid the cost of I/O operations, this is a simple and native way to accomplish it (which does not use threads). Node is designed to be single threaded (look up the event loop), so avoid using threads if possible. If my assumption is correct, I recommend you use Promise.race
with setTimeout
(example in link). With this strategy, you would race a list of promises which each try some I/O operation and reject the promise if there is an error (otherwise timeout). The Promise.race
statement continues after the first resolution/rejection, which seems to be what you want. Hope this helps someone!
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
I really wanted this (placeholders should look the same for text boxes as select boxes!) and straight CSS wasn't working in Chrome. Here is what I did:
First make sure your select tag has a .has-prompt
class.
Then initialize this class somewhere in document.ready
.
# Adds a class to select boxes that have prompt currently selected.
# Allows for placeholder-like styling.
# Looks for has-prompt class on select tag.
Mess.Views.SelectPromptStyler = Backbone.View.extend
el: 'body'
initialize: ->
@$('select.has-prompt').trigger('change')
events:
'change select.has-prompt': 'changed'
changed: (e) ->
select = @$(e.currentTarget)
if select.find('option').first().is(':selected')
select.addClass('prompt-selected')
else
select.removeClass('prompt-selected')
Then in CSS:
select.prompt-selected {
color: $placeholder-color;
}
If you don't have .NET 5.0, extend the DateTime class to include week number.
public static class Extension {
public static int Week(this DateTime date) {
var day = (int)CultureInfo.CurrentCulture.Calendar.GetDayOfWeek(date);
return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date.AddDays(4 - (day == 0 ? 7 : day)), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
}
@beanland; You have to write
-webkit-appearance:none;
in your css.
read this http://trentwalton.com/2010/07/14/css-webkit-appearance/
I fix without .row
<div class="col col-33 left" ng-repeat="photo in photos">
Content here...
</div>
and css
.left {
float: left;
}
If you are concerned about the file's content being served rather than its output. You can use a double extension like: file.inc.php
. It then serves the same purpose of helpfulness and maintainability.
I normally have 2 php files for each page on my site:
welcome.php
in the root folder, containing all of the HTML markup. welcome.inc.php
in the inc
folder, containing all PHP functions specific to the welcome.php
page.EDIT: Another benefit of using the double extention .inc.php
would be that any IDE can still recognise the file as PHP code.
When indicating HTTP Basic Authentication we return something like:
WWW-Authenticate: Basic realm="myRealm"
Whereas Basic
is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.
You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.
From recollection, Windows Challenge Response uses a different scheme and different arguments.
The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.
My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.
For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.
Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.
The other alternative is burn the AJAX request but that's a poor user experience.
Use typings to access node functions from TypeScript:
typings install env~node --global
If you don't have typings install it:
npm install typings --global
The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.
https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html
Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.
I needed an example using React.Component
so I am posting it:
import React from 'react';
import * as Redux from 'react-redux';
class NavigationHeader extends React.Component {
}
const mapStateToProps = function (store) {
console.log(`mapStateToProps ${store}`);
return {
navigation: store.navigation
};
};
export default Redux.connect(mapStateToProps)(NavigationHeader);
I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.
Install express
npm install express
Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server
Put something like the following in the server.js file and read about this on the express gihub site:
var express = require('express');
var app = express();
var path = require('path');
// __dirname will use the current path from where you run this file
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
app.listen(8000);
console.log('Listening on port 8000');
After you've saved server.js, you can run the server using:
node server.js
http://localhost:8000/FILENAME
and you should see the HTML file you were trying to loadTry to load your scripts in Head section.
Moreover, it will be better if you define your scripts under some call like: document.ready
, if you defined these scripts in body section
ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS .
class and #
ID prefixes, so that's pretty much it.
Localhost generally refers to the machine you're looking at. On most machines localhost resolves to the IP address 127.0.0.1 which is the loopback address.
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
You can find the default Android menu icons here - link is broken now.
Update: You can find Material Design icons here.
Try this:
select max(Emp_Sal)
from Employee a
where 1 = ( select count(*)
from Employee b
where b.Emp_Sal > a.Emp_Sal)
Please check this out below sample code for semaphore implementation(Lock and unlock).
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include<string.h>
#include<malloc.h>
#include <sys/sem.h>
int main()
{
int key,share_id,num;
char *data;
int semid;
struct sembuf sb={0,-1,0};
key=ftok(".",'a');
if(key == -1 ) {
printf("\n\n Initialization Falied of shared memory \n\n");
return 1;
}
share_id=shmget(key,1024,IPC_CREAT|0744);
if(share_id == -1 ) {
printf("\n\n Error captured while share memory allocation\n\n");
return 1;
}
data=(char *)shmat(share_id,(void *)0,0);
strcpy(data,"Testing string\n");
if(!fork()) { //Child Porcess
sb.sem_op=-1; //Lock
semop(share_id,(struct sembuf *)&sb,1);
strncat(data,"feeding form child\n",20);
sb.sem_op=1;//Unlock
semop(share_id,(struct sembuf *)&sb,1);
_Exit(0);
} else { //Parent Process
sb.sem_op=-1; //Lock
semop(share_id,(struct sembuf *)&sb,1);
strncat(data,"feeding form parent\n",20);
sb.sem_op=1;//Unlock
semop(share_id,(struct sembuf *)&sb,1);
}
return 0;
}
In my opinion, it is not possible for the like button (and I hope it is not possible).
But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.
Sorry to bump an old question but the answer is to count the character length of the cell and not its value.
CellCount = Cells(Row, 10).Value
If Len(CellCount) <= "13" Then
'do something
End If
hope that helps. Cheers
The following solution worked for me in Bootstrap 3.3.4:
CSS:
/*no collapse*/
.navbar-collapse.collapse.off {
display: block!important;
}
.navbar-collapse.collapse.off ul {
margin: 0;
padding: 0;
}
.navbar-nav.no-collapse>li,
.navbar-nav.no-collapse {
float: left !important;
}
.navbar-right.no-collapse {
float: right!important;
}
then add the .no-collapse class to each of the lists and the .off class to the main container. Here is an example written in jade:
nav.navbar.navbar-default.navbar-fixed-top
.container-fluid
.collapse.navbar-collapse.off
ul.nav.navbar-nav.no-collapse
li
a(href='#' class='glyph')
i(class='glyphicon glyphicon-info-sign')
ul.nav.navbar-nav.navbar-right.no-collapse
li.dropdown
a.dropdown-toggle(href='#', data-toggle='dropdown' role='button' aria-expanded='false')
| Tools
span.caret
ul.dropdown-menu(role='menu')
li
a(href='#') Tool #1
li
a(href='#')
| Logout
Any time you do a remove() or a removeAll(), you should call
validate();
repaint();
after you have completed add()'ing the new components.
Calling validate() or revalidate() is mandatory when you do a remove() - see the relevant javadocs.
My own testing indicates that repaint() is also necessary. I'm not sure exactly why.
Private constructor means a user cannot directly instantiate a class. Instead, you can create objects using something like the Named Constructor Idiom, where you have static
class functions that can create and return instances of a class.
The Named Constructor Idiom is for more intuitive usage of a class. The example provided at the C++ FAQ is for a class that can be used to represent multiple coordinate systems.
This is pulled directly from the link. It is a class representing points in different coordinate systems, but it can used to represent both Rectangular and Polar coordinate points, so to make it more intuitive for the user, different functions are used to represent what coordinate system the returned Point
represents.
#include <cmath> // To get std::sin() and std::cos()
class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
inline Point::Point(float x, float y)
: x_(x), y_(y) { }
inline Point Point::rectangular(float x, float y)
{ return Point(x, y); }
inline Point Point::polar(float radius, float angle)
{ return Point(radius*std::cos(angle), radius*std::sin(angle)); }
There have been a lot of other responses that also fit the spirit of why private constructors are ever used in C++ (Singleton pattern among them).
Another thing you can do with it is to prevent inheritance of your class, since derived classes won't be able to access your class' constructor. Of course, in this situation, you still need a function that creates instances of the class.
<?php echo substr("abcabcabc", 0, -3); ?>
use this
from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})
You need to use delegates and protocols. Here is a site with an example http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
Change visible="false"
to style="visibility:hidden"
on your tags..
or better use a class to show/hide the labels..
.hidden{
visibility:hidden;
}
then on your labels add class="hidden"
and with your script remove the class
document.getElementById("endTimeLabel").className = 'hidden'; // to hide
and
document.getElementById("endTimeLabel").className = ''; // to show
Normally the native way we do things in linux and the way we think is from left to right.
So you would go and write what you are looking for first:
find / -name "*.php"
Then you probably hit enter and realize you are getting too many files from
directories you wish not to.
Let's exclude /media to avoid searching your mounted drives.
You should now just APPEND the following to the previous command:
-print -o -path '/media' -prune
so the final command is:
find / -name "*.php" -print -o -path '/media' -prune
...............|<--- Include --->|....................|<---------- Exclude --------->|
I think this structure is much easier and correlates to the right approach
public interface A{
int x=65;
}
public interface B{
int x=66;
}
public class D implements A,B {
public static void main(String[] a){
System.out.println(x); // which x?
}
}
Here is the solution.
System.out.println(A.x); // done
I think it is the one reason why interface variable are static.
Don't declare variables inside Interface.
Add the css
<style type="text/css">
textarea
{
border:1px solid #999999
width:99%;
margin:5px 0;
padding:1%;
}
</style>
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
double x;
char *s;
s = " -2309.12E-15";
x = atof(s); /* x = -2309.12E-15 */
printf("x = %4.4f\n",x);
With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.
# Option one
older_method_string = "%.9f" % numvar
# Option two
newer_method_string = "{:.9f}".format(numvar)
But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has info on the various flags.
Python 3.6 (officially released in December of 2016), added the f
string literal, see more information here, which extends the str.format
method (use of curly braces such that f"{numvar:.9f}"
solves the original problem), that is,
# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.
Here's my go-to method for a yes/no answer.
It's case-insensitive also.
This just checks for the errors given by the input and sets the choice
variable to whatever you require so it can be used below in the code.
@echo off
choice /M "[Opt 1] Do you want to continue [Yes/No]"
if errorlevel 255 (
echo Error
) else if errorlevel 2 (
set "YourChoice=will not"
) else if errorlevel 1 (
set "YourChoice=will"
) else if errorlevel 0 (
goto :EOF
)
echo %YourChoice%
pause
You could use RGBa ('a' being alpha transparency), but it's not widely supported yet. It will be, though, so you could use it now and add a fallback:
a:link {
color: rgb(0,0,255);
}
a:link.lighter {
color: rgb(128,128,255); /* This gets applied only in browsers that don't apply the rgba line */
}
a:link.lighter { /* This comes after the previous line, so has priority in supporting browsers */
color: rgba(0,0,255,0.5); /* last value is transparency */
}
(SELECT column1 as column FROM table )
UNION
(SELECT column2 as column FROM table )
this can also be tried...
SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM login_log l
LEFT JOIN (SELECT ip_location.ip, ip_location.hostname
FROM ip_location
WHERE ip_location.ip is null)tbl2
You can check the application-specific data in your emulator as follows,
adb shell
in cmd/data/data/
and navigate into your applicationThere you can find the cache data and databases specific to your application
In my projects, this piece of code always worked as a default serializer which serializes the specified value as if there was no special converter:
serializer.Serialize(writer, value);
v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.
So, you should override it with display: flex
in your HTML or CSS to make it work with justify-content.
They are extension methods. Welcome to a whole new fluent world. :)
Why not just INNER JOIN the table with itself?
SELECT a.firstname, a.lastname, a.address
FROM list a
INNER JOIN list b ON a.address = b.address
WHERE a.id <> b.id
A DISTINCT is needed if the address could exist more than two times.
You want to set height which may set for all devices?
Decide upon the design of the site i.e Height on various devices.
Ex:
Height-100px
for bubbles on device with -min-width: 700px
.Height-50px
for bubbles on device with < 700px
;Have your css which has height 50px;
and add this media query
@media only screen and (min-width: 700px) {
/* Styles */
.bubble {
height: 100px;
margin: 20px;
}
.bubble:after {
bottom: -50px;
border-width: 50px 50px 0;
}
.bubble:before {
top: 100px;
border-width: 52px 52px 0;
}
.bubble1 {
height: 100px;
margin: 20px;
}
.bubble1:after {
bottom: -50px;
border-width: 50px 50px 0;
}
.bubble1:before {
top: 100px;
border-width: 52px 52px 0;
}
.bubble2 {
height: 100px;
margin: 20px;
}
.bubble2:after {
bottom: -50px;
border-width: 50px 50px 0;
}
.bubble2:before {
top: 100px;
border-width: 52px 52px 0;
}
}
This will make your bubbles have Height of 100px on devices greater than 700px and a margin of 20px;
A Quick and dirty way: Just write your query as db.getCollection('collection').find({}).toArray()
and right click Copy JSON
. Paste the data in the editor of your choice.
We can achieve it in multiple ways.
Using Kernel#exec
, nothing after this command is executed:
exec('ls ~')
Using backticks or %x
`ls ~`
=> "Applications\nDesktop\nDocuments"
%x(ls ~)
=> "Applications\nDesktop\nDocuments"
Using Kernel#system
command, returns true
if successful, false
if unsuccessful and returns nil
if command execution fails:
system('ls ~')
=> true
If you have released to Apple TestFlight for testing
You have to click the link each time and select No, only after that, your tester can see the build. This is quite annoying if you want to get your build delivered as soon as possible.
Do this for the next build, (If do this before the build then this error will not occur)
The solution is add the following setting to your iOS Info.plist
:
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
Can not add "Missing Compliance", see this Missing Compliance
You can do it using a straight forward select like this:
SELECT *
FROM sys.indexes
WHERE name='YourIndexName' AND object_id = OBJECT_ID('Schema.YourTableName')
Use scikit-learn:
from sklearn.preprocessing import MinMaxScaler
data = np.array([1,2,3]).reshape(-1, 1)
scaler = MinMaxScaler()
scaler.fit(data)
print(scaler.transform(data))
try this:
select TITLE,
(length(DESCRIPTION )-length(replace(DESCRIPTION ,'value','')))/5 as COUNT
FROM <table>
You can give the surrounding div
a
text-align: right
this will leave white space to the left of the image. (= the image will occupy the whole line).
If you want content to be shown to the left hand side of the image, use
float: right
on the image. However, the surrounding div
will then need overflow: auto
to stretch to the needed height.
Below are some of the tools which you can use to perform reverse engineering from an APK file to source code :
I would point a beginner to the Wiki article on the Main function, then supplement it with this.
Java only starts running a program with the specific public static void main(String[] args)
signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main()
and the one true main()
.
String[] args
is a collection of String
s, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
i was also facing the same problem and tried almost all the things but finally i restarted my server and i found everything started working fine..i don't know how.....i think it was some server side problem that's why my PHP CODE was not giving any error.
The below is a compact script that will check if "running" and attempt start service until the service returns as running.
$Service = 'ServiceName'
If ((Get-Service $Service).Status -ne 'Running') {
do {
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
} until ((Get-Service $Service).Status -eq 'Running')
} Return "$($Service) has STARTED"
In .NET 4.5 it's possible to bind to static properties, read more
You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:
public static event EventHandler MyPropertyChanged;
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.
simple answer
$ heroku config:set DISABLE_COLLECTSTATIC=1
after
$ git push heroku master
you can set the dataset to grid as follows:
//assuming your dataset object is ds
datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();
tablename is the name of the table, which you want to show on the grid.
I hope, it helps.
B.R.
You need to change source to viewmodel object:
myBinding.Source = viewModelObject;
Here is an implementation in Kotlin
try {
val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
val inputStreamReader = InputStreamReader(inputStream)
val sb = StringBuilder()
var line: String?
val br = BufferedReader(inputStreamReader)
line = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()
var content : String = sb.toString()
Log.d(TAG, content)
} catch (e:Exception){
Log.d(TAG, e.toString())
}
From http://developer.android.com/sdk/index.html, it seems that you can install the SDK anywhere, so long as you
<sdk>/tools/
folder"<sdk>/tools
directory to your system pathMore info can be found here: http://developer.android.com/sdk/installing.html
You can use sort() function. sort() exists in algorithm header file
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";
sort(str.begin(), str.end());
cout<<str<<endl;
return 0;
}
Output:
achklors
You need to set a -D system property called java.library.path
that points at the directory containing the sqljdbc_auth.dll
.
you should add plug in to your local setting of firefox in your user home
vladimir@shinsengumi ~/.mozilla/plugins $ pwd
/home/vladimir/.mozilla/plugins
vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
lrwxrwxrwx 1 vladimir vladimir 60 Jan 1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so
Try this:
// this will fix old browsers
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return i;
}
}
return -1;
}
}
// example
if ([1, 2, 3].indexOf(2) != -1) {
// yay!
}
Turns out that YUI's reset CSS strips the list style from 'ul li' instead of just 'ul', which is why setting it just in 'ul' never worked.
On Mac Lion :
I just had to go to /path/to/android-sdk/tools
and run android adb update
for the devices to be detected.
There is also the rather spiffy FileStream
, introduced in SQL Server 2008.
You can add this script to make a error when user inpect :D
Try this code
<script type="text/javascript">_x000D_
eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(3(){(3 a(){8{(3 b(2){7((\'\'+(2/2)).6!==1||2%5===0){(3(){}).9(\'4\')()}c{4}b(++2)})(0)}d(e){g(a,f)}})()})();',17,17,'||i|function|debugger|20|length|if|try|constructor|||else|catch||5000|setTimeout'.split('|'),0,{}))_x000D_
</script>
_x000D_
From http://www.bloggerku.com/2017/08/memasang-anti-inspect.html
/**
* Get JSONP data for cross-domain AJAX requests
* @private
* @link http://cameronspear.com/blog/exactly-what-is-jsonp/
* @param {String} url The URL of the JSON request
* @param {String} callback The name of the callback to run on load
*/
var loadJSONP = function ( url, callback ) {
// Create script with url and callback (if specified)
var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
var script = window.document.createElement( 'script' );
script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;
// Insert script tag into the DOM (append to <head>)
ref.parentNode.insertBefore( script, ref );
// After the script is loaded (and executed), remove it
script.onload = function () {
this.remove();
};
};
/**
* Example
*/
// Function to run on success
var logAPI = function ( data ) {
console.log( data );
}
// Run request
loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );
If you use both finish and exit your app will close complitely
finish();
System.exit(0);
Setting the slice to nil
is the best way to clear a slice. nil
slices in go are perfectly well behaved and setting the slice to nil
will release the underlying memory to the garbage collector.
package main
import (
"fmt"
)
func dump(letters []string) {
fmt.Println("letters = ", letters)
fmt.Println(cap(letters))
fmt.Println(len(letters))
for i := range letters {
fmt.Println(i, letters[i])
}
}
func main() {
letters := []string{"a", "b", "c", "d"}
dump(letters)
// clear the slice
letters = nil
dump(letters)
// add stuff back to it
letters = append(letters, "e")
dump(letters)
}
Prints
letters = [a b c d]
4
4
0 a
1 b
2 c
3 d
letters = []
0
0
letters = [e]
1
1
0 e
Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil
will remove that aliasing.
This method changes the capacity to zero though.
Here's a bash function that will print the repository name (if it has been properly set up):
__get_reponame ()
{
local gitdir=$(git rev-parse --git-dir)
if [ $(cat ${gitdir}/description) != "Unnamed repository; edit this file 'description' to name the repository." ]; then
cat ${gitdir}/description
else
echo "Unnamed repository!"
fi
}
Explanation:
local gitdir=$(git rev-parse --git-dir)
This executes git rev-parse --git-dir
, which prints the full path to the .git
directory of the currrent repository. It stores the path in $gitdir
.
if [ $(cat ${gitdir}/description) != "..." ]; then
This executes cat ${gitdir}/description
, which prints the contents of the .git/description
of your current repository. If you've properly named your repository, it will print a name. Otherwise, it will print Unnamed repository; edit this file 'description' to name the repository.
cat ${gitdir}/description
If the repo was properly named, then print the contents.
else
Otherwise...
echo "Unnamed repository!"
Tell the user that the repo was unnamed.
Something similar is implemented in this script.
"TypeScript Fundamentals" -- a Pluralsight video-course by Dan Wahlin and John Papa is a really good, presently (March 25, 2016) updated to reflect TypeScript 1.8, introduction to Typescript.
For me the really good features, beside the nice possibilities for intellisense, are the classes, interfaces, modules, the ease of implementing AMD, and the possibility to use the Visual Studio Typescript debugger when invoked with IE.
To summarize: If used as intended, Typescript can make JavaScript programming more reliable, and easier. It can increase the productivity of the JavaScript programmer significantly over the full SDLC.
If you only need to exclude out enter
, escape
and spacebar
keys, you can do the following:
$("#text1").keyup(function(event) {
if (event.keyCode != '13' && event.keyCode != '27' && event.keyCode != '32') {
alert('test');
}
});
You can refer to the complete list of keycode here for your further modification.
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".
Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.
The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)
License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.
Here's an easy way without ifelse
:
(a/sum(a))^(a>0)
An example:
a <- c(0, 1, 0, 0, 1, 1, 0, 1)
(a/sum(a))^(a>0)
[1] 1.00 0.25 1.00 1.00 0.25 0.25 1.00 0.25
If you want to move down at the end of the page (so you don't need to scroll down to bottom) , you can use:
$('body').animate({ scrollTop: $(document).height() });
You might need to enable the table for full-text indexing.
Joining elements in a list space separated:
word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
joined_string = w + joined_string + " "
print(joined_string.rstrim())
For example:
you can use:
df %>% filter(!is.na(a))
to remove the NA in column a.
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
We can parse csv files with quoted strings and delimited by say | with following code
while read -r line
do
field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')
echo "$field1 $field2"
done < "$csvFile"
awk
parses the string fields to variables and tr
removes the quote.
Slightly slower as awk
is executed for each field.
g1
here is a DataFrame. It has a hierarchical index, though:
In [19]: type(g1)
Out[19]: pandas.core.frame.DataFrame
In [20]: g1.index
Out[20]:
MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'),
('Mallory', 'Seattle')], dtype=object)
Perhaps you want something like this?
In [21]: g1.add_suffix('_Count').reset_index()
Out[21]:
Name City City_Count Name_Count
0 Alice Seattle 1 1
1 Bob Seattle 2 2
2 Mallory Portland 2 2
3 Mallory Seattle 1 1
Or something like:
In [36]: DataFrame({'count' : df1.groupby( [ "Name", "City"] ).size()}).reset_index()
Out[36]:
Name City count
0 Alice Seattle 1
1 Bob Seattle 2
2 Mallory Portland 2
3 Mallory Seattle 1
I had this same problem and it turns out it was because I had the Chrome extension "HTTPS Everywhere" running. Disabling the extension solved my problem.
You can implement an initialisation function:
employee init_employee() {
empolyee const e = {0,"none"};
return e;
}
An alternative way of doing it is by using the choice
method of the Generator
class, https://github.com/numpy/numpy/issues/10835
import numpy as np
# generate the random array
A = np.random.randint(5, size=(10,3))
# use the choice method of the Generator class
rng = np.random.default_rng()
A_sampled = rng.choice(A, 2)
leading to a sampled data,
array([[1, 3, 2],
[1, 2, 1]])
The running time is also profiled compared as follows,
%timeit rng.choice(A, 2)
15.1 µs ± 115 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.random.permutation(A)[:2]
4.22 µs ± 83.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit A[np.random.randint(A.shape[0], size=2), :]
10.6 µs ± 418 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
But when the array goes big, A = np.random.randint(10, size=(1000,300))
. working on the index is the best way.
%timeit A[np.random.randint(A.shape[0], size=50), :]
17.6 µs ± 657 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit rng.choice(A, 50)
22.3 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit np.random.permutation(A)[:50]
143 µs ± 1.33 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
So the permutation
method seems to be the most efficient one when your array is small while working on the index is the optimal solution when your array goes big.
This worked for me:
git branch
Copy the current branch name to clipboard
git pull origin <paste-branch-name>
git push
This answer only really works if you don't need to do anything other than transferring the inner code (innerHTML) from one to the other:
// Define old parent
var oldParent = document.getElementById('old-parent');
// Define new parent
var newParent = document.getElementById('new-parent');
// Basically takes the inner code of the old, and places it into the new one
newParent.innerHTML = oldParent.innerHTML;
// Delete / Clear the innerHTML / code of the old Parent
oldParent.innerHTML = '';
Hope this helps!
Check this idea out. http://pastie.org/1096892
I think it's close. HTML 5 really needs to add the change event to the spec. The only problem is that the callback function evaluates if (before == $(this).html()) before the content is actually updated in $(this).html(). setTimeout don't work, and it's sad. Let me know what you think.
Semaphore :
Using a counter or flag to control access some shared resources in a concurrent system, implies use of Semaphore.
Example:
Flags only reveal the current state of Resource, no count or any other information on the waiting or running objects on the resource.
Monitor :
A Monitor synchronizes access to an Object by communicating with threads interested in the object, asking them to acquire access or wait for some condition to become true.
Example:
Here's a modification to mercurial's answer that uses the subquery on the decode as well, allowing the use of variables in both instances.
DECLARE
@EncodeIn VARCHAR(100) = 'Test String In',
@EncodeOut VARCHAR(500),
@DecodeOut VARCHAR(200)
SELECT @EncodeOut =
CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
, 'VARCHAR(MAX)'
)
FROM (
SELECT CAST(@EncodeIn AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp;
PRINT @EncodeOut
SELECT @DecodeOut =
CAST(
CAST(N'' AS XML).value(
'xs:base64Binary(sql:column("bin"))'
, 'VARBINARY(MAX)'
)
AS VARCHAR(MAX)
)
FROM (
SELECT CAST(@EncodeOut AS VARCHAR(MAX)) AS bin
) AS bin_sql_server_temp;
PRINT @DecodeOut
Yes. It is done with a filter on the appender.
Here is the appender configuration I normally use, limited to only INFO level.
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="${HOMEDRIVE}\\PI.Logging\\PI.ECSignage.${COMPUTERNAME}.log" />
<appendToFile value="true" />
<maxSizeRollBackups value="30" />
<maximumFileSize value="5MB" />
<rollingStyle value="Size" /> <!--A maximum number of backup files when rolling on date/time boundaries is not supported. -->
<staticLogFileName value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss.ffff} [%2thread] %-5level %20.20type{1}.%-25method at %-4line| (%-30.30logger) %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="INFO" />
</filter>
</appender>
We are using Response.SetCookie()
for update the old one cookies and Response.Cookies.Add()
are use to add the new cookies. Here below code CompanyId
is update in old cookie[OldCookieName]
.
HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
You can do this with SQL Server Management Studio.
? Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, expand the menu "INSERT and UPDATE specification" and select "Cascade" as Delete Rule.
When mixing C and C++ (i.e., a. calling C function from C++; and b. calling C++ function from C), the C++ name mangling causes linking problems. Technically speaking, this issue happens only when the callee functions have been already compiled into binary (most likely, a *.a library file) using the corresponding compiler.
So we need to use extern "C" to disable the name mangling in C++.
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
If you want to increase or add time limit to all sites then you can add below lines to the
nginx.conf
file.
Add below lines to the http
section of /usr/local/etc/nginx/nginx.conf
or /etc/nginx/nginx.conf
file.
fastcgi_read_timeout 600;
proxy_read_timeout 600;
If the above lines doesn't exist in conf
file then add them, otherwise increase fastcgi_read_timeout
and proxy_read_timeout
to make sure that nginx and php-fpm did not timeout.
To increase time limit for only one site then you can edit in vim
/etc/nginx/sites-available/example.com
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_read_timeout 300;
}
and after adding these lines in nginx.conf
, then don't forget to restart nginx.
service php7-fpm reload
service nginx reload
or, if you're using valet then simply type valet restart
.
You can get the attributes of a model object returned as a hash using either
@post.attributes
or
@post.as_json
as_json
allows you to include associations and their attributes as well as specify which attributes to include/exclude (see documentation). However, if you only need the attributes of the base object, benchmarking in my app with ruby 2.2.3 and rails 4.2.2 demonstrates that attributes
requires less than half as much time as as_json
.
>> p = Problem.last
Problem Load (0.5ms) SELECT "problems".* FROM "problems" ORDER BY "problems"."id" DESC LIMIT 1
=> #<Problem id: 137, enabled: true, created_at: "2016-02-19 11:20:28", updated_at: "2016-02-26 07:47:34">
>>
>> p.attributes
=> {"id"=>137, "enabled"=>true, "created_at"=>Fri, 19 Feb 2016 11:20:28 UTC +00:00, "updated_at"=>Fri, 26 Feb 2016 07:47:34 UTC +00:00}
>>
>> p.as_json
=> {"id"=>137, "enabled"=>true, "created_at"=>Fri, 19 Feb 2016 11:20:28 UTC +00:00, "updated_at"=>Fri, 26 Feb 2016 07:47:34 UTC +00:00}
>>
>> n = 1000000
>> Benchmark.bmbm do |x|
?> x.report("attributes") { n.times { p.attributes } }
?> x.report("as_json") { n.times { p.as_json } }
>> end
Rehearsal ----------------------------------------------
attributes 6.910000 0.020000 6.930000 ( 7.078699)
as_json 14.810000 0.160000 14.970000 ( 15.253316)
------------------------------------ total: 21.900000sec
user system total real
attributes 6.820000 0.010000 6.830000 ( 7.004783)
as_json 14.990000 0.050000 15.040000 ( 15.352894)
Why not use an empty ajax update panel and wire the linkbutton's click event to it? This way only the update panel will get updated, thus avoiding a postback and allowing you to run your javascript
Add jar files mail.jar,activation.jar,additionnal.jar
String sub="Thank you for your online registration" ;
Mail m = new Mail("emailid", "password");
String[] toArr = {"[email protected]",sEmailId};
m.setFrom("[email protected]");
m.setTo(toArr);
m.setSubject(sub);
m.setBody(msg);
try{
if(m.send()) {
} else {
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
package com.example.ekktra;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content- handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public Mail(String user, String pass) {
this();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") /*&& !_body.equals("")*/) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
public void setTo(String[] toArr) {
// TODO Auto-generated method stub
this._to=toArr;
}
public void setFrom(String string) {
// TODO Auto-generated method stub
this._from=string;
}
public void setSubject(String string) {
// TODO Auto-generated method stub
this._subject=string;
}
}
If you have your dates in DateTime variables, they don't have a format.
You can use the Date
property to return a DateTime value with the time portion set to midnight. So, if you have:
DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;
if(dt1.Date > dt2.Date)
{
//It's a later date
}
else
{
//It's an earlier or equal date
}
The example you are referring to is called Upcasting in java.
It creates a subclass object with a super class variable pointing to it.
The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.
For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine
class Machine{
public void start(){
System.out.println("Machine Started");
}
}
class Camera extends Machine{
public void start(){
System.out.println("Camera Started");
}
public void snap(){
System.out.println("Photo taken");
}
}
Machine machine1 = new Camera();
machine1.start();
If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started"
The variable is still a reference of Machine class. If you attempt machine1.snap();
the code will not compile
The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap()
wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start()
). You can not ask a machine reference to take a snap. :)
Here's a simple way to test it:
public class OperatorTest {
public static void main(String[] args) {
boolean a = false;
a &= b();
}
private static boolean b() {
System.out.println("b() was called");
return true;
}
}
The output is b() was called
, therefore the right-hand operand is evaluated.
So, as already mentioned by others, a &= b
is the same as a = a & b
.
I've got this error working in ASP.net. When I run the application from visual studio it worked all fine, but when I published the project and tested it , I've got that error "Autocomplete is not a function" in chrom Inspect debugger. I found out that the deferences between two environments were caused by a definition in web.config. in compilation tag. if assign debug="false" then all bundel definitions are executed and compilation is done as a release. if debug = true" then compilation is for a debug stage that not include bundeling and minifyning js library. Therefore the deferences between environments.
<system.web>
<compilation debug="false" targetFramework="4.5.1"/>
<httpRuntime targetFramework="4.5.1"/>
</system.web>
In addition, examining those two environments I saw that for debug environment everywhere (_Layout.cshtml) @Scripts.Render("~/bundles/jquery") was in the code, where (under APP_Start) BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Static/js/lib/jquery-{version}.js",
"~/Static/js/lib/jquery-ui.js"));
it rended as:
<script src="/Static/js/lib/jquery-1.12.4.js"></script>
<script src="/Static/js/lib/jquery-ui.js"></script>
and the other environment (debug = false)
<script src="/bundles/jquery?v=YOLEkbKJYtNeDq0o56xjzXWKoYzrF5Vkqgyc9Cb0YgI1"></script>
In debug mode it works and the other one got the problem.
Aspecting the js lib I saw two files of jquery-ui:
jquery-ui.js
jquery-ui.min.js
it turns out that both of them come as default from the template of new mvc project. When jquery-ui.min.js was deleted from the library the problem resolved.
I belive that even though jquery-ui.js was defined in BundleConfig.cs, actually jquery-ui.min.js was taken.
By the way, jquery-ui.min.js didn't include autocomple function apposed to jquery-ui.js that included it.
cheers.
Uri to String
Uri uri;
String stringUri;
stringUri = uri.toString();
String to Uri
Uri uri;
String stringUri;
uri = Uri.parse(stringUri);
I accidentally ended up writing almost the same as provided by git-extras. So if you prefer a single custom command instead of installing a bunch of other extra commands, just place this git-pr
file somewhere in your $PATH
and then you can just write:
git pr 42
// or
git pr upstream 42
// or
git pr https://github.com/peerigon/phridge/pull/1
var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
g.DrawString( ... );
}
picturebox1.Image = bmp;
Notwithstanding the advice not to modify Object.prototype, this can still be really useful for testing, within a limited scope. The author of the accepted answer changed it, but is still setting Object.id
, which doesn't make sense to me. Here's a snippet that does the job:
// Generates a unique, read-only id for an object.
// The _uid is generated for the object the first time it's accessed.
(function() {
var id = 0;
Object.defineProperty(Object.prototype, '_uid', {
// The prototype getter sets up a property on the instance. Because
// the new instance-prop masks this one, we know this will only ever
// be called at most once for any given object.
get: function () {
Object.defineProperty(this, '_uid', {
value: id++,
writable: false,
enumerable: false,
});
return this._uid;
},
enumerable: false,
});
})();
function assert(p) { if (!p) throw Error('Not!'); }
var obj = {};
assert(obj._uid == 0);
assert({}._uid == 1);
assert([]._uid == 2);
assert(obj._uid == 0); // still
Javadoc comments can be automatically appended by using your IDE's autocomplete feature. Try typing /**
and hitting Enter to generate a sample Javadoc comment.
/**
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return
* @throws JSONException
*/
For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):
http://ayria.livejournal.com/33438.html
Basically copy the code below into a text file and name it pre-revprop-change.bat
and save it in the \hooks
subdirectory for your repository.
@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5
:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME
:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION
:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY
goto :eof
:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT
:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT
:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
For MySQL Workbench 8.0 navigate to:
Server > Data Import
A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.
Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.
Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.
That's it!
For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard