The simplest that helped me:
rm -rf _dir_in_question_
svn up
If you have changes in the problematic dir, then this is not a good solution for you.
First of all stop the server and image the disc. There's no point only having one shot at this. Then take a look here.
If your MySQL process is running, stop it. On Debian:
sudo service mysql stop
Go to your data folder. On Debian:
cd /var/lib/mysql/$DATABASE_NAME
Try running:
myisamchk -r $TABLE_NAME
If that doesn't work, you can try:
myisamchk -r -v -f $TABLE_NAME
You can start your MySQL server again. On Debian:
sudo service mysql start
Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2
:
1,000.46
But in Germany you would change comma and point:
1.000,46
This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure
of the Zend Framework for this task. This component will parse the string to a float by the users language.
I believe this problem is coming from the .svn file. It's either incorrect in the old parent, the new parent or the old one. I would try reverting back to your starting point. Use an export to get a clean copy of the folder. Move the clean copy to the new location, and use an add and delete to do the move. That's manually doing what SVN does, but it might work.
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if (b1 is null)
return b2 is null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return obj is BOX b2? (length == b2.length &&
breadth == b2.breadth &&
height == b2.height): false;
}
public override int GetHashCode()
{
return (height,length,breadth).GetHashCode();
}
}
Add /usr/local/bin
to your PATH
environment variable, earlier in the list than /usr/bin
.
Generally this is done in your shell's rc file, e.g. for bash, you'd put this in .bashrc
:
export PATH="/usr/local/bin:$PATH"
This will cause your shell to look first for a python
in /usr/local/bin
, before it goes with the one in /usr/bin
.
(Of course, this means you also need to have /usr/local/bin/python
point to python2.7
- if it doesn't already, you'll need to symlink it.)
I had the same problem while creating AVD with 4.2.2 images, I resolved it by doing the following :
Check if there exist a "default" folder in adt-bundle-windows-x86_64-20131030\sdk\system-images\android-17.
If it exists then move the contents(downloaded system images) of the "default" folder to adt-bundle-windows-x86_64-20131030\sdk\system-images\android-17.
Hope this helps.
This will surely help on bootstrap timepicker
format :"DD:MM:YYYY HH:mm"
One might consider adding this line to ~/.bash_profile
(or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.
alias utc='date -u && date -u +%s'
You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:
sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
open new terminal and validate environment is clean from old RVM settings (should be no output):
env | grep rvm
if there was output, try to open new terminal, if it does not help then restart your computer.
\curl -L https://get.rvm.io |
bash -s stable --ruby --autolibs=enable --auto-dotfiles
If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.
Watch out!! If there's spaces they will not be considered by the LEN method in T-SQL. Don't let this trick you and use
select max(datalength(Desc)) from table_name
Seem this bug is not fixed yet [1]. Some people get worked, some people not. I also get not worked.
I tried clear cache with command: npm cache verify
then run install command again. I got worked.
One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.
PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.
pip install py-mini-racer
from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
return a+c+b;
}
""")
ctx.call("escramble_758")
And yes, you have to replace document.write
with return
as others suggested
If you want to just accept defaults you can use:
\n | ./shell_being_run
Check the installed version(s) of pg_dump:
find / -name pg_dump -type f 2>/dev/null
My output was:
/usr/pgsql-9.3/bin/pg_dump
/usr/bin/pg_dump
There are two versions installed. To update pg_dump with the newer version:
sudo ln -s /usr/pgsql-9.3/bin/pg_dump /usr/bin/pg_dump --force
This will create the symlink to the newer version.
Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.
public function upload_file() {
***// Upload folder location***
$config['upload_path'] = './public/upload/';
***// Allowed file type***
$config['allowed_types'] = 'jpg|jpeg|png|pdf';
***// Max size, i will set 2MB***
$config['max_size'] = '2024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
***// load upload library***
$this->load->library('upload', $config);
***// do_upload is the method, to send the particular image and file on that
// particular
// location that is detail in $config['upload_path'].
// In bracks will set name upload, here you need to set input name attribute
// value.***
if($this->upload->do_upload('upload')) {
$data = $this->upload->data();
$post['upload'] = $data['file_name'];
} else {
$error = array('error' => $this->upload->display_errors());
}
}
Full process (Unix svn package):
Check files are not in SVN:
> svn st -u folder
? folder
Add all (including ignored files):
> svn add folder
A folder
A folder/file1.txt
A folder/folder2
A folder/folder2/file2.txt
A folder/folderToIgnore
A folder/folderToIgnore/fileToIgnore1.txt
A fileToIgnore2.txt
Remove "Add" Flag to All * Ignore * files:
> cd folder
> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'
> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'
Edit svn ignore on folder
svn propedit svn:ignore .
Add two singles lines with just the following:
folderToIgnore
fileToIgnore2.txt
Check which files will be upload and commit:
> cd ..
> svn st -u
A folder
A folder/file1.txt
A folder/folder2
A folder/folder2/file2.txt
> svn ci -m "Commit message here"
You can use Apache Tika for that:
String parse(File xlsxFile) {
return new Tika().parseToString(xlsxFile);
}
Tika uses Apache POI for parsing XLSX files.
Here are some usage examples for Tiki.
Alternatively, if you want to handle each cell of the spreadsheet individually, here's one way to do this with POI:
void parse(File xlsx) {
try (XSSFWorkbook workbook = new XSSFWorkbook(xlsx)) {
// Handle each cell in each sheet
workbook.forEach(sheet -> sheet.forEach(row -> row.forEach(this::handle)));
}
catch (InvalidFormatException | IOException e) {
System.out.println("Can't parse file " + xlsx);
}
}
void handle(Cell cell) {
final String cellContent;
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellContent = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
cellContent = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
cellContent = String.valueOf(cell.getBooleanCellValue());
break;
default:
cellContent = "Don't know how to handle cell " + cell;
}
System.out.println(cellContent);
}
Microsoft Visio 2013 Standard Edition does not provide UML shapes, you have to upgrade to Microsoft Visio 2013 Professional.
document.activeElement
is now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. You can fall back to querySelector
(if that is supported). It's also worth mentioning that document.activeElement
will return document.body
if no element is focused — even if the browser window doesn't have focus.
The following code will work around this issue and fall back to querySelector
giving a little better support.
var focused = document.activeElement;
if (!focused || focused == document.body)
focused = null;
else if (document.querySelector)
focused = document.querySelector(":focus");
An addition thing to note is the performance difference between these two methods. Querying the document with selectors will always be much slower than accessing the activeElement
property. See this jsperf.com test.
Some time ago I used DIA - free and platform-independent. It was ok. Now I use Enterprise Architect but it's not free.
You need to declare the type of the protocol as AnyObject
.
protocol ProtocolNameDelegate: AnyObject {
// Protocol stuff goes here
}
class SomeClass {
weak var delegate: ProtocolNameDelegate?
}
Using AnyObject
you say that only classes can conform to this protocol, whereas structs or enums can't.
From the javadoc of java.rmi.registry.Registry
Therefore, a registry's remote object implementation is typically exported with a well-known address, such as with a well-known
ObjID
and TCP port number (default is1099
).
See more in the javadoc of java.rmi.registry.LocateRegistry
.
If you are executing a stored procedure from Informix using EntityFrameworkCore you need to include the command EXECUTE PROCEDURE
var spresult = _informixContext.procdata.FromSql("EXECUTE PROCEDURE dummyproc ({0},{1},{2})", parameters: new[] { p0, p1,p2 }).ToList();
The goal is to make the <body> element take up the available height of the screen.
If you don't expect your content to take up more than the height of the screen, or you plan to make an inner scrollable element, set
body {
height: 100vh;
}
otherwise, you want <body> to become scrollable when there is more content than the screen can hold, so set
body {
min-height: 100vh;
}
this alone achieves the goal, albeit with a possible, and probably desirable, refinement.
Removing the margin of <body>.
body {
margin: 0;
}
there are two main reasons for doing so.
P.S. if you want the background to be a radial gradient with its center in the center of the screen and not in the bottom right corner as with your example, consider using something like
body {
min-height: 100vh;
margin: 0;
background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(0,0,0,1) 100%);
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title>test</title>
</head>
<body>
</body>
</html>
_x000D_
The easiest solution I found is to just rename the php folder version as such:
That way only two of them will be read by MAMP. Done!
No, only use semicolons when they're required.
If you don't want to use str.lower()
, you can use a regular expression:
import re
if re.search('mandy', 'Mandy Pande', re.IGNORECASE):
# Is True
Provide a portable and generic getdelim
function, test passed via msvc, clang, gcc.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
ssize_t
portabl_getdelim(char ** restrict linep,
size_t * restrict linecapp,
int delimiter,
FILE * restrict stream) {
if (0 == *linep) {
*linecapp = 8;
*linep = malloc(*linecapp);
if (0 == *linep) {
return EOF;
}
}
ssize_t linelen = 0;
int c = 0;
char *p = *linep;
while (EOF != (c = fgetc(stream))) {
if (linelen == (ssize_t) *linecapp - 1) {
*linecapp <<= 1;
char *p1 = realloc(*linep, *linecapp);
if (0 == *p1) {
return EOF;
}
p = p1 + linelen;
}
*p++ = c;
linelen++;
if (delimiter == c) {
*p = 0;
return linelen;
}
}
return EOF == c ? EOF : linelen;
}
int
main(int argc, char **argv) {
const char *filename = "/a/b/c.c";
FILE *file = fopen(filename, "r");
if (!file) {
perror(filename);
return 1;
}
char *line = 0;
size_t linecap = 0;
ssize_t linelen;
while (0 < (linelen = portabl_getdelim(&line, &linecap, '\n', file))) {
fwrite(line, linelen, 1, stdout);
}
if (line) {
free(line);
}
fclose(file);
return 0;
}
Use the method that accepts a Comparator
when you want to sort in something other than natural order.
A lot of things can configured in applicationproperties. Unfortunately this feature only in Version 1.3, but you can add in a Config-Class
@Autowired(required = true)
public void configureJackson(ObjectMapper jackson2ObjectMapper) {
jackson2ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
[UPDATE: You must work on the ObjectMapper because the build()
-method is called before the config is runs.]
I use this one:
find . -name ".git" -type d | sed 's/\/.git//' | xargs -P10 -I{} git -C {} pull
Universal: Updates all git repositories that are below current directory.
In 2.2.0+, when using v-for with a component, a key is now required.
<div v-for="item in items" :key="item.id">
The following can be used to test for the existence of a file, and then to delete it.
Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
I used the following steps to create a new hot fix branch from a Tag.
Syntax
git checkout -b <New Branch Name> <TAG Name>
Steps to do it.
git push -u origin NewBranchName
I hope this would help.
Try running the entire script through jslint. This may help point you at the cause of the error.
Edit Ok, it's not quite the syntax of the script that's the problem. At least not in a way that jslint can detect.
Having played with your live code at http://ft2.hostei.com/ft.v1/, it looks like there are syntax errors in the generated code that your script puts into an onclick
attribute in the DOM. Most browsers don't do a very good job of reporting errors in JavaScript run via such things (what is the file and line number of a piece of script in the onclick
attribute of a dynamically inserted element?). This is probably why you get a confusing error message in Chrome. The FireFox error message is different, and also doesn't have a useful line number, although FireBug does show the code which causes the problem.
This snippet of code is taken from your edit
function which is in the inline script block of your HTML:
var sub = document.getElementById('submit');
...
sub.setAttribute("onclick", "save(\""+file+"\", document.getElementById('name').value, document.getElementById('text').value");
Note that this sets the onclick
attribute of an element to invalid JavaScript code:
<input type="submit" id="submit" onclick="save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value">
The JS is:
save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value
Note the missing close paren to finish the call to save
.
As an aside, inserting onclick
attributes is not a very modern or clean way of adding event handlers in JavaScript. Why are you not using the DOM's addEventListener
to simply hook up a function to the element? If you were using something like jQuery, this would be simpler still.
By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.
From a broken link:
Within an Aggregate there is an Aggregate Root. The Aggregate Root is the parent Entity to all other Entities and Value Objects within the Aggregate.
A Repository operates upon an Aggregate Root.
More info can also be found here.
You could detect position of the mouse pointer and then move the web page (with body position relative) so they hover over what you want them to click.
For an example you can paste this code on the current page in your browser console (and refresh afterwards)
var upvote_position = $('#answer-12878316').position();
$('body').mousemove(function (event) {
$(this).css({
position: 'relative',
left: (event.pageX - upvote_position.left - 22) + 'px',
top: (event.pageY - upvote_position.top - 35) + 'px'
});
});
Adding to a well-populated page:
I had this come up when I tried to move the eclipse installation to a different location on my drive. I tried grepping for the old directory path in the package, thinking perhaps I could fix it with sed, but the path was written in multiple formats and even found in binary files. I gave up, made a fresh install, and re-installed my plugins.
(Here's a question about moving an eclipse installation, but it didn't give me enough to make it work.)
SELECT *
FROM (
SELECT *
FROM users
WHERE 1
ORDER BY
rand()
LIMIT 20
) q
ORDER BY
name
bundler clean
Stopped the message showing for me, as a last step after I tried all of the above.
One very quick way around this is, when you're viewing the "Your connection is not private" screen:
type badidea
type thisisunsafe
(credit to The Java Guy for finding the new passphrase)
That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.
This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.
Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea
ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.
Edit: as of 30 Jan 2018 this passphrase appears to no longer work.
If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:
How to create a self-signed certificate with openssl?
Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.
Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea
passphrase no longer works.
Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).
The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).
The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:
Wikipedia: List of Internet Top Level Domains: Special Use Domains
These top-level domains seem to be exempt from the new https-only restrictions:
See the answer and link from codinghands to the original question for more information:
I'd suggest <a href='page1.jsp'>Refresh</a>
.
"pop"ing the first element of an Array is called "shift" ("unshift" being the operation of adding one element in front of the array).
It depends on of Maven version. When you will install newer version of Maven, this error would not appear. You may also add another directory with tools.jar file lib/tools.jar - it also solve this problem.
Apache on Ubuntu, using the Apache plugin:
sudo certbot certonly --cert-name example.com -d m.example.com,www.m.example.com
The above command is vividly explained in the Certbot user guide on changing a certificate's domain names. Note that the command for changing a certificate's domain names applies to adding new domain names as well.
Edit
If running the above command gives you the error message
Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
To check whether postfix is running or not
sudo postfix status
If it is not running, start it.
sudo postfix start
Then telnet to localhost port 25 to test the email id
ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix
Hi,
Are you there?
regards,
Admin
.
Do not forget the . at the end, which indicates end of line
Today things have changed a little.
Now we avoid use ProgressDialog to show spinning progress:
If you want to put in your app a spinning progress you should use an Activity indicators:
http://developer.android.com/design/building-blocks/progress.html#activity
If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):
bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
x, y = self.label.get_position()
self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))
You can set the label position independently of the ticks by using:
ax.xaxis.set_label_coords(x0, y0)
that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.
The best solution for this if you are using bootstrap so just do one thing remove @media print {} all code inside this. and enable background graphics from more settings while taking print preview.
This is not exactly beautiful but without extra software
class timeit():
from datetime import datetime
def __enter__(self):
self.tic = self.datetime.now()
def __exit__(self, *args, **kwargs):
print('runtime: {}'.format(self.datetime.now() - self.tic))
Then you can run it like:
with timeit():
# your code, e.g.,
print(sum(range(int(1e7))))
% 49999995000000
% runtime: 0:00:00.338492
You just have to push the tag after you run the git tag 2.0
command.
So just do git push --tags
now.
Use Html Encrypter The part of the Head which has
<link rel="stylesheet" href="styles/css.css" type="text/css" media="screen" />
<script type="text/javascript" src="script/js.js" language="javascript"></script>
copy and paste it to HTML Encrypter and the Result will goes like this
and paste it the location where you cut the above sample
<Script Language='Javascript'>
<!-- HTML Encryption provided by iWEBTOOL.com -->
<!--
document.write(unescape('%3C%6C%69%6E%6B%20%72%65%6C%3D%22%73%74%79%6C%65%73%68%65%65%74%22%20%68%72%65%66%3D%22%73%74%79%6C%65%73%2F%63%73%73%2E%63%73%73%22%20%74%79%70%65%3D%22%74%65%78%74%2F%63%73%73%22%20%6D%65%64%69%61%3D%22%73%63%72%65%65%6E%22%20%2F%3E%0A%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%20%73%72%63%3D%22%73%63%72%69%70%74%2F%6A%73%2E%6A%73%22%20%6C%61%6E%67%75%61%67%65%3D%22%6A%61%76%61%73%63%72%69%70%74%22%3E%3C%2F%73%63%72%69%70%74%3E%0A'));
//-->
HTML ENCRYPTER Note: if you have a java script in your page try to export to .js file and make it like as the example above.
And Also this Encrypter is not always working in some code that will make ur website messed up... Select the best part you want to hide like for example in <form> </form>
This can be reverse by advance user but not all noob like me knows it.
Hope this will help
You can use tf.convert_to_tensor()
:
import tensorflow as tf
import numpy as np
data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)
data_tf = tf.convert_to_tensor(data_np, np.float32)
sess = tf.InteractiveSession()
print(data_tf.eval())
sess.close()
Here's a link to the documentation for this method:
https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor
Referred main
as the main function and exit_gracefully
as the CTRL + c handler
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
exit_gracefully()
Try killing the pythonw process from the Task Manager (if Windows) if nothing else works.
Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim
EXEC xp_cmdshell 'sqlcmd -S ' + @DBServerName + ' -d ' + @DBName + ' -i ' + @FilePathName
If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true
in your tsconfig.json
file.
This bash script does ssh into a target remote machine, and run some command in the remote machine, do not forget to install expect before running it (on mac brew install expect
)
#!/usr/bin/expect
set username "enterusenamehere"
set password "enterpasswordhere"
set hosts "enteripaddressofhosthere"
spawn ssh $username@$hosts
expect "$username@$hosts's password:"
send -- "$password\n"
expect "$"
send -- "somecommand on target remote machine here\n"
sleep 5
expect "$"
send -- "exit\n"
If your template.html
file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.
However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.
Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML
prop.
var __html = require('./template.html');
var template = { __html: __html };
React.module.exports = React.createClass({
render: function() {
return(
<div dangerouslySetInnerHTML={template} />
);
}
});
This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.
The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.
If your template.html
file looked something like this
<div class='foo'>
<h1>Hello</h1>
<p>Some paragraph text</p>
<button>Click</button>
</div>
Then you could convert it instead to a JSX file that looked like this.
module.exports = function(props) {
return (
<div className='foo'>
<h1>Hello</h1>
<p>Some paragraph text</p>
<button>Click</button>
</div>
);
};
Then you can require and use it without needing stringify.
var Template = require('./template');
module.exports = React.createClass({
render: function() {
var bar = 'baz';
return(
<Template foo={bar}/>
);
}
});
It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.
Use WatiN if you need to see the impact of JS on the page [and you're prepared to start a browser]
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
Tried and always successful
When you have 2 formats in the same column: A - one can be sorted as oldest to newest (real date such as 17/4/2017) B - the other as A to Z ( not real date such as 15/3/2018 00.00.00 )
Select only B cells and replace " 00.00.00" with "blank", so it now appears as "15/3/2018"
Select only B cells and select -- data -- text to column --Delimited --Next -- unselect all -- Next -- Date DMY -- finish
Select the whole cells A and B and sort as you like oldest to newest
you can combine them using LINQ:
list = list1.Concat(list2).Concat(list3).ToList();
the more traditional approach of using List.AddRange()
might be more efficient though.
Realizing the revision of the code I found the cause of why the reading method did not work for me. The problem was that one of the dependencies that my project used jersey 1.x. Update the version, adjust the client and it works.
I use the following maven dependency:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>
Regards
Carlos Cepeda
For latest 2.1 Graph API, an example to get likes for imdb.com will be
Using this to get the id https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%253A%252F%252Fwww.imdb.com%3Ffields%3Dlikes&version=v2.1
and then get the likes
https://developers.facebook.com/tools/explorer/?method=GET&path=414652589771%2Flikes&version=v2.1
URL /?id={url}
Represents an external URL as it relates to the Facebook social graph - shares and comments from the URL on Facebook, and any Open Graph objects associated with the URL.
Reference http://harshtechtalk.com/how-get-likes-count-posts-comments-facebook-graph-api/
If these don't depend on the class or instance, then just make them a function.
As this would seem like the obvious solution. Unless of course you think it's going to need to be overwritten, subclassed, etc. If so, then the previous answers are the best bet. Fingers crossed I won't get marked down for merely offering an alternative solution that may or may not fit someone’s needs ;).
As the correct answer will depend on the use case of the code in question ;)
I want columns One and Two to shrink/grow to fit rather than being fixed.
Have you tried: flex-basis: auto
or this:
flex: 1 1 auto
, which is short for:
flex-grow: 1
(grow proportionally)flex-shrink: 1
(shrink proportionally)flex-basis: auto
(initial size based on content size)or this:
main > section:first-child {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:nth-child(2) {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:last-child {
flex: 20 1 auto;
display: flex;
flex-direction: column;
}
Related:
Passing data between FirstViewController to SecondViewController as below
For example:
FirstViewController String value as
StrFirstValue = @"first";
So we can pass this value in the second class using the below steps:
We need to create a string object in the SecondViewController.h file
NSString *strValue;
Need to declare a property as the below declaration in the .h file
@property (strong, nonatomic) NSString *strSecondValue;
Need synthesize that value in the FirstViewController.m file below the header declaration
@synthesize strValue;
And in file FirstViewController.h:
@property (strong, nonatomic) NSString *strValue;
In FirstViewController, from which method we navigate to the second view, please write the below code in that method.
SecondViewController *secondView= [[SecondViewController alloc]
initWithNibName:@"SecondViewController " bundle:[NSBundle MainBundle]];
[secondView setStrSecondValue:StrFirstValue];
[self.navigationController pushViewController:secondView animated:YES ];
Generally speaking, 5xx response codes indicate non-programmatic failures, such as a database connection failure, or some other system/library dependency failure. In many cases, it is expected that the client can re-submit the same request in the future and expect it to be successful.
Yes, some web-frameworks will respond with 5xx codes, but those are typically the result of defects in the code and the framework is too abstract to know what happened, so it defaults to this type of response; that example, however, doesn't mean that we should be in the habit of returning 5xx codes as the result of programmatic behavior that is unrelated to out of process systems. There are many, well defined response codes that are more suitable than the 5xx codes. Being unable to parse/validate a given input is not a 5xx response because the code can accommodate a more suitable response that won't leave the client thinking that they can resubmit the same request, when in fact, they can not.
To be clear, if the error encountered by the server was due to CLIENT input, then this is clearly a CLIENT error and should be handled with a 4xx response code. The expectation is that the client will correct the error in their request and resubmit.
It is completely acceptable, however, to catch any out of process errors and interpret them as a 5xx response, but be aware that you should also include further information in the response to indicate exactly what failed; and even better if you can include SLA times to address.
I don't think it's a good practice to interpret, "an unexpected error" as a 5xx error because bugs happen.
It is a common alert monitor to begin alerting on 5xx types of errors because these typically indicate failed systems, rather than failed code. So, code accordingly!
This solution is written in PHP, but it should be easily adapted to other languages.
The original .htaccess
regex can cause problems with files like json-1.3.js
. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)
First, we use the following rewrite rule in .htaccess:
RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
Now, we write the following PHP function:
/**
* Given a file, i.e. /css/base.css, replaces it with a string containing the
* file's mtime, i.e. /css/base.1221534296.css.
*
* @param $file The file to be loaded. Must be an absolute path (i.e.
* starting with slash).
*/
function auto_version($file)
{
if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
return $file;
$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}
Now, wherever you include your CSS, change it from this:
<link rel="stylesheet" href="/css/base.css" type="text/css" />
To this:
<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />
This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.
This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.
Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.
Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.
Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.
Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?
What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.
An Angular approach to the methods previously described is to import DOCUMENT
from @angular/common
(or @angular/platform-browser
in Angular
< 4) and use
document.location.href = 'https://stackoverflow.com';
inside a function.
some-page.component.ts
import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: Document) { }
goToUrl(): void {
this.document.location.href = 'https://stackoverflow.com';
}
some-page.component.html
<button type="button" (click)="goToUrl()">Click me!</button>
Check out the plateformBrowser repo for more info.
In order to best standardise your @font-face embedded fonts across browsers try including the below inside your @font-face declaration or on your body font styling:
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
At present there looks to be no universal fix across all platforms and browser builds. As stated frequently all browsers/OS have different text rendering engines.
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
Since the static method 'GetAccessControl' seems to be missing from the present version of .Net core/Standard I had to modify @Bryce Wagner's answer (I went ahead and used more modern syntax):
public static class PermissionHelper
{
public static bool? CurrentUserHasWritePermission(string filePath)
=> new WindowsPrincipal(WindowsIdentity.GetCurrent())
.SelectWritePermissions(filePath)
.FirstOrDefault();
private static IEnumerable<bool?> SelectWritePermissions(this WindowsPrincipal user, string filePath)
=> from rule in filePath
.GetFileSystemSecurity()
.GetAccessRules(true, true, typeof(NTAccount))
.Cast<FileSystemAccessRule>()
let right = user.HasRightSafe(rule)
where right.HasValue
// Deny takes precedence over allow
orderby right.Value == false descending
select right;
private static bool? HasRightSafe(this WindowsPrincipal user, FileSystemAccessRule rule)
{
try
{
return user.HasRight(rule);
}
catch
{
return null;
}
}
private static bool? HasRight(this WindowsPrincipal user,FileSystemAccessRule rule )
=> rule switch
{
{ FileSystemRights: FileSystemRights fileSystemRights } when (fileSystemRights &
(FileSystemRights.WriteData | FileSystemRights.Write)) == 0 => null,
{ IdentityReference: { Value: string value } } when value.StartsWith("S-1-") &&
!user.IsInRole(new SecurityIdentifier(rule.IdentityReference.Value)) => null,
{ IdentityReference: { Value: string value } } when value.StartsWith("S-1-") == false &&
!user.IsInRole(rule.IdentityReference.Value) => null,
{ AccessControlType: AccessControlType.Deny } => false,
{ AccessControlType: AccessControlType.Allow } => true,
_ => null
};
private static FileSystemSecurity GetFileSystemSecurity(this string filePath)
=> new FileInfo(filePath) switch
{
{ Exists: true } fileInfo => fileInfo.GetAccessControl(),
{ Exists: false } fileInfo => (FileSystemSecurity)fileInfo.Directory.GetAccessControl(),
_ => throw new Exception($"Check the file path, {filePath}: something's wrong with it.")
};
}
I know I'm joining late to the discussion, but I think this can be useful to others.
I wanted to avoid deprecated stuff and after a lot of fiddling I found a simple way to send to servers requiring Implicit SSL: use NuGet and add the MailKit package to the project. (I used VS2017 targetting .NET 4.6.2 but it should work on lower .NET versions...)
Then you'll only need to do something like this:
using MailKit.Net.Smtp;
using MimeKit;
var client = new SmtpClient();
client.Connect("server.name", 465, true);
// Note: since we don't have an OAuth2 token, disable the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove ("XOAUTH2");
if (needsUserAndPwd)
{
// Note: only needed if the SMTP server requires authentication
client.Authenticate (user, pwd);
}
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress("[email protected]"));
msg.To .Add(new MailboxAddress("[email protected]"));
msg.Subject = "This is a test subject";
msg.Body = new TextPart("plain") {
Text = "This is a sample message body"
};
client.Send(msg);
client.Disconnect(true);
Of course you can also tweak it to use Explicit SSL or no transport security at all.
You don't need to apply to_date()
to sysdate
. It is already there:
select 1
from dual
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');
If you are concerned about the time component on the date, then use trunc()
:
select 1
from dual
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
TO_DATE('20/06/2014', 'DD/MM/YYYY');
No, you don't it's enough to do something like this:
<ul class="clearfix">
<li>one</li>
<li>two></li>
</ul>
And the following CSS:
ul li {float: left;}
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
}
I hope following code will give you more information.
select * from information_schema.triggers where
information_schema.triggers.trigger_schema like '%your_db_name%'
This will give you total 22 Columns in MySQL version: 5.5.27 and Above
TRIGGER_CATALOG
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED
SQL_MODE
DEFINER
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION
Dinqyjs has a linq-like syntax and provides polyfills for functions like map and indexOf, and has been designed specifically for working with arrays in Javascript.
Just had the same issue, for those having the same one it may be that you put the library on the modulepath rather than the classpath while adding it to your project
In SSMS, "Query" menu item... "Results to"... "Results to File"
Shortcut = CTRL+shift+F
You can set it globally too
"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down
Edit: after comment
In SSMS, "Query" menu item... "SQLCMD" mode
This allows you to run "command line" like actions.
A quick test in my SSMS 2008
:OUT c:\foo.txt
SELECT * FROM sys.objects
Edit, Sep 2012
:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects
Replace the comma with an empty string:
var x = parseFloat("2,299.00".replace(",",""))_x000D_
alert(x);
_x000D_
Installing m2eclipse
All downloads are provided under the terms and conditions of the Eclipse Foundation Software User Agreement unless otherwise specified.
m2e is tested against Eclipse 4.2 (Juno) and 4.3 (Kepler).
See http://wiki.eclipse.org/M2E_updatesite_and_gittags for detailed information about available builds and m2e build repository layout.
m2e 1.3 and earlier version have been removed from the main m2e update site. These old releases are still available and can be installed from repositories documented in http://wiki.eclipse.org/M2E_updatesite_and_gittags
Please note that links below point at Eclipse p2 repositories; you must access them from Eclipse (see how). Update Sites Latest m2e release (recommended) http://download.eclipse.org/technology/m2e/releases m2e milestone builds towards version 1.5 http://download.eclipse.org/technology/m2e/milestones/1.5 Latest m2e 1.5 SNAPSHOT build (not tested, not hosted at eclipse.org) http://repository.takari.io:8081/nexus/content/sites/m2e.extras/m2e/1.5.0/N/LATEST/
-webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */ animation-fill-mode: forwards;
Browser Support
Usage:-
.fadeIn {
animation-name: fadeIn;
-webkit-animation-name: fadeIn;
animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;
animation-timing-function: ease;
-webkit-animation-timing-function: ease;
animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
Express has removed this functionality and now recommends you use the basic-auth library.
Here's an example of how to use:
var http = require('http')
var auth = require('basic-auth')
// Create server
var server = http.createServer(function (req, res) {
var credentials = auth(req)
if (!credentials || credentials.name !== 'aladdin' || credentials.pass !== 'opensesame') {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="example"')
res.end('Access denied')
} else {
res.end('Access granted')
}
})
// Listen
server.listen(3000)
To send a request to this route you need to include an Authorization header formatted for basic auth.
Sending a curl request first you must take the base64 encoding of name:pass
or in this case aladdin:opensesame
which is equal to YWxhZGRpbjpvcGVuc2VzYW1l
Your curl request will then look like:
curl -H "Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l" http://localhost:3000/
There are already answers which give how to change Inner HTML of element.
But I would suggest, you should use some animation like Fade Out/ Fade In to change HTML which gives good effect of changed HTML rather instantly changing inner HTML.
$('#regTitle').fadeOut(500, function() {
$(this).html('Hello World!').fadeIn(500);
});
If you have many functions which need this, then you can call common function which changes inner Html.
function changeInnerHtml(elementPath, newText){
$(elementPath).fadeOut(500, function() {
$(this).html(newText).fadeIn(500);
});
}
document.location
is an object, not a string. It returns (by default) the full path, but it actually holds more info than that.
Shortcut for solution: document.location.toString().substring(2,3);
Or use document.location.href
or window.location.href
No, there is no better way; yours is canonical.
For those still having this issue, my issue was resolved in the AndroidManifest.xml file. Where it says <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">
, you need to remove NoActionBar
, making it <activity android:name=".MainActivity" android:theme="@style/AppTheme">
, because with NoActionBar set the app doesnt know whether or not it wants an action bar when you call one up inside of MainActivity.java
I threw CMS's excellent answer into a quick jQuery extension:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window);
It expects an array of objects which contain "text" and "value" keys. So usage is as follows:
var options = [
{text: "one", value: 1},
{text: "two", value: 2}
];
$("#foo").replaceOptions(options);
Docker for Mac (Beta)
~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/log/d??ocker.log
I think, from your description, the following would suffice:
DELETE FROM guide_category
WHERE id_guide NOT IN (SELECT id_guide FROM guide)
I assume, that there are no referential integrity constraints on the tables involved, are there?
I was able to solve this in Eclipse Helios by right-clicking on the project, picking "Java Build Path", "Add Library...", "JRE System Library", "Workspace default JRE (jdk1.6.0_17)" and finally "Finish".
An alternative, you can also use fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
I have a completely different take on this. I use MailHide for this.
MailHide is a system from Google whereby the user needs to complete a reCAPTCHA test to then reveal the email to them.
document.getElementById('myframe1').contentWindow.document.getElementById('x')
contentWindow
is supported by all browsers including the older versions of IE.
Note that if the iframe
's src
is from another domain, you won't be able to access its content due to the Same Origin Policy.
My example to your questions:
def get_sublist(row, col1, col2):
return mylist[row[col1]:row[col2]+1]
df.apply(get_sublist, axis=1, col1='col_1', col2='col_2')
<div id="hassaan">
<div class="label">My Label:</div>
<div class="text">My text</div>
</div>
CSS:
#hassaan{ margin:auto; width:960px;}
#hassaan:nth-child(n){ clear:both;}
.label, .text{ width:480px; float:left;}
It is working for me.
etMsgDescription.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maximum_character)});
etMsgDescription.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tvCharacterLimite.setText(" "+String.valueOf(maximum_character - etMsgDescription.getText().length()));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
If you want to save any string to mysql database do this:->
Your database field structure i phpmyadmin [ or any other control panel] should set to utf8-gerneral-ci
2) you should change your string [Ex. textbox1.text] to byte, therefor
2-1) define byte[] st2;
2-2) convert your string [textbox1.text] to unicode [ mmultibyte string] by :
byte[] st2 = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);
3) execute this sql command before any query:
string mysql_query2 = "SET NAMES 'utf8'";
cmd.CommandText = mysql_query2;
cmd.ExecuteNonQuery();
3-2) now you should insert this value in to for example name field by :
cmd.CommandText = "INSERT INTO customer (`name`) values (@name)";
4) the main job that many solution didn't attention to it is the below line: you should use addwithvalue instead of add in command parameter like below:
cmd.Parameters.AddWithValue("@name",ut);
++++++++++++++++++++++++++++++++++ enjoy real data in your database server instead of ????
It looks like you just want:
eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
? (DateTime?) null
: DateTime.Parse(dateTimeEnd);
Note that this will throw an exception if dateTimeEnd
isn't a valid date.
An alternative would be:
DateTime validValue;
eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
? validValue
: (DateTime?) null;
That will now set the result to null
if dateTimeEnd
isn't valid. Note that TryParse
handles null
as an input with no problems.
Check this example how we could implement this.
public class HoverableDropdownTest {
private WebDriver driver;
private Actions action;
//Edit: there may have been a typo in the '- >' expression (I don't really want to add this comment but SO insist on ">6 chars edit"...
Consumer < By > hover = (By by) -> {
action.moveToElement(driver.findElement(by))
.perform();
};
@Test
public void hoverTest() {
driver.get("https://www.bootply.com/render/6FC76YQ4Nh");
hover.accept(By.linkText("Dropdown"));
hover.accept(By.linkText("Dropdown Link 5"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4"));
hover.accept(By.linkText("Dropdown Submenu Link 5.4.1"));
}
@BeforeTest
public void setupDriver() {
driver = new FirefoxDriver();
action = new Actions(driver);
}
@AfterTest
public void teardownDriver() {
driver.quit();
}
}
For detailed answer, check here - http://www.testautomationguru.com/selenium-webdriver-automating-hoverable-multilevel-dropdowns/
If you want to round the decimal, look at Math.Round()
For the most common purpose, you should use bindValue
.
bindParam
has two tricky or unexpected behaviors:
bindParam(':foo', 4, PDO::PARAM_INT)
does not work, as it requires passing a variable (as reference).bindParam(':foo', $value, PDO::PARAM_INT)
will change $value
to string after running execute()
. This, of course, can lead to subtle bugs that might be difficult to catch.Source: http://php.net/manual/en/pdostatement.bindparam.php#94711
Everybody has a really nice and verbose answer with examples and I really appreciate it. I just wanted to give a short few lines answer for people who are still not quite clear conceptually:
If you create your own iterator, it is a little bit involved - you have to create a class and at least implement the iter and the next methods. But what if you don't want to go through this hassle and want to quickly create an iterator. Fortunately, Python provides a short-cut way to defining an iterator. All you need to do is define a function with at least 1 call to yield and now when you call that function it will return "something" which will act like an iterator (you can call next method and use it in a for loop). This something has a name in Python called Generator
Hope that clarifies a bit.
Even though it's stated in many of the other answers here, the component should either:
implement shouldComponentUpdate
to render only when state or properties change
switch to extending a PureComponent, which already implements a shouldComponentUpdate
method internally for shallow comparisons.
Here's an example that uses shouldComponentUpdate
, which works only for this simple use case and demonstration purposes. When this is used, the component no longer re-renders itself on each click, and is rendered when first displayed, and after it's been clicked once.
var TimeInChild = React.createClass({_x000D_
render: function() {_x000D_
var t = new Date().getTime();_x000D_
_x000D_
return (_x000D_
<p>Time in child:{t}</p>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
var Main = React.createClass({_x000D_
onTest: function() {_x000D_
this.setState({'test':'me'});_x000D_
},_x000D_
_x000D_
shouldComponentUpdate: function(nextProps, nextState) {_x000D_
if (this.state == null)_x000D_
return true;_x000D_
_x000D_
if (this.state.test == nextState.test)_x000D_
return false;_x000D_
_x000D_
return true;_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
var currentTime = new Date().getTime();_x000D_
_x000D_
return (_x000D_
<div onClick={this.onTest}>_x000D_
<p>Time in main:{currentTime}</p>_x000D_
<p>Click me to update time</p>_x000D_
<TimeInChild/>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(<Main/>, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
_x000D_
for unable to verify the first certificate in nodejs reject unauthorized is needed
request({method: "GET",
"rejectUnauthorized": false,
"url": url,
"headers" : {"Content-Type": "application/json",
function(err,data,body) {
}).pipe(
fs.createWriteStream('file.html'));
//use css
.blue {
background-color:blue !important;
}
.blue th {
color:white !important;
}
//html
<table class="table blue">.....</table>
from: Outline effect to text
.strokeme
{
color: white;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
}
In case someone stumbles in on this like I did, you can filter on multiple tags by adding a comma in between, like so:
adb logcat -s "browser","webkit"
Set the items into display: inline
and use :after
:
.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }
and add the class into your html spans:
<span class="medium break-after">We</span>
The following works as of now (tested in Chrome and Firefox):
<form onsubmit="event.preventDefault(); validateMyForm();">
Where validateMyForm() is a function that returns false
if validation fails. The key point is to use the name event
. We cannot use for e.g. e.preventDefault()
.
Im also got the same Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
what i did is i triggered the close button event which is in the dialog header like
this is working fine for me to close the dialog
function btnClose() {
$(".ui-dialog-titlebar-close").trigger('click');
}
Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.
First the Demo: http://jsfiddle.net/pnYWY/
First the DIVs...
<style>
.moveDiv {
position:absolute;
left:20px;
top:20px;
width:10px;
height:10px;
background-color:#ccc;
}
.moveDivB {
position:absolute;
left:20px;
top:20px;
width:10px;
height:10px;
background-color:#ccc;
}
</style>
<div class="moveDiv"></div>
<div class="moveDivB"></div>
example 1) Start
// first animation (fire right away)
var myVar = setInterval(function(){
$(function() { // jquery document.ready
// returns true if it just took a step
// returns false if the div has arrived
if( !move_div_step(55,25,'.moveDiv') )
{
// arrived...
console.log('arrived');
clearInterval(myVar);
}
});
},50); // set speed here in ms for your delay
example 2) Delayed Start
// pause and then fire an animation..
setTimeout(function(){
var myVarB = setInterval(function(){
$(function() { // jquery document.ready
// returns true if it just took a step
// returns false if the div has arrived
if( !move_div_step(25,55,'.moveDivB') )
{
// arrived...
console.log('arrived');
clearInterval(myVarB);
}
});
},50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing
Now the Function:
function move_div_step(xx,yy,target) // takes one pixel step toward target
{
// using a line algorithm to move a div one step toward a given coordinate.
var div_target = $(target);
// get current x and current y
var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
var y = div_target.position().top;
// if x and y are = to xx and yy (destination), then div has arrived at it's destination.
if(x == xx && y == yy)
return false;
// find the distances travelled
var dx = xx - x;
var dy = yy - y;
// preventing time travel
if(dx < 0) dx *= -1;
if(dy < 0) dy *= -1;
// determine speed of pixel travel...
var sx=1, sy=1;
if(dx > dy) sy = dy/dx;
else if(dy > dx) sx = dx/dy;
// find our one...
if(sx == sy) // both are one..
{
if(x <= xx) // are we going forwards?
{
x++; y++;
}
else // .. we are going backwards.
{
x--; y--;
}
}
else if(sx > sy) // x is the 1
{
if(x <= xx) // are we going forwards..?
x++;
else // or backwards?
x--;
y += sy;
}
else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
{
if(y <= yy) // going forwards?
y++;
else // .. or backwards?
y--;
x += sx;
}
// move the div
div_target.css("left", x);
div_target.css("top", y);
return true;
} // END :: function move_div_step(xx,yy,target)
using Eloquent
$data = array(
array('user_id'=>'Coder 1', 'subject_id'=> 4096),
array('user_id'=>'Coder 2', 'subject_id'=> 2048),
//...
);
Model::insert($data);
var fs = require('fs');
function base64Encode(file) {
var body = fs.readFileSync(file);
return body.toString('base64');
}
var base64String = base64Encode('test.jpg');
console.log(base64String);
The Application settings of an Android project's properties in Visual Studio 2017 (15.8.5) has them combined:
To get something like this
with Bootstrap 3 and Jquery use the following HTML code:
<div class="btn-group">
<input id="searchinput" type="search" class="form-control">
<span id="searchclear" class="glyphicon glyphicon-remove-circle"></span>
</div>
and some CSS:
#searchinput {
width: 200px;
}
#searchclear {
position: absolute;
right: 5px;
top: 0;
bottom: 0;
height: 14px;
margin: auto;
font-size: 14px;
cursor: pointer;
color: #ccc;
}
and Javascript:
$("#searchclear").click(function(){
$("#searchinput").val('');
});
Of course you have to write more Javascript for whatever functionality you need, e.g. to hide the 'x' if the input is empty, make Ajax requests and so on. See http://www.bootply.com/121508
On my Mac, this is the only solution worked for me.
https://stackoverflow.com/a/45530305/5414448
1 - Download the .sql file and remember it's location.
2 - Open your mysql from command prompt or terminal.
3 - Create a database with the same name as that of the database present in the .sql file (create database your_database_name)
4 - Now exit out from the mysql command line client
5 - Now try and execute this command =>
mysql -u your_username -p your_database_name < your_sql_file_with_complete_location
example - mysql -u root -p trial < /home/abc/Desktop/trial.sql
here my .sql file is named trial and is present in the desktop, the database is also name trial
6 - You should now have your sql file imported to the corresponding mysql database.
By using just jQuery, you cannot avoid a server call.
However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.
To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.
Try
yum list installed | grep reponame
On one of my servers:
yum list installed | grep remi ImageMagick2.x86_64 6.6.5.10-1.el5.remi installed memcache.x86_64 1.4.5-2.el5.remi installed mysql.x86_64 5.1.54-1.el5.remi installed mysql-devel.x86_64 5.1.54-1.el5.remi installed mysql-libs.x86_64 5.1.54-1.el5.remi installed mysql-server.x86_64 5.1.54-1.el5.remi installed mysqlclient15.x86_64 5.0.67-1.el5.remi installed php.x86_64 5.3.5-1.el5.remi installed php-cli.x86_64 5.3.5-1.el5.remi installed php-common.x86_64 5.3.5-1.el5.remi installed php-domxml-php4-php5.noarch 1.21.2-1.el5.remi installed php-fpm.x86_64 5.3.5-1.el5.remi installed php-gd.x86_64 5.3.5-1.el5.remi installed php-mbstring.x86_64 5.3.5-1.el5.remi installed php-mcrypt.x86_64 5.3.5-1.el5.remi installed php-mysql.x86_64 5.3.5-1.el5.remi installed php-pdo.x86_64 5.3.5-1.el5.remi installed php-pear.noarch 1:1.9.1-6.el5.remi installed php-pecl-apc.x86_64 3.1.6-1.el5.remi installed php-pecl-imagick.x86_64 3.0.1-1.el5.remi.1 installed php-pecl-memcache.x86_64 3.0.5-1.el5.remi installed php-pecl-xdebug.x86_64 2.1.0-1.el5.remi installed php-soap.x86_64 5.3.5-1.el5.remi installed php-xml.x86_64 5.3.5-1.el5.remi installed remi-release.noarch 5-8.el5.remi installed
It works.
This may support
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="PRODUCTION_Default5" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function max()
{
window.open("", "_self", "fullscreen=yes, scrollbars=auto");
}
</script>
</head>
<body onload="max()">
<form id="form1" runat="server">
<div>
This is Test Page
</div>
</form>
</body>
</html>
You can use the path
module to join the path of the directory in which helper1.js
lives to the relative path of foobar.json
. This will give you the absolute path to foobar.json
.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
Use update instead of stop
http://api.jqueryui.com/sortable/
update( event, ui )
Type: sortupdate
This event is triggered when the user stopped sorting and the DOM position has changed.
.
stop( event, ui )
Type: sortstop
This event is triggered when sorting has stopped. event Type: Event
Piece of code:
<script type="text/javascript">
var sortable = new Object();
sortable.s1 = new Array(1, 2, 3, 4, 5);
sortable.s2 = new Array(1, 2, 3, 4, 5);
sortable.s3 = new Array(1, 2, 3, 4, 5);
sortable.s4 = new Array(1, 2, 3, 4, 5);
sortable.s5 = new Array(1, 2, 3, 4, 5);
sortingExample();
function sortingExample()
{
// Init vars
var tDiv = $('<div></div>');
var tSel = '';
// ul
for (var tName in sortable)
{
// Creating ul list
tDiv.append(createUl(sortable[tName], tName));
// Add selector id
tSel += '#' + tName + ',';
}
$('body').append('<div id="divArrayInfo"></div>');
$('body').append(tDiv);
// ul sortable params
$(tSel).sortable({connectWith:tSel,
start: function(event, ui)
{
ui.item.startPos = ui.item.index();
},
update: function(event, ui)
{
var a = ui.item.startPos;
var b = ui.item.index();
var id = this.id;
// If element moved to another Ul then 'update' will be called twice
// 1st from sender list
// 2nd from receiver list
// Skip call from sender. Just check is element removed or not
if($('#' + id + ' li').length < sortable[id].length)
{
return;
}
if(ui.sender === null)
{
sortArray(a, b, this.id, this.id);
}
else
{
sortArray(a, b, $(ui.sender).attr('id'), this.id);
}
printArrayInfo();
}
}).disableSelection();;
// Add styles
$('<style>')
.attr('type', 'text/css')
.html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
.appendTo('head');
printArrayInfo();
}
function printArrayInfo()
{
var tStr = '';
for ( tName in sortable)
{
tStr += tName + ': ';
for(var i=0; i < sortable[tName].length; i++)
{
// console.log(sortable[tName][i]);
tStr += sortable[tName][i] + ', ';
}
tStr += '<br>';
}
$('#divArrayInfo').html(tStr);
}
function createUl(tArray, tId)
{
var tUl = $('<ul>', {id:tId, class:'sortableClass'})
for(var i=0; i < tArray.length; i++)
{
// Create Li element
var tLi = $('<li>' + tArray[i] + '</li>');
tUl.append(tLi);
}
return tUl;
}
function sortArray(a, b, idA, idB)
{
var c;
c = sortable[idA].splice(a, 1);
sortable[idB].splice(b, 0, c);
}
</script>
I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.
As you have written h_url is global var like var = h_url;
so you can use that variable anywhere in your file.
h_url=document.getElementById("u").value;
Here h_url contain value of your search box text value whatever user has typed.
document.getElementById("u");
This is the identifier of your form field with some specific ID
.
Your Search Field without id
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
Alter Search Field with id
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
When you click on submit that will try to fetch value from document.getElementById("u").value;
which is syntactically right but you haven't define id so that will return null
.
So, Just make sure while you use form fields first define that ID and do other task letter.
I hope this helps you and never get Cannot set property 'value' of null
Error.
I don't think I have much to add to eg. Triptych's answer or CMS's answer on why using for...in
should be avoided in some cases.
I do, however, would like to add that in modern browsers there is an alternative to for...in
that can be used in those cases where for...in
can't be used. That alternative is for...of
:
for (var item of items) {
console.log(item);
}
Unfortunately, no version of Internet Explorer supports for...of
(Edge 12+ does), so you'll have to wait a bit longer until you can use it in your client side production code. However, it should be safe to use in your server side JS code (if you use Node.js).
Short and sweet.
[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
HTML example to send different form action on different button click:
<form action="/login" method="POST">
<input type="text" name="username" value="your_username" />
<input type="password" name="password" value="your_password" />
<button type="submit">Login</button>
<button type="submit" formaction="/users" formmethod="POST">Add User</button>
</form>
Same form is being used to add a new user and login user.
Implement the View.OnClickListener interface and override the onClick method.
ImageView btnSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search1);
ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch: {
Intent intent = new Intent(Search.this,SearchFeedActivity.class);
startActivity(intent);
break;
}
I have created function to disable previous date, disable flexible weekend days (Like Saturday, Sunday)
We are using beforeShowDay method of jQuery UI datepicker plugin.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
var NotBeforeToday = function(date) {_x000D_
var now = new Date(); //this gets the current date and time_x000D_
if (date.getFullYear() == now.getFullYear() && date.getMonth() == now.getMonth() && date.getDate() >= now.getDate() && (date.getDay() > 0 && date.getDay() < 6) )_x000D_
return [true,""];_x000D_
if (date.getFullYear() >= now.getFullYear() && date.getMonth() > now.getMonth() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
if (date.getFullYear() > now.getFullYear() && (date.getDay() > 0 && date.getDay() < 6))_x000D_
return [true,""];_x000D_
return [false,""];_x000D_
}_x000D_
_x000D_
_x000D_
jQuery("#datepicker").datepicker({_x000D_
beforeShowDay: NotBeforeToday_x000D_
});
_x000D_
Here today's date is 15th Sept. I have disabled Saturday and Sunday.
I'm using the latest Bootstrap 3 DateTime Picker (http://eonasdan.github.io/bootstrap-datetimepicker/)
This is how you should use DateTime Picker inline:
var selectedDate = $("#datetimepicker").find(".active").data("day");
The above returned: 03/23/2017
Finally got the answer for datepicker date change method:
$('#formatdate').change(function(){
$('#datpicker').datepicker("option","dateFormat","yy-mm-dd");
});
I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.
Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.
This indicates it only applies to hash or array elements!
To clarify there is no such thing as a mutable string in C# (or .NET in general). Other langues support mutable strings (string which can change) but the .NET framework does not.
So the correct answer to your question is ALL string are immutable in C#.
string has a specific meaning. "string" lowercase keyword is merely a shortcut for an object instantiated from System.String class. All objects created from string class are ALWAYS immutable.
If you want a mutable representation of text then you need to use another class like StringBuilder. StringBuilder allows you to iteratively build a collection of 'words' and then convert that to a string (once again immutable).
Setting 700 to .ssh and 600 to authorized_keys solved the issue.
chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys
Currently VARCHAR behaves exactly the same as VARCHAR2. However, the type VARCHAR
should not be used as it is reserved for future usage.
Taken from: Difference Between CHAR, VARCHAR, VARCHAR2
The best way to solve this issue is using the formula to calculate a slope:
(y1-y2/x1-x2)
*define x1 as the first moment, so value will be "C4=1" define x2 as the first moment, so value will be "C5=2"
In order to get the correct percentage growth we can follow this order:
=(((B4-B5)/(C4-C5))/ABS(B4))*100
Perfectly Works!
Look here.
Your URL is quite incorrect. Should look like this:
url="jdbc:oracle:thin:@localhost:1521:orcl"
You don't register a driver class, either. You want to download the thin driver JAR, put it in your CLASSPATH, and make your code look more like this.
UPDATE: The "14" in "ojdbc14.jar" stands for JDK 1.4. You should match your driver version with the JDK you're running. I'm betting that means JDK 5 or 6.
In Angular 7.X
The CSS classes are updated as follows, depending on the type of the expression evaluation:
string - the CSS classes listed in the string (space delimited) are added
Array - the CSS classes declared as Array elements are added
Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.
<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
If using a third party library is an option, there is jOOU (a spin off library from jOOQ), which offers wrapper types for unsigned integer numbers in Java. That's not exactly the same thing as having primitive type (and thus byte code) support for unsigned types, but perhaps it's still good enough for your use-case.
import static org.joou.Unsigned.*;
// and then...
UByte b = ubyte(1);
UShort s = ushort(1);
UInteger i = uint(1);
ULong l = ulong(1);
All of these types extend java.lang.Number
and can be converted into higher-order primitive types and BigInteger
.
(Disclaimer: I work for the company behind these libraries)
try this code I think it is more optimal.
HeaderRow is used to repeat the header of the table for each new page automatically
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
PdfPTable table = new PdfPTable(10) { HorizontalAlignment = Element.ALIGN_CENTER, WidthPercentage = 100, HeaderRows = 2 };
table.SetWidths(new float[] { 2f, 6f, 6f, 3f, 5f, 8f, 5f, 5f, 5f, 5f });
table.AddCell(new PdfPCell(new Phrase("SER.\nNO.", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("TYPE OF SHIPPING", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("ORDER NO.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("QTY.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DISCHARGE PPORT", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DESCRIPTION OF GOODS", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("LINE DOC. RECL DATE", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("CLEARANCE DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("CUSTOM PERMIT NO.", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DISPATCH DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("AWB/BL NO.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("COMPLEX NAME", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("G. W. Kgs.", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("DESTINATION", times)) { GrayFill = 0.95f });
table.AddCell(new PdfPCell(new Phrase("OWNER DOC. RECL DATE", times)) { GrayFill = 0.95f });
Using Font Awesome 5, the markup is a bit more complex than the previouis answer. Per the FA documentation, the markup should be:
<ul class="fa-ul">
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
<li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
<li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
<li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>
As stated by pnt you can have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.
Taking it further from there: Here's how it might be possible to set any runtime parameters for each of those installations:
You can run javacpl.exe or javacpl.cpl of the respective Java-version itself (bin-folder). The specific control panel opens fine. Adding parameters there is possible.
Here is another option that outputs mm/dd/yy:
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
<table>
<col width="130">
<col width="80">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
I was working with Live Server and lots stuff stuck. I try many things to fix but exact issue of 255 don't figure out.
Even I had resolved issue 100%
Replace my sshd_config file from similar other my debian server
[email protected]:~# cp sshd_config sshd_config.snippetbucket.com.bkp #keep my backup file
[email protected]:~# echo "" > sshd_config
[email protected]:~# nano sshd_config #replaced all content with other exact same server
[email protected]:~# sudo service ssh restart #normally restart server
That's 100% resolve my issue immediate.
#SnippetBucket-Tip: Always take backup of ssh related files, which help on quick restoration.
Note: After apply given changes you need to exit rescue mode and reboot your vps / dedicated server normally, than your ssh connection works.
During rescue mode ssh don't allow user to login as normally. only rescue ssh related login and password works.
Consider using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern
You can change the decorator at runtime with one that has different properties when an event occurs.
I can't speak directly for ASP.NET MVC, but for ASP.NET Web Forms, the trick is to create a FormsAuthenticationTicket
and encrypt it into a cookie once the user has been authenticated. This way, you only have to call the database once (or AD or whatever you are using to perform your authentication), and each subsequent request will authenticate based on the ticket stored in the cookie.
A good article on this: http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html (broken link)
Edit:
Since the link above is broken, I would recommend LukeP's solution in his answer above: https://stackoverflow.com/a/10524305 - I would also suggest that the accepted answer be changed to that one.
Edit 2: An alternative for the broken link: https://web.archive.org/web/20120422011422/http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html
objdump -TC /usr/lib/libexample.so
Try nslookup google.com to determine if there's a DNS issue. 192.168.1.254 is your local network address and it looks like your system is using it as a DNS server. Is this your gateway/modem router as well? What happens when you try ping google.com. Can you browse to it on a Internet web browser?
Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.
Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.
The problem in your code is that it's creating lots of heavy String
objects, copying their contents and performing operations on them. Instead, you should use StringBuilder
to avoid creating new String
objects on each append and to avoid copying the char arrays. The implementation for your case would be something like this:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
for (String line; (line = r.readLine()) != null; ) {
total.append(line).append('\n');
}
You can now use total
without converting it to String
, but if you need the result as a String
, simply add:
String result = total.toString();
I'll try to explain it better...
a += b
(or a = a + b
), where a
and b
are Strings, copies the contents of both a
and b
to a new object (note that you are also copying a
, which contains the accumulated String
), and you are doing those copies on each iteration.a.append(b)
, where a
is a StringBuilder
, directly appends b
contents to a
, so you don't copy the accumulated string at each iteration.use os.walk to recursively list your files
import os
root = "/home"
pattern = "145992"
alist_filter = ['jpg','bmp','png','gif']
path=os.path.join(root,"mydir_to_scan")
for r,d,f in os.walk(path):
for file in f:
if file[-3:] in alist_filter and pattern in file:
print os.path.join(root,file)
On mac os, please follow below steps:
Stop MySQL
$ sudo /usr/local/mysql/support-files/mysql.server stop Start it in safe mode:
$ sudo mysqld_safe --skip-grant-tables (above line is the whole command)
This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:
$ mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; Start MySQL
sudo /usr/local/mysql/support-files/mysql.server start your new password is 'password'.
There are two typical ways of declaring a function. I prefer the second approach.
function function_name {
command...
}
or
function_name () {
command...
}
To call a function with arguments:
function_name "$arg1" "$arg2"
The function refers to passed arguments by their position (not by name), that is $1
, $2
, and so forth. $0
is the name of the script itself.
Example:
function_name () {
echo "Parameter #1 is $1"
}
Also, you need to call your function after it is declared.
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
Output:
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
Calling .isoformat()
on a date
object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
The best way is deltaE. DeltaE is a number that shows the difference of the colors. If deltae < 1 then the difference can't recognize by human eyes. I wrote a code in canvas and js for converting rgb to lab and then calculating delta e. On this example the code is recognising pixels which have different color with a base color that I saved as LAB1. and then if it is different makes those pixels red. You can increase or reduce the sensitivity of the color difference with increae or decrease the acceptable range of delta e. In this example I assigned 10 for deltaE in the line that I wrote (deltae <= 10):
<script>
var constants = {
canvasWidth: 700, // In pixels.
canvasHeight: 600, // In pixels.
colorMap: new Array()
};
// -----------------------------------------------------------------------------------------------------
function fillcolormap(imageObj1) {
function rgbtoxyz(red1,green1,blue1){ // a converter for converting rgb model to xyz model
var red2 = red1/255;
var green2 = green1/255;
var blue2 = blue1/255;
if(red2>0.04045){
red2 = (red2+0.055)/1.055;
red2 = Math.pow(red2,2.4);
}
else{
red2 = red2/12.92;
}
if(green2>0.04045){
green2 = (green2+0.055)/1.055;
green2 = Math.pow(green2,2.4);
}
else{
green2 = green2/12.92;
}
if(blue2>0.04045){
blue2 = (blue2+0.055)/1.055;
blue2 = Math.pow(blue2,2.4);
}
else{
blue2 = blue2/12.92;
}
red2 = (red2*100);
green2 = (green2*100);
blue2 = (blue2*100);
var x = (red2 * 0.4124) + (green2 * 0.3576) + (blue2 * 0.1805);
var y = (red2 * 0.2126) + (green2 * 0.7152) + (blue2 * 0.0722);
var z = (red2 * 0.0193) + (green2 * 0.1192) + (blue2 * 0.9505);
var xyzresult = new Array();
xyzresult[0] = x;
xyzresult[1] = y;
xyzresult[2] = z;
return(xyzresult);
} //end of rgb_to_xyz function
function xyztolab(xyz){ //a convertor from xyz to lab model
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var x2 = x/95.047;
var y2 = y/100;
var z2 = z/108.883;
if(x2>0.008856){
x2 = Math.pow(x2,1/3);
}
else{
x2 = (7.787*x2) + (16/116);
}
if(y2>0.008856){
y2 = Math.pow(y2,1/3);
}
else{
y2 = (7.787*y2) + (16/116);
}
if(z2>0.008856){
z2 = Math.pow(z2,1/3);
}
else{
z2 = (7.787*z2) + (16/116);
}
var l= 116*y2 - 16;
var a= 500*(x2-y2);
var b= 200*(y2-z2);
var labresult = new Array();
labresult[0] = l;
labresult[1] = a;
labresult[2] = b;
return(labresult);
}
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageX = 0;
var imageY = 0;
context.drawImage(imageObj1, imageX, imageY, 240, 140);
var imageData = context.getImageData(0, 0, 240, 140);
var data = imageData.data;
var n = data.length;
// iterate over all pixels
var m = 0;
for (var i = 0; i < n; i += 4) {
var red = data[i];
var green = data[i + 1];
var blue = data[i + 2];
var xyzcolor = new Array();
xyzcolor = rgbtoxyz(red,green,blue);
var lab = new Array();
lab = xyztolab(xyzcolor);
constants.colorMap.push(lab); //fill up the colormap array with lab colors.
}
}
// -----------------------------------------------------------------------------------------------------
function colorize(pixqty) {
function deltae94(lab1,lab2){ //calculating Delta E 1994
var c1 = Math.sqrt((lab1[1]*lab1[1])+(lab1[2]*lab1[2]));
var c2 = Math.sqrt((lab2[1]*lab2[1])+(lab2[2]*lab2[2]));
var dc = c1-c2;
var dl = lab1[0]-lab2[0];
var da = lab1[1]-lab2[1];
var db = lab1[2]-lab2[2];
var dh = Math.sqrt((da*da)+(db*db)-(dc*dc));
var first = dl;
var second = dc/(1+(0.045*c1));
var third = dh/(1+(0.015*c1));
var deresult = Math.sqrt((first*first)+(second*second)+(third*third));
return(deresult);
} // end of deltae94 function
var lab11 = new Array("80","-4","21");
var lab12 = new Array();
var k2=0;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageData = context.getImageData(0, 0, 240, 140);
var data = imageData.data;
for (var i=0; i<pixqty; i++) {
lab12 = constants.colorMap[i];
var deltae = deltae94(lab11,lab12);
if (deltae <= 10) {
data[i*4] = 255;
data[(i*4)+1] = 0;
data[(i*4)+2] = 0;
k2++;
} // end of if
} //end of for loop
context.clearRect(0,0,240,140);
alert(k2);
context.putImageData(imageData,0,0);
}
// -----------------------------------------------------------------------------------------------------
$(window).load(function () {
var imageObj = new Image();
imageObj.onload = function() {
fillcolormap(imageObj);
}
imageObj.src = './mixcolor.png';
});
// ---------------------------------------------------------------------------------------------------
var pixno2 = 240*140;
</script>
Scenario
I was getting SSLHandshake exceptions on devices running versions of Android earlier than Android 5.0. In my use case I also wanted to create a TrustManager to trust my client certificate.
I implemented NoSSLv3SocketFactory and NoSSLv3Factory to remove SSLv3 from my client's list of supported protocols but I could get neither of these solutions to work.
Some things I learned:
What worked for me
Allow Android's security Provider
to update when starting your app.
The default Provider before 5.0+ does not disable SSLv3. Provided you have access to Google Play services it is relatively straightforward to patch Android's security Provider from your app.
private void updateAndroidSecurityProvider(Activity callingActivity) {
try {
ProviderInstaller.installIfNeeded(this);
} catch (GooglePlayServicesRepairableException e) {
// Thrown when Google Play Services is not installed, up-to-date, or enabled
// Show dialog to allow users to install, update, or otherwise enable Google Play services.
GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), callingActivity, 0);
} catch (GooglePlayServicesNotAvailableException e) {
Log.e("SecurityException", "Google Play Services not available.");
}
}
If you now create your OkHttpClient or HttpURLConnection TLSv1.1 and TLSv1.2 should be available as protocols and SSLv3 should be removed. If the client/connection (or more specifically it's SSLContext) was initialised before calling ProviderInstaller.installIfNeeded(...)
then it will need to be recreated.
Don't forget to add the following dependency (latest version found here):
compile 'com.google.android.gms:play-services-auth:16.0.1'
Sources:
Aside
I didn't need to explicitly set which cipher algorithms my client should use but I found a SO post recommending those considered most secure at the time of writing: Which Cipher Suites to enable for SSL Socket?
I solve this problem by adding extension method to IEnumerable.
public static class DataTableEnumerate
{
public static void Fill<T> (this IEnumerable<T> Ts, ref DataTable dt) where T : class
{
//Get Enumerable Type
Type tT = typeof(T);
//Get Collection of NoVirtual properties
var T_props = tT.GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();
//Fill Schema
foreach (PropertyInfo p in T_props)
dt.Columns.Add(p.Name, p.GetMethod.ReturnParameter.ParameterType.BaseType);
//Fill Data
foreach (T t in Ts)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo p in T_props)
row[p.Name] = p.GetValue(t);
dt.Rows.Add(row);
}
}
}
The following can be used to get the date:
function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}
Dataframes have a sort_index
method which returns a copy by default. Pass inplace=True
to operate in place.
import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())
Gives me:
A
1 4
29 2
100 1
150 5
234 3
The location of the sitemap affects which URLs that it can include, but otherwise there is no standard. Here is a good link with more explaination: http://www.sitemaps.org/protocol.html#location
The only thing that appears to work is to set flex-wrap: wrap;
on the container and them somehow make the child you want to break out after to fill the full width, so width: 100%;
should work.
If, however, you can't stretch the element to 100% (for example, if it's an <img>
), you can apply a margin to it, like width: 50px; margin-right: calc(100% - 50px)
.
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
You need to "seed" the generator. Check out this short video, it will clear things up.
Open the start menu and type cmd
into the search box
Hold Ctrl + Shift
and press Enter
This runs the Command Prompt in Administrator mode.
Now type regsvr32 MyComobject.dll
PHP 5.3 has functions to create and reformat at DateTime object from whatever format you specify:
$mysql_date = "2012-01-02"; // date in Y-m-d format as MySQL stores it
$date_obj = date_create_from_format('Y-m-d',$mysql_date);
$date = date_format($date_obj, 'm/d/Y');
echo $date;
Outputs:
01/02/2012
MySQL can also control the formatting by using the STR_TO_DATE()
function when inserting/updating, and the DATE_FORMAT()
when querying.
$php_date = "01/02/2012";
$update_query = "UPDATE `appointments` SET `start_time` = STR_TO_DATE('" . $php_date . "', '%m/%d/%Y')";
$query = "SELECT DATE_FORMAT(`start_time`,'%m/%d/%Y') AS `start_time` FROM `appointments`";
I already showed this elsewhere on SO (How to use a variable in the format specifier statement? , not an exact duplicate IMHO), but I think it is worthwhile to place it here. It is possible to use the techniques from other answers for this question to make a simple function
function itoa(i) result(res)
character(:),allocatable :: res
integer,intent(in) :: i
character(range(i)+2) :: tmp
write(tmp,'(i0)') i
res = trim(tmp)
end function
which you can use after without worrying about trimming and left-adjusting and without writing to a temporary variable:
OPEN(1, FILE = 'Output'//itoa(i)//'.TXT')
It requires Fortran 2003 because of the allocatable string.
You can do that in PL/SQL Developer v10.
1. Click on Table that you want to generate script for.
2. Click Export data.
3. Check if table is selected that you want to export data for.
4. Click on SQL inserts tab.
5. Add where clause if you don't need the whole table.
6. Select file where you will find your SQL script.
7. Click export.
First install setuptools
sudo pip install setuptools
Then install mysql-connector
sudo pip install mysql-connector
If using Python3, then replace pip by pip3
@Mihai-Andrei Dinculescu's answer is correct, but for the benefit of searchers, there is also a subtle point that can cause this error.
Adding a '/' on the end of your URL will stop EnableCors from working in all instances (e.g. from the homepage).
I.e. This will not work
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net/", "*", "*");
config.EnableCors(cors);
but this will work:
var cors = new EnableCorsAttribute("http://testing.azurewebsites.net", "*", "*");
config.EnableCors(cors);
The effect is the same if using the EnableCors Attribute.
thead {
position: fixed;
height: 10px; /* This is whatever height you want */
}
tbody {
position: fixed;
margin-top: 10px; /* This has to match the height of thead */
height: 300px; /* This is whatever height you want */
}
bobince's answer will let you know in which cases "height: XX%;" will or won't work.
If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom
. Example for square:
<div class="square-container">
<div class="square-content">
<!-- put your content in here -->
</div>
</div>
.square-container { /* any display: block; element */
position: relative;
height: 0;
padding-bottom: 100%; /* of parent width */
}
.square-content {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
}
The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video
.e:hover{
background-color:#FF0000;
}
If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the String
constructor and provide a Charset
, or use InputStreamReader
with the appropriate Charset
instead.
Simply casting from int
to char
only works if you want ISO-8859-1, if you're reading bytes from a stream directly.
EDIT: If you are already using a Reader
, then casting the return value of read()
to char
is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call read(char[], int, int)
to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.
It seems, that the simple way
-Dmaven.javadoc.skip=true
does not work with the release-plugin. in this case you have to pass the parameter as an "argument"
mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"
def merge_sort(x):
if len(x) < 2:return x
result,mid = [],int(len(x)/2)
y = merge_sort(x[:mid])
z = merge_sort(x[mid:])
while (len(y) > 0) and (len(z) > 0):
if y[0] > z[0]:result.append(z.pop(0))
else:result.append(y.pop(0))
result.extend(y+z)
return result
The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way
bool AppendCharToCharArray( char *array, size_t n, char c )
{
size_t sz = std::strlen( array );
if ( sz + 1 < n )
{
array[sz] = c;
array[sz + 1] = '\0';
}
return ( sz + 1 < n );
}
If you need a function that will contain a copy of the original array plus the given character then it could look the following way
char * CharArrayPlusChar( const char *array, char c )
{
size_t sz = std::strlen( array );
char *s = new char[sz + 2];
std::strcpy( s, array );
s[sz] = c;
s[sz + 1] = '\0';
return ( s );
}
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
you can also just do it this way
document.getElementById(id).outerHTML
where id is the id of the element that you are looking for
It is difficult to distinguish between undefined and null. Null is a value you can assign to a variable when you want to indicate that the variable has no particular value. Undefined is a special value which will be the default value of unassigned variables.
var _undefined;
var _null = null;
alert(_undefined);
alert(_null);
alert(_undefined == _null);
alert(_undefined === _null);
You're applying transitions only to the :hover
pseudo-class, and not to the element itself.
.item {
height:200px;
width:200px;
background:red;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-ms-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
}
.item:hover {
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Demo: http://jsfiddle.net/7uR8z/6/
If you don't want the transition to affect the mouse-over
event, but only mouse-out
, you can turn transitions off for the :hover
state :
.item:hover {
-webkit-transition: none;
-moz-transition: none;
-ms-transition: none;
-o-transition: none;
transition: none;
zoom: 1;
filter: alpha(opacity=50);
opacity: 0.5;
}
Let's measure the performance by using the following piece of code.
import numpy as np
import time
exec_time0 = []
exec_time1 = []
exec_time2 = []
sizeOfArray = 5000
numOfIterations = 200
for i in xrange(numOfIterations):
A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
a = time.clock()
res = (A==B).all()
b = time.clock()
exec_time0.append( b - a )
a = time.clock()
res = np.array_equal(A,B)
b = time.clock()
exec_time1.append( b - a )
a = time.clock()
res = np.array_equiv(A,B)
b = time.clock()
exec_time2.append( b - a )
print 'Method: (A==B).all(), ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)
Output
Method: (A==B).all(), 0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515
According to the results above, the numpy methods seem to be faster than the combination of the == operator and the all() method and by comparing the numpy methods the fastest one seems to be the numpy.array_equal method.
Here is something:
char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
for( int i = data; i < data_length; ++i )
{
char const byte = data[i];
string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}
Today, I used this logic why I don't know getting the count of RS.
int chkSize = 0;
if (rs.next()) {
do { ..... blah blah
enter code here for each rs.
chkSize++;
} while (rs.next());
} else {
enter code here for rs size = 0
}
// good luck to u.
lapply(your_dataframe, class) gives you something like:
$tikr [1] "factor"
$Date [1] "Date"
$Open [1] "numeric"
$High [1] "numeric"
... etc.
Try
$ awk 'NF>1{print $NF}' file
example.
line.
file.
To get the result in one line as in your example, try:
{
sub(/\./, ",", $NF)
str = str$NF
}
END { print str }
output:
$ awk -f script.awk file
example, line, file,
Pure bash:
$ while read line; do [ -z "$line" ] && continue ;echo ${line##* }; done < file
example.
line.
file.
I understand this is an older question, but I would like to add another disadvantage of Single Page Applications:
If you build an API that returns results in a data language (such as XML or JSON) rather than a formatting language (like HTML), you are enabling greater application interoperability, for example, in business-to-business (B2B) applications. Such interoperability has great benefits but does allow people to write software to "mine" (or steal) your data. This particular disadvantage is common to all APIs that use a data language, and not to SPAs in general (indeed, an SPA that asks the server for pre-rendered HTML avoids this, but at the expense of poor model/view separation). This risk exposed by this disadvantage can be mitigated by various means, such as request limiting and connection blocking, etc.
The other answers are all good approaches. However, there are a few other options in R that haven't been mentioned, including lowess
and approx
, which may give better fits or faster performance.
The advantages are more easily demonstrated with an alternate dataset:
sigmoid <- function(x)
{
y<-1/(1+exp(-.15*(x-100)))
return(y)
}
dat<-data.frame(x=rnorm(5000)*30+100)
dat$y<-as.numeric(as.logical(round(sigmoid(dat$x)+rnorm(5000)*.3,0)))
Here is the data overlaid with the sigmoid curve that generated it:
This sort of data is common when looking at a binary behavior among a population. For example, this might be a plot of whether or not a customer purchased something (a binary 1/0 on the y-axis) versus the amount of time they spent on the site (x-axis).
A large number of points are used to better demonstrate the performance differences of these functions.
Smooth
, spline
, and smooth.spline
all produce gibberish on a dataset like this with any set of parameters I have tried, perhaps due to their tendency to map to every point, which does not work for noisy data.
The loess
, lowess
, and approx
functions all produce usable results, although just barely for approx
. This is the code for each using lightly optimized parameters:
loessFit <- loess(y~x, dat, span = 0.6)
loessFit <- data.frame(x=loessFit$x,y=loessFit$fitted)
loessFit <- loessFit[order(loessFit$x),]
approxFit <- approx(dat,n = 15)
lowessFit <-data.frame(lowess(dat,f = .6,iter=1))
And the results:
plot(dat,col='gray')
curve(sigmoid,0,200,add=TRUE,col='blue',)
lines(lowessFit,col='red')
lines(loessFit,col='green')
lines(approxFit,col='purple')
legend(150,.6,
legend=c("Sigmoid","Loess","Lowess",'Approx'),
lty=c(1,1),
lwd=c(2.5,2.5),col=c("blue","green","red","purple"))
As you can see, lowess
produces a near perfect fit to the original generating curve. Loess
is close, but experiences a strange deviation at both tails.
Although your dataset will be very different, I have found that other datasets perform similarly, with both loess
and lowess
capable of producing good results. The differences become more significant when you look at benchmarks:
> microbenchmark::microbenchmark(loess(y~x, dat, span = 0.6),approx(dat,n = 20),lowess(dat,f = .6,iter=1),times=20)
Unit: milliseconds
expr min lq mean median uq max neval cld
loess(y ~ x, dat, span = 0.6) 153.034810 154.450750 156.794257 156.004357 159.23183 163.117746 20 c
approx(dat, n = 20) 1.297685 1.346773 1.689133 1.441823 1.86018 4.281735 20 a
lowess(dat, f = 0.6, iter = 1) 9.637583 10.085613 11.270911 11.350722 12.33046 12.495343 20 b
Loess
is extremely slow, taking 100x as long as approx
. Lowess
produces better results than approx
, while still running fairly quickly (15x faster than loess).
Loess
also becomes increasingly bogged down as the number of points increases, becoming unusable around 50,000.
EDIT: Additional research shows that loess
gives better fits for certain datasets. If you are dealing with a small dataset or performance is not a consideration, try both functions and compare the results.
I am reading some data from a file using read. Here I am reading data in a 2d char pointer but the method is the same for the 1d also. Just read character by character and do not worry about the exceptions because the condition in the while loop is handling the exceptions :D
while ( (n = read(fd, buffer,1)) > 0 )
{
if(buffer[0] == '\n')
{
r++;
char**tempData=(char**)malloc(sizeof(char*)*r);
for(int a=0;a<r;a++)
{
tempData[a]=(char*)malloc(sizeof(char)*BUF_SIZE);
memset(tempData[a],0,BUF_SIZE);
}
for(int a=0;a<r-1;a++)
{
strcpy(tempData[a],data[a]);
}
data=tempData;
c=0;
}
else
{
data[r-1][c]=buffer[0];
c++;
buffer[1]='\0';
}
}
Here are two ways you could do this, if you are scheduling the reboot.
First you could create a task on one machine using credentials that have rights needed to connect and reboot another machine. This makes the scheduler responsible for securely storing the credentials. The reboot command (I'm a Powershell guy, but this is cleaner.) is:
SHUTDOWN /r /f /m \\ComputerName
The command line to create a scheduled task on the local machine, to remotely reboot another, would be:
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f /m \\ComputerName" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU "domain\username" /RP "password"
I prefer the second way, where you use your current credentials to create a scheduled task that runs with the system account on a remote machine.
SCHTASKS /Create /TN "Reboot Server" /TR "shutdown.exe /r /f" /SC ONCE /ST 00:00 /SD "12/24/2012" /RU SYSTEM /S ComputerName
This also works through the GUI, just enter SYSTEM as the user name, leaving the password fields blank.
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
Two other simple possibilities:
There is an old (unfashionable) solution to the "a daemon that binds on a low port and hands control to your daemon". It's called inetd (or xinetd). The cons are:
Pros:
Another alternative: a hacked-up proxy (netcat or even something more robust) from the privileged port to some arbitrary high-numbered port where you can run your target daemon. (Netcat is obviously not a production solution, but "just my dev box", right?). This way you could continue to use a network-capable version of your server, would only need root/sudo to start proxy (at boot), wouldn't be relying on complex/potentially fragile capabilities.
www.phplivedocx.org is a SOAP based service that means that you always need to be online for testing the Files also does not have enough examples for its use . Strangely I found only after 2 days of downloading (requires additionaly zend framework too) that its a SOAP based program(cursed me !!!)...I think without COM its just not possible on a Linux server and the only idea is to change the doc file in another usable file which PHP can parse...