I know this is an old thread, but there is a simple way to handle this requirement without using stored procedures. This may help someone.
set @exist_Check := (
select count(*) from information_schema.columns
where TABLE_NAME='YOUR_TABLE'
and COLUMN_NAME='YOUR_COLUMN'
and TABLE_SCHEMA=database()
) ;
set @sqlstmt := if(@exist_Check>0,'alter table YOUR_TABLE drop column YOUR_COLUMN', 'select ''''') ;
prepare stmt from @sqlstmt ;
execute stmt ;
Hope this helps someone, as it did me (after a lot of trial and error).
worked for me
.hasDatepicker {
position: relative;
z-index: 9999;
}
@
before a function call suppresses any errors that may be reported during the function call.
Adding a @
before session_start
tells PHP to avoid printing error messages.
For example:
Using session_start()
after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", @session_start()
will still fail in this case, but the error message is not printed on screen.
Before including the files or redirecting to new page use the exit()
function, otherwise it will give an error.
This code can be used in all cases:
<?php
if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
session_start();
}
?>
Something like this is what I use all the time. No need for any base64 decoding.
<html>
<head>
<script>
window.onload = function(event) {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
$('#accessKeyField').val(event.target.result);
}
var file = event.target.files[0];
fileReader.readAsText(file);
document.getElementById('fileInput').value = null;
}
</script>
</head>
<body>
<input type="file" id="fileInput" style="height: 20px; width: 100px;">
</body>
</html>
Magic commands such as
%matplotlib qt
work in the iPython console and Notebook, but do not work within a script.
In that case, after importing:
from IPython import get_ipython
use:
get_ipython().run_line_magic('matplotlib', 'inline')
for inline plotting of the following code, and
get_ipython().run_line_magic('matplotlib', 'qt')
for plotting in an external window.
Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.
Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
Here is a way to get a NIO FileChannel from System.in and check for availability of data using a timeout, which is a special case of the problem described in the question. Run it at the console, don't type any input, and wait for the results. It was tested successfully under Java 6 on Windows and Linux.
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
public class Main {
static final ByteBuffer buf = ByteBuffer.allocate(4096);
public static void main(String[] args) {
long timeout = 1000 * 5;
try {
InputStream in = extract(System.in);
if (! (in instanceof FileInputStream))
throw new RuntimeException(
"Could not extract a FileInputStream from STDIN.");
try {
int ret = maybeAvailable((FileInputStream)in, timeout);
System.out.println(
Integer.toString(ret) + " bytes were read.");
} finally {
in.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/* unravels all layers of FilterInputStream wrappers to get to the
* core InputStream
*/
public static InputStream extract(InputStream in)
throws NoSuchFieldException, IllegalAccessException {
Field f = FilterInputStream.class.getDeclaredField("in");
f.setAccessible(true);
while( in instanceof FilterInputStream )
in = (InputStream)f.get((FilterInputStream)in);
return in;
}
/* Returns the number of bytes which could be read from the stream,
* timing out after the specified number of milliseconds.
* Returns 0 on timeout (because no bytes could be read)
* and -1 for end of stream.
*/
public static int maybeAvailable(final FileInputStream in, long timeout)
throws IOException, InterruptedException {
final int[] dataReady = {0};
final IOException[] maybeException = {null};
final Thread reader = new Thread() {
public void run() {
try {
dataReady[0] = in.getChannel().read(buf);
} catch (ClosedByInterruptException e) {
System.err.println("Reader interrupted.");
} catch (IOException e) {
maybeException[0] = e;
}
}
};
Thread interruptor = new Thread() {
public void run() {
reader.interrupt();
}
};
reader.start();
for(;;) {
reader.join(timeout);
if (!reader.isAlive())
break;
interruptor.start();
interruptor.join(1000);
reader.join(1000);
if (!reader.isAlive())
break;
System.err.println("We're hung");
System.exit(1);
}
if ( maybeException[0] != null )
throw maybeException[0];
return dataReady[0];
}
}
Interestingly, when running the program inside NetBeans 6.5 rather than at the console, the timeout doesn't work at all, and the call to System.exit() is actually necessary to kill the zombie threads. What happens is that the interruptor thread blocks (!) on the call to reader.interrupt(). Another test program (not shown here) additionally tries to close the channel, but that doesn't work either.
Just as a side note:
Printing is O(1) but building a string and then printing is O(n), where n is the total number of characters in the string. So yes, while building the string is "cleaner", it's not the most efficient method of doing so.
The way I would do it is as follows:
from sys import stdout
printf = stdout.write
Now you have a "print function" that prints out any string you give it without returning the new line character each time.
printf("Hello,")
printf("World!")
The output will be: Hello, World!
However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.
printf(str(2) + " " + str(4))
The output will be: 2 4
in my opinion the easiest way would be somthing like this:
<?php>
echo '<a href="link.php?submit='.$value.'">Submit</a>';
</?>
within the "link.php" you can request the value like this:
$_REQUEST['submit']
You can use a ComboBox
with its ComboBoxStyle
(appears as DropDownStyle
in later versions) set to DropDownList
. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
Since there is a delimiter, you should use that instead of worrying about how long the md5 is.
>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
Alternatively
>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'
GOPATH
is discussed here:
The
GOPATH
Environment Variable
GOPATH
may be set to a colon-separated list of paths inside which Go code, package objects, and executables may be found.Set a
GOPATH
to use goinstall to build and install your own code and external libraries outside of the Go tree (and to avoid writing Makefiles).
And GOROOT
is discussed here:
$GOROOT
The root of the Go tree, often$HOME/go
. This defaults to the parent of the directory whereall.bash
is run. If you choose not to set$GOROOT
, you must run gomake instead of make or gmake when developing Go programs using the conventional makefiles.
CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
@CODE XML
,@ERRFLAG CHAR(1) = '0' OUTPUT
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DELETE tb_SampleTest
WHERE
CODE IN(
SELECT Item.value('.', 'VARCHAR(20)')
FROM @CODE.nodes('RecordList/ID') AS x(Item)
)
IF @@ROWCOUNT = 0
SET @ERRFLAG = 200
SET NOCOUNT OFF
Get string value delete
<RecordList>
<ID>1</ID>
<ID>2</ID>
</RecordList>
import time
year = time.strftime("%Y") # or "%y"
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.
You can review permissions using the following command.
Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell
Found this tip here (updated link, thanks "unbob"):
https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/
It fixed it for me.
A someone more direct answer is to fix the bug.
%SPARK_HOME%\bin\spark-class2.cmd; Line 54
Broken: set RUNNER="%JAVA_HOME%\bin\java"
Windows Style: set "RUNNER=%JAVA_HOME%\bin\java"
Otherwise, the RUNNER ends up with quotes, and the command
"%RUNNER%" -Xmx128m ...
ends up with double-quotes. The result is that the Program and File are treated as separate parameters.
If you want to change background color, try this:
plt.rcParams['figure.facecolor'] = 'white'
You don't need to use java variables. To include system env variables add the following to your application.properties
file:
spring.datasource.url = ${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/"nameofDB"
spring.datasource.username = ${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password = ${OPENSHIFT_MYSQL_DB_PASSWORD}
But the way suggested by @Stefan Isele is more preferable, because in this case you have to declare just one env variable: spring.profiles.active
. Spring will read the appropriate property file automatically by application-{profile-name}.properties
template.
There are basically 2 different ways to INSERT records without having an error:
1) When the IDENTITY_INSERT is set OFF. The PRIMARY KEY "ID" MUST NOT BE PRESENT
2) When the IDENTITY_INSERT is set ON. The PRIMARY KEY "ID" MUST BE PRESENT
As per the following example from the same Table created with an IDENTITY PRIMARY KEY:
CREATE TABLE [dbo].[Persons] (
ID INT IDENTITY(1,1) PRIMARY KEY,
LastName VARCHAR(40) NOT NULL,
FirstName VARCHAR(40)
);
1) In the first example, you can insert new records into the table without getting an error when the IDENTITY_INSERT is OFF. The PRIMARY KEY "ID" MUST NOT BE PRESENT from the "INSERT INTO" Statements and a unique ID value will be added automatically:. If the ID is present from the INSERT in this case, you will get the error "Cannot insert explicit value for identify column in table..."
SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE');
INSERT INTO Persons (FirstName,LastName)
VALUES ('JOE','BROWN');
OUTPUT of TABLE [dbo].[Persons] will be:
ID LastName FirstName
1 DOE Jane
2 BROWN JOE
2) In the Second example, you can insert new records into the table without getting an error when the IDENTITY_INSERT is ON. The PRIMARY KEY "ID" MUST BE PRESENT from the "INSERT INTO" Statements as long as the ID value does not already exist: If the ID is NOT present from the INSERT in this case, you will get the error "Explicit value must be specified for identity column table..."
SET IDENTITY_INSERT [dbo].[Persons] ON;
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (5,'JOHN','WHITE');
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (3,'JACK','BLACK');
OUTPUT of TABLE [dbo].[Persons] will be:
ID LastName FirstName
1 DOE Jane
2 BROWN JOE
3 BLACK JACK
5 WHITE JOHN
The simplest way to extract a number from a string is to use regular expressions and findall
.
>>> import re
>>> s = '300 gm'
>>> re.findall('\d+', s)
['300']
>>> s = '300 gm 200 kgm some more stuff a number: 439843'
>>> re.findall('\d+', s)
['300', '200', '439843']
It might be that you need something more complex, but this is a good first step.
Note that you'll still have to call int
on the result to get a proper numeric type (rather than another string):
>>> map(int, re.findall('\d+', s))
[300, 200, 439843]
You need to fix your selector. Although CSS syntax requires multiple classes to be space separated, selector syntax would require them to be directly concatenated, and dot prefixed:
$(".ui-icon.ui-icon-circle-triangle-w").text(...);
or better:
$(".ui-datepicker-prev > span").text(...);
If you are on MariaDB, no need to use stored procedures. Just use, for example:
ALTER TABLE table_name ADD COLUMN IF NOT EXISTS column_name tinyint(1) DEFAULT 0;
I was able to get what I needed using Martinho Fernandes' solution below. The code is:
var test = "My cow always gives milk";
var testRE = test.match("cow(.*)milk");
alert(testRE[1]);
You'll notice that I am alerting the testRE variable as an array. This is because testRE is returning as an array, for some reason. The output from:
My cow always gives milk
Changes into:
always gives
This worked for me:
git init
git remote add origin PATH/TO/REPO
git fetch
git reset origin/master # Required when the versioned files existed in path before "git init" of this repo.
git checkout -t origin/master
NOTE: -t
will set the upstream branch for you, if that is what you want, and it usually is.
According to Effective Java 2nd edition (Item 13):
"If a package-private top-level class (or interface) is used by only one class, consider making the top-level class a private nested class of the sole class that uses it (Item 22). This reduces its accessibility from all the classes in its package to the one class that uses it. But it is far more important to reduce the accessibility of a gratuitously public class than a package-private top-level class: ... "
The nested class may be static or non-static based on whether the member class needs access to the enclosing instance (Item 22).
$( document.activeElement )
Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation
"if you restore the primary key, you sure may revert it back to AUTO_INCREMENT"
There should be no question of whether or not it is desirable to "restore the PK property" and "restore the autoincrement property" of the ID column.
Given that it WAS an autoincrement in the prior definition of the table, it is quite likely that there exists some program that inserts into this table without providing an ID value (because the ID column is autoincrement anyway).
Any such program's operation will break by not restoring the autoincrement property.
If I am not wrong, in software application framework, based on the context, you can consider middleware
for the following roles that can be combined in order to perform certain activities in between the user request
and the application response
.
Just pass the images from an array to it like so
-(void) saveMePlease {
//Loop through the array here
for (int i=0:i<[arrayOfPhotos count]:i++){
NSString *file = [arrayOfPhotos objectAtIndex:i];
NSString *path = [get the path of the image like you would in DOCS FOLDER or whatever];
NSString *imagePath = [path stringByAppendingString:file];
UIImage *image = [[[UIImage alloc] initWithContentsOfFile:imagePath]autorelease];
//Now it will do this for each photo in the array
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
Sorry for typo's kinda just did this on the fly but you get the point
defaultdict
can do something like that for you.
Example:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(<class 'list'>, {})
>>> d['new'].append(10)
>>> d
defaultdict(<class 'list'>, {'new': [10]})
Remove all widths set using CSS and set white-space to nowrap like so:
.content-loader tr td {
white-space: nowrap;
}
I would also remove the fixed width from the container (or add overflow-x: scroll
to the container) if you want the fields to display in their entirety without it looking odd...
See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp
The registry path for official images (without a slash in the name) is library/<image>
. Try this instead:
docker pull registry.hub.docker.com/library/busybox
You might also be interested in C, it will also delete the end of line like D, but additionally it will put you in Insert mode at the cursor location.
If you use old version of MySQL you can always use \P combined with some nice piece of awk code. Interesting example here
http://www.dbasquare.com/2012/03/28/how-to-work-with-a-long-process-list-in-mysql/
Isn't it exactly what you need?
I post my final way of doing it based on the accepted answer:
@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {
private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
private String uploadsDirName;
@Override
public void init() throws ServletException {
super.init();
uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
File save = new File(uploadsDirName, getFilename(part) + "_"
+ System.currentTimeMillis());
final String absolutePath = save.getAbsolutePath();
log.debug(absolutePath);
part.write(absolutePath);
sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
}
}
// helpers
private static String getFilename(Part part) {
// courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
where :
@SuppressWarnings("serial")
class Controller extends HttpServlet {
static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
static ServletContext sc;
Logger log;
// private
// "/WEB-INF/app.properties" also works...
private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
private Properties properties;
@Override
public void init() throws ServletException {
super.init();
// synchronize !
if (sc == null) sc = getServletContext();
log = LoggerFactory.getLogger(this.getClass());
try {
loadProperties();
} catch (IOException e) {
throw new RuntimeException("Can't load properties file", e);
}
}
private void loadProperties() throws IOException {
try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
if (is == null)
throw new RuntimeException("Can't locate properties file");
properties = new Properties();
properties.load(is);
}
}
String property(final String key) {
return properties.getProperty(key);
}
}
and the /WEB-INF/app.properties :
upload.location=C:/_/
HTH and if you find a bug let me know
^
Add the string you're searching for (CTR
) to the regex like this:
^CTR
Example: regex
That should be enough!
However, if you need to get the text from the whole line in your language of choice, add a "match anything" pattern .*
:
^CTR.*
Example: more regex
If you want to get crazy, use the end of line matcher
$
Add that to the growing regex pattern:
^CTR.*$
Example: lets get crazy
Note: Depending on how and where you're using regex, you might have to use a multi-line modifier to get it to match multiple lines. There could be a whole discussion on the best strategy for picking lines out of a file to process them, and some of the strategies would require this:
Multi-line flag m
(this is specified in various ways in various languages/contexts)
/^CTR.*/gm
Example: we had to use m on regex101
?: Operator
If you want to shorten If/Else you can use ?:
operator as:
condition ? action-on-true : action-on-false(else)
For instance:
let gender = isMale ? 'Male' : 'Female';
In this case else
part is mandatory.
&& Operator
In another case, if you have only if
condition you can use &&
operator as:
condition && action;
For instance:
!this.settings && (this.settings = new TableSettings());
FYI: You have to try to avoid using if-else or at least decrease using it and try to replace it with Polymorphism or Inheritance. Go for being Anti-If guy.
If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.
var merge = _.merge(arr1, arr2);
Which is the short version of:
var merge = _.chain(arr1).zip(arr2).map(function(item) {
return _.merge.apply(null, item);
}).value();
Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.
var merge = _.map(arr1, function(item) {
return _.merge(item, _.find(arr2, { 'member' : item.member }));
});
You can easily convert this to a mixin. See the example below:
_.mixin({_x000D_
'mergeByKey' : function(arr1, arr2, key) {_x000D_
var criteria = {};_x000D_
criteria[key] = null;_x000D_
return _.map(arr1, function(item) {_x000D_
criteria[key] = item[key];_x000D_
return _.merge(item, _.find(arr2, criteria));_x000D_
});_x000D_
}_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
"country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
"country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
"name": 'yyyyyyyyyy',_x000D_
"age": 26_x000D_
}, {_x000D_
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
"name": 'xxxxxx',_x000D_
"age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
Older MySQL versions this is enough:
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice`) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
Nowdays, if you use MariaDB the subquery should be limited.
SELECT
`userName`,
`carPrice`
FROM `users`
LEFT JOIN (SELECT * FROM `cars` ORDER BY `carPrice` LIMIT 18446744073709551615) as `cars`
ON cars.belongsToUser=users.id
WHERE `id`='4'
Edit the file /etc/postgresql/<version>/main/pg_hba.conf
and find the following line:
local all postgres md5
Edit the line and change md5
at the end to trust
and save the file
Reload the postgresql service
$ sudo service postgresql reload
This will load the configuration files. Now you can modify the postgres
user by logging into the psql
shell
$ psql -U postgres
Update the postgres
user's password
alter user postgres with password 'secure-passwd-here';
Edit the file /etc/postgresql/<version>/main/pg_hba.conf
and change trust
back to md5
and save the file
Reload the postgresql service
$ sudo service postgresql reload
Verify that the password change is working
$ psql -U postgres -W
I think it will be sometime before we get to see access to the NFC as the pure security side of it like for example being able to walk past somebody brush past them and & get your phone to the zap the card details or simply Wave your phone over someone's wallet which They left on the desk.
I think the first step is for Apple to talk to banks and find more ways of securing cards and NFC before This will be allowed
Sub Scrape()
Dim Browser As InternetExplorer
Dim Document As htmlDocument
Dim Elements As IHTMLElementCollection
Dim Element As IHTMLElement
Set Browser = New InternetExplorer
Browser.Visible = True
Browser.navigate "http://www.stackoverflow.com"
Do While Browser.Busy And Not Browser.readyState = READYSTATE_COMPLETE
DoEvents
Loop
Set Document = Browser.Document
Set Elements = Document.getElementById("hmenus").getElementsByTagName("li")
For Each Element In Elements
Debug.Print Element.innerText
'Questions
'Tags
'Users
'Badges
'Unanswered
'Ask Question
Next Element
Set Document = Nothing
Set Browser = Nothing
End Sub
To use Vim to retab a set of files (e.g. all the *.ts files in a directory hierarchy) from say 2 spaces to 4 spaces you can try this from the command line:
find . -name '*.ts' -print0 | xargs -0 -n1 vim -e '+set ts=2 noet | retab! | set ts=4 et | retab | wq'
What this is doing is using find
to pass all the matching files to xargs
(the -print0 option on find works with the -0 option to xargs in order to handle files w/ spaces in the name).
xargs runs vim in ex mode (-e
) on each file executing the given ex command which is actually several commands, to change the existing leading spaces to tabs, resetting the tab stop and changing the tabs back to spaces and finally saving and exiting.
Running in ex mode prevents this: Vim: Warning: Input is not from a terminal
for each file.
This should work:
$('.myClass, .myOtherClass').removeClass('theclass');
You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.
It's the same as you would do in CSS.
In a multi-select option box, you can use $('#input1 :selected').length;
to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.
function refreshButtons () {
if ($('#input :selected').length == 0)
{
$('#submit').attr ('disabled', 'disabled');
}
else
{
$('#submit').removeAttr ('disabled');
}
}
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
If you just want to get the file names and not directory names then use :
dir /b /a-d > file.txt
If you face this issue only in Chrome and in IE, for instance, everything is fine, then just enable checkbutton "Disable cache" in Dev Tools (F12 -> "Network" tab) and clear history in the last hour.
I had this problem and above solution worked for me.
This worked for me for a format like YYYY.MM.DD-HH.MM.SS.fff. Attempting to make this code capable of accepting any string format will be like reinventing the wheel (i.e. there are functions for all this in Boost.
std::chrono::system_clock::time_point string_to_time_point(const std::string &str)
{
using namespace std;
using namespace std::chrono;
int yyyy, mm, dd, HH, MM, SS, fff;
char scanf_format[] = "%4d.%2d.%2d-%2d.%2d.%2d.%3d";
sscanf(str.c_str(), scanf_format, &yyyy, &mm, &dd, &HH, &MM, &SS, &fff);
tm ttm = tm();
ttm.tm_year = yyyy - 1900; // Year since 1900
ttm.tm_mon = mm - 1; // Month since January
ttm.tm_mday = dd; // Day of the month [1-31]
ttm.tm_hour = HH; // Hour of the day [00-23]
ttm.tm_min = MM;
ttm.tm_sec = SS;
time_t ttime_t = mktime(&ttm);
system_clock::time_point time_point_result = std::chrono::system_clock::from_time_t(ttime_t);
time_point_result += std::chrono::milliseconds(fff);
return time_point_result;
}
std::string time_point_to_string(std::chrono::system_clock::time_point &tp)
{
using namespace std;
using namespace std::chrono;
auto ttime_t = system_clock::to_time_t(tp);
auto tp_sec = system_clock::from_time_t(ttime_t);
milliseconds ms = duration_cast<milliseconds>(tp - tp_sec);
std::tm * ttm = localtime(&ttime_t);
char date_time_format[] = "%Y.%m.%d-%H.%M.%S";
char time_str[] = "yyyy.mm.dd.HH-MM.SS.fff";
strftime(time_str, strlen(time_str), date_time_format, ttm);
string result(time_str);
result.append(".");
result.append(to_string(ms.count()));
return result;
}
I prefer
if(ddl.Items.FindByValue(string) != null)
{
ddl.Items.FindByValue(string).Selected = true;
}
Replace ddl with the dropdownlist ID and string with your string variable name or value.
rand(1,20)
Docs for PHP's rand function are here:
http://php.net/manual/en/function.rand.php
Use the srand()
function to set the random number generator's seed value.
Just call moment as a function without any arguments:
moment()
For timezone information with moment, look at the moment-timezone
package: http://momentjs.com/timezone/
Life span of java Thread is over after completion of run()
method. Same thread can't be started again.
Looper transforms normal Thread
into a message loop. Key methods of Looper
are :
void prepare ()
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().
void loop ()
Run the message queue in this thread. Be sure to call quit() to end the loop.
void quit()
Quits the looper.
Causes the loop() method to terminate without processing any more messages in the message queue.
This mindorks article by Janishar explains the core concepts in nice way.
Looper
is associated with a Thread. If you need Looper
on UI thread, Looper.getMainLooper()
will return associated thread.
You need Looper
to be associated with a Handler.
Looper
, Handler
, and HandlerThread
are the Android’s way of solving the problems of asynchronous programming.
Once you have Handler
, you can call below APIs.
post (Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
boolean sendMessage (Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.
HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes
In some scenarios, you can't run Runnable
tasks on UI Thread.
e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream
In these cases, HandlerThread
is useful. You can get Looper
object from HandlerThread
and create a Handler
on HandlerThread
instead of main thread.
The HandlerThread code will be like this:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
Refer to below post for example code:
I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach
Class First {
private Second second;
public First(int num, String str) {
if(second== null)
{
//when junit runs, you get the mocked object(not null), hence don't
//initialize
second = new Second(str);
}
this.num = num;
}
... // some other methods
}
And, for test:
class TestFirst{
@InjectMock
First first;//inject mock the real testable class
@Mock
Second second
testMethod(){
//now you can play around with any method of the Second class using its
//mocked object(second),like:
when(second.getSomething(String.class)).thenReturn(null);
}
}
If you're not using a remote repository (like artifactory), use plain old:
mvn clean install
Pretty old topic but AFAIK, if you run your own repository (eg: with artifactory) to share jar among your team(s), you might want to use
mvn clean deploy
instead.
This way, your continuous integration server can be sure that all dependencies are correctly pushed into your remote repository. If you missed one, mvn will not be able to find it into your CI local m2 repository.
May be this can help other guys: I had the same problem, and after looking with Google I found that can be because of the permissions of the folder... So, you need first to add permissions...
$ chmod 777 share_folder
Then run again
$ sudo mount -t vboxsf D:\share_folder_vm \share_folder
Check the answers here: Error mounting VirtualBox shared folders in an Ubuntu guest...
@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @type = "date" } })
this works well
I tried to connect my servo to the Arduino 5V pin, but the processor and that is why I got this failure
avrdude: stk500_recv(): programmer is not responding
Solution: buy a new Arduino and external 5 V power supply for the servo.
if you used typescript add config to the MongoOptions
const MongoOptions: MongoClientOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
const client = await MongoClient.connect(url, MongoOptions);
if you not used typescript
const MongoOptions= {
useNewUrlParser: true,
useUnifiedTopology: true,
};
try following to see all instances of python
whereis python
which python
Then remove all instances using:
sudo apt autoremove python
repeat sudo apt autoremove python(for all versions) that should do it, then install Anaconda and manage Pythons however you like if you need to reinstall it.
You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.
example:
if (wc_get_page_id( 'cart' ) == get_the_ID()) {
// Do something.
}
Using UNION
automatically removes duplicate rows unless you specify UNION ALL
:
http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx
Try a different protocol. git:// may have problems from your firewall, for example; try a git clone with https: instead.
Is there a particular reason you have chosen XML config files? I have done XML configs in the past, and they have often turned out to be more of a headache than anything else.
I guess the real question is whether using something like the Preferences API might work better in your situation.
Reasons to use the Preferences API over a roll-your-own XML solution:
Avoids typical XML ugliness (DocumentFactory, etc), along with avoiding 3rd party libraries to provide the XML backend
Built in support for default values (no special handling required for missing/corrupt/invalid entries)
No need to sanitize values for XML storage (CDATA wrapping, etc)
Guaranteed status of the backing store (no need to constantly write XML out to disk)
Backing store is configurable (file on disk, LDAP, etc.)
Multi-threaded access to all preferences for free
With dplyr 0.7.2
, you can use the very useful case_when
function :
x=read.table(
text="V1 V2 V3 V4
1 1 2 3 5
2 2 4 4 1
3 1 4 1 1
4 4 5 1 3
5 5 5 5 4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
x$V2==4 & x$V3!=1 ~ 2,
TRUE ~ 0)
Expressed with dplyr::mutate
, it gives:
x = x %>% mutate(
V5 = case_when(
V1==1 & V2!=4 ~ 1,
V2==4 & V3!=1 ~ 2,
TRUE ~ 0
)
)
Please note that NA
are not treated specially, as it can be misleading. The function will return NA
only when no condition is matched. If you put a line with TRUE ~ ...
, like I did in my example, the return value will then never be NA
.
Therefore, you have to expressively tell case_when
to put NA
where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_
. Hint: the dplyr::coalesce()
function can be really useful here sometimes!
Moreover, please note that NA
alone will usually not work, you have to put special NA
values : NA_integer_
, NA_character_
or NA_real_
.
All the provided answers assume that you are able to unplug and reconnect the USB cable. In situations where this is not possible (e.g., when you are remote), you can do the following to essentially do what the suggested udev rules would do on re-plug:
lsusb
Find the device you care about, e.g.:
Bus 003 Device 005: ID 18d1:4ee4 Google Inc. Nexus
Take note of the bus number it is on and then execute, e.g. for bus 003
:
sudo chmod a+w /dev/bus/usb/003/*
Clearly this may be more permissive than you want (there may be more devices attached than just this one), but you get the idea.
One of the biggest uses is that you can bind UI components to one, and they'll respond appropriately if the collection's contents change. For example, if you bind a ListView's ItemsSource to one, the ListView's contents will automatically update if you modify the collection.
EDIT: Here's some sample code from MSDN: http://msdn.microsoft.com/en-us/library/ms748365.aspx
In C#, hooking the ListBox to the collection could be as easy as
listBox.ItemsSource = NameListData;
though if you haven't hooked the list up as a static resource and defined NameItemTemplate you may want to override PersonName's ToString(). For example:
public override ToString()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
**UPDATE: ** Please ignore this reply. I did not consider the possibility that for the struct, the value was uninitialized but just happened to be 0. There is not an initialization difference between struct and class.
I am seeing another different between structs and classes having to do with default initialization.
struct Foo {
int a;
};
class Bar {
int a;
};
class Tester {
Foo m_Foo = Foo();
Bar m_Bar = Bar();
public:
Tester() {}
};
int main() {
auto myTester = Tester();
}
Run that code and examine myTester. You'll find that for m_Foo, the struct, m_Foo.a has been initialized to 0, but for m_Bar, the class, m_Bar.a is uninitialized. So there does appear to be a difference in what the default constructor does for struct vs. class. I'm seeing this with Visual Studio.
The upcoming ECMAScript language specification, edition 6, includes Unicode-aware regular expressions. Support must be enabled with the u
modifier on the regex. See Unicode-aware regular expressions in ES6.
Until ES 6 is finished and widely adopted among browser vendors you're still on your own, though. Update: There is now a transpiler named regexpu that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. Try it out online.
Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.
Check your expectations here: Javascript RegExp Unicode Character Class tester (Edit: the original page is down, the Internet Archive still has a copy.)
Flagrant Badassery has an article on JavaScript, Regex, and Unicode that sheds some light on the matter.
Also read Regex and Unicode here on SO. Probably you have to build your own "punctuation character class".
Check out the Regular Expression: Match Unicode Block Range builder, which lets you build a JavaScript regular expression that matches characters that fall in any number of specified Unicode blocks.
I just did it for the "General Punctuation" and "Supplemental Punctuation" sub-ranges, and the result is as simple and straight-forward as I would have expected it:
[\u2000-\u206F\u2E00-\u2E7F]
There also is XRegExp, a project that brings Unicode support to JavaScript by offering an alternative regex engine with extended capabilities.
And of course, required reading: mathiasbynens.be - JavaScript has a Unicode problem:
? is called Ternary (conditional) operator : example
This will not help for the browser, but you can also define a proxy in your code to use with a HTTP client:
// proxy
private static final String PROXY = "123.123.123.123";
// proxy host
private static final HttpHost PROXY_HOST = new HttpHost(PROXY, 8080);
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, PROXY_HOST);
The version of EnterpriseLibrary on my machine had other parameters. This was working:
SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
retval.Direction = System.Data.ParameterDirection.ReturnValue;
cmd.Parameters.Add(retval);
db.ExecuteNonQuery(cmd);
object o = cmd.Parameters["@ReturnValue"].Value;
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
Here you are ;-)
<script type="text/javascript">
alert("Hello there.\nI am on a second line ;-)")
</script>
Step 1: Create separate component like this
Component name : pagebase.js
Step 2: Inside this use code this
export const BASE_URL = "http://192.168.10.10:4848/";
export const API_KEY = 'key_token';
Step 3: Use it in any component, for using it first import this component then use it. Import it and use it:
import * as base from "./pagebase";
base.BASE_URL
base.API_KEY
I've approached this in a different way. I've created a function which simply returns true or false.. Usage:
If FieldContains("A;B;C",MyFieldVariable,True|False) then
.. Do Something
End If
Public Function FieldContains(Searchfor As String, SearchField As String, AllowNulls As Boolean) As Boolean
If AllowNulls And Len(SearchField) = 0 Then Return True
For Each strSearchFor As String In Searchfor.Split(";")
If UCase(SearchField) = UCase(strSearchFor) Then
Return True
End If
Next
Return False
End Function
You can even simulate a queue using only one stack. The second (temporary) stack can be simulated by the call stack of recursive calls to the insert method.
The principle stays the same when inserting a new element into the queue:
A Queue class using only one Stack, would be as follows:
public class SimulatedQueue<E> {
private java.util.Stack<E> stack = new java.util.Stack<E>();
public void insert(E elem) {
if (!stack.empty()) {
E topElem = stack.pop();
insert(elem);
stack.push(topElem);
}
else
stack.push(elem);
}
public E remove() {
return stack.pop();
}
}
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
You could wrap your maven command in a bash script:
#!/bin/bash
export YOUR_VAR=thevalue
mvn test
unset YOUR_VAR
This has been answered by a lot of people, but I feel like the simplest solution has been left out.
SQL SERVER (I believe its 2012+) has implicit string equivalents for DATETIME2 as shown here
Look at the section on "Supported string literal formats for datetime2"
To answer the OPs question explicitly:
DECLARE @myVar NCHAR(32)
DECLARE @myDt DATETIME2
SELECT @myVar = @GETDATE()
SELECT @myDt = @myVar
PRINT(@myVar)
PRINT(@myDt)
output:
Jan 23 2019 12:24PM
2019-01-23 12:24:00.0000000
Note:
The first variable (myVar
) is actually holding the value '2019-01-23 12:24:00.0000000'
as well. It just gets formatted to Jan 23 2019 12:24PM
due to default formatting set for SQL SERVER that gets called on when you use PRINT
. Don't get tripped up here by that, the actual string in (myVer)
= '2019-01-23 12:24:00.0000000'
I'm not sure I understand the question correctly, but if you want to prevent people from writing in the input field you can use the disabled
attribute.
<input disabled="disabled" id="price_from" value="price from ">
If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
Try it ..
UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
FROM STAGING b
WHERE a.ID = b.ID)
WHERE EXISTS (SELECT 1
FROM STAGING b
WHERE a.ID=b.ID
);
One of the best ways:
data = pd.DataFrame(digits.data)
Digits is the sklearn dataframe and I converted it to a pandas DataFrame
Current there are four sample projects:
The accepted answer is awesome.
But there is something missing:
So I created the Hello Async repository to add the missing things:
The accepted answer already provides sample code snippets for Async Code Inline, Async Action Generator and Redux Thunk. For the sake of completeness, I provide code snippets for Redux Saga:
// actions.js
export const showNotification = (id, text) => {
return { type: 'SHOW_NOTIFICATION', id, text }
}
export const hideNotification = (id) => {
return { type: 'HIDE_NOTIFICATION', id }
}
export const showNotificationWithTimeout = (text) => {
return { type: 'SHOW_NOTIFICATION_WITH_TIMEOUT', text }
}
Actions are simple and pure.
// component.js
import { connect } from 'react-redux'
// ...
this.props.showNotificationWithTimeout('You just logged in.')
// ...
export default connect(
mapStateToProps,
{ showNotificationWithTimeout }
)(MyComponent)
Nothing is special with component.
// sagas.js
import { takeEvery, delay } from 'redux-saga'
import { put } from 'redux-saga/effects'
import { showNotification, hideNotification } from './actions'
// Worker saga
let nextNotificationId = 0
function* showNotificationWithTimeout (action) {
const id = nextNotificationId++
yield put(showNotification(id, action.text))
yield delay(5000)
yield put(hideNotification(id))
}
// Watcher saga, will invoke worker saga above upon action 'SHOW_NOTIFICATION_WITH_TIMEOUT'
function* notificationSaga () {
yield takeEvery('SHOW_NOTIFICATION_WITH_TIMEOUT', showNotificationWithTimeout)
}
export default notificationSaga
Sagas are based on ES6 Generators
// index.js
import createSagaMiddleware from 'redux-saga'
import saga from './sagas'
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(saga)
Please refer to the runnable project if the code snippets above don't answer all of your questions.
For a API v3 solution, refer to:
http://blog.enbake.com/draw-circle-with-google-maps-api-v3
It creates circle around points and then show markers within and out of the range with different colors. They also calculate dynamic radius but in your case radius is fixed so may be less work.
You should make x
and y
numpy arrays, not lists:
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
0.478,0.335,0.365,0.424,0.390,0.585,0.511])
With this change, it produces the expect plot. If they are lists, m * x
will not produce the result you expect, but an empty list. Note that m
is anumpy.float64
scalar, not a standard Python float
.
I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:
In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]
while multiplying a list with a float gives an error (as I think it should):
In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'
The weird thing is that multiplying a Python list with a Numpy scalar apparently works:
In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []
In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]
In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]
So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:
In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123, 2.123, 3.123])
You can try to download and install TheGun Text Editor. Which can help you to open large csv file easily.
You can check detailed article here https://developingdaily.com/article/how-to/what-is-csv-file-and-how-to-open-a-large-csv-file/82
Of course. if you are running on Tensorflow or CNTk backends, your code will run on your GPU devices defaultly.But if Theano backends, you can use following
Theano flags:
"THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py"
I stumbled on this question while trying to do the same thing (I think). Here is how I did it:
df['index_col'] = df.index
You can then sort on the new index column, if you like.
Begin by installing this package through Composer. Run the following from the terminal:
composer require "laravelcollective/html":"^5.3.0"
Next, add your new provider to the providers array of config/app.php:
'providers' => [
// ...
Collective\Html\HtmlServiceProvider::class,
// ...
],
Finally, add two class aliases to the aliases array of config/app.php:
'aliases' => [
// ...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
// ...
],
SRC:
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
redirect with query string
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
// var url = '@Url.Action("Details", "Artists",new { NestId = '+NestId+' })';
var url = '@ Url.Content("~/Artists/Details?NestId =' + NestId + '")'
window.location.href = url;
})
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
_x000D_
What's wrong with the printStacktrace()
method provided by Throwable
(and thus every exception)? It shows all the info you requested, including the type, message, and stack trace of the root exception and all (nested) causes. In Java 7, it even shows you the information about "supressed" exceptions that might occur in a try-with-resources statement.
Of course you wouldn't want to write to System.err
, which the no-argument version of the method does, so instead use one of the available overloads.
In particular, if you just want to get a String:
Exception e = ...
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionDetails = sw.toString();
If you happen to use the great Guava library, it provides a utility method doing this: com.google.common.base.Throwables#getStackTraceAsString(Throwable)
.
It is actually executing the command, changing the directory to some_directory
, however, this is performed in a sub-process shell, and affects neither make nor the shell you're working from.
If you're looking to perform more tasks within some_directory
, you need to add a semi-colon and append the other commands as well. Note that you cannot use newlines as they are interpreted by make as the end of the rule, so any newlines you use for clarity needs to be escaped by a backslash.
For example:
all:
cd some_dir; echo "I'm in some_dir"; \
gcc -Wall -o myTest myTest.c
Note also that the semicolon is necessary between every command even though you add a backslash and a newline. This is due to the fact that the entire string is parsed as a single line by the shell. As noted in the comments, you should use '&&' to join commands, which mean they only get executed if the preceding command was successful.
all:
cd some_dir && echo "I'm in some_dir" && \
gcc -Wall -o myTest myTest.c
This is especially crucial when doing destructive work, such as clean-up, as you'll otherwise destroy the wrong stuff, should the cd
fail for whatever reason.
A common usage though is to call make in the sub directory, which you might want to look into. There's a command line option for this so you don't have to call cd
yourself, so your rule would look like this
all:
$(MAKE) -C some_dir all
which will change into some_dir
and execute the Makefile
in there with the target "all". As a best practice, use $(MAKE)
instead of calling make
directly, as it'll take care to call the right make instance (if you, for example, use a special make version for your build environment), as well as provide slightly different behavior when running using certain switches, such as -t
.
For the record, make always echos the command it executes (unless explicitly suppressed), even if it has no output, which is what you're seeing.
SELECT o.OrderId,
--MAX(o.NegotiatedPrice, o.SuggestedPrice)
(SELECT MAX(v) FROM (VALUES (o.NegotiatedPrice), (o.SuggestedPrice)) AS value(v)) as ChoosenPrice
FROM Order o
Links with href="#" should almost always be replaced with a button element:
<button class="someclass">Text</button>
Using links with href="#" is also an accessibility concern as these links will be visible to screen readers, which will read out "Link - Text" but if the user clicks it won't go anywhere.
You can use Enumeration
:
Hashtable<Integer, String> table = ...
Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
Integer key = enumKey.nextElement();
String val = table.get(key);
if(key==0 && val.equals("0"))
table.remove(key);
}
Must it be mutable? Use a list. Must it not be mutable? Use a tuple.
Otherwise, it's a question of choice.
For collections of heterogeneous objects (like a address broken into name, street, city, state and zip) I prefer to use a tuple. They can always be easily promoted to named tuples.
Likewise, if the collection is going to be iterated over, I prefer a list. If it's just a container to hold multiple objects as one, I prefer a tuple.
I had this problem and it was caused by the second level cache:
Hence, because the cache wasn't invalidated, hibernate assumed that it was dealing with a detached instance of the same entity.
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
Has anyone considered the answer provided here?
I suppose the objective-c equivalent would be
+ (BOOL)isSimulator {
NSOperatingSystemVersion ios9 = {9, 0, 0};
NSProcessInfo *processInfo = [NSProcessInfo processInfo];
if ([processInfo isOperatingSystemAtLeastVersion:ios9]) {
NSDictionary<NSString *, NSString *> *environment = [processInfo environment];
NSString *simulator = [environment objectForKey:@"SIMULATOR_DEVICE_NAME"];
return simulator != nil;
} else {
UIDevice *currentDevice = [UIDevice currentDevice];
return ([currentDevice.model rangeOfString:@"Simulator"].location != NSNotFound);
}
}
Just for reference, here is a benchmark of different technique rendering performances,
http://jsperf.com/zp-string-concatenation/6
m,
I recommend you to read more about the this keyword.
You cannot expect "this" to select the "select" tag in this case.
What you want to do in this case is use obj.id
to get the id of select tag.
There is a Yahoo YUI component (Browser History Manager) which can handle this: http://developer.yahoo.com/yui/history/
You can use a defaultdict for this.
from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')
This is slightly more efficient than setdefault
since you don't end up creating new lists that you don't end up using. Every call to setdefault
is going to create a new list, even if the item already exists in the dictionary.
It maybe not exactly what you are looking for, but
Google's Chart API is pretty cool and easy to use.
Here the official link for jdk source. http://www.oracle.com/technetwork/java/javase/downloads/index.html (you may need to scroll to the bottom of the page)
Are you trying to pass the command line arguments to the program AS you launch it? I am working on something right now that does exactly this, and it was a lot simpler than I thought. If I go into the command line, and type
C:\folder\app.exe/xC:\folder\file.txt
then my application launches, and creates a file in the specified directory with the specified name.
I wanted to do this through a Powershell script on a remote machine, and figured out that all I needed to do was put
$s = New-PSSession -computername NAME -credential LOGIN
Invoke-Command -session $s -scriptblock {C:\folder\app.exe /xC:\folder\file.txt}
Remove-PSSession $s
(I have a bunch more similar commands inside the session, this is just the minimum it requires to run) notice the space between the executable, and the command line arguments. It works for me, but I am not sure exactly how your application works, or if that is even how you pass arguments to it.
*I can also have my application push the file back to my own local computer by changing the script-block to
C:\folder\app.exe /x"\\LocalPC\DATA (C)\localfolder\localfile.txt"
You need the quotes if your file-path has a space in it.
EDIT: actually, this brought up some silly problems with Powershell launching the application as a service or something, so I did some searching, and figured out that you can call CMD to execute commands for you on the remote computer. This way, the command is carried out EXACTLY as if you had just typed it into a CMD window on the remote machine. Put the command in the scriptblock into double quotes, and then put a cmd.exe /C before it. like this:
cmd.exe /C "C:\folder\app.exe/xC:\folder\file.txt"
this solved all of the problems that I have been having recently.
EDIT EDIT: Had more problems, and found a much better way to do it.
start-process -filepath C:\folder\app.exe -argumentlist "/xC:\folder\file.txt"
and this doesn't hang up your terminal window waiting for the remote process to end. Just make sure you have a way to terminate the process if it doesn't do that on it's own. (mine doesn't, required the coding of another argument)
DISCLAIMER: This answer was written in 2008.
Since then, PHP has given us
password_hash
andpassword_verify
and, since their introduction, they are the recommended password hashing & checking method.The theory of the answer is still a good read though.
\0
in it, which can seriously weaken security.)The objective behind hashing passwords is simple: preventing malicious access to user accounts by compromising the database. So the goal of password hashing is to deter a hacker or cracker by costing them too much time or money to calculate the plain-text passwords. And time/cost are the best deterrents in your arsenal.
Another reason that you want a good, robust hash on a user accounts is to give you enough time to change all the passwords in the system. If your database is compromised you will need enough time to at least lock the system down, if not change every password in the database.
Jeremiah Grossman, CTO of Whitehat Security, stated on White Hat Security blog after a recent password recovery that required brute-force breaking of his password protection:
Interestingly, in living out this nightmare, I learned A LOT I didn’t know about password cracking, storage, and complexity. I’ve come to appreciate why password storage is ever so much more important than password complexity. If you don’t know how your password is stored, then all you really can depend upon is complexity. This might be common knowledge to password and crypto pros, but for the average InfoSec or Web Security expert, I highly doubt it.
(Emphasis mine.)
Entropy. (Not that I fully subscribe to Randall's viewpoint.)
In short, entropy is how much variation is within the password. When a password is only lowercase roman letters, that's only 26 characters. That isn't much variation. Alpha-numeric passwords are better, with 36 characters. But allowing upper and lower case, with symbols, is roughly 96 characters. That's a lot better than just letters. One problem is, to make our passwords memorable we insert patterns—which reduces entropy. Oops!
Password entropy is approximated easily. Using the full range of ascii characters (roughly 96 typeable characters) yields an entropy of 6.6 per character, which at 8 characters for a password is still too low (52.679 bits of entropy) for future security. But the good news is: longer passwords, and passwords with unicode characters, really increase the entropy of a password and make it harder to crack.
There's a longer discussion of password entropy on the Crypto StackExchange site. A good Google search will also turn up a lot of results.
In the comments I talked with @popnoodles, who pointed out that enforcing a password policy of X length with X many letters, numbers, symbols, etc, can actually reduce entropy by making the password scheme more predictable. I do agree. Randomess, as truly random as possible, is always the safest but least memorable solution.
So far as I've been able to tell, making the world's best password is a Catch-22. Either its not memorable, too predictable, too short, too many unicode characters (hard to type on a Windows/Mobile device), too long, etc. No password is truly good enough for our purposes, so we must protect them as though they were in Fort Knox.
Bcrypt and scrypt are the current best practices. Scrypt will be better than bcrypt in time, but it hasn't seen adoption as a standard by Linux/Unix or by webservers, and hasn't had in-depth reviews of its algorithm posted yet. But still, the future of the algorithm does look promising. If you are working with Ruby there is an scrypt gem that will help you out, and Node.js now has its own scrypt package. You can use Scrypt in PHP either via the Scrypt extension or the Libsodium extension (both are available in PECL).
I highly suggest reading the documentation for the crypt function if you want to understand how to use bcrypt, or finding yourself a good wrapper or use something like PHPASS for a more legacy implementation. I recommend a minimum of 12 rounds of bcrypt, if not 15 to 18.
I changed my mind about using bcrypt when I learned that bcrypt only uses blowfish's key schedule, with a variable cost mechanism. The latter lets you increase the cost to brute-force a password by increasing blowfish's already expensive key schedule.
I almost can't imagine this situation anymore. PHPASS supports PHP 3.0.18 through 5.3, so it is usable on almost every installation imaginable—and should be used if you don't know for certain that your environment supports bcrypt.
But suppose that you cannot use bcrypt or PHPASS at all. What then?
Try an implementation of PDKBF2 with the maximum number of rounds that your environment/application/user-perception can tolerate. The lowest number I'd recommend is 2500 rounds. Also, make sure to use hash_hmac() if it is available to make the operation harder to reproduce.
Coming in PHP 5.5 is a full password protection library that abstracts away any pains of working with bcrypt. While most of us are stuck with PHP 5.2 and 5.3 in most common environments, especially shared hosts, @ircmaxell has built a compatibility layer for the coming API that is backward compatible to PHP 5.3.7.
The computational power required to actually crack a hashed password doesn't exist. The only way for computers to "crack" a password is to recreate it and simulate the hashing algorithm used to secure it. The speed of the hash is linearly related to its ability to be brute-forced. Worse still, most hash algorithms can be easily parallelized to perform even faster. This is why costly schemes like bcrypt and scrypt are so important.
You cannot possibly foresee all threats or avenues of attack, and so you must make your best effort to protect your users up front. If you do not, then you might even miss the fact that you were attacked until it's too late... and you're liable. To avoid that situation, act paranoid to begin with. Attack your own software (internally) and attempt to steal user credentials, or modify other user's accounts or access their data. If you don't test the security of your system, then you cannot blame anyone but yourself.
Lastly: I am not a cryptographer. Whatever I've said is my opinion, but I happen to think it's based on good ol' common sense ... and lots of reading. Remember, be as paranoid as possible, make things as hard to intrude as possible, and then, if you are still worried, contact a white-hat hacker or cryptographer to see what they say about your code/system.
I have try twitter geo api, failed.
Google map api, failed, so far, no way you can get city limit by any api.
twitter api geo endpoint will NOT give you city boundary,
what they provide you is ONLY bounding box with 5 point(lat, long)
I have had good experiences with Rational Purify. I have also heard nice things about Valgrind
Don't bother with open/readdir and use glob
instead:
foreach(glob($log_directory.'/*.*') as $file) {
...
}
>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'
Wow, I had the same problem, but a line of code resolved my problem. I wrote
$last_child_topic.find( "*" ).prop( "disabled", true );
$last_child_topic.find( "option" ).prop( "disabled", false ); //This seems to work on mine
I send the form to a php script then it prints the correct value for each options while it was "null" before.
Tell me if this works out. I wonder if this only works on mine somehow.
If you want to analyze, repair and optimize all tables in all databases in your MySQL server, you can do this in one go from the command line. You will need root to do that though.
mysqlcheck -u root -p --auto-repair --optimize --all-databases
Once you run that, you will be prompted to enter your MySQL root password. After that, it will start and you will see results as it's happening.
Example output:
yourdbname1.yourdbtable1 OK
yourdbname2.yourdbtable2 Table is already up to date
yourdbname3.yourdbtable3
note : Table does not support optimize, doing recreate + analyze instead
status : OK
etc..
etc...
Repairing tables
yourdbname10.yourdbtable10
warning : Number of rows changed from 121378 to 81562
status : OK
If you don't know the root password and are using WHM, you can change it from within WHM by going to: Home > SQL Services > MySQL Root Password
No.
if ([[UIScreen mainScreen] bounds].size.height > 960)
on iPhone 5 is wrong
if ([[UIScreen mainScreen] bounds].size.height == 568)
You're right, no API at all that I'm aware to export PrivateKey marked as non-exportable. But if you patch (in memory) normal APIs, you can use the normal way to export :)
There is a new version of mimikatz that also support CNG Export (Windows Vista / 7 / 2008 ...)
Run it and enter the following commands in its prompt:
privilege::debug
(unless you already have it or target only CryptoApi)crypto::patchcng
(nt 6) and/or crypto::patchcapi
(nt 5 & 6)crypto::exportCertificates
and/or crypto::exportCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE
The exported .pfx files are password protected with the password "mimikatz"
You can use the built in dir()
function to get a list of all the attributes a module has. Try this at the command line to see how it works.
>>> import moduleName
>>> dir(moduleName)
Also, you can use the hasattr(module_name, "attr_name")
function to find out if a module has a specific attribute.
See the Guide to Python introspection for more information.
Building on Chad's answer, you also want to add that function to the onload event to ensure it is resized when the page loads as well.
jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame()
{
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
}
it's file:///android_asset/... not file:///android_assets/... notice the plural of assets is wrong even if your file name is assets
Correct answer is: $("#selElement_Id option:selected").removeAttr("selected");
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
You could use WITH to define your expressions. Then do a simple Sub-SELECT to access those definitions.
CREATE VIEW MyView
AS
WITH MyVars (SomeVar, Var2)
AS (
SELECT
'something' AS 'SomeVar',
123 AS 'Var2'
)
SELECT *
FROM MyTable
WHERE x = (SELECT SomeVar FROM MyVars)
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
An array "decays" into a pointer to its first element, so scanf("%s", string)
is equivalent to scanf("%s", &string[0])
. On the other hand, scanf("%s", &string)
passes a pointer-to-char[256]
, but it points to the same place.
Then scanf
, when processing the tail of its argument list, will try to pull out a char *
. That's the Right Thing when you've passed in string
or &string[0]
, but when you've passed in &string
you're depending on something that the language standard doesn't guarantee, namely that the pointers &string
and &string[0]
-- pointers to objects of different types and sizes that start at the same place -- are represented the same way.
I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)
You can make a helper for that: Make a helper function so that you can use it everywhere in your application
function getStandardResponse(status,message,data){
return {
status: status,
message : message,
data : data
}
}
Here is my topic route where I am trying to get all topics
router.get('/', async (req, res) => {
const topics = await Topic.find().sort('name');
return res.json(getStandardResponse(true, "", topics));
});
Response we get
{
"status": true,
"message": "",
"data": [
{
"description": "sqswqswqs",
"timestamp": "2019-11-29T12:46:21.633Z",
"_id": "5de1131d8f7be5395080f7b9",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031579309.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "sqswqswqs",
"timestamp": "2019-11-29T12:50:35.627Z",
"_id": "5de1141bc902041b58377218",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575031835605.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": " ",
"timestamp": "2019-11-30T06:51:18.936Z",
"_id": "5de211665c3f2c26c00fe64f",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096678917.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "null",
"timestamp": "2019-11-30T06:51:41.060Z",
"_id": "5de2117d5c3f2c26c00fe650",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575096701051.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "swqdwqd wwwwdwq",
"timestamp": "2019-11-30T07:05:22.398Z",
"_id": "5de214b2964be62d78358f87",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575097522372.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
},
{
"description": "swqdwqd wwwwdwq",
"timestamp": "2019-11-30T07:36:48.894Z",
"_id": "5de21c1006f2b81790276f6a",
"name": "topics test xqxq",
"thumbnail": "waterfall-or-agile-inforgraphics-thumbnail-1575099408870.jpg",
"category_id": "5de0fe0b4f76c22ebce2b70a",
"__v": 0
}
]
}
Promise can be cancelled with the help of AbortController
.
Is there a method for clearing then: yes you can reject the promise with
AbortController
object and then thepromise
will bypass all then blocks and go directly to the catch block.
Example:
import "abortcontroller-polyfill";
let controller = new window.AbortController();
let signal = controller.signal;
let elem = document.querySelector("#status")
let example = (signal) => {
return new Promise((resolve, reject) => {
let timeout = setTimeout(() => {
elem.textContent = "Promise resolved";
resolve("resolved")
}, 2000);
signal.addEventListener('abort', () => {
elem.textContent = "Promise rejected";
clearInterval(timeout);
reject("Promise aborted")
});
});
}
function cancelPromise() {
controller.abort()
console.log(controller);
}
example(signal)
.then(data => {
console.log(data);
})
.catch(error => {
console.log("Catch: ", error)
});
document.getElementById('abort-btn').addEventListener('click', cancelPromise);
Html
<button type="button" id="abort-btn" onclick="abort()">Abort</button>
<div id="status"> </div>
Note: need to add polyfill, not supported in all browser.
Live Example
ADB will often fail if there is a newline in adb_usb.ini
. Remove it, restart it, and that will often solve the problem (at least for me anyway).
I had a similar issue as you, although I was trying to use start
to open Chrome and using the file path. I used only start chrome.exe
and it opened just fine. You may want to try to do the same with exe file. Using the file path may be unnecessary.
Here are some examples (using the file name you gave in a comment on another answer):
Instead of C:\Program^ Files\temp.exe
you can try temp.exe
.
Instead of start C:\Program^ Files\temp.exe
you can try start
temp.exe
I had the same problem, and using this solved it.
var w = window.innerWidth;
var h = window.innerHeight;
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
You have to be careful when you say "rollback". If you used to have one version of a file in commit $A, and then later made two changes in two separate commits $B and $C (so what you are seeing is the third iteration of the file), and if you say "I want to roll back to the first one", do you really mean it?
If you want to get rid of the changes both the second and the third iteration, it is very simple:
$ git checkout $A file
and then you commit the result. The command asks "I want to check out the file from the state recorded by the commit $A".
On the other hand, what you meant is to get rid of the change the second iteration (i.e. commit $B) brought in, while keeping what commit $C did to the file, you would want to revert $B
$ git revert $B
Note that whoever created commit $B may not have been very disciplined and may have committed totally unrelated change in the same commit, and this revert may touch files other than file you see offending changes, so you may want to check the result carefully after doing so.
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
Spring exposes the current HttpServletRequest
object (as well as the current HttpSession
object) through a wrapper object of type ServletRequestAttributes
. This wrapper object is bound to ThreadLocal and is obtained by calling the static
method RequestContextHolder.currentRequestAttributes()
.
ServletRequestAttributes
provides the method getRequest()
to get the current request, getSession()
to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Note that the RequestContextHolder.currentRequestAttributes()
method returns an interface and needs to be typecasted to ServletRequestAttributes
that implements the interface.
Spring Javadoc: RequestContextHolder | ServletRequestAttributes
You can use Flex
and Flexible
widgets. for example:
Flex(
direction: Axis.vertical,
children: <Widget>[
... other widgets ...
Flexible(
flex: 1,
child: ListView.builder(
itemCount: ...,
itemBuilder: (context, index) {
...
},
),
),
],
);
this is the macro for my cocos2d project. should be the same for other apps.
#define WIDTH_IPAD 1024
#define WIDTH_IPHONE_5 568
#define WIDTH_IPHONE_4 480
#define HEIGHT_IPAD 768
#define HEIGHT_IPHONE 320
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
//width is height!
#define IS_IPHONE_5 ( [ [ UIScreen mainScreen ] bounds ].size.height == WIDTH_IPHONE_5 )
#define IS_IPHONE_4 ( [ [ UIScreen mainScreen ] bounds ].size.height == WIDTH_IPHONE_4 )
#define cp_ph4(__X__, __Y__) ccp(cx_ph4(__X__), cy_ph4(__Y__))
#define cx_ph4(__X__) (IS_IPAD ? (__X__ * WIDTH_IPAD / WIDTH_IPHONE_4) : (IS_IPHONE_5 ? (__X__ * WIDTH_IPHONE_5 / WIDTH_IPHONE_4) : (__X__)))
#define cy_ph4(__Y__) (IS_IPAD ? (__Y__ * HEIGHT_IPAD / HEIGHT_IPHONE) : (__Y__))
#define cp_pad(__X__, __Y__) ccp(cx_pad(__X__), cy_pad(__Y__))
#define cx_pad(__X__) (IS_IPAD ? (__X__) : (IS_IPHONE_5 ? (__X__ * WIDTH_IPHONE_5 / WIDTH_IPAD) : (__X__ * WIDTH_IPHONE_4 / WIDTH_IPAD)))
#define cy_pad(__Y__) (IS_IPAD ? (__Y__) : (__Y__ * HEIGHT_IPHONE / HEIGHT_IPAD))
$(function(){
var search = 'foo';
$("table tr td").filter(function() {
return $(this).text() == search;
}).parent('tr').css('color','red');
});
Will turn the text red for rows which have a cell whose text is 'foo'.
I use directive to prevent default behaviour:
module.directive('preventDefault', function() {
return function(scope, element, attrs) {
angular.element(element).bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
}
});
And then, in html:
<button class="secondaryButton" prevent-default>Secondary action</button>
This directive can also be used with <a>
and all other tags
I had same problem, now its resolved. I have tesseract2, under this folders for 32 bit and 64 bit, I copied files 64 bit folder(as my system is 64 bit) to main folder ("Tesseract2") and under bin/Debug folder. Now my solution is working fine.
Edit the tty configuration in /etc/init/tty*.conf
with a shellscript as a parameter :
(...)
exec /sbin/getty -n -l theInputScript.sh -8 38400 tty1
(...)
This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.
A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.
Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.
For MacOS this worked for me without the need to hardcode a particular Java version:
launchctl setenv JAVA_HOME "$(jenv javahome)"
Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.
String mob=edit_mobile.getText().toString();
if (mob.length() >= 10) {
if (mob.contains("+91")) {
mob= mob.substring(3, 13);
}
if (mob.substring(0, 1).contains("0")) {
mob= mob.substring(1, 11);
}
if (mob.contains("+")) {
mob= mob.replace("+", "");
}
mob= mob.substring(0, 10);
Log.i("mob", mob);
}
row_count = $('#my_table').find('tr').length;
column_count = $('#my_table').find('td').length / row_count;
According to PLINQ (available since .Net 4.0), you can do an
IEnumerable<T>.AsParallel().ForAll()
to do a parallel foreach loop on an IEnumerable.
you can try another usage using format
grammer suger:
re_genre = r'{}'.format(your_variable)
regex_pattern = re.compile(re_genre)
You could also use os.scandir
:
with os.scandir(os.getcwd()) as mydir:
dirs = [i.name for i in mydir if i.is_dir()]
In case you want the full path you can use i.path
.
Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory.
There is a comprehensive list of tools on the PostgreSQL Wiki:
https://wiki.postgresql.org/wiki/PostgreSQL_Clients
And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.
Very late to the party, but A simple solution is using VBA to create a custom function.
Add the function to VBA in the WorkBook, Worksheet, or a VBA Module
Function LastSegment(S, C)
LastSegment = Right(S, Len(S) - InStrRev(S, C))
End Function
Then the cell formula
=lastsegment(B1,"/")
in a cell and the string to be searched in cell B1 will populate the cell with the text trailing the last "/" from cell B1. No length limit, no obscure formulas. Only downside I can think is the need for a macro-enabled workbook.
Any user VBA Function can be called this way to return a value to a cell formula, including as a parameter to a builtin Excel function.
If you are going to use the function heavily you'll want to check for the case when the character is not in the string, then string is blank, etc.
Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.
Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.
To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:
private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
URL url = new URL(thisUrl);
builder = new Uri.Builder()
.scheme(url.getProtocol())
.authority(url.getAuthority())
.appendPath(url.getPath());
return builder.build();
}
This is are other ways of printing empty lines in python
# using \n after the string creates an empty line after this string is passed to the the terminal.
print("We need to put about", average_passengers_per_car, "in each car. \n")
print("\n") #prints 2 empty lines
print() #prints 1 empty line
When you do self.button = Button(...).grid(...)
, what gets assigned to self.button
is the result of the grid()
command, not a reference to the Button
object created.
You need to assign your self.button
variable before packing/griding it.
It should look something like this:
self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)
Using wamp do the following and hopefully, it will resolve an issue
Make these changes in PHP Options to correct:
max_execution_time 180
memory_limit 512M or your highest available
post_max_size 32M
upload_max_filesize 64M
First Method
View someView = findViewById(R.id.randomViewInMainLayout);// get Any child View
// Find the root view
View root = someView.getRootView()
// Set the color
root.setBackgroundColor(getResources().getColor(android.R.color.red));
Second Method
Add this single line after setContentView(...);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
Third Method
set background color to the rootView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="@+id/rootView"
</LinearLayout>
Important Thing
rootView.setBackgroundColor(0xFF00FF00); //after 0x the other four pairs are alpha,red,green,blue color.
Add ID current
for active/current page:
<div class="menuBar">
<ul>
<li id="current"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
#current a { color: #ff0000; }
Here is my updated code. Checks to see if version exists before saving and saves as the next available version number.
Sub SaveNewVersion()
Dim fileName As String, index As Long, ext As String
arr = Split(ActiveWorkbook.Name, ".")
ext = arr(UBound(arr))
fileName = ActiveWorkbook.FullName
If InStr(ActiveWorkbook.Name, "_v") = 0 Then
fileName = ActiveWorkbook.Path & "\" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
End If
Do Until Len(Dir(fileName)) = 0
index = CInt(Split(Right(fileName, Len(fileName) - InStr(fileName, "_v") - 1), ".")(0))
index = index + 1
fileName = Left(fileName, InStr(fileName, "_v") - 1) & "_v" & index & "." & ext
'Debug.Print fileName
Loop
ActiveWorkbook.SaveAs (fileName)
End Sub
Print a unicode character directly from python interpreter:
el@apollo:~$ python
Python 2.7.3
>>> print u'\u2713'
?
Unicode character u'\u2713'
is a checkmark. The interpreter prints the checkmark on the screen.
Print a unicode character from a python script:
Put this in test.py:
#!/usr/bin/python
print("here is your checkmark: " + u'\u2713');
Run it like this:
el@apollo:~$ python test.py
here is your checkmark: ?
If it doesn't show a checkmark for you, then the problem could be elsewhere, like the terminal settings or something you are doing with stream redirection.
Store unicode characters in a file:
Save this to file: foo.py:
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')
Run it and pipe output to file:
python foo.py > tmp.txt
Open tmp.txt and look inside, you see this:
el@apollo:~$ cat tmp.txt
e with obfuscation: é
Thus you have saved unicode e with a obfuscation mark on it to a file.
pip3 install goto-statement
Tested on Python 2.6 through 3.6 and PyPy.
Link: goto-statement
foo.py
from goto import with_goto
@with_goto
def bar():
label .bar_begin
...
goto .bar_begin
It should be:
ClientThread hey = clients.get(clients.size() - 1);
clients.remove(hey);
Or you can do
clients.remove(clients.size() - 1);
The minus ones are because size() returns the number of elements, but the ArrayList's first element's index is 0 and not 1.
mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name
should probably be
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
They are not lists, they are a list and a tuple. You can read about tuples in the Python tutorial. While you can mutate lists, this is not possible with tuples.
In [1]: x = (1, 2)
In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython console> in <module>()
TypeError: 'tuple' object does not support item assignment
It is simple way to use scroll bar to table body
/* It is simple way to use scroll bar to table body*/
table tbody {
display: block;
max-height: 300px;
overflow-y: scroll;
}
table thead, table tbody tr {
display: table;
width: 100%;
table-layout: fixed;
}
_x000D_
<table>
<thead>
<th>Invoice Number</th>
<th>Purchaser</th>
<th>Invoice Amount</th>
<th>Invoice Date</th>
</thead>
<tbody>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
</tbody>
</table>
_x000D_
also works if you do a "display: block;" on the td, destroying the td identity, but works!
Java doesn't have a general purpose define
preprocessor directive.
In the case of constants, it is recommended to declare them as static finals
, like in
private static final int PROTEINS = 100;
Such declarations would be inlined by the compilers (if the value is a compile-time constant).
Please note also that public static final constant fields are part of the public interface and their values shouldn't change (as the compiler inlines them). If you do change the value, you would need to recompile all the sources that referenced that constant field.
For those of us still working with older browsers, here's some extended backwards compatibility:
<div style="text-align: center;">
<div style="display:-moz-inline-stack; display:inline-block; zoom:1; *display:inline; text-align: left;">
Line 1: Testing<br>
Line 2: More testing<br>
Line 3: Even more testing<br>
</div>
</div>
_x000D_
Partially inspired by this post: https://stackoverflow.com/a/12567422/14999964.
Vertical alignment is now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide range of web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfills or different approaches for IE8/9.
In the following I'll show you how to do that in only 3 lines of text (regardless of old flexbox syntax).
Note: it's better to use an additional class instead of altering .jumbotron
to achieve the vertical alignment. I'd use vertical-center
class name for instance.
Example Here (A Mirror on jsbin).
<div class="jumbotron vertical-center"> <!--
^--- Added class -->
<div class="container">
...
</div>
</div>
.vertical-center {
min-height: 100%; /* Fallback for browsers do NOT support vh unit */
min-height: 100vh; /* These two lines are counted as one :-) */
display: flex;
align-items: center;
}
Important notes (Considered in the demo):
A percentage values of height
or min-height
properties is relative to the height
of the parent element, therefore you should specify the height
of the parent explicitly.
Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.
In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-center
in this case - won't take the available space inside the parent, therefore we need to specify the width
property like: width: 100%
.
Also in some of web browsers as mentioned above, the flex item - .container
in this case - may not appear at the center horizontally. It seems the applied left/right margin
of auto
doesn't have any effect on the flex item.
Therefore we need to align it by box-pack / justify-content
.
For further details and/or vertical alignment of columns, you could refer to the topic below:
This is the old answer I wrote at the time I answered this question. This method has been discussed here and it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:
In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middle
declaration. Spec from W3C:
middle
Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.
In cases that the parent - .vertical-center
element in this case - has an explicit height
, by any chance if we could have a child element having the exact same height
of the parent, we would be able to move the baseline of the parent to the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container
- aligned to the center vertically.
That being said, we could create a full-height element within the .vertical-center
by ::before
or ::after
pseudo elements and also change the default display
type of it and the other child, the .container
to inline-block
.
Then use vertical-align: middle;
to align the inline elements vertically.
Here you go:
<div class="jumbotron vertical-center">
<div class="container">
...
</div>
</div>
.vertical-center {
height:100%;
width:100%;
text-align: center; /* align the inline(-block) elements horizontally */
font: 0/0 a; /* remove the gap between inline(-block) elements */
}
.vertical-center:before { /* create a full-height inline block pseudo=element */
content: " ";
display: inline-block;
vertical-align: middle; /* vertical alignment of the inline element */
height: 100%;
}
.vertical-center > .container {
max-width: 100%;
display: inline-block;
vertical-align: middle; /* vertical alignment of the inline element */
/* reset the font property */
font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}
Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to auto
or 0
or change its display
type to none
if needed so:
@media (max-width: 768px) {
.vertical-center:before {
height: auto;
/* Or */
display: none;
}
}
And one more thing:
If there are footer
/header
sections around the container, it's better to position that elements properly (relative
, absolute
? up to you.) and add a higher z-index
value (for assurance) to keep them always on the top of the others.
I know that this is too late but here is my approach:
<GridViewColumn x:Name="GridHeaderLocalSize" Width="100">
<GridViewColumn.Header>
<GridViewColumnHeader HorizontalContentAlignment="Right">
<Grid Width="Auto" HorizontalAlignment="Right">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Local size" TextAlignment="Right" Padding="0,0,5,0"/>
</Grid>
</GridViewColumnHeader>
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Width="{Binding ElementName=GridHeaderLocalSize, Path=Width, FallbackValue=100}" HorizontalAlignment="Right" TextAlignment="Right" Padding="0,0,5,0" Text="Text" >
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
The main idea is to bind the width of the cellTemplete element to the width of the ViewGridColumn. Width=100 is default width used until first resize. There isn't any code behind. Everything is in xaml.
You can't resize the array, per se, but you can create a new array and efficiently copy the elements from the old array to the new array using some utility function like this:
public static int[] removeElement(int[] original, int element){
int[] n = new int[original.length - 1];
System.arraycopy(original, 0, n, 0, element );
System.arraycopy(original, element+1, n, element, original.length - element-1);
return n;
}
A better approach, however, would be to use an ArrayList (or similar List structure) to store your data and then use its methods to remove elements as needed.
type test struct {
Test string `json:"test"`
}
func test(w http.ResponseWriter, req *http.Request) {
var t test_struct
body, _ := ioutil.ReadAll(req.Body)
json.Unmarshal(body, &t)
fmt.Println(t)
}
My opinion is that selectedIndex
or using objectAtIndex
is not necessarily the best way to switch the tab. If you reorder your tabs, a hard coded index selection might mess with your former app behavior.
If you have the object reference of the view controller you want to switch to, you can do:
tabBarController.selectedViewController = myViewController
Of course you must make sure, that myViewController
really is in the list of tabBarController.viewControllers
.
One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));
Get URI, trim slashes, convert to array, grab last part
string * and string& differ in a couple of ways. First of all, the pointer points to the address location of the data. The reference points to the data. If you had the following function:
int foo(string *param1);
You would have to check in the function declaration to make sure that param1 pointed to a valid location. Comparatively:
int foo(string ¶m1);
Here, it is the caller's responsibility to make sure the pointed to data is valid. You can't pass a "NULL" value, for example, int he second function above.
With regards to your second question, about the method return values being a reference, consider the following three functions:
string &foo();
string *foo();
string foo();
In the first case, you would be returning a reference to the data. If your function declaration looked like this:
string &foo()
{
string localString = "Hello!";
return localString;
}
You would probably get some compiler errors, since you are returning a reference to a string that was initialized in the stack for that function. On the function return, that data location is no longer valid. Typically, you would want to return a reference to a class member or something like that.
The second function above returns a pointer in actual memory, so it would stay the same. You would have to check for NULL-pointers, though.
Finally, in the third case, the data returned would be copied into the return value for the caller. So if your function was like this:
string foo()
{
string localString = "Hello!";
return localString;
}
You'd be okay, since the string "Hello" would be copied into the return value for that function, accessible in the caller's memory space.
For me it wasn't working even with hibernate.hbm2ddl.auto
set to update
. It turned out that the generated creation SQL was invalid, because one of my column names (user
) was an SQL keyword. This failed softly, and it wasn't obvious what was going on until I inspected the logs.
This is fairly straightforward. In your JS, all you would do is this or something similar:
var array = ["thing1", "thing2", "thing3"];
var parameters = {
"array1[]": array,
...
};
$.post(
'your/page.php',
parameters
)
.done(function(data, statusText) {
// This block is optional, fires when the ajax call is complete
});
In your php page, the values in array form will be available via $_POST['array1']
.
references
In a webpage where I wanted a in image to scale with browser size change and remain at the top, next to a fixed div, all I had to do was use a single CSS line: overflow:hidden;
and it did the trick. The image scales perfectly.
What is especially nice is that this is pure css and will work even if Javascript is turned off.
CSS:
#ImageContainerDiv {
overflow: hidden;
}
HTML:
<div id="ImageContainerDiv">
<a href="URL goes here" target="_blank">
<img src="MapName.png" alt="Click to load map" />
</a>
</div>
Google treat Gmail accounts differently depending on the available user information, probably to curb spammers.
I couldn't use SMTP until I did the phone verification. Made another account to double check and I was able to confirm it.
Open this file
edit these parameters:
Use Vim:
diff /path/to/a /path/to/b | vim -R -
Or better still, VimDiff (or vim -d
, which is shorter to type) will show differences between two, three or four files side-by-side.
vim -d /path/to/[ab]
vimdiff file1 file2 file3 file4
I think that substr() throws an exception if str only contains the whitespace.
I would modify it to the following code:
string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
if (first == std::string::npos)
return "";
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
for a non-nested dict (since the title does not mention that case, it might be interesting for other people)
{str(k): str(v) for k, v in my_dict.items()}
Changing PHP version from 5.6 to 5.5 Fixed it.
You have to go to control panel > CGI Script and change PHP version there.
You also can Redirect
within the Route
as follows. This is for handle invalid routes.
<Route path='*' render={() =>
(
<Redirect to="/error"/>
)
}/>
Iam using Catalina and use this mysql_secure_installation
command and now works for me:
$ mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.
Enter current password for root (enter for none): << enter root here >>
i enter root
as current password
OK, successfully used password, moving on...
Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.
and do the rest
I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.
LINUX
struct timeval tv;
tv.tv_sec = 30; // 30 Secs Timeout
tv.tv_usec = 0; // Not init'ing this can cause strange errors
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));
WINDOWS
DWORD timeout = SOCKET_READ_TIMEOUT_SEC * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
NOTE: You have put this setting before bind()
function call for proper run
We can try this command instead of using && method:
try {hostname; if ($lastexitcode -eq 0) {ipconfig /all | findstr /i bios}} catch {echo err} finally {}
This question is old. But I would like to mention an other approach. Using Enums for declaring constant values. Based on the answer of Nandkumar Tekale, the Enum can be used as below:
Enum:
public enum Planck {
REDUCED();
public static final double PLANCK_CONSTANT = 6.62606896e-34;
public static final double PI = 3.14159;
public final double REDUCED_PLANCK_CONSTANT;
Planck() {
this.REDUCED_PLANCK_CONSTANT = PLANCK_CONSTANT / (2 * PI);
}
public double getValue() {
return REDUCED_PLANCK_CONSTANT;
}
}
Client class:
public class PlanckClient {
public static void main(String[] args) {
System.out.println(getReducedPlanckConstant());
// or using Enum itself as below:
System.out.println(Planck.REDUCED.getValue());
}
public static double getReducedPlanckConstant() {
return Planck.PLANCK_CONSTANT / (2 * Planck.PI);
}
}
Reference : The usage of Enums for declaring constant fields is suggested by Joshua Bloch in his Effective Java book.
If you are using mongoose, I have found the following plugin to be a useful implementation of the JSON Patch format
First open Visual studio ..select your project in solution explorer..Right click and choose option "browse with" then set IE as default browser.
Now open IE ..go to
Tools >> Internet option >> Advance>> uncheck the checkbox having "Disable Script Debugging (Internet Explorer).
and then click Apply
and OK
and you are done ..
Now you can set breakpoints in your JS file and then hit the debug button in VS..
EDIT:- For asp.net web application right click on the page which is your startup page(say default.aspx) and perform the same steps. :)
I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round
function does not round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...
The ability to round a (Python) float to some number of decimal places is something that's frequently requested, but turns out to be rarely what's actually needed. The beguilingly simple answer round(x, number_of_places)
is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:
>>> round(52.15, 1)
52.1
With a naive understanding of what round
does, this looks wrong: surely it should be rounding up to 52.2
rather than down to 52.1
? To understand why such behaviours can't be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it's far from simple.
So here's what's really happening in the example above. (deep breath) We're displaying a decimal representation of the nearest binary floating-point number to the nearest n
-digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):
First the numeric literal 52.15
gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47
, or 52.14999999999999857891452847979962825775146484375
.
Internally as the first step of the round
operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15
, we end up rounding down and getting a string 52.1
. This explains why we're getting 52.1
as the final output instead of 52.2
.
Then in the second step of the round
operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1
, which is now 7332423143312589 * 2**-47
, or 52.10000000000000142108547152020037174224853515625
.
Finally, as part of Python's read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1
as the final output.
In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That's due to Python's choice of repr
implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:
>>> x = 15.34509809234
>>> x
15.34509809234
Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here's the original example executed in Python 2.6:
>>> round(52.15, 1)
52.200000000000003
Not only do we round in the opposite direction, getting 52.2
instead of 52.1
, but the displayed value doesn't even print as 52.2
! This behaviour has caused numerous reports to the Python bug tracker along the lines of "round is broken!". But it's not round
that's broken, it's user expectations. (Okay, okay, round
is a little bit broken in Python 2.6, in that it doesn't use correct rounding.)
Short version: if you're using two-argument round, and you're expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you're asking for trouble.
So enough with the "two-argument round is bad" argument. What should you be using instead? There are a few possibilities, depending on what you're trying to do.
If you're rounding for display purposes, then you don't want a float result at all; you want a string. In that case the answer is to use string formatting:
>>> format(66.66666666666, '.4f')
'66.6667'
>>> format(1.29578293, '.6f')
'1.295783'
Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.
>>> format(52.15, '.1f')
'52.1'
If you're operating in a context where it matters which direction decimal halfway cases are rounded (for example, in some financial contexts), you might want to represent your numbers using the Decimal
type. Doing a decimal round on the Decimal
type makes a lot more sense than on a binary type (equally, rounding to a fixed number of binary places makes perfect sense on a binary type). Moreover, the decimal
module gives you better control of the rounding mode. In Python 3, round
does the job directly. In Python 2, you need the quantize
method.
>>> Decimal('66.66666666666').quantize(Decimal('1e-4'))
Decimal('66.6667')
>>> Decimal('1.29578293').quantize(Decimal('1e-6'))
Decimal('1.295783')
In rare cases, the two-argument version of round
really is what you want: perhaps you're binning floats into bins of size 0.01
, and you don't particularly care which way border cases go. However, these cases are rare, and it's difficult to justify the existence of the two-argument version of the round
builtin based on those cases alone.
It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment
as you can see above).
Try checking to see if Hibernate core is put in as dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.11.Final</version>
<scope>compile</scope>
</dependency>
Below link will provide sample code. #Swift3
User need to pull up last table view cell, at least hight of 2 cell to fetch more data from server.
You will found Process cell also to show loading process as in last cell.
Its in Swift3
Write a Vim function in .vimrc using the searchpair
built-in function:
searchpair({start}, {middle}, {end} [, {flags} [, {skip}
[, {stopline} [, {timeout}]]]])
Search for the match of a nested start-end pair. This can be
used to find the "endif" that matches an "if", while other
if/endif pairs in between are ignored.
[...]
Yes.
Set a reference to MS Scripting runtime ('Microsoft Scripting Runtime'). As per @regjo's comment, go to Tools->References and tick the box for 'Microsoft Scripting Runtime'.
Create a dictionary instance using the code below:
Set dict = CreateObject("Scripting.Dictionary")
or
Dim dict As New Scripting.Dictionary
Example of use:
If Not dict.Exists(key) Then
dict.Add key, value
End If
Don't forget to set the dictionary to Nothing
when you have finished using it.
Set dict = Nothing
If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe
container anytime the height of the framed content changes.
Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).
window.addEventListener("load", function(){
if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe
send_height_to_parent_function = function(){
var height = document.getElementsByTagName("html")[0].clientHeight;
//console.log("Sending height as " + height + "px");
parent.postMessage({"height" : height }, "*");
}
// send message to parent about height updates
send_height_to_parent_function(); //whenever the page is loaded
window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
var observer = new MutationObserver(send_height_to_parent_function); // whenever DOM changes PT1
var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
observer.observe(window.document, config); // PT3
});
Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.
<script>
window.addEventListener("message", function(e){
var this_frame = document.getElementById("healthy_behavior_iframe");
if (this_frame.contentWindow === e.source) {
this_frame.height = e.data.height + "px";
this_frame.style.height = e.data.height + "px";
}
})
</script>