There are generally 2 levels of buffering-
1. Kernel buffer Cache (makes read/write faster)
2. Buffering in I/O library (reduces no. of system calls)
Let's take example of fprintf and write()
.
When you call fprintf()
, it doesn't wirte directly to the file. It first goes to stdio buffer in the program's memory. From there it is written to the kernel buffer cache by using write system call. So one way to skip I/O buffer is directly using write(). Other ways are by using setbuff(stream,NULL)
. This sets the buffering mode to no buffering and data is directly written to kernel buffer.
To forcefully make the data to be shifted to kernel buffer, we can use "\n", which in case of default buffering mode of 'line buffering', will flush I/O buffer.
Or we can use fflush(FILE *stream)
.
Now we are in kernel buffer. Kernel(/OS) wants to minimise disk access time and hence it reads/writes only blocks of disk. So when a read()
is issued, which is a system call and can be invoked directly or through fscanf()
, kernel reads the disk block from disk and stores it in a buffer. After that data is copied from here to user space.
Similarly that fprintf()
data recieved from I/O buffer is written to the disk by the kernel. This makes read() write() faster.
Now to force the kernel to initiate a write()
, after which data transfer is controlled by hardware controllers, there are also some ways. We can use O_SYNC
or similar flags during write calls. Or we could use other functions like fsync(),fdatasync(),sync()
to make the kernel initiate writes as soon as data is available in the kernel buffer.
How just spotted here the problem is that you have to wait that the programs that you run from your script finish their jobs.
If in your script you run program in background you can try something more.
In general a call to sync
before you exit allows to flush file system buffers and can help a little.
If in the script you start some programs in background (&
), you can wait that they finish before you exit from the script. To have an idea about how it can function you can see below
#!/bin/bash
#... some stuffs ...
program_1 & # here you start a program 1 in background
PID_PROGRAM_1=${!} # here you remember its PID
#... some other stuffs ...
program_2 & # here you start a program 2 in background
wait ${!} # You wait it finish not really useful here
#... some other stuffs ...
daemon_1 & # We will not wait it will finish
program_3 & # here you start a program 1 in background
PID_PROGRAM_3=${!} # here you remember its PID
#... last other stuffs ...
sync
wait $PID_PROGRAM_1
wait $PID_PROGRAM_3 # program 2 is just ended
# ...
Since wait
works with jobs as well as with PID
numbers a lazy solution should be to put at the end of the script
for job in `jobs -p`
do
wait $job
done
More difficult is the situation if you run something that run something else in background because you have to search and wait (if it is the case) the end of all the child process: for example if you run a daemon probably it is not the case to wait it finishes :-).
Note:
wait ${!} means "wait till the last background process is completed" where $!
is the PID of the last background process. So to put wait ${!}
just after program_2 &
is equivalent to execute directly program_2
without sending it in background with &
From the help of wait
:
Syntax
wait [n ...]
Key
n A process ID or a job specification
When we give any command, the streams of that command are stored in the memory location called buffer(a temporary memory location) in our computer. When all the temporary memory location is full then we use flush(), which flushes all the streams of data and executes them completely and gives a new space to new streams in buffer temporary location. -Hope you will understand
Dan's idea doesn't quite work:
#!/usr/bin/env python
class flushfile(file):
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
import sys
sys.stdout = flushfile(sys.stdout)
print "foo"
The result:
Traceback (most recent call last):
File "./passpersist.py", line 12, in <module>
print "foo"
ValueError: I/O operation on closed file
I believe the problem is that it inherits from the file class, which actually isn't necessary. According to the docs for sys.stdout:
stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.
so changing
class flushfile(file):
to
class flushfile(object):
makes it work just fine.
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
This is my code: (work for PHP7)
private function closeConnection()
{
@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
ignore_user_abort(true);
set_time_limit(0);
ob_start();
// do initial processing here
echo json_encode(['ans' => true]);
header('Connection: close');
header('Content-Length: ' . ob_get_length());
ob_end_flush();
ob_flush();
flush();
}
For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:
I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.
I would rather use plt.clf()
after every plt.show()
to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.
Similarly, you could do plt.cla()
to just clear the current axes.
To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()
The right way is:
db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})
$elemMatch
allows you to match more than one component within the same array element.
Without $elemMatch
mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.
See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.
Try this code for the 24 hrs format of time.
<script type="text/javascript">
var a="12:23:35";
var b="15:32:12";
var aa1=a.split(":");
var aa2=b.split(":");
var d1=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa1[0],10),parseInt(aa1[1],10),parseInt(aa1[2],10));
var d2=new Date(parseInt("2001",10),(parseInt("01",10))-1,parseInt("01",10),parseInt(aa2[0],10),parseInt(aa2[1],10),parseInt(aa2[2],10));
var dd1=d1.valueOf();
var dd2=d2.valueOf();
if(dd1<dd2)
{alert("b is greater");}
else alert("a is greater");
}
</script>
I think your cron is not correct. According to what you described, you may need to change cron schedule to
*/5 * * * *
What you put in your schedule now mean it will poll the SCM at 5 past of every hour.
If you want to create a small dots, just use icon from font awesome.
fa fa-circle
I finally managed to create a query that does exactly what i wanted to have:
A filtered nested boolean query. I am not sure why this is not documented. Maybe someone here can tell me?
Here is the query:
GET /test/object/_search
{
"from": 0,
"size": 20,
"sort": {
"_score": "desc"
},
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"term": {
"state": 1
}
}
]
}
},
"query": {
"bool": {
"should": [
{
"bool": {
"must": [
{
"match": {
"name": "foo"
}
},
{
"match": {
"name": "bar"
}
}
],
"should": [
{
"match": {
"has_image": {
"query": 1,
"boost": 100
}
}
}
]
}
},
{
"bool": {
"must": [
{
"match": {
"info": "foo"
}
},
{
"match": {
"info": "bar"
}
}
],
"should": [
{
"match": {
"has_image": {
"query": 1,
"boost": 100
}
}
}
]
}
}
],
"minimum_should_match": 1
}
}
}
}
}
In pseudo-SQL:
SELECT * FROM /test/object
WHERE
((name=foo AND name=bar) OR (info=foo AND info=bar))
AND state=1
Please keep in mind that it depends on your document field analysis and mappings how name=foo is internally handled. This can vary from a fuzzy to strict behavior.
"minimum_should_match": 1 says, that at least one of the should statements must be true.
This statements means that whenever there is a document in the resultset that contains has_image:1 it is boosted by factor 100. This changes result ordering.
"should": [
{
"match": {
"has_image": {
"query": 1,
"boost": 100
}
}
}
]
Have fun guys :)
This code will split it up for you:
list($whole, $decimal) = explode('.', $your_number);
where $whole is the whole number and $decimal will have the digits after the decimal point.
You should chain the replace() together instead of assigning the result and replacing again.
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
.replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
.replace(/.bbbbbb/g,'/world\">Helloworld</a>');
See DEMO.
this is the best source:
http://www.sommarskog.se/arrays-in-sql.html
create a split function using the link, and use it like:
DELETE YourTable
FROM YourTable d
LEFT OUTER JOIN dbo.splitFunction(@Parameter) s ON d.ID=s.Value
WHERE s.Value IS NULL
I prefer the number table approach
This is code based on the above link that should do it for you...
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
CREATE TABLE Numbers
(Number int NOT NULL,
CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
SET @x=@x+1
INSERT INTO Numbers VALUES (@x)
END
use this function to split your string, which does not loop and is very fast:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
/**
Takes the given @List string and splits it apart based on the given @SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.
Returns a table, one row per item in the list, with a column name "ListValue"
EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')
returns:
ListValue
-----------
1
12
123
1234
54321
6
A
*
|||
B
(10 row(s) affected)
**/
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO @ParsedList
(ListValue)
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = @SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
RETURN
END --Function FN_ListToTable
you can use this function as a table in a join:
SELECT
Col1, COl2, Col3...
FROM YourTable
INNER JOIN dbo.FN_ListToTable(',',@YourString) s ON YourTable.ID = s.ListValue
here is your delete:
DELETE YourTable
FROM YourTable d
LEFT OUTER JOIN dbo.FN_ListToTable(',',@Parameter) s ON d.ID=s.ListValue
WHERE s.ListValue IS NULL
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
None of the above worked for me, but brew reinstall icu4c
did.
For Windows, when you install a package, you type:
python -m pip install [packagename]
First of all if the size of the image is smaller than the container, then only "img-fluid" class will not solve your problem. you have to set the width of image to 100%, for that you can use Bootstrap class "w-100". keep in mind that "container-fluid" and "col-12" class sets left and right padding to 15px and "row" class sets left and right margin to "-15px" by default. make sure to set them to 0.
Note:
"px-0" is a bootstrap class which sets left and right padding to 0 and
"mx-0" is a bootstrap class which sets left and right margin to 0
P.S. i am using Bootstrap 4.0 version.
<div class="container-fluid px-0">
<div class="row mx-0">
<div class="col-12 px-0">
<img src="images/top.jpg" class="img-fluid w-100">
</div>
</div>
</div>
Based on the existing answer(s) I'd like to add a "shorter" version without the if:
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int count = 0, lastIndex = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
lastIndex += findStr.length() - 1;
count++;
}
System.out.println(count); // output: 3
You can just add '\r' at the end of the string plus a comma at the end of print function. For example:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),
Check if you have a compression enabled or disabled. If you use it or someone enabled it then app.use(express.static(xxx))
won't help. Make sure your server allows for compression.
I started to see the similar error when I added Brotli and Compression Plugins to my Webpack. Then your server needs to support this type of content compression too.
If you are using Express then the following should help:
app.use(url, expressStaticGzip(dir, gzipOptions)
Module is called: express-static-gzip
My settings are:
const gzipOptions = {
enableBrotli: true,
customCompressions: [{
encodingName: 'deflate',
fileExtension: 'zz'
}],
orderPreference: ['br']
}
If your method is void and you want to check for an exception, you could use expected
:
https://weblogs.java.net/blog/johnsmart/archive/2009/09/27/testing-exceptions-junit-47
The easiest way would be to create a new (simple) Maven project using the "new project" wizard. You can then migrate your source into the Maven folder structure + the auto generated POM file.
A GUID is a 16-byte (128-bit) number, typically represented by a 32-character hexadecimal string. A GUID (in hex form) need not contain any alpha characters, though by chance it probably would. If you are targeting a GUID in hex form, you can check that the string is 32-characters long (after stripping dashes and curly brackets) and has only letters A-F and numbers.
There is certain style of presenting GUIDs (dash-placement) and regular expressions can be used to check for this, e.g.,
@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$"
from http://www.geekzilla.co.uk/view8AD536EF-BC0D-427F-9F15-3A1BC663848E.htm. That said, it should be emphasized that the GUID really is a 128-bit number and could be represented in a number of different ways.
According to the docs (http://ca3.php.net/language.oop5.cloning):
$a = clone $b;
@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.
var currentZoom = 1.0;
$(document).ready(function () {
$('#btn_ZoomIn').click(
function () {
$('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
})
$('#btn_ZoomOut').click(
function () {
$('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
})
$('#btn_ZoomReset').click(
function () {
currentZoom = 1.0
$('#divName').animate({ 'zoom': 1 }, 'slow');
})
});
EDIT:
Create a class that extends AsyncTask
public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
public ImageLoadTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
}
}
And call this like new ImageLoadTask(url, imageView).execute();
Direct method:
Use this method and pass your url as string. It returns a bitmap. Set the bitmap to your ImageView.
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
And then this to ImageView like so:
imageView.setImageBitmap(getBitmapFromURL(url));
And dont forget about this permission in maifest.
<uses-permission android:name="android.permission.INTERNET" />
NOTE:
Try to call this method from another thread or AsyncTask because we are performing networking operations.
I generally like to create my own function as has been stated above. However I like to add a few things to it so that if I accidentally leave in debugging code I can quickly find it in the code base. Maybe this will help someone else out.
function _pr($d) {
echo "<div style='border: 1px solid#ccc; padding: 10px;'>";
echo '<strong>' . debug_backtrace()[0]['file'] . ' ' . debug_backtrace()[0]['line'] . '</strong>';
echo "</div>";
echo '<pre>';
if(is_array($d)) {
print_r($d);
} else if(is_object($d)) {
var_dump($d);
}
echo '</pre>';
}
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new
keywords has a simple answer: Yes. I'll illustrate...
You can either use the exports
variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require()
is a reference to the value of module.exports
.
A pseudo-code example of how a module is defined:
var theModule = {
exports: {}
};
(function(module, exports, require) {
// Your module code goes here
})(theModule, theModule.exports, theRequireFunction);
In the example above module.exports
and exports
are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.
Since you can attach a function directly to module.exports
you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)
So the following is perfectly good code and I personally encourage it:
// My module
function MyObject(bar) {
this.bar = bar;
}
MyObject.prototype.foo = function foo() {
console.log(this.bar);
};
module.exports = MyObject;
// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"
Same thing goes for non-constructor like functions:
// My Module
exports.someFunction = function someFunction(msg) {
console.log(msg);
}
// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"
If you're not joining two dictionaries, but adding new key-value pairs to a dictionary, then using the subscript notation seems like the best way.
import timeit
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary.update({"aaa": 123123, "asd": 233})')
>> 0.49582505226135254
timeit.timeit('dictionary = {"karga": 1, "darga": 2}; dictionary["aaa"] = 123123; dictionary["asd"] = 233;')
>> 0.20782899856567383
However, if you'd like to add, for example, thousands of new key-value pairs, you should consider using the update()
method.
The following example using the iris dataset works fine:
dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +
geom_point() + geom_line()
ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.
This is how to do it-
Add a ToolTip object to your form. One object is enough for the entire form.
ToolTip toolTip = new ToolTip();
Add the control to the tooltip with the desired text.
toolTip.SetToolTip(Button1,"Click here");
truncate tableName
That is what you are looking for.
Truncate will delete all records in the table, emptying it.
First WebClient
is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
I had to add:
secureTextEntry={true}
Along with
password={true}
As of 0.55
The Problem is caused by mksdcard not being installed correctly.
if you are running 64 bit, do this to fix the mksdcard problem.
sudo dpkg --add-architecture amd64
sudo apt-get update
sudo apt-get install libncurses5:amd64 libstdc++6:amd64 zlib1g:amd64
and 32 bit:
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
In SDK 6.0, the error message is different but means the same thing.
Unable to run mksdcard
Oracle as well as modern versions of Ubuntu have moved to newer versions of Java. The default for Ubuntu 20.04 is OpenJDK 11 which is good enough for most purposes.
If you really need it for running legacy programs, OpenJDK 8 is also available for Ubuntu 20.04 from the official repositories.
If you really need exactly Java 7, the best bet as of 2020 is to download a Zulu distribution. The easiest to install if you have root privileges is the .DEB version, otherwise download the .ZIP one.
If you run a script directly e.g., ./xx.py
and your script has no shebang such as #!/usr/bin/env python
at the very top then your shell may execute it as a shell script. POSIX says:
If the execl() function fails due to an error equivalent to the [ENOEXEC] error defined in the System Interfaces volume of POSIX.1-2008, the shell shall execute a command equivalent to having a shell invoked with the pathname resulting from the search as its first operand, with any remaining arguments passed to the new shell, except that the value of "$0" in the new shell may be set to the command name. If the executable file is not a text file, the shell may bypass this command execution. In this case, it shall write an error message, and shall return an exit status of 126.
Note: you may get ENOEXEC
if your text file has no shebang.
Without the shebang, you shell tries to run your Python script as a shell script that leads to the error: import: command not found
.
Also, if you run your script as python xx.py
then you do not need the shebang. You don't even need it to be executable (+x
). Your script is interpreted by python
in this case.
On Windows, shebang is not used unless pylauncher is installed. It is included in Python 3.3+.
If you like me, you will have two terminals app, one is the default terminal with bash as the default shell and another iTerm 2 with zsh as its shell. To have both commands and zsh in iTerm 2 from bash, you need to do the following:
On iTerm 2, go to preferences (or command ,). Then go to the profile tab and go down to command. As you can see on the picture below, you need to select command option and paste path of zsh shell (to find the path, you can do which zsh
).
At this point you will have the zsh as your default shell ONLY for iTerm 2 and you will have bash as the global default shell on default mac terminal app. Next, we are still missing the commands from bash in zsh. So to do this, you need to go on your bash (where you have your commands working) and get the PATH variable from env (use this command to do that: env | grep PATH
).
Once you have that, go to your iTerm 2 and paste your path on "send text at start" option.
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin && clear
Just reopen iTerm 2 and we are done!
The proper URL scheme is tel:[number] so you would do
<a href="tel:5551234567"><img src="callme.jpg" /></a>
_x000D_
adding a br tag between the divs worked. add br tag between two divs that are display:table-row in a parent with display:table
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
I find lots of answer for this kind of question misleading
Modified from this post: https://www.webmasterworld.com/linux/3613813.htm
The following code will create bash window and works exactly as a bash window. Hope this helps. Too many wrong/not-working answers out there...
Process proc;
try {
//create a bash window
proc = Runtime.getRuntime().exec("/bin/bash");
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
BufferedReader err = new BufferedReader(new InputStreamReader(
proc.getErrorStream()));
//input into the bash window
out.println("cd /my_folder");
out.println("rm *.jar");
out.println("svn co path to repo");
out.println("mvn compile package install");
out.println("exit");
String line;
System.out.println("----printing output-----");
while ((line = in.readLine()) != null) {
System.out.println(line);
}
while((line = err.readLine()) != null) {
//read errors
}
proc.waitFor();
in.close();
out.close();
err.close();
proc.destroy();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I tried the steps here:
http://jyotirbhandari.blogspot.com/2011/09/java-error-invalidalgorithmparameterexc.html
And, that fixed the issue. I made some minor tweaks - I set the two parameters using System.getProperty...
Using React and Axios, join proxy link to the URL and add header as shown below
https://cors-anywhere.herokuapp.com/
+ Your API URL
Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.
axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
.then(response => console.log(response:data);
}
This is just a quick fix, if you're struggling with why you're not able to get a response, you CAN use this. But again it's not the best answer for production.
Got several downvotes and it completely makes sense, I should have added the warning a long time ago.
You need to add a reference to System.Web.Extensions.dll
in project for System.Web.Script.Serialization error.
myString += Environment.NewLine;
myString = myString + Environment.NewLine;
There is a difference, but there is no difference in that example.
Using the more verbose method: new Array()
does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
x = new Array(5);
alert(x.length); // 5
To illustrate the different ways to create an array:
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
Another difference is that when using new Array()
you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array()
because you can prevent the overflow from happening.
As pointed out in this answer, new Array(5)
will not actually add five undefined
items to the array. It simply adds space for five items. Be aware that using Array
this way makes it difficult to rely on array.length
for calculations.
It seems like that it is only me who are so clumsy, because i have yet to found a solution that my case required.
I am developing a multi-modular project, thus base android module configuration is extracted in single gradle script. All the concrete versions of sdks/libs are also extracted in a script.
A script containing versions looked like this:
...
ext.androidVersions = [
compile_sdk_version : '27',
min_sdk_version : '19',
target_sdk_version : '27',
build_tool_version : '27.0.3',
application_id : 'com.test.test',
]
...
Not accustomed to groovy syntax my eye has not spotted that the values for compile, min and target sdks were not integers but STRINGS! Therefore a compiler rightfully complained about not being able to find an sdk a version of which would match HASH STRING '27'.
So the solution would be to make sdk's versions integers: ...
ext.androidVersions = [
compile_sdk_version : 27,
min_sdk_version : 19,
target_sdk_version : 27,
build_tool_version : '27.0.3',
application_id : 'com.test.test',
]
...
Start -> shift + command Prompt right click will helps to use as another user or as Admin
I prefer a popup.
$shell = new-object -comobject "WScript.Shell"
$choice = $shell.popup("Insert question here",0,"Popup window title",4+32)
If $choice equals 6, the answer was Yes If $choice equals 7, the answer was No
I'm finding out that the location of the log4j.properties file depends on the type of Eclipse project.
Specifically, for an Eclipse Dynamic Web Project, most of the answers that involve adding the log4j.properties to the war file do not actually add the properties file in the correct location, especially for Tomcat/Apache.
Here is some of my research and my solution to the issue (again specifically for a Dynamic Web Project running on Tomcat/Apache 6.0)
Please refer to this article around how Tomcat will load classes. It's different than the normal class loader for Java. (https://www.mulesoft.com/tcat/tomcat-classpath) Note that it only looks in two places in the war file, WEB-INF/classes and WEB-INF/lib.
Note that with a Dynamic Web Project, it is not wise to store your .properties file in the build/../classes directory, as this directory is wiped whenever you clean-build your project.
Tomcat does not handle .property files in the WEB-INF/lib location.
You cannot store the log4j.properties file in the src directory, as Eclipse abstracts that directory away from your view.
The one way I have found to resolve this is to alter the build and add an additional directory that will eventually load into the WEB-INF/classes directory in the war file. Specifically....
(1) Right click your project in the project explorer, select 'New'->'Folder'. You can name the folder anything, but the standard in this case is 'resources'. The new folder should appear at the root level of your project.
(2) Move the log4j.properties file into this new folder.
(3) Right click the project again, and select 'Build-Path'->'Configure Build Path'. Select the 'Sources' tab. Click the 'Add Folder' button. Browse to find your new folder you created in step (1) above. Select 'OK'.
(4) Once back to the eclipse Project Explorer view, note that the folder has now moved to the 'Java Resources' area (ie it's no longer at the root due to eclipse presentation abstraction).
(5) Clean build your project.
(6) To validate that the .properties file now exists in WEB-INF/classes in your war file, export a war file to an easy location (right click Project -> Export -> War file) and checkout the contents. Note that the log4j.properties file now appears in the WEB-INF/classes.
(7) Promote your project to Tomcat/Apache and note that log4j now works.
Now that log4j works, start logging, solve world problems, take some time off, and enjoy a tasty adult beverage.
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
You can try ezxml -- it's a lightweight parser written entirely in C.
For C++ you can check out TinyXML++
There are a thousand and one ways to do it. Here's one using dc
(a reverse-polish desk calculator which supports unlimited precision arithmetic):
dc <<<"$num1 $num2 + p"
But if that's too bash-y for you (or portability matters) you could say
echo $num1 $num2 + p | dc
But maybe you're one of those people who thinks RPN is icky and weird; don't worry! bc
is here for you:
bc <<< "$num1 + $num2"
echo $num1 + $num2 | bc
That said, there are some unrelated improvements you could be making to your script:
#!/bin/bash
num=0
metab=0
for ((i=1; i<=2; i++)); do
for j in output-$i-* ; do # 'for' can glob directly, no need to ls
echo "$j"
# 'grep' can read files, no need to use 'cat'
metab=$(grep EndBuffer "$j" | awk '{sum+=$2} END { print sum/120}')
num=$(( $num + $metab ))
done
echo "$num"
done
As described in Bash FAQ 022, Bash does not natively support floating point numbers. If you need to sum floating point numbers the use of an external tool (like bc
or dc
) is required.
In this case the solution would be
num=$(dc <<<"$num $metab + p")
To add accumulate possibly-floating-point numbers into num
.
Well I can change them in chrome. Its simple and works fine in Chrome using -webkit css properties.
The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.
http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm
Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.
I put the data starting on row 5:
Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.
That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.
Make sure in your AndroidManifest.xml
the package name is correct. That fixed the problem for me when my R.whatever
was marked red!
I would also recommend checking all your gradle
files to make sure those package names are correct. That shouldn't make everything red, but it will stop your gradle
files from syncing properly.
I think the easiest solution would be
git checkout master
git remote update
git merge origin/Develop -X theirs
git commit -m commit -m "New release"
git push --recurse-submodules=check --progress "origin" refs/heads/Master
This also preserves the history of all the branches in use
There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.
They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.
Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools
There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?
If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.
On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).
foreach
can handle arrays and objects. You can check this with:
$can_foreach = is_array($var) || is_object($var);
if ($can_foreach) {
foreach ($var as ...
}
You don't need to specifically check for Traversable
as others have hinted it in their answers, because all objects - like all arrays - are traversable in PHP.
More technically:
foreach
works with all kinds of traversables, i.e. with arrays, with plain objects (where the accessible properties are traversed) andTraversable
objects (or rather objects that define the internalget_iterator
handler).
(source)
Simply said in common PHP programming, whenever a variable is
and is not
you can use foreach
on it.
It may be late but there is a new simple solution to this question for who ever wants it.
In kotlin
val player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI)
player.start()
Above code will play default ringtone but if you want default alarm, change
Settings.System.DEFAULT_RINGTONE_URI
to
Settings.System.DEFAULT_ALARM_ALERT_URI
This works for me perfectly fine:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("mailto:" + address));
startActivity(Intent.createChooser(intent, "E-mail"));
If you're on windows and using apache, maybe via WAMP or the Drupal stack installer, you can additionally download the git for windows package, which includes many useful linux command line tools, one of which is openssl.
The following command creates the self signed certificate and key needed for apache and works fine in windows:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt
A few more things not covered by other answers:
# ':' is the delimiter here, and there are three fields on each line in the file
# IFS set below is restricted to the context of `read`, it doesn't affect any other code
while IFS=: read -r field1 field2 field3; do
# process the fields
# if the line has less than three fields, the missing fields will be set to an empty string
# if the line has more than three fields, `field3` will get all the values, including the third field plus the delimiter(s)
done < input.txt
while read -r line; do
# process the line
done < <(command ...)
This approach is better than command ... | while read -r line; do ...
because the while loop here runs in the current shell rather than a subshell as in the case of the latter. See the related post A variable modified inside a while loop is not remembered.
find ... -print0
while read -r -d '' line; do
# logic
# use a second 'read ... <<< "$line"' if we need to tokenize the line
done < <(find /path/to/dir -print0)
Related read: BashFAQ/020 - How can I find and safely handle file names containing newlines, spaces or both?
while read -u 3 -r line1 && read -u 4 -r line2; do
# process the lines
# note that the loop will end when we reach EOF on either of the files, because of the `&&`
done 3< input1.txt 4< input2.txt
Based on @chepner's answer here:
-u
is a bash extension. For POSIX compatibility, each call would look something like read -r X <&3
.
while read -r line; do
my_array+=("$line")
done < my_file
If the file ends with an incomplete line (newline missing at the end), then:
while read -r line || [[ $line ]]; do
my_array+=("$line")
done < my_file
readarray -t my_array < my_file
or
mapfile -t my_array < my_file
And then
for line in "${my_array[@]}"; do
# process the lines
done
More about the shell builtins read
and readarray
commands - GNU
Related posts:
To use CSS3 Animation you must also define the actual animation keyframes (which you named spin
)
Read https://developer.mozilla.org/en-US/docs/CSS/Tutorials/Using_CSS_animations for more info
Once you've configured the animation's timing, you need to define the appearance of the animation. This is done by establishing two or more keyframes using the
@keyframes
at-rule. Each keyframe describes how the animated element should render at a given time during the animation sequence.
Demo at http://jsfiddle.net/gaby/9Ryvs/7/
@-moz-keyframes spin {
from { -moz-transform: rotate(0deg); }
to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
from { -webkit-transform: rotate(0deg); }
to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
/bin/sh
is usually some other shell trying to mimic The Shell. Many distributions use /bin/bash
for sh
, it supports source
. On Ubuntu, though, /bin/dash
is used which does not support source
. Most shells use .
instead of source
. If you cannot edit the script, try to change the shell which runs it.
Updated.. I solved this issue by stating the charset on PDO connection as below:
"mysql:host=$host;dbname=$db;charset=utf8"
All data received was then in the correct charset for the rest of the code to use
You may want to use the onLoad
event, as in the following example:
<iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe>
The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)
If the iframe is showing a page within the same domain of the parent, you would be able to access the location with contentWindow.location
, as in the following example:
<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>
You actually want TestClass.instance_methods
, unless you're interested in what TestClass
itself can do.
class TestClass
def method1
end
def method2
end
def method3
end
end
TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]
Or you can call methods
(not instance_methods
) on the object:
test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]
You could try:
agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)
I put together this html/jQuery dynamic YouTube video modal script that auto plays the YouTube video when the trigger (link) is clicked, the trigger also contains the link to play. The script will find the native bootstrap modal call and open the shared modal template with the data from the trigger. See Below and let me know what you think. I would love to hear thoughts...
HTML MODAL TRIGGER:
<a href="#" class="btn btn-default" data-toggle="modal" data-target="#videoModal" data-theVideo="http://www.youtube.com/embed/loFtozxZG0s" >VIDEO</a>
HTML MODAL VIDEO TEMPLATE:
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div>
<iframe width="100%" height="350" src=""></iframe>
</div>
</div>
</div>
</div>
</div>
THE JQUERY FUNCTION:
//FUNCTION TO GET AND AUTO PLAY YOUTUBE VIDEO FROM DATATAG
function autoPlayYouTubeModal(){
var trigger = $("body").find('[data-toggle="modal"]');
trigger.click(function() {
var theModal = $(this).data( "target" ),
videoSRC = $(this).attr( "data-theVideo" ),
videoSRCauto = videoSRC+"?autoplay=1" ;
$(theModal+' iframe').attr('src', videoSRCauto);
$(theModal+' button.close').click(function () {
$(theModal+' iframe').attr('src', videoSRC);
});
});
}
THE FUNCTION CALL:
$(document).ready(function(){
autoPlayYouTubeModal();
});
The FIDDLE: http://jsfiddle.net/jeremykenedy/h8daS/1/
You do not need to pass the size parameter, just declare Varchar
already understands that it is MAX like:
cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";
I worked out on Xcode 6.4 on swift. See below.
var view1: UIView!
func assignTapToView1() {
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
// tap.delegate = self
view1.addGestureRecognizer(tap)
self.view .addSubview(view1)
...
}
func handleTap() {
print("tap working")
view1.removeFromSuperview()
// view1.alpha = 0.1
}
You may be able to do this by modifying the request options as below. If you are using a self-signed certificate or a missing intermediary, setting strictSSL to false will not force request package to validate the certificate.
var options = {
host: 'jira.example.com',
path: '/secure/attachment/206906/update.xlsx',
strictSSL: false
}
Applying
<item name="android:statusBarColor">@color/color_primary_dark</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
in Theme.AppCompat.Light.DarkActionBar
didn't worked for me. What did the trick is , giving colorPrimaryDark
as usual along with android:colorPrimary
in styles.xml
<item name="android:colorAccent">@color/color_primary</item>
<item name="android:colorPrimary">@color/color_primary</item>
<item name="android:colorPrimaryDark">@color/color_primary_dark</item>
and in setting
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
Window window = this.Window;
Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
}
didn't had to set statusbar color in code .
A secondary option would be to match and return non-digits with some expression similar to,
/\D+/g
which would likely work for that specific string in the question (1 ding ?
).
function non_digit_string(str) {_x000D_
const regex = /\D+/g;_x000D_
let m;_x000D_
_x000D_
non_digit_arr = [];_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
_x000D_
m.forEach((match, groupIndex) => {_x000D_
if (match.trim() != '') {_x000D_
non_digit_arr.push(match.trim());_x000D_
}_x000D_
});_x000D_
}_x000D_
return non_digit_arr;_x000D_
}_x000D_
_x000D_
const str = `1 ding ? 124_x000D_
12 ding ?_x000D_
123 ding ? 123`;_x000D_
console.log(non_digit_string(str));
_x000D_
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
jex.im visualizes regular expressions:
Make sure you also start the MySQL service in Xampp control panel. This might resolve this.
Do configure --help
and see what other options are available.
It is very common to provide different options to override different locations. By standard, --prefix
overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.
The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:
./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc
I believe that should do it.
I was having the same problem, in my case the package name was wrong, fixing it solved the problem.
You can also set the options --log-fd if you just want to read your logs with a less. For example :
valgrind --log-fd=1 ls | less
For most of the people who are more familiar with MariaDB or MySQL this seems little confusing because in MariaDB or MySQL they have different schemas (which includes different tables, view , PLSQL blocks and DB objects etc) and USERS are the accounts which can access those schema. Therefore no specific user can belong to any particular schema. The permission has be to given to that Schema then the user can access it. The Users and Schema is separated in databases like MySQL and MariaDB.
In Oracle schema and users are almost treated as same. To work with that schema you need to have the permission which is where you will feel that the schema name is nothing but user name. Permissions can be given across schemas to access different database objects from different schema. In oracle we can say that a user owns a schema because when you create a user you create DB objects for it and vice a versa.
I need to make a POST request via Curl from the command line. Data for this request is located in a file...
All you need to do is have the --data
argument start with a @
:
curl -H "Content-Type: text/xml" --data "@path_of_file" host:port/post-file-path
For example, if you have the data in a file called stuff.xml
then you would do something like:
curl -H "Content-Type: text/xml" --data "@stuff.xml" host:port/post-file-path
The stuff.xml
filename can be replaced with a relative or full path to the file: @../xml/stuff.xml
, @/var/tmp/stuff.xml
, ...
Math.round(number*100.0)/100.0;
Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.
public static class dynamicHelper
{
public static ExpandoObject convertToExpando(object obj)
{
//Get Properties Using Reflections
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = obj.GetType().GetProperties(flags);
//Add Them to a new Expando
ExpandoObject expando = new ExpandoObject();
foreach (PropertyInfo property in properties)
{
AddProperty(expando, property.Name, property.GetValue(obj));
}
return expando;
}
public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
//Take use of the IDictionary implementation
var expandoDict = expando as IDictionary;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}
}
Usage:
//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);
//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");
This can be done by cloning to a new directory, then moving the .git
directory into your existing directory.
If your existing directory is named "code".
git clone https://myrepo.com/git.git temp
mv temp/.git code/.git
rm -rf temp
This can also be done without doing a checkout during the clone command; more information can be found here.
Have your tried using the 'return' keyword?
def rps():
return True
To set up VS code path permanently on Mac OS;
just open .bash_profile using the following command on terminal
open -t .bash_profile
Then add the following path to .bash_profile
code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}
save the .bash_profile file and quit the terminal. Then reopen the terminal and type code .
to open VS code.
value_counts omits NaN by default so you're most likely dealing with "".
So you can just filter them out like
filter = df["Tenant"] != ""
dfNew = df[filter]
You can use require as well to render images like
//then in the render function of Jsx insert the mainLogo variable
class NavBar extends Component {
render() {
return (
<nav className="nav" style={nbStyle}>
<div className="container">
//right below here
<img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
</div>
</nav>
);
}
}
as others mentioned well and in this thread
You can use the HttpWebRequest class to do so.
Example here:
using System;
using System.Net;
using System.Text;
using System.IO;
public class Test
{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);
// Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Console.WriteLine ("Content length is {0}", response.ContentLength);
Console.WriteLine ("Content type is {0}", response.ContentType);
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream ();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
Console.WriteLine ("Response stream received.");
Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}
/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:
Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>
*/
For
<%=clients%>
to work you need to have a public or protected variable clients
in the code-behind.
Here is an article that explains it: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
I prefer the first version to start a java application just because it has less pitfalls ("welcome to classpath hell"). The second one requires an executable jar file and the classpath for that application has to be defined inside the jar's manifest (all other classpath declaration will be silently ignored...). So with the second version you'd have to look into the jar, read the manifest and try to find out if the classpath entries are valid from where the jar is stored... That's avoidable.
I don't expect any performance advantages or disadvantages for either version. It's just telling the jvm which class to use for the main thread and where it can find the libraries.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
Yes you are right, your example doesn't do any harm (at least not on most modern operating systems). All the memory allocated by your process will be recovered by the operating system once the process exits.
Source: Allocation and GC Myths (PostScript alert!)
Allocation Myth 4: Non-garbage-collected programs should always deallocate all memory they allocate.
The Truth: Omitted deallocations in frequently executed code cause growing leaks. They are rarely acceptable. but Programs that retain most allocated memory until program exit often perform better without any intervening deallocation. Malloc is much easier to implement if there is no free.
In most cases, deallocating memory just before program exit is pointless. The OS will reclaim it anyway. Free will touch and page in the dead objects; the OS won't.
Consequence: Be careful with "leak detectors" that count allocations. Some "leaks" are good!
That said, you should really try to avoid all memory leaks!
Second question: your design is ok. If you need to store something until your application exits then its ok to do this with dynamic memory allocation. If you don't know the required size upfront, you can't use statically allocated memory.
showInventory(player); // I get the error here.
void showInventory(player& obj) { // By Johnny :D
this means that player is an datatype and showInventory expect an referance to an variable of type player.
so the correct code will be
void showInventory(player& obj) { // By Johnny :D
for(int i = 0; i < 20; i++) {
std::cout << "\nINVENTORY:\n" + obj.getItem(i);
i++;
std::cout << "\t\t\t" + obj.getItem(i) + "\n";
i++;
}
}
players myPlayers[10];
std::string toDo() //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "\nWhat do you wish to do?\n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return NULL;
}
else if(ans == commands[1]) {
showInventory(myPlayers[0]); // or any other index,also is not necessary to have an array
return NULL;
}
}
If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:
[
{"key": value},
{"key": value},
...
This is still valid JSON.
Then, use the node.js readline module to process them one line at a time.
var fs = require("fs");
var lineReader = require('readline').createInterface({
input: fs.createReadStream("input.txt")
});
lineReader.on('line', function (line) {
line = line.trim();
if (line.charAt(line.length-1) === ',') {
line = line.substr(0, line.length-1);
}
if (line.charAt(0) === '{') {
processRecord(JSON.parse(line));
}
});
function processRecord(record) {
// Process the records one at a time here!
}
There is an attribute called android:weightSum.
You can set android:weightSum="2" in the parent linear_layout and android:weight="1" in the inner linear_layout.
Remember to set the inner linear_layout to fill_parent so weight attribute can work as expected.
Btw, I don't think its necesary to add a second view, altough I haven't tried. :)
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:weightSum="2">
<LinearLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_weight="1">
</LinearLayout>
</LinearLayout>
You just need to set the related drawables and set them in the checkbox:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new checkbox"
android:background="@drawable/my_checkbox_background"
android:button="@drawable/my_checkbox" />
The trick is on how to set the drawables. Here's a good tutorial about this.
easily kick out the problem by just add this line both try and catch block
path: node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js
bson = require('bson'); instead
bson = require('./win32/ia32/bson');
bson = require('../build/Release/bson');
That is all!!!
Cause
A container with the same name is still existing.
Solution
To reuse the same container name, delete the existing container by:
docker rm <container name>
Explanation
Containers can exist in following states, during which the container name can't be used for another container:
created
restarting
running
paused
exited
dead
You can see containers in running
state by using :
docker ps
To show containers in all states and find out if a container name is taken, use:
docker ps -a
This worked for me for a format like YYYY.MM.DD-HH.MM.SS.fff. Attempting to make this code capable of accepting any string format will be like reinventing the wheel (i.e. there are functions for all this in Boost.
std::chrono::system_clock::time_point string_to_time_point(const std::string &str)
{
using namespace std;
using namespace std::chrono;
int yyyy, mm, dd, HH, MM, SS, fff;
char scanf_format[] = "%4d.%2d.%2d-%2d.%2d.%2d.%3d";
sscanf(str.c_str(), scanf_format, &yyyy, &mm, &dd, &HH, &MM, &SS, &fff);
tm ttm = tm();
ttm.tm_year = yyyy - 1900; // Year since 1900
ttm.tm_mon = mm - 1; // Month since January
ttm.tm_mday = dd; // Day of the month [1-31]
ttm.tm_hour = HH; // Hour of the day [00-23]
ttm.tm_min = MM;
ttm.tm_sec = SS;
time_t ttime_t = mktime(&ttm);
system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t);
time_point_result += std::chrono::milliseconds(fff);
return time_point_result;
}
std::string time_point_to_string(std::chrono::system_clock::time_point &tp)
{
using namespace std;
using namespace std::chrono;
auto ttime_t = system_clock::to_time_t(tp);
auto tp_sec = system_clock::from_time_t(ttime_t);
milliseconds ms = duration_cast<milliseconds>(tp - tp_sec);
std::tm * ttm = localtime(&ttime_t);
char date_time_format[] = "%Y.%m.%d-%H.%M.%S";
char time_str[] = "yyyy.mm.dd.HH-MM.SS.fff";
strftime(time_str, strlen(time_str), date_time_format, ttm);
string result(time_str);
result.append(".");
result.append(to_string(ms.count()));
return result;
}
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
Try this:
num = input("Please input your number: ")
num = float("%0.2f" % (num))
print(num)
I believe this is a lot simpler. For 1 decimal place use %0.1f
. For 2 decimal places use %0.2f
and so on.
Or, if you want to reduce it all to 2 lines:
num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)
For finding flash memory defects, I had to write this script which shows all 1K blocks which contain differences (not only the first one as cmp -b
does)
#!/bin/sh
f1=testinput.dat
f2=testoutput.dat
size=$(stat -c%s $f1)
i=0
while [ $i -lt $size ]; do
if ! r="`cmp -n 1024 -i $i -b $f1 $f2`"; then
printf "%8x: %s\n" $i "$r"
fi
i=$(expr $i + 1024)
done
Output:
2d400: testinput.dat testoutput.dat differ: byte 3, line 1 is 200 M-^@ 240 M-
2dc00: testinput.dat testoutput.dat differ: byte 8, line 1 is 327 M-W 127 W
4d000: testinput.dat testoutput.dat differ: byte 37, line 1 is 270 M-8 260 M-0
4d400: testinput.dat testoutput.dat differ: byte 19, line 1 is 46 & 44 $
Disclaimer: I hacked the script in 5 min. It doesn't support command line arguments nor does it support spaces in file names
Using in place string concatenation by '+' is THE WORST method of concatenation in terms of stability and cross implementation as it does not support all values. PEP8 standard discourages this and encourages the use of format(), join() and append() for long term use.
As quoted from the linked "Programming Recommendations" section:
For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
2014 iframe embed on how to embed a youtube video with autoplay and no suggested videos at end of clip
rel=0&autoplay
Example Below: .
<iframe width="640" height="360" src="//www.youtube.com/embed/JWgp7Ny3bOo?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
Default Rpi resolution is : 1366x768 if i'm not mistaken.
You can change it though.
You will find all the information about it in this link.
Search "hdmi mode" on that page.
Hope it helps.
To update and/or enhance the answer by @Hans Passant I would separate the retrieval of the property into an extension method. This has the added benefit of removing the nasty magic string in the method GetProperty()
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
Your test is then reduced to two lines
var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));
In laymans terms, and practicality, I see this as an old DOS trick/thing. Whoa! What was that? DOS? Never heard of it!
".." backs you out of the current sub-directory one time to a higher folder/directory, and .. enter typed twice backs you out too 2 higher parent folders. Keep adding the ".. enter" back to back and you will soon find yourself at the top level of the directory.
As for Newbies to understand this better, consider this (in terms of the home PC or "C:\ drive" if you know what that means, rather than the web-servers/host "root directory" ). While your at it, Consider your website existing somewhere on your home PC's hard drive, buried in some folder under the C:\ drive. Lastly, you can think of it as ".." is back one directory and "/" is forward one directory/folder.
Now! If you are using the command prompt and are within the "myDocuments" folder of your PC you must back out of that folder to get closer to the higher directory "C:\" by typing the "../". If you wanted to access a file that is located in the widows directory while you are still in the myDocuments folder you would theoretically type ../windows; in reality of DOS command prompt you would simply type .., but I am setting you up for the web. The / redirects forward to another directory naturally.
Using "myDocuments" lets pretend that you created 2 folders within it called "PHP1" and "PHP2", in such we now have the folders:
In PHP1 you place a file called index.php. and in PHP2 folder you placed a file called Found.php. it now becomes:
Inside the C:\myDocuments\PHP1\index.php file you would need to edit and type something like:
<?php include ('../php2/found.php')?>
The ../ is positional thus it considers your current file location "C:\myDocuments\PHP1\index.php" and is a directive telling it to back out of PHP1 directory and enter or move forward into PHP2 directory to look for the Found.php file. But does it read it? See my thoughts on trouble shooting below.
Now! suppose you have 1 folder PHP1 and a sub-folder PHP2:
you would simply reference/code
<?php include('/PHP2/found.php') ?>
as PHP2 exist as a sub-directory, below or within PHP1 directory.
If the above does not work it may have something to do with access/htaccess or permission to the directory or a typo. To enhance this...getting into trouble shooting...If the "found.php" file has errors/typo's within it, it will crash upon rendering at the error, such could be the reason (require/require_once) that you are experiencing the illusion that it is not changing directories or accessing the file. At last thought on the matter, you may need to instantiate your functions or references in order to use the included/require "whatever" by creating a new variable or object such as
$newObject = new nameobject("origianlThingy");
Remember, just because you are including/requiring something, sometimes means just that, it is included/required to run, but it might need to be recreated to make it active or access it. New will surely re-create an instance of it "if it is readable" and make it available within the current document while preserving the original. However you should reference the newly created variable $newObject in all instances....if its global.
To put this in perspective of some web host account; the web host is some whopping over sized hard-drive (like that on your PC) and your domain is nothing more than a folder they have assigned to you. Your folder is called the root. Inside that folder you can do anything you are allowed to do.
your "one of many ways" to move between directories/folders is to use the ../
however many times to back out of your current in reference to folder position you want to find.
In my drunken state I realize that I know too much to be sane, and not enough to be insane!"
This should work in your case without removing namespaces:
XmlNode idNode = myXmlDoc.GetElementsByTagName("id")[0];
Using unzip
unzip -c whatever.war META-INF/MANIFEST.MF
It will print the output in terminal.
And for extracting all the files,
unzip whatever.war
Using jar
jar xvf test.war
Note! The jar
command will extract war contents to current directory. Not to a subdirectory (like Tomcat does).
See if this helps. I can set variables for Elapsed Days, Hours, Minutes, Seconds. You can format this to your liking or include in a user defined function.
Note: Don't use DateDiff(hh,@Date1,@Date2). It is not reliable! It rounds in unpredictable ways
Given two dates... (Sample Dates: two days, three hours, 10 minutes, 30 seconds difference)
declare @Date1 datetime = '2013-03-08 08:00:00'
declare @Date2 datetime = '2013-03-10 11:10:30'
declare @Days decimal
declare @Hours decimal
declare @Minutes decimal
declare @Seconds decimal
select @Days = DATEDIFF(ss,@Date1,@Date2)/60/60/24 --Days
declare @RemainderDate as datetime = @Date2 - @Days
select @Hours = datediff(ss, @Date1, @RemainderDate)/60/60 --Hours
set @RemainderDate = @RemainderDate - (@Hours/24.0)
select @Minutes = datediff(ss, @Date1, @RemainderDate)/60 --Minutes
set @RemainderDate = @RemainderDate - (@Minutes/24.0/60)
select @Seconds = DATEDIFF(SS, @Date1, @RemainderDate)
select @Days as ElapsedDays, @Hours as ElapsedHours, @Minutes as ElapsedMinutes, @Seconds as ElapsedSeconds
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Works on python 3 and python 2.
# when server knows where the request is coming from.
import sys
if sys.version_info[0] == 3:
from urllib.request import urlopen
else:
from urllib import urlopen
with urlopen('https://www.facebook.com/') as \
url:
data = url.read()
print data
# When the server does not know where the request is coming from.
# Works on python 3.
import urllib.request
user_agent = \
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
url = 'https://www.facebook.com/'
headers = {'User-Agent': user_agent}
request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
data = response.read()
print data
You can use the old Stupid Scanner trick oneliner to do that without any additional dependency like guava:
String text = new Scanner(AppropriateClass.class.getResourceAsStream("foo.txt"), "UTF-8").useDelimiter("\\A").next();
Guys, don't use 3rd party stuff unless you really need that. There is a lot of functionality in the JDK already.
You could use SET DATEFORMAT, like in this example
declare @dates table (orig varchar(50) ,parsed datetime)
SET DATEFORMAT ydm;
insert into @dates
select '2008-09-01','2008-09-01'
SET DATEFORMAT ymd;
insert into @dates
select '2008-09-01','2008-09-01'
select * from @dates
You would need to specify the dateformat in the code when you parse your XML data
You could set its width
:
<input type="text" id="text" name="text_name" style="width: 300px;" />
or even better define a class:
<input type="text" id="text" name="text_name" class="mytext" />
and in a separate CSS file apply the necessary styling:
.mytext {
width: 300px;
}
If you want to limit the number of characters that the user can type into this textbox you could use the maxlength
attribute:
<input type="text" id="text" name="text_name" class="mytext" maxlength="25" />
if i want to check if any speicfic position of command line arguement is passed or not then how to check? like for example in some scenarios 2 command line args will be passed and in some only one will be passed then how do it check wheather the specfic commnad line is passed or not?
public class check {
public static void main(String[] args) {
if(args[0].length()!=0)
{
System.out.println("entered first if");
}
if(args[0].length()!=0 && args[1].length()!=0)
{
System.out.println("entered second if");
}
}
}
So in the above code if args[1] is not passed then i get java.lang.ArrayIndexOutOfBoundsException:
so how do i tackle this where i can check if second arguement is passed or not and if passed then enter it. need assistance asap.
Credits to osexp2003 and j.a. …
Instead of putting:
&>> your_file.log
behind a line in:
crontab -e
I use:
#!/bin/bash
exec &>> your_file.log
…
at the beginning of a BASH script.
Advantage: You have the log definitions within your script. Good for Git etc.
Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.
You can override this behaviour by declaring it locally using var
, but if you don't use var
, then a variable name used in a function will be global if that variable has been declared globally.
That's why it's considered best practice to always declare your variables explicitly with var
. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
I thought about block-transfer acceleration methods built into many graphics cards. But then you would have to copy over all the data byte-wise, so this doesn't help you much if you don't want to implement a whole portion of your logic in unmanaged and hardware-dependent code...
Another way of optimization similar to the approach shown above would be to store as much of your data as possible in a long[] rather than a byte[] right from the start, for example if you are reading it sequentially from a binary file, or if you use a memory mapped file, read in data as long[] or single long values. Then, your comparison loop will only need 1/8th of the number of iterations it would have to do for a byte[] containing the same amount of data. It is a matter of when and how often you need to compare vs. when and how often you need to access the data in a byte-by-byte manner, e.g. to use it in an API call as a parameter in a method that expects a byte[]. In the end, you only can tell if you really know the use case...
That is only possible if that site has declared anchors in the page. It is done by giving a tag a name or id attribute, so look for any of those close to where you want to link to.
And then the syntax would be
<a href="page.html#anchor">text</a>
http://php.net/manual/en/language.types.string.php says:
Note: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum)
In PHP 5.x, strings were limited to 231-1 bytes, because internal code recorded the length in a signed 32-bit integer.
You can slurp in the contents of an entire file, for instance using file_get_contents()
However, a PHP script has a limit on the total memory it can allocate for all variables in a given script execution, so this effectively places a limit on the length of a single string variable too.
This limit is the memory_limit
directive in the php.ini configuration file. The memory limit defaults to 128MB in PHP 5.2, and 8MB in earlier releases.
If you don't specify a memory limit in your php.ini file, it uses the default, which is compiled into the PHP binary. In theory you can modify the source and rebuild PHP to change this default value.
If you specify -1
as the memory limit in your php.ini file, it stop checking and permits your script to use as much memory as the operating system will allocate. This is still a practical limit, but depends on system resources and architecture.
Re comment from @c2:
Here's a test:
<?php
// limit memory usage to 1MB
ini_set('memory_limit', 1024*1024);
// initially, PHP seems to allocate 768KB for basic operation
printf("memory: %d\n", memory_get_usage(true));
$str = str_repeat('a', 255*1024);
echo "Allocated string of 255KB\n";
// now we have allocated all of the 1MB of memory allowed
printf("memory: %d\n", memory_get_usage(true));
// going over the limit causes a fatal error, so no output follows
$str = str_repeat('a', 256*1024);
echo "Allocated string of 256KB\n";
printf("memory: %d\n", memory_get_usage(true));
Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:
RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’
And from there I ran a restore statement with MOVE
using logical names.
RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'
When it was done restoring, I almost wept with joy.
Good luck!
TS has many utility methods for arrays which are available via the prototype of Arrays. There are multiple which can achieve this goal but the two most convenient for this purpose are:
Array.indexOf()
Takes any value as an argument and then returns the first index at which a given element can be found in the array, or -1 if it is not present.Array.includes()
Takes any value as an argument and then determines whether an array includes a this value. The method returning true
if the value is found, otherwise false
.Example:
const channelArray: string[] = ['one', 'two', 'three'];
console.log(channelArray.indexOf('three')); // 2
console.log(channelArray.indexOf('three') > -1); // true
console.log(channelArray.indexOf('four') > -1); // false
console.log(channelArray.includes('three')); // true
*************Resolved - #1214 - The used table type doesn't support FULLTEXT indexes***************
Its Very Simple to resolve this issue. People are answering here in very difficult words which are not easily understandable by the people who are not technical.
So i am mentioning here steps in very simple words will resolve your issue.
1.) Open your .sql file with Notepad by right clicking on file>Edit Or Simply open a Notepad file and drag and drop the file on Notepad and the file will be opened. (Note: Please don't change the extention .sql of file as its still your sql database. Also to keep a copy of your sql file to save yourself from any mishappening)
2.) Click on Notepad Menu Edit > Replace (A Window will be pop us with Find What & Replace With Fields)
3.) In Find What Field Enter ENGINE=InnoDB & In Replace With Field Enter ENGINE=MyISAM
4.) Now Click on Replace All Button
5.) Click CTRL+S or File>Save
6.) Now Upload This File and I am Sure your issue will be resolved....
This is a bit more readable:
Object[] allValues = all.getDeclaringClass().getEnumConstants();
SOLUTION
This means that you are missing the right for using it. Create it with Netsh Commands for Hypertext Transfer Protocol > add urlacl.
1) Open "Command Line Interface (CLI)" called "Command shell" with Win+R write "cmd"
2) Open CLI windows like administrator with mouse context menu on opened windows or icon "Run as administrator"
3) Insert command to register url
netsh http add urlacl url=http://{ip_addr}:{port}/ user=everyone
NOTE:
netsh http delete urlacl url=http://{ip_addr}:{port}/
Use a T-SQL IF
:
IF @ABC IS NOT NULL AND @ABC != -1
UPDATE [TABLE_NAME] SET XYZ=@ABC
Take a look at the MSDN docs.
In modern browsers, use Intl.DateTimeFormat
and force 12hr format with options:
let now = new Date();
new Intl.DateTimeFormat('default',
{
hour12: true,
hour: 'numeric',
minute: 'numeric'
}).format(now);
// 6:30 AM
Using default
will honor browser's default locale if you add more options, yet will still output 12hr format.
You will get output from column
value 9 to 26 as you have mentioned OFFSET
as 8
If someone needs to zip a single file (and not a folder): http://blogs.msdn.com/b/jerrydixon/archive/2014/08/08/zipping-a-single-file-with-powershell.aspx
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[string]$sourceFile,
[Parameter(Mandatory=$True)]
[ValidateScript({-not(Test-Path -Path $_ -PathType Leaf)})]
[string]$destinationFile
)
<#
.SYNOPSIS
Creates a ZIP file that contains the specified innput file.
.EXAMPLE
FileZipper -sourceFile c:\test\inputfile.txt
-destinationFile c:\test\outputFile.zip
#>
function New-Zip
{
param([string]$zipfilename)
set-content $zipfilename
("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
function Add-Zip
{
param([string]$zipfilename)
if(-not (test-path($zipfilename)))
{
set-content $zipfilename
("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Start-sleep -milliseconds 500
}
}
dir $sourceFile | Add-Zip $destinationFile
It's really simple. It's a new feature introduced in J2SE 5. Specifying angular brackets after the class name means you are creating a temporary data type which can hold any type of data.
Example:
class A<T>{
T obj;
void add(T obj){
this.obj=obj;
}
T get(){
return obj;
}
}
public class generics {
static<E> void print(E[] elements){
for(E element:elements){
System.out.println(element);
}
}
public static void main(String[] args) {
A<String> obj=new A<String>();
A<Integer> obj1=new A<Integer>();
obj.add("hello");
obj1.add(6);
System.out.println(obj.get());
System.out.println(obj1.get());
Integer[] arr={1,3,5,7};
print(arr);
}
}
Instead of <T>
, you can actually write anything and it will work the same way. Try writing <ABC>
in place of <T>
.
This is just for convenience:
<T>
is referred to as any type<E>
as element type<N>
as number type<V>
as value<K>
as keyBut you can name it anything you want, it doesn't really matter.
Moreover, Integer
, String
, Boolean
etc are wrapper classes of Java which help in checking of types during compilation. For example, in the above code, obj
is of type String
, so you can't add any other type to it (try obj.add(1)
, it will cast an error). Similarly, obj1
is of the Integer
type, you can't add any other type to it (try obj1.add("hello")
, error will be there).
You can use:
double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;
As said above you can put it inside a ScrollView
... and if you want the Scroll View to be horizontal put it inside HorizontalScrollView
... and if you want your component (or layout) to support both put inside both of them like this:
<HorizontalScrollView>
<ScrollView>
<!-- SOME THING -->
</ScrollView>
</HorizontalScrollView>
and with setting the layout_width
and layout_height
ofcourse.
The best time for Kruskal's is O(E logV). For Prim's using fib heaps we can get O(E+V lgV). Therefore on a dense graph, Prim's is much better.
I had this problem it was wrecking my head, my routing is read from a JSON file and then fed into a directive. I could click on a ui-state but I couldn't reload the page. So a collegue of mine showed me a nice little trick for it.
This worked for me.
Hope it helps
Two things you could do I think...
Here's how you could do either:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "notepad.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
#Do Other Stuff Here....
$p.WaitForExit()
$p.ExitCode
OR
Start-Job -Name DoSomething -ScriptBlock {
& ping.exe somehost
Write-Output $LASTEXITCODE
}
#Do other stuff here
Get-Job -Name DoSomething | Wait-Job | Receive-Job
Open another url like a click in link
window.location.href = "http://example.com";
I created a custom useQuery hook
import { useLocation } from "react-router-dom";
const useQuery = (): URLSearchParams => {
return new URLSearchParams(useLocation().search)
}
export default useQuery
Use it as
const query = useQuery();
const id = query.get("id") as string
Send it as so
history.push({
pathname: "/template",
search: `id=${values.id}`,
});
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
If anyone's still looking for a solution to this, I found an answer at How to play ringtone/alarm sound in Android
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
You can change TYPE_NOTIFICATION to TYPE_ALARM, but you'll want to keep track of your Ringtone r in order to stop playing it... say, when the user clicks a button or something.
Using this answer from Asya Kamsky, I wrote a one-line bat script for Windows. The line looks like this:
mongo --quiet %1 --eval "printjson(db.%2.find().toArray())" > output.json
Then one can run it:
exportToJson.bat DbName CollectionName
In your example
return $cnf::getConfig($key)
Probably should be:
return $cnf->getConfig($key)
And make getConfig not static
The key is to keep the declarations of the variable in the header file and source file the same.
I use this trick
------sample.c------
#define sample_c
#include sample.h
(rest of sample .c)
------sample.h------
#ifdef sample_c
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN int x;
Sample.c is only compiled once and it defines the variables. Any file that includes sample.h is only given the "extern" of the variable; it does allocate space for that variable.
When you change the type of x, it will change for everybody. You won't need to remember to change it in the source file and the header file.
If you are using jQuery:
$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);
For more information: http://api.jquery.com/jQuery.inArray/
The Best Way I Can Use My Project.Use hasOwnProperty
in Tricky Way!.
var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();
arr.constructor.prototype.hasOwnProperty('push') //true (This is an Array)
obj.constructor.prototype.hasOwnProperty('push') // false (This is an Object)
How about mkString ?
theStrings.mkString(",")
A variant exists in which you can specify a prefix and suffix too.
See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.
Another approach would be using a java 8 stream.
List<Customer> customer = myObjects.stream()
.filter(Customer.class::isInstance)
.map(Customer.class::cast)
.collect(toList());
UPDATE:
After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all i
s.
First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).
Then, I changed only the following Excel options (i.e. all the other are left as is after installation):
Advanced > General > Ask to update automatic links
checked:Trust Center > Trust Center Settings... > External Content > Enable All...
(although that one that relates to Data Connections is most likely not important for the case):I prepared and placed to C:\
a workbook exactly as per @Siddharth Rout
suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).
The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:
WARNING #1
After click on Update
I expectedly got another:
WARNING #2
So, I suppose my testing environment is now pretty much similar to OP
's) So far so good, we finally go to
Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).
1. Simple Application.Workbooks.Open
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
No surprise - this produces BOTH warnings, as for manual opening above.
2. Application.DisplayAlerts = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
This code ends up with WARNING #1, and either option clicked (Update
/ Don't Update
) produces NO further warnings, i.e. Application.DisplayAlerts = False
suppresses WARNING #2.
3. Application.AskToUpdateLinks = False
Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True
Opposite to DisplayAlerts
, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False
suppresses WARNING #1.
4. Double False
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Apparently, this code ends up with suppressing BOTH WARNINGS.
5. UpdateLinks:=False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False
Finally, this 1-line solution (originally proposed by @brettdj
) works the same way as Double False: NO WARNINGS are shown!
Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:
Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)
Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm
Original answer (tested for Excel 2007 with certain options):
This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder
:
Sub WorkbookOpening2007()
Dim InputFolder As String
Dim LoopFileNameExt As String
InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!
LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""
Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True
LoopFileNameExt = Dir
Loop
End Sub
I tried it with books with unavailable external links - no warnings.
Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm
I Had the same problem, in my case, was because i was returned a digit:
def __str__(self):
return self.code
str is waiting for a str, not another.
now work good with:
def __str__(self):
return self.name
where name is a STRING.
All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time
<input type="submit" name="Submit_this" id="This" />
Additional to previous answers, if you are having problems with getting the right path(like AndroZip) you can use this:
public String getPath(Uri uri ,ContentResolver contentResolver) {
String[] projection = { MediaStore.MediaColumns.DATA};
Cursor cursor;
try{
cursor = contentResolver.query(uri, projection, null, null, null);
} catch (SecurityException e){
String path = uri.getPath();
String result = tryToGetStoragePath(path);
return result;
}
if(cursor != null) {
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
else
return uri.getPath(); // FOR OI/ASTRO/Dropbox etc
}
private String tryToGetStoragePath(String path) {
int actualPathStart = path.indexOf("//storage");
String result = path;
if(actualPathStart!= -1 && actualPathStart< path.length())
result = path.substring(actualPathStart+1 , path.length());
return result;
}
I had the same issue which after setting following path variables got vanished Note AVD Home path is different from other three.
<property name="cronExpression" value="0 0/30 * * * ?" />
You can use jQuery load method to get the contents and insert into an element.
Try this:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
e.g:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.
I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:
You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.
It is advised to load your scripts at the bottom of your <body>
block to speed up the page load, like this:
<body>
<!-- your content -->
<!-- your scripts -->
<script src=".."></script>
</body>
</html>
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8
If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:
var data = context.MyEntities.AsNoTracking().Where(...).ToList();
As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
It seems the following elegant recursive solution has not been mentioned, although it has been around for a long time. Referring to Knuth's Art of Computer Programming,
mean_1 = x_1, variance_1 = 0; //initial conditions; edge case;
//for k >= 2,
mean_k = mean_k-1 + (x_k - mean_k-1) / k;
variance_k = variance_k-1 + (x_k - mean_k-1) * (x_k - mean_k);
then for a list of n>=2
values, the estimate of the standard deviation is:
stddev = std::sqrt(variance_n / (n-1)).
Hope this helps!
Even if the equals method were comparing those two fields, then logically, it would be just the same code as you doing it manually. OK, it might be "messy", but it's still the correct answer
Yes there are ways to load classes and to "unload" them later on. The trick is to implement your own classloader which resides between high level class loader (the System class loader) and the class loaders of the app server(s), and to hope that the app server's class loaders do delegate the classloading to the upper loaders.
A class is defined by its package, its name, and the class loader it originally loaded. Program a "proxy" classloader which is the first that is loaded when starting the JVM. Workflow:
java.x
and sun.x
to the system classloader (these must not be loaded through any other classloader than the system classloader).Done right there should not come a ClassCastException or LinkageError etc.
For more informations about class loader hierarchies (yes, that's exactly what you are implementing here ;- ) look at "Server-Based Java Programming" by Ted Neward - that book helped me implementing something very similar to what you want.
1) php artisan -V
2) php artisan --version
AND its define at the composer.json file
"require": {
...........
"laravel/framework": "^6.2",
...........
},
You can make an accessor to keep the "10" as int 10 in it.
Example:
x = tonumber("10")
if you print the x variable, it will output an int 10 and not "10"
same like Python process
x = int("10")
Thanks.
I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.
For purely html @isherwood has a great solution. For jQuery, give your select drop down an ID then select it with jQuery:
<form>
<select id="myDropDown">
<option value="0">aaaa</option>
<option value="1">bbbb</option>
</select>
</form>
Then use this jQuery to clear the drop down on page load:
$(document).ready(function() {
$('#myDropDown').val('');
});
Or put it inside a function by itself:
$('#myDropDown').val('');
accomplishes what you're looking for and it is easy to put this in functions that may get called on your page if you need to blank out the drop down without reloading the page.
In SQL Server you can use YEAR
, MONTH
and DAY
instead of DATEPART
.
(at least in SQL Server 2005/2008, I'm not sure about SQL Server 2000 and older)
I prefer using these "short forms" because to me, YEAR(getdate())
is shorter to type and better to read than DATEPART(yyyy, getdate())
.
So you could also query your table like this:
select *
from your_table
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
UPDATE Nov 19 2012: There's now a new ModelMapper project too.
Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:
[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }
It will hide the time button from the date picker too.
Sorry if this answer is a little late ;)
Not sure how to explain this but I ran into something similar today.
Not being able to set .user:first-of-type{}
while .user:last-of-type{}
worked fine.
This was fixed after I wrapped them inside a div without any class or styling:
https://codepen.io/adrianTNT/pen/WgEpbE
<style>
.user{
display:block;
background-color:#FFCC00;
}
.user:first-of-type{
background-color:#FF0000;
}
</style>
<p>Not working while this P additional tag exists</p>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
<p>Working while inside a div:</p>
<div>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
</div>
Check out my post on this subject.
From angular 7 and up, since ngModel is deprecated, we can simply use the control to get the new selected value very easily in a reactive way.
Example:
<form [formGroup]="frmMyForm">
<select class="form-control" formControlName="fieldCtrl">
<option value=""></option>
<option value="val1">label val 1</option>
<option value="val2">label val 2</option>
<option value="val3">label val 3</option>
</select>
</form>
this.frmMyForm.get('fieldCtrl').valueChanges.subscribe( value => {
this.selectedValue = value;
});
By using this fully reactive way, we can upgrade older angular application version to newer ones more easily.
Remember that in git
you have:
HEAD
pointer, which tells you what commit you're working onPlease include detailed explanations about:
--hard
,--soft
and--merge
;
In increasing order of dangerous-ness:
--soft
moves HEAD
but doesn't touch the staging area or the working tree.--mixed
moves HEAD
and updates the staging area, but not the working tree.--merge
moves HEAD
, resets the staging area, and tries to move all the changes in your working tree into the new working tree.--hard
moves HEAD
and adjusts your staging area and working tree to the new HEAD
, throwing away everything.concrete use cases and workflows;
--soft
when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.--
# git reset --soft example
touch foo // Add a file, make some changes.
git add foo //
git commit -m "bad commit message" // Commit... D'oh, that was a mistake!
git reset --soft HEAD^ // Go back one commit and fix things.
git commit -m "good commit" // There, now it's right.
--
Use --mixed
(which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.
Use --merge
when you want to move to a new spot but incorporate the changes you already have into that the working tree.
Use --hard
to wipe everything out and start a fresh slate at the new commit.
Before you begin: You must know that every object in memory needs to be deallocated from memory for a new writer to happen. You can't just simply write on top of something as you do on paper. You must first erase (dealloc) it and then you can write onto it. If at the moment that the erase is done (or half done) and nothing has yet been wrote (or half wrote) and you try to read it could be very problematic! Atomic and nonatomic help you treat this problem in different ways.
First read this question and then read Bbum's answer. In addition, then read my summary.
atomic
will ALWAYS guarantee
Retain counts are the way in which memory is managed in Objective-C. When you create an object, it has a retain count of 1. When you send an object a retain message, its retain count is incremented by 1. When you send an object a release message, its retain count is decremented by 1. When you send an object an autorelease message, its retain count is decremented by 1 at some stage in the future. If an object's retain count is reduced to 0, it is deallocated.
What?! Are multithreading and thread safety different?
Yes. Multithreading means: multiple threads can read a shared piece of data at the same time and we will not crash, yet it doesn't guarantee that you aren't reading from a non-autoreleased value. With thread safety, it's guaranteed that what you read is not auto-released. The reason that we don't make everything atomic by default is, that there is a performance cost and for most things don't really need thread safety. A few parts of our code need it and for those few parts, we need to write our code in a thread-safe way using locks, mutex or synchronization.
nonatomic
Overall they are different in 2 aspects:
Crashing or not because of having or not having an autorelease pool.
Allowing to be read right in the middle of a 'not yet finished write or empty value' or not allowing and only allowing to read when the value is fully written.
This could be updated to ES6 with arrow functions and look like:
getFeed().then(data => vm.feed = data);
If you wish to use the async function
, you could also do like that:
async function myFunction(){
vm.feed = await getFeed();
// do whatever you need with vm.feed below
}
Since you're using SQL 2008:
UPDATE
table_Name
SET
column_A
= CASE
WHEN @flag = '1' THEN @new_value
ELSE 0
END + column_A,
column_B
= CASE
WHEN @flag = '0' THEN @new_value
ELSE 0
END + column_B
WHERE
ID = @ID
If you were using SQL 2012:
UPDATE
table_Name
SET
column_A = column_A + IIF(@flag = '1', @new_value, 0),
column_B = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
ID = @ID
to stop IIS manually:
you get a search result for the manager (Internet Information Services (IIS) manager, on the right side of it there are restart/stop/start buttons.
If you don't want IIS to start on startup because its really annoying..:
oh and IIS and xampp basically do the same thing just in a bit different way. ANd if you have Xampp for your projects then its not really all that nessecary to leave it on if you don't ever use it anyways.
To inspect files, run docker run -it <image> /bin/sh
to get an interactive terminal. The list of images can be obtained by docker images
. In contrary to docker exec
this solution works also in case when an image doesn't start (or quits immediately after running).
public class RuntimeVsCompileTime {
public static void main(String[] args) {
//test(new D()); COMPILETIME ERROR
/**
* Compiler knows that B is not an instance of A
*/
test(new B());
}
/**
* compiler has no hint whether the actual type is A, B or C
* C c = (C)a; will be checked during runtime
* @param a
*/
public static void test(A a) {
C c = (C)a;//RUNTIME ERROR
}
}
class A{
}
class B extends A{
}
class C extends A{
}
class D{
}
Here is an example of random 5 numbers taken from a range of 0 to 100 (both 0 and 100 included) with no duplication.
let finals = [];
const count = 5; // Considering 5 numbers
const max = 100;
for(let i = 0; i < max; i++){
const rand = Math.round(Math.random() * max);
!finals.includes(rand) && finals.push(rand)
}
finals = finals.slice(0, count)
if you run node index.js
,Node will use 3000
If you run PORT=4444 node index.js
, Node will use process.env.PORT
which equals to 4444
in this example. Run with sudo
for ports below 1024.
each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.
For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.
http:..../somelink?componentId=123
would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123
The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.
Another difference is when async
function returns just Task
instead of Task<T>
then you cannot use
GetFooAsync(...).Result;
Whereas
GetFooAsync(...).GetAwaiter().GetResult();
still works.
I know the example code in the question is for the case Task<T>
, however the question is asked generally.
In my particular case it was easier to do this:
panel.setOpaque(true);
panel.setBackground(new Color(0,0,0,0,)): // any color with alpha 0 (in this case the color is black
There are 2 major differentiation's between Vector and ArrayList.
Vector is synchronized by default, and ArrayList is not. Note : you can make ArrayList also synchronized by passing arraylist object to Collections.synchronizedList() method. Synchronized means : it can be used with multiple threads with out any side effect.
ArrayLists grow by 50% of the previous size when space is not sufficient for new element, where as Vector will grow by 100% of the previous size when there is no space for new incoming element.
Other than this, there are some practical differences between them, in terms of programming effort:
When to use which one?
Note : even though arraylist grows by 100%, you can avoid this by ensurecapacity() method to make sure that you are allocating sufficient memory at the initial stages itself.
Hope it helps.
This might be extremely convoluted and I might be missing the obvious, but without OpenPyXL filling in the column_dimensions in Iterable Worksheets (see my comment above), the only way I can see of finding the column size without loading everything is to parse the xml directly:
from xml.etree.ElementTree import iterparse
from openpyxl import load_workbook
wb=load_workbook("/path/to/workbook.xlsx", use_iterators=True)
ws=wb.worksheets[0]
xml = ws._xml_source
xml.seek(0)
for _,x in iterparse(xml):
name= x.tag.split("}")[-1]
if name=="col":
print "Column %(max)s: Width: %(width)s"%x.attrib # width = x.attrib["width"]
if name=="cols":
print "break before reading the rest of the file"
break
Java has no map literal, so there's no nice way to do exactly what you're asking.
If you need that type of syntax, consider some Groovy, which is Java-compatible and lets you do:
def map = [name:"Gromit", likes:"cheese", id:1234]
$('#hello').hide('slide', {direction: 'left'}, 1000);
requires the jQuery-ui library. See http://www.jqueryui.com
This is the simplest way I know to do this:
rm **/@(*.doc|*.pdf)
**
makes this work recursively
@(*.doc|*.pdf)
looks for a file ending in pdf OR doc
Easy to safely test by replacing rm
with ls
In case you are running a java program: - run your program in a terminal using the correct command for linux it would be 'java -jar myprogram.jar' and add -Xms256m -Xmx512m, for instance: 'java -jar myprogram.jar Xms256m -Xmx512m'
In case you are running a .sh script (linux, mac?) or a .bat script (windows) open the script and look for the java options if they are present and increase the memory.
If all of the above doesn't work, check your processes (ctrl+alt+delete on windows) (ps aux on linux/mac) and kill the processes which use allot of memory and are not necessary for your operating system! => Try to re-run your program.
Simple Solution from ascending to descending and vice versa is:
STRINGS
str = ['ravi', 'aravind', 'joker', 'poker']
asc_string = str.sort # => ["aravind", "joker", "poker", "ravi"]
asc_string.reverse # => ["ravi", "poker", "joker", "aravind"]
DIGITS
digit = [234,45,1,5,78,45,34,9]
asc_digit = digit.sort # => [1, 5, 9, 34, 45, 45, 78, 234]
asc_digit.reverse # => [234, 78, 45, 45, 34, 9, 5, 1]
You were just adding the html string. Not the element you created with a click event listener.
Try This:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<table id="addNodeTable">
<tr>
<td>
Row 1
</td>
</tr>
<tr >
<td>
Row 2
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#addNodeTable tr:last").append('<tr><td></td></tr>').find("td:last").append(test);
});
</script>
Create the column:
ALTER TABLE yourtable ADD COLUMN combined VARCHAR(50);
Update the current values:
UPDATE yourtable SET combined = CONCAT(zipcode, ' - ', city, ', ', state);
Update all future values automatically:
CREATE TRIGGER insert_trigger
BEFORE INSERT ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);
CREATE TRIGGER update_trigger
BEFORE UPDATE ON yourtable
FOR EACH ROW
SET new.combined = CONCAT(new.zipcode, ' - ', new.city, ', ', new.state);
sometimes it happens that server do made some mistakes. try log out/sign in and everything might be right then. (Yes it happened this afternoon to me.)
The best way to extract the values is to just do the following
json.loads(dataframe[column].value_counts().to_json())
This returns a dictionary which you can use like any other dict. Using values or keys.
{"apple": 5, "sausage": 2, "banana": 2, "cheese": 1}
Do not waste time implementing Sorting Algorithm by your own. Instead; use
Collections.sort() to sort data.