Here's another C version. It defines a macro called wicked_cast()
for inline type punning via C99 union literals and the non-standard __typeof__
operator.
#include <limits.h>
#if UCHAR_MAX == UINT_MAX
#error endianness irrelevant as sizeof(int) == 1
#endif
#define wicked_cast(TYPE, VALUE) \
(((union { __typeof__(VALUE) src; TYPE dest; }){ .src = VALUE }).dest)
_Bool is_little_endian(void)
{
return wicked_cast(unsigned char, 1u);
}
If integers are single-byte values, endianness makes no sense and a compile-time error will be generated.
Please try the below XAML snippet:
<Button Width="300" Height="50">
<StackPanel Orientation="Horizontal">
<Image Source="Pictures/img.jpg" Width="20" Height="20"/>
<TextBlock Text="Blablabla" VerticalAlignment="Center" />
</StackPanel>
</Button>
In XAML elements are in a tree structure. So you have to add the child control to its parent control. The below code snippet also works fine. Give a name for your XAML root grid as 'MainGrid'.
Image img = new Image();
img.Source = new BitmapImage(new Uri(@"foo.png"));
StackPanel stackPnl = new StackPanel();
stackPnl.Orientation = Orientation.Horizontal;
stackPnl.Margin = new Thickness(10);
stackPnl.Children.Add(img);
Button btn = new Button();
btn.Content = stackPnl;
MainGrid.Children.Add(btn);
For me it was just a matter of changing the path variable to: 'C:\Program Files\Mozilla Firefox' instead of 'C:\Program Files (x86)\Mozilla Firefox'
You can use the jQuery ajax method link if you want to pass data from client to server.
In this case you can use $_SERVER['HTTP_USER_AGENT']
variable to found browser user agent.
This is a common question. In base, the option you're looking for is aggregate
. Assuming your data.frame
is called "mydf", you can use the following.
> aggregate(B ~ A, mydf, sum)
A B
1 1 5
2 2 3
3 3 11
I would also recommend looking into the "data.table" package.
> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
A V1
1: 1 5
2: 2 3
3: 3 11
Guid.TryParse()
https://msdn.microsoft.com/de-de/library/system.guid.tryparse(v=vs.110).aspx
or
Guid.TryParseExact()
https://msdn.microsoft.com/de-de/library/system.guid.tryparseexact(v=vs.110).aspx
in .NET 4.0 (or 3.5?)
On my Fedora 10 system, with findutils-4.4.0-1.fc10.i386
:
find <path> -daystart -ctime 0 -print
The -daystart
flag tells it to calculate from the start of today instead of from 24 hours ago.
Note however that this will actually list files created or modified in the last day. find
has no options that look at the true creation date of the file.
Actually Shay levy's answer is almost correct but i got an weird issue as i mentioned in his comment column. So i split the command into two lines and it works fine.
$Ipaddress= Read-Host "Enter the IP address:"
$Port= Read-host "Enter the port number to access:"
$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)
if($t.Connected)
{
"Port $Port is operational"
}
else
{
"Port $Port is closed, You may need to contact your IT team to open it. "
}
<% String s="Hi"; %>
var v ="<%=s%>";
Below is the simplest and fastest way to determine if a record exists in database or not Good thing is it works in all Relational DB's
SELECT distinct 1 products.id FROM products WHERE products.id = ?;
I used withStyles
instead of makeStyle
EX :
import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";
const useStyles = theme => ({
root: {
flexGrow: 1,
},
});
class App extends Component {
render() {
const { classes } = this.props;
return(
<div className={classes.root}>
Test
</div>
)
}
}
export default withStyles(useStyles)(App)
From the theoretical point of view:
From the technical point of view:
refs/tags/
namespace, and can point to tag objects (annotated and optionally GPG signed tags) or directly to commit object (less used lightweight tag for local names), or in very rare cases even to tree object or blob object (e.g. GPG signature).refs/heads/
namespace, and can point only to commit objects. The HEAD
pointer must refer to a branch (symbolic reference) or directly to a commit (detached HEAD or unnamed branch).refs/remotes/<remote>/
namespace, and follow ordinary branches in remote repository <remote>
.See also gitglossary manpage:
branch
A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch.
tag
A ref pointing to a tag or commit object. In contrast to a head, a tag is not changed by a commit. Tags (not tag objects) are stored in
$GIT_DIR/refs/tags/
. [...]. A tag is most typically used to mark a particular point in the commit ancestry chain.tag object
An object containing a ref pointing to another object, which can contain a message just like a commit object. It can also contain a (PGP) signature, in which case it is called a "signed tag object".
You can open your command prompt as the intended user:
You will be prompted with login and password
Once CommandP Prompt starts you can double check which user you are running as by the command whoami
.
Now you can change directory to your project and run
dotnet run
You passed an argument to a function which didn't take any. For example:
def takes_no_arguments
end
takes_no_arguments 1
# ArgumentError: wrong number of arguments (1 for 0)
Just thought I would expand on this a bit.
If you perform a MYSQLI SELECT query that returns 0 results, it returns FALSE.
However, if you get this error and you have written your own MYSQLI Query function, then you can also get this error if the query you are running is not a select but an update. An update query will return either TRUE or FALSE. So if you just assume that any non false result will have records returned, then you will trip up when you run an update or anything other than select.
The easiest solution, once you have checked that its not false, is to first check that the result of the query is an object.
$sqlResult = $connection->query($sql);
if (!$sqlResult)
{
...
}
else if (is_object($sqlResult))
{
$sqlRowCount = $sqlResult->num_rows;
}
else
{
$sqlRowCount = 0;
}
I had a similar issue after upgrading from PHP 5.5 to PHP 5.6. The phpize
and php-config
libraries being used to compile the phalcon extension were still the ones from PHP 5.5. I had to run the command below:
sudo apt-get install php5.6-dev
There will be a long stacktrace, the key information I saw was this:
update-alternatives: using /usr/bin/php-config5.6 to provide /usr/bin/php-config (php-config) in auto mode
update-alternatives: using /usr/bin/phpize5.6 to provide /usr/bin/phpize (phpize) in auto mode
I hope this helps someone.
I tried working with the string form rather than the number and this seemed to work. I have only tested this on Chrome but it should be universal:
function removeExponent(s) {
var ie = s.indexOf('e');
if (ie != -1) {
if (s.charAt(ie + 1) == '-') {
// negative exponent, prepend with .0s
var n = s.substr(ie + 2).match(/[0-9]+/);
s = s.substr(2, ie - 2); // remove the leading '0.' and exponent chars
for (var i = 0; i < n; i++) {
s = '0' + s;
}
s = '.' + s;
} else {
// positive exponent, postpend with 0s
var n = s.substr(ie + 1).match(/[0-9]+/);
s = s.substr(0, ie); // strip off exponent chars
for (var i = 0; i < n; i++) {
s += '0';
}
}
}
return s;
}
I use:
from pathlib import Path
import platform
import tempfile
tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())
This is because on MacOS, i.e. Darwin, tempfile.gettempdir()
and os.getenv('TMPDIR')
return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'
; it is one that I do not always want.
The other day I found myself in a situation where %n
would nicely solve my problem. Unlike my earlier answer, in this case, I cannot devise a good alternative.
I have a GUI control that displays some specified text. This control can display part of that text in bold (or in italics, or underlined, etc.), and I can specify which part by specifying starting and ending character indices.
In my case, I am generating the text to the control with snprintf
, and I'd like one of the substitutions to be made bold. Finding the starting and ending indices to this substitution is non-trivial because:
The string contains multiple substitutions, and one of the substitutions is arbitrary, user-specified text. This means that doing a textual search for the substitution I care about is potentially ambiguous.
The format string might be localized, and it might use the $
POSIX extension for positional format specifiers. Therefore searching the original format string for the format specifiers themselves is non-trivial.
The localization aspect also means that I cannot easily break up the format string into multiple calls to snprintf
.
Therefore the most straightforward way to find the indices around a particular substitution would be to do:
char buf[256];
int start;
int end;
snprintf(buf, sizeof buf,
"blah blah %s %f yada yada %n%s%n yakety yak",
someUserSpecifiedString,
someFloat,
&start, boldString, &end);
control->set_text(buf);
control->set_bold(start, end);
I am using Android Studio 4 developing a Fluter/Dart application. There does not seem to be a Sync project with gradle button or file menu item, there is no clean or rebuild either.
I fixed the problem by removing the .idea folder. The suggestion included removing .gradle as well, but it did not exist.
Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid()
gives desired result.
If you don't have the ability to edit the java code to insert the .setLogLevel()
statements and you don't want yet more external files to deploy, you can use a brute force way to solve this. Just filter out the INFO lines using grep.
spark-submit --deploy-mode client --master local <rest-of-cmd> | grep -v -F "INFO"
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
FileInfo.Length
will do the trick (per MSDN it "[g]ets the size, in bytes, of the current file.") There is a nice page on MSDN on common I/O tasks.
I put this function in a util file in one of the apps in my project:
import logging
import re
from django.db import connection
logger = logging.getLogger(__name__)
def sql_logger():
logger.debug('TOTAL QUERIES: ' + str(len(connection.queries)))
logger.debug('TOTAL TIME: ' + str(sum([float(q['time']) for q in connection.queries])))
logger.debug('INDIVIDUAL QUERIES:')
for i, query in enumerate(connection.queries):
sql = re.split(r'(SELECT|FROM|WHERE|GROUP BY|ORDER BY|INNER JOIN|LIMIT)', query['sql'])
if not sql[0]: sql = sql[1:]
sql = [(' ' if i % 2 else '') + x for i, x in enumerate(sql)]
logger.debug('\n### {} ({} seconds)\n\n{};\n'.format(i, query['time'], '\n'.join(sql)))
Then, when needed, I just import it and call it from whatever context (usually a view) is necessary, e.g.:
# ... other imports
from .utils import sql_logger
class IngredientListApiView(generics.ListAPIView):
# ... class variables and such
# Main function that gets called when view is accessed
def list(self, request, *args, **kwargs):
response = super(IngredientListApiView, self).list(request, *args, **kwargs)
# Call our function
sql_logger()
return response
It's nice to do this outside the template because then if you have API views (usually Django Rest Framework), it's applicable there too.
If you want to wrap your text but maintain alignment then you can wrap that cell in a minipage
or varwidth
environment (varwidth comes from the varwidth package). Varwidth will be "as wide as it's contents but no wider than X". You can create a custom column type which acts like "p{xx}" but shrinks to fit by using
\newcolumntype{M}[1]{>{\begin{varwidth}[t]{#1}}l<{\end{varwidth}}}
which may require the array
package. Then when you use something like \begin{tabular}{llM{2in}}
the first two columns we be normal left-aligned and the third column will be normal left aligned but if it gets wider than 2in then the text will be wrapped.
In addition with skaffman answer, simple if-else you can use ternary operator like this
<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>
You can use the following option to check for the files:
wget --delete-after URL
Another solution, for those of us without an internet connection to our development machine is:
Create a folder called system-images
in the top level of your SDK directory (next to platforms
and tools
). Create subdirs android-14
and android-15
(as applicable).
Extract the complete armeabi-v7a
folder to these directory; sysimg_armv7a-15_r01.zip (from, e.g. google's repository) goes to android-15
, sysimg_armv7a-14_r02.zip to android-14
.
I've not tried this procedure offline, I finally relented and used my broadband allowance at home, but these are the target locations for these large sysimg's, for future reference.
I've tried creating the image
subdirs where they were absent in 14 and 15 but while this allowed the AVD to create an image (for 15 but not 14) it hadn't shown the Android logo after 15 minutes.
Since v-ref is no longer a directive, but a special attribute, it can also be dynamically defined. This is especially useful in combination with v-for.
For example:
<ul>
<li v-for="(item, key) in items" v-on:click="play(item,$event)">
<a v-bind:ref="'key' + item.id" v-bind:href="item.url">
<!-- content -->
</a>
</li>
</ul>
and in Vue component you can use
var recordingModel = new Vue({
el:'#rec-container',
data:{
items:[]
},
methods:{
play:function(key,e){
// it contains the bound reference
console.log(this.$refs['item'+key]);
}
}
});
For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.
This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.
To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.
cc -DDISPLAY_STRING demo.c
If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.
#define TERMINAL "/dev/ttyUSB0"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int set_interface_attribs(int fd, int speed)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
return 0;
}
void set_mincount(int fd, int mcount)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error tcgetattr: %s\n", strerror(errno));
return;
}
tty.c_cc[VMIN] = mcount ? 1 : 0;
tty.c_cc[VTIME] = 5; /* half second timer */
if (tcsetattr(fd, TCSANOW, &tty) < 0)
printf("Error tcsetattr: %s\n", strerror(errno));
}
int main()
{
char *portname = TERMINAL;
int fd;
int wlen;
char *xstr = "Hello!\n";
int xlen = strlen(xstr);
fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening %s: %s\n", portname, strerror(errno));
return -1;
}
/*baudrate 115200, 8 bits, no parity, 1 stop bit */
set_interface_attribs(fd, B115200);
//set_mincount(fd, 0); /* set to pure timed read */
/* simple output */
wlen = write(fd, xstr, xlen);
if (wlen != xlen) {
printf("Error from write: %d, %d\n", wlen, errno);
}
tcdrain(fd); /* delay for output */
/* simple noncanonical input */
do {
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
#ifdef DISPLAY_STRING
buf[rdlen] = 0;
printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
unsigned char *p;
printf("Read %d:", rdlen);
for (p = buf; rdlen-- > 0; p++)
printf(" 0x%x", *p);
printf("\n");
#endif
} else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else { /* rdlen == 0 */
printf("Timeout from read\n");
}
/* repeat read to get full message */
} while (1);
}
For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.
Use the JSON.stringify() to get the string in JSON format, ensure that while making the AJAX call you pass below mentioned attributes:
Below is the give jquery code to make ajax post call to asp.net web api:
var product =_x000D_
JSON.stringify({_x000D_
productGroup: "Fablet",_x000D_
productId: 1,_x000D_
productName: "Lumia 1525 64 GB",_x000D_
sellingPrice: 700_x000D_
});_x000D_
_x000D_
$.ajax({_x000D_
URL: 'http://localhost/api/Products',_x000D_
type: 'POST',_x000D_
contentType: 'application/json',_x000D_
data: product,_x000D_
success: function (data, status, xhr) {_x000D_
alert('Success!');_x000D_
},_x000D_
error: function (xhr, status, error) {_x000D_
alert('Update Error occurred - ' + error);_x000D_
}_x000D_
});
_x000D_
result() returns Object type data. . . . result_array() returns Associative Array type data.
another way
List<int> list=new List<int>();
IEnumerable<int> enumerable =Enumerable.Range(1, 300);
foreach (var item in enumerable )
{
list.add(item);
}
In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.
For example:
INSERT INTO MyTable
( Column1, Column2, Column3 )
VALUES
('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
('Billy', 125, 'London Office'),
('Miranda', 126, 'Bristol Office');
I think its pretty straight forward with reflection
MyClass mobj = MyClass.class.cast(obj);
and if class name is different
Object newObj = Class.forName(classname).cast(obj);
Channel compatriot 'billings' (of freenode/#centos fame) shared his method with me:
diff -Naur dir1/ dir2
Including the final directory forward slash doesn't matter.
Also, it appears the -u
option is not available on some older/server versions of diff.
The difference in diffs:
# diff -Nar /tmp/dir1 /tmp/dir2/
diff -Nar /tmp/dir1/file /tmp/dir2/file
28a29
> TEST
# diff -qr /tmp/dir1/ /tmp/dir2/
Files /tmp/dir1/file and /tmp/dir2/file differ
In case you have NA's:
sapply(data, mean, na.rm = T) # Returns a vector (with names)
lapply(data, mean, na.rm = T) # Returns a list
Remember that "mean" needs numeric data. If you have mixed class data, then use:
numdata<-data[sapply(data, is.numeric)]
sapply(numdata, mean, na.rm = T) # Returns a vector
lapply(numdata, mean, na.rm = T) # Returns a list
The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities
$idsToFilter = array(1,2,3,4);
$member->getComments()->filter(
function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
}
);
Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.
var nDays = ( Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;
as a function:
function DaysBetween(StartDate, EndDate) {
// The number of milliseconds in all UTC days (no DST)
const oneDay = 1000 * 60 * 60 * 24;
// A day in UTC always lasts 24 hours (unlike in other time formats)
const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());
// so it's safe to divide by 24 hours
return (start - end) / oneDay;
}
So Nodejs comes with the default global variable called '__fileName'
that holds the current file being executed
My advice is to pass the __fileName to a service from any file , so that the retrieval of the fileName is made dynamic
Below, I make use of the fileName string and then split it based on the path.sep
. Note path.sep avoids issues with posix file seperators and windows file seperators (issues with '/' and '\'). It is much cleaner. Getting the substring and getting only the last seperated name and subtracting it with the actulal length by 3 speaks for itself.
You can write a service like this (Note this is in typescript , but you can very well write it in js )
export class AppLoggingConstants {
constructor(){
}
// Here make sure the fileName param is actually '__fileName'
getDefaultMedata(fileName: string, methodName: string) {
const appName = APP_NAME;
const actualFileName = fileName.substring(fileName.lastIndexOf(path.sep)+1, fileName.length - 3);
//const actualFileName = fileName;
return appName+ ' -- '+actualFileName;
}
}
export const AppLoggingConstantsInstance = new AppLoggingConstants();
Short answer
mvn install
- adds all artifact (dependencies) specified in pom, to the local repository (from remote sources).
.NET and Internet Explorer don't send requests for localhost through any proxies, so they don't come up on Fiddler.
Many alternatives are available
Use your machine name instead of localhost. Using Firefox (with the fiddler add-on installed) to make the request. Use http://ipv4.fiddler instead of localhost.
For more info http://www.fiddler2.com/Fiddler/help/hookup.asp
Custom toasts from the background are blocked, Android 11 protects users by deprecating custom toast views. For security reasons and to maintain a good user experience, the system blocks toasts that contain custom views if those toasts are sent from the background by an app that targets Android 11.
addCallback() method added in Android R If you want to be notified when a toast (text or custom) appears or disappears.
The most important text in toast API changes that for apps that target Android 11 the getView()
method returns null when you access it, So, ensure to protect your apps from FATAL EXCEPTION, you know what I mean :)
Use snackbars instead if applicable.
It's recommended that you use snackbars instead where possible. If your app's use case prevents you from using snackbars, such as when you need to send the user a message while your app is in the background, you can still use text toasts because they aren't restricted by the new behavior change.
See the official docs for more details on the topic.
if (-e $base_path)
{
# code
}
-e
is the 'existence' operator in Perl.
You can check permissions and other attributes using the code on this page.
above answer didnt help me as my string value was "700.00"
with Swift 2.2 this works for me
let myString = "700.00"
let myInt = (myString as NSString).integerValue
I passed myInt to NSFormatterClass
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0
let priceValue = formatter.stringFromNumber(myInt!)!
//Now priceValue is ? 700
Thanks to this blog post.
in Swift 4.2 and Xcode 10
Initially my text field is like this.
After adding padding in left side my text field is...
//Code for left padding
textFieldName.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: textFieldName.frame.height))
textFieldName.leftViewMode = .always
Like this we can create right side also.(textFieldName.rightViewMode = .always)
If you want SharedInstance type code(Write once use every ware) see the below code.
//This is my shared class
import UIKit
class SharedClass: NSObject {
static let sharedInstance = SharedClass()
//This is my padding function.
func textFieldLeftPadding(textFieldName: UITextField) {
// Create a padding view
textFieldName.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 3, height: textFieldName.frame.height))
textFieldName.leftViewMode = .always//For left side padding
textFieldName.rightViewMode = .always//For right side padding
}
private override init() {
}
}
Now call this function like this.
//This single line is enough
SharedClass.sharedInstance.textFieldLeftPadding(textFieldName:yourTF)
String x = "stackoverflow";
String [] y = x.split("");
I solved this problem by ORDERING my source data (xls, csv, whatever) such that the longest text values on at the top of the file. Excel is great. use the LEN() function on your challenging column. Order by that length value with the longest value on top of your dataset. Save. Try the import again.
"This is probably because of mod_security or some similar server security feature which blocks known
spider/bot
user agents (urllib uses something like python urllib/3.3.0, it's easily detected)" - as already mentioned by Stefano Sanfilippo
from urllib.request import Request, urlopen
url="https://stackoverflow.com/search?q=html+error+403"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
The web_byte is a byte object returned by the server and the content type present in webpage is mostly utf-8. Therefore you need to decode web_byte using decode method.
This solves complete problem while I was having trying to scrap from a website using PyCharm
P.S -> I use python 3.4
This is a faster version of the code from the post marked as the answer.
All of the benchmarks that I have performed show that a simple for loop that only contains something like an array fill is typically twice as fast if it is decrementing versus if it is incrementing.
Also, the array Length property is already passed as the parameter so it doesn't need to be retrieved from the array properties. It should also be pre-calculated and assigned to a local variable. Loop bounds calculations that involve a property accessor will re-compute the value of the bounds before each iteration of the loop.
public static byte[] CreateSpecialByteArray(int length)
{
byte[] array = new byte[length];
int len = length - 1;
for (int i = len; i >= 0; i--)
{
array[i] = 0x20;
}
return array;
}
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
This is how I cleared my recyclerview and added new items to it with animation:
mList.clear();
mAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
//reset adapter with empty array list (it did the trick animation)
mAdapter = new MyAdapter(context, mList);
recyclerView.setAdapter(mAdapter);
mList.addAll(newList);
mAdapter.notifyDataSetChanged();
I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/
Changing the name in res>values>strings.xml will change the app name that is shown in the apps menu after installation
Renaming the android studio project folder (when android studio is closed) will likely satisfy many developers
As far as I know, that calculator does not offer mod functions. You can however computer it by hand in a fairly straightforward manner. Ex.
(1)50 mod 3
(2)50/3 = 16.66666667
(3)16.66666667 - 16 = 0.66666667
(4)0.66666667 * 3 = 2
Therefore 50 mod 3 = 2
Things to Note: On line 3, we got the "minus 16" by looking at the result from line (2) and ignoring everything after the decimal. The 3 in line (4) is the same 3 from line (1).
Hope that Helped.
Edit As a result of some trials you may get x.99991 which you will then round up to the number x+1.
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
Bootstrap tabs are not responsive out of the box. Responsive, IMO, is a style change, changing functions is Adaptive. There are a few plugins to turn the Bootstrap 3 tabs into a Collapse component. The best and most updated one is : https://github.com/flatlogic/bootstrap-tabcollapse.
Here's one way of implementing it:
This turns the content into a collapse component:
Dependencies:
HTML -- same as question with class name addition:
<ul class="nav nav-tabs content-tabs" id="maincontent" role="tablist">
jQuery:
$(document).ready(function() {
// DEPENDENCY: https://github.com/flatlogic/bootstrap-tabcollapse
$('.content-tabs').tabCollapse();
// initialize tab function
$('.nav-tabs a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
});
CSS -- optional for fat fingers and active states:
.panel-heading {
padding: 0
}
.panel-heading a {
display: block;
padding: 20px 10px;
}
.panel-heading a.collapsed {
background: #fff
}
.panel-heading a {
background: #f7f7f7;
border-radius: 5px;
}
.panel-heading a:after {
content: '-'
}
.panel-heading a.collapsed:after {
content: '+'
}
.nav.nav-tabs li a,
.nav.nav-tabs li.active > a:hover,
.nav.nav-tabs li.active > a:active,
.nav.nav-tabs li.active > a:focus {
border-bottom-width: 0px;
outline: none;
}
.nav.nav-tabs li a {
padding-top: 20px;
padding-bottom: 20px;
}
.tab-pane {
background: #fff;
padding: 10px;
border: 1px solid #ddd;
margin-top: -1px;
}
First line will reset form inputs
$('form#myform').trigger("reset"); //Line1
$('form#myform select').trigger("change"); //Line2
Second one will reset select2
Optional: You can use this if you have different types registered with different events
$('form#myform select, form input[type=checkbox]').trigger("change"); //Line2
html link example:
<!-- boostrap button + fontawesome icon -->
<a class="btn btn-primary" id="BT_Download" target="_blank" href="DownloadDoc?Id=32">
<i class="icon-file-text icon-large"></i>
Download Document
</a>
use this in jQuery
$('#BT_Download').attr('disabled',true);
add this to css :
a[disabled="disabled"] {
pointer-events: none;
}
Just for those people that have been idiots like me, or have had something odd happen to their vagrant machine. This error can also occur when you changed the permissions of the vagrant user's home directory (deliberately or by accident).
You can log in instead (as described in other posts) using the password ('vagrant') and then run the following command to fix the permissions.
sudo chown -R vagrant:vagrant /home/vagrant
Then you should be able to log in again without entering the password.
TL;DR: The permissions on your vagrant home folder are wrong.
If you have a Collection of stdClass objects, you could try with this:
$data = $data->map(function ($item){
return get_object_vars($item);
});
In Python 3 (I haven't tried this in Python 2), you can also simply do
with open('output.csv','w',newline='') as f:
writer=csv.writer(f)
writer.writerow(mystuff)
...
as per documentation.
More on this in the doc's footnote:
If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.
By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)
So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).
If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,
old question but this is a pretty neat and clean fix, might come in use for people who are still wondering if it's possible :):
br{_x000D_
content: '.';_x000D_
display: inline-block;_x000D_
width: 100%;_x000D_
border-bottom: 1px dashed black;_x000D_
}
_x000D_
with this fix you can also remove BRs on websites ( just set the width to 0px )
Eureka moment!
I have had this error before.
Did you invoke the perl debugger with something like :-
perl -d yourprog.pl > log.txt
If so whats going on is perl debug tries to query and perhaps reset the terminal width. When stdout is not a terminal this fails with the IOCTL message.
The alternative would be for your debug session to hang forever because you did not see the prompt for instructions.
I had the same requirement and I have done this in following way.You also can try out this..
Use loadData method
web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");
movDirector movProducer like all are my string variable.
In short i retain custom styling for my url.
As of now there is just two property for firefox scrollbar customization is available .
scrollbar-color & scrollbar width
scrollbar-color:red yellow; (track,thumb) scrollbar-width:5px;
HTML
<div class="demo">
css
.demo {
overflow-y:scroll;
}
.demo {
scrollbar-color:red yellow;
scrollbar-width:5px;
}
Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:
months = {
'January': 1,
'February': 2,
...
}
or
months = dict(
January=1,
February=2,
...
)
Then, you can use the symbolic name for the constants like this:
mymonth = months['January']
There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a "symbolic" (constant string) way to access the value.
Edit: I like Alexandru's answer too!
I have written my own that you can use. This one works has sqlite, is thread safe and is in C++ for UNIX.
You should be able to pick it apart and use the C compatible code.
(function( $ ) {
$.fn.keepRatio = function(which) {
var $this = $(this);
var w = $this.width();
var h = $this.height();
var ratio = w/h;
$(window).resize(function() {
switch(which) {
case 'width':
var nh = $this.width() / ratio;
$this.css('height', nh + 'px');
break;
case 'height':
var nw = $this.height() * ratio;
$this.css('width', nw + 'px');
break;
}
});
}
})( jQuery );
$(document).ready(function(){
$('#foo').keepRatio('width');
});
Working example: http://jsfiddle.net/QtftX/1/
Both perform the same function but driver.get(); seems more popular.
driver.navigate().to();
is best used when you are already in the middle of a script and you want to redirect from current URL to a new one. For the sake of differentiating your codes, you can use driver.get();
to launch the first URL after opening a browser instance, albeit both will work either way.
A shorthand answer assuming
import matplotlib.pyplot as plt
:
plt.gca().set_title('title')
as in:
plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...
Then there is no need for superfluous variables.
For add new PCH file follow bellow steps :
(1) Add New fiew - Select iOS - Other and PCH File
(2) add path of this PCH file to your Project - BuildSetting - Apple LLVM 6.0 Language
Add Set Prefix Header Path YourApplicationName(root-path)/filename.pch
If there are no formats in the string, you can use puts
(or fputs
):
puts("hello%");
if there is a format in the string:
printf("%.2f%%", 53.2);
As noted in the comments, puts
appends a \n
to the output and fputs
does not.
And to insert blank line between tables you can use these both methods
table.setSpacingBefore();
table.setSpacingAfter();
Put very simply, request timeout means there was no response whereas destination unreachable may mean the address specified does not exist i.e. you typed in the wrong IP address.
emacs with ruby-mode, rdebug and a ruby interactive inferior shell.
It's true, there are also more complete option, like changing the name of the app for a sentence you want. Check this tutorial it can help:
http://www.firstdroid.com/2010/08/04/adding-progress-bar-on-webview-android-tutorials/
In that tutorial you have a complete example how to use the progressbar in a webview app.
Adrian.
The problem is that the checkout takes place on a laptop and in this case subversion can not cope with the off-line synchronization. The problem is reproducable on an other laptop while on a desktop I have no problem checking out the same repository.
I hope this answer wil help you, it took me quite long to find out.
March 2014: Good news! Python 3.4 ships with Pip. Pip has long been Python's de-facto standard package manager. You can install a package like this:
pip install httpie
Wahey! This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup.
However, there remains a number of outstanding frustrations with the Python packaging experience. Cumulatively, they make Python very unwelcoming for newbies. Also, the long history of neglect (ie. not shipping with a package manager for 14 years from Python 2.0 to Python 3.3) did damage to the community. I describe both below.
It's important to understand that while experienced users are able to work around these frustrations, they are significant barriers to people new to Python. In fact, the difficulty and general user-unfriendliness is likely to deter many of them.
Every language with a package manager has an official (or quasi-official) repository for the community to download and publish packages. Python has the Python Package Index, PyPI. https://pypi.python.org/pypi
Let's compare its pages with those of RubyGems and Npm (the Node package manager).
rails
express
simplejson
You'll see the RubyGems and Npm pages both begin with a one-line description of the package, then large friendly instructions how to install it.
Meanwhile, woe to any hapless Python user who naively browses to PyPI. On https://pypi.python.org/pypi/simplejson/ , they'll find no such helpful instructions. There is however, a large green 'Download' link. It's not unreasonable to follow it. Aha, they click! Their browser downloads a .tar.gz
file. Many Windows users can't even open it, but if they persevere they may eventually extract it, then run setup.py
and eventually with the help of Google setup.py install
. Some will give up and reinvent the wheel..
Of course, all of this is wrong. The easiest way to install a package is with a Pip command. But PyPI didn't even mention Pip. Instead, it led them down an archaic and tedious path.
Numpy is one of Python's most popular libraries. Try to install it with Pip, you get this cryptic error message:
Error: Unable to find vcvarsall.bat
Trying to fix that is one of the most popular questions on Stack Overflow: "error: Unable to find vcvarsall.bat"
Few people succeed.
For comparison, in the same situation, Ruby prints this message, which explains what's going on and how to fix it:
Please update your PATH to include build tools or download the DevKit from http://rubyinstaller.org/downloads and follow the instructions at http://github.com/oneclick/rubyinstaller/wiki/Development-Kit
Ruby and Nodejs ship with full-featured package managers, Gem (since 2007) and Npm (since 2011), and have nurtured sharing communities centred around GitHub. Npm makes publishing packages as easy as installing them, it already has 64k packages. RubyGems lists 72k packages. The venerable Python package index lists only 41k.
Flying in the face of its "batteries included" motto, Python shipped without a package manager until 2014.
Until Pip, the de facto standard was a command easy_install
. It was woefully inadequate. The was no command to uninstall packages.
Pip was a massive improvement. It had most the features of Ruby's Gem. Unfortunately, Pip was--until recently--ironically difficult to install. In fact, the problem remains a top Python question on Stack Overflow: "How do I install pip on Windows?"
<div id="item">show taille height</div>
<script>
alert(document.getElementById('item').offsetHeight);
</script>
If you can use JQuery, then using the JQuery :focus selector will do the needful
$(this).is(':focus');
You could add justify-content: space-between
to the parent element. In doing so, the children flexbox items will be aligned to opposite sides with space between them.
#container {
width: 500px;
border: solid 1px #000;
display: flex;
justify-content: space-between;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You could also add margin-left: auto
to the second element in order to align it to the right.
#b {
width: 20%;
border: solid 1px #000;
height: 200px;
margin-left: auto;
}
#container {_x000D_
width: 500px;_x000D_
border: solid 1px #000;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#a {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
#b {_x000D_
width: 20%;_x000D_
border: solid 1px #000;_x000D_
height: 200px;_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="a">_x000D_
a_x000D_
</div>_x000D_
<div id="b">_x000D_
b_x000D_
</div>_x000D_
</div>
_x000D_
You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.
CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4
Mind that you need to use the wildcards in PATINDEX on either side.
Credit to @rominator007
I wrapped it into a function (because you may want to use it again)
function Replace-AllStringsInFile($SearchString,$ReplaceString,$FullPathToFile)
{
$content = [System.IO.File]::ReadAllText("$FullPathToFile").Replace("$SearchString","$ReplaceString")
[System.IO.File]::WriteAllText("$FullPathToFile", $content)
}
NOTE: This is NOT case sensitive!!!!!
See this post: String.Replace ignoring case
Similar to the above answer, but written differently.
$.extend(
{
redirectPost: function (location, args) {
var form = $('<form>', { action: location, method: 'post' });
$.each(args,
function (key, value) {
$(form).append(
$('<input>', { type: 'hidden', name: key, value: value })
);
});
$(form).appendTo('body').submit();
}
});
This is an extension to Langdon's answer with a directive approach to the problem. If you're going to have multiple galleries on the page this may be one way to go about it without much fuss.
Usage:
<gallery images="items"></gallery>
<gallery images="cats"></gallery>
In my case I exported Drupal instance from server to localhost on XAMPP. It obviously did not do justice to the file and directory ownership and Apache was throwing the above error.
This is the ownership of files and directories initially:
To give read permissions to my files and execute permission to my directories I could do so that all users can read, write and execute:
sudo chmod 777 -R
but that would not be the ideal solution coz this would be migrated back to server and might end up with a security loophole.
A script is given in this blog: https://www.drupal.org/node/244924
#!/bin/bash
# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:
1) Path to your Drupal installation.
2) Username of the user that you want to give files/directories ownership.
3) HTTPD group name (defaults to www-data for Apache).
Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}
if [ $(id -u) != 0 ]; then
printf "**************************************\n"
printf "* Error: You must run this with sudo or root*\n"
printf "**************************************\n"
print_help
exit 1
fi
drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"
# Parse Command Line Arguments
while [ "$#" -gt 0 ]; do
case "$1" in
--drupal_path=*)
drupal_path="${1#*=}"
;;
--drupal_user=*)
drupal_user="${1#*=}"
;;
--httpd_group=*)
httpd_group="${1#*=}"
;;
--help) print_help;;
*)
printf "***********************************************************\n"
printf "* Error: Invalid argument, run --help for valid arguments. *\n"
printf "***********************************************************\n"
exit 1
esac
shift
done
if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
printf "*********************************************\n"
printf "* Error: Please provide a valid Drupal path. *\n"
printf "*********************************************\n"
print_help
exit 1
fi
if [ -z "${drupal_user}" ] || [[ $(id -un "${drupal_user}" 2> /dev/null) != "${drupal_user}" ]]; then
printf "*************************************\n"
printf "* Error: Please provide a valid user. *\n"
printf "*************************************\n"
print_help
exit 1
fi
cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .
printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;
printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done setting proper permissions on files and directories"
And need to invoke the command:
sudo bash /Applications/XAMPP/xamppfiles/htdocs/fix-permissions.sh --drupal_path=/Applications/XAMPP/xamppfiles/htdocs/rkmission --drupal_user=daemon --httpd_group=admin
In my case the user on which Apache is running is 'daemon'. You can identify the user by just running this php script in a php file through localhost:
<?php echo exec('whoami');?>
Below is the right user with right file permissions for Drupal:
You might have to change it back once it is transported back to server!
These are the two options I managed to build, not having the luxury of working with var
type, nor with additional variables on the line:
string f = "aS.".Substring(0, "aS.".IndexOf("S"));
Console.WriteLine(f);
string s = "aS.".Split("S".ToCharArray(),StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(s);
This is what it gets:
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
Try to make Treemap < Integer, Treemap<Integer, obj> >
In java, Treemap is sorted map. And the number of item in row and col wont screw the 2D-index you want to set. Then you can get a col-row table like structure.
Swift 4 Version
If you want to create a name for NotificationCenter:
extension Notification.Name {
static let updateDataList1 = Notification.Name("updateDataList1")
}
Subscribe to notifications:
NotificationCenter.default.addObserver(self, selector: #selector(youFunction), name: .updateDataList1, object: nil)
Send notification:
NotificationCenter.default.post(name: .updateDataList1, object: nil)
If you just want a class with variables to use:
class Keys {
static let key1 = "YOU_KEY"
static let key2 = "YOU_KEY"
}
Or:
struct Keys {
static let key1 = "YOU_KEY"
static let key2 = "YOU_KEY"
}
Just append #[id of the div you want to scroll to]
to your page url. For example, if I wanted to scroll to the copyright section of this stackoverflow question, the URL would change from
http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load
to
http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load#copyright
notice the #copyright
at the end of the URL.
Another way to solve this would be with a LEFT JOIN
, which could be more efficient. I'll first start with an example that considers only the date field, as probably it is more common to store date + time in one datetime column, and I also want to keep the query simple so it's easier to understand.
So, with this particular example, if you want to show the oldest record based on the date column, and assuming that your table name is called people
you can use the following query:
SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date > p2.date
WHERE p2.date is NULL
GROUP BY p.name
What the LEFT JOIN
does, is when the p.date
column is at its minimum value, there will be no p2.date
with a smaller value on the left join and therefore the corresponding p2.date
will be NULL
. So, by adding WHERE p2.date is NULL
, we make sure to show only the records with the oldest date.
And similarly, if you want to show the newest record instead, you can just change the comparison operator in the LEFT JOIN
:
SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date < p2.date
WHERE p2.date is NULL
GROUP BY p.name
Now, for this particular example where date+time are separate columns, you would need to add them in some way if you want to query based on the datetime of two columns combined, for example:
SELECT p.* FROM people p
LEFT JOIN people p2 ON p.name = p2.name AND p.date + INTERVAL TIME_TO_SEC(p.time) SECOND > p2.date + INTERVAL TIME_TO_SEC(p2.time) SECOND
WHERE p2.date is NULL
GROUP BY p.name
You can read more about this (and also see some other ways to accomplish this) on the The Rows Holding the Group-wise Maximum of a Certain Column page.
var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']
First check the list:-
git stash list
copy the index you wanted to pop from the stash list
git stash pop stash@{index_number}
eg.:
git stash pop stash@{1}
I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?
Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...
Add permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Import:
import android.telephony.TelephonyManager;
Use the below code:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
imei = tm.getDeviceId();
// get SimSerialNumber
simSerialNumber = tm.getSimSerialNumber();
<?php //-- Very simple variant
$useragent = $_SERVER['HTTP_USER_AGENT'];
$iPod = stripos($useragent, "iPod");
$iPad = stripos($useragent, "iPad");
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android");
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices
$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS||$webOS||$Blackberry||$IEMobile||$OperaMini);
if ($DEVICE !=true) {?>
<!-- What you want for all non-mobile devices. Anything with all HTML codes-->
<?php }else{ ?>
<!-- What you want for all mobile devices. Anything with all HTML codes -->
<?php } ?>
FIRST: make sure you have a color as a bitmap, like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
(e is from the event handler wich picked my color!)
What I did when I had this problem a whilke ago, I first got the rgba (red, green, blue and alpha) values. Next I created 3 floats: float hue, float saturation, float brightness. Then you simply do:
hue = yourcolor.Gethue;
saturation = yourcolor.GetSaturation;
brightness = yourcolor.GetBrightness;
The whole lot looks like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
float hue;
float saturation;
float brightness;
hue = paintcolor.GetHue();
saturation = paintcolor.GetSaturation();
brightness = paintcolor.GetBrightness();
If you now want to display them in a label, just do:
yourlabelname.Text = hue.ToString;
yourlabelname.Text = saturation.ToString;
yourlabelname.Text = brightness.ToString;
Here you go, you now have RGB Values into HSV values :)
Hope this helps
Pass --jars
with the path of jar
files separated by ,
to spark-submit
.
For reference:
--driver-class-path is used to mention "extra" jars to add to the "driver" of the spark job
--driver-library-path is used to "change" the default library path for the jars needed for the spark driver
--driver-class-path will only push the jars to the driver machine. If you want to send the jars to "executors", you need to use --jars
And to set the jars programatically set the following config:
spark.yarn.dist.jars
with comma-separated list of jars.
Eg:
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Spark config example") \
.config("spark.yarn.dist.jars", "<path-to-jar/test1.jar>,<path-to-jar/test2.jar>") \
.getOrCreate()
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
There is pure CSS4 solution:
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
user-select
is a CSS Module Level 4 specification, that is currently a draft and non-standard CSS property, but browsers support it well — see #search=user-select.
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
_x000D_
<div class="selectable">
click and all this will be selected
</div>
_x000D_
Read more on user-select here on MDN and play with it here in w3scools
You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen. This blog talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.
Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.
If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.
For more info on these techniques, please click here to refer the article
String[] s = {"a", "x", "y"};
Arrays.sort(s, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
System.out.println(Arrays.toString(s));
-> [y, x, a]
Now you have to implement the Comparator for your Person class.
Something like (for ascending order): compare(Person a, Person b) = a.id < b.id ? -1 : (a.id == b.id) ? 0 : 1
or Integer.valueOf(a.id).compareTo(Integer.valueOf(b.id))
.
To minimize confusion you should implement an ascending Comparator and convert it to a descending one with a wrapper (like this) new ReverseComparator<Person>(new PersonComparator())
.
I guess you want to get number(s) from the string. In which case, you can use the following:
// Returns an array of numbers located in the string
function get_numbers(input) {
return input.match(/[0-9]+/g);
}
var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');
alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null
Left bit shifting to multiply by any power of two and right bit shifting to divide by any power of two.
For example, x = x * 2;
can also be written as x<<1
or x = x*8
can be written as x<<3
(since 2 to the power of 3 is 8). Similarly x = x / 2;
is x>>1
and so on.
i used pagewil's print method, and it worked very nicely.
here is my slightly extended version with (sloppy) indents and distinct prop/ob delimiters:
var print = function(obj, delp, delo, ind){
delp = delp!=null ? delp : "\t"; // property delimeter
delo = delo!=null ? delo : "\n"; // object delimeter
ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
var str='';
for(var prop in obj){
if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
}else{
str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
}
}
return str;
};
SET GLOBAL auto_increment_offset=1;
SET GLOBAL auto_increment_increment=5;
auto_increment_offset: interval between successive column values
auto_increment_offset: determines the starting point for the AUTO_INCREMENT column value. The default value is 1.
I'd recommend the following solution.
It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.
from os import environ
REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
raise EnvironmentError(f'Failed because {diff} are not set')
What you suggest is impossible. You will always have collisions.
In order to map two objects to another single set, the mapped set must have a minimum size of the number of combinations expected:
Assuming a 32-bit integer, you have 2147483647 positive integers. Choosing two of these where order doesn't matter and with repetition yields 2305843008139952128 combinations. This does not fit nicely in the set of 32-bit integers.
You can, however fit this mapping in 61 bits. Using a 64-bit integer is probably easiest. Set the high word to the smaller integer and the low word to the larger one.
for word in d:
if d in paid[j]:
do_something()
will try all the words in the list d
and check if they can be found in the string paid[j]
.
This is not very efficient since paid[j]
has to be scanned again for each word in d
. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.
sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]
s1 = set(sentence.split())
s2 = set(d)
print (s1.intersection(s2))
Output:
{'come', 'easy'}
I also had problem with refused connection on port 80. I didn't use localhost.
curl --data-binary "@/textfile.txt" "http://www.myserver.com/123.php"
Problem was that I had umlauts äåö in my textfile.txt.
Example query:
DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)
Here fields
are column on which you want to group the duplicate rows.
If you put position:relative;
on the outer element, the inner element will place itself according to this one. Then a width:auto;
on the inner element will be the same as the width of the outer.
import datetime
from dateutil.rrule import DAILY,rrule
date=datetime.datetime(2019,1,10)
date1=datetime.datetime(2019,2,2)
for i in rrule(DAILY , dtstart=date,until=date1):
print(i.strftime('%Y%b%d'),sep='\n')
OUTPUT:
2019Jan10
2019Jan11
2019Jan12
2019Jan13
2019Jan14
2019Jan15
2019Jan16
2019Jan17
2019Jan18
2019Jan19
2019Jan20
2019Jan21
2019Jan22
2019Jan23
2019Jan24
2019Jan25
2019Jan26
2019Jan27
2019Jan28
2019Jan29
2019Jan30
2019Jan31
2019Feb01
2019Feb02
All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).
So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.
Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.
Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.
As per Apple:
A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.
Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).
The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.
So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.
The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.
With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.
Private Sub Open_multiple_sub_pages_from_main_page()
Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True
' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"
' Wait while IE loading...
While IE.Busy
DoEvents
Wend
Set objCollection = IE.Document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "txtUserName" Then
' Set text for search
objCollection(i).Value = "1234"
End If
If objCollection(i).Name = "txtPwd" Then
' Set text for search
objCollection(i).Value = "password"
End If
If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
Set objElement = objCollection(i)
End If
i = i + 1
Wend
objElement.Click ' click button to load page
' Wait while IE re-loading...
While IE.Busy
DoEvents
Wend
' Show IE
IE.Visible = True
Set Doc = IE.Document
Dim links, link
Dim j As Integer 'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n 'loop to go thru all "a" item so it loads next page
links(j).Click
While IE.Busy
DoEvents
Wend
'-------------Do stuff here: copy field value and paste in excel sheet. Will post another question for this------------------------
IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click 'save
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click 'close
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
j = j + 2
Wend
End Sub
Another solution would be dictdiffer
(https://github.com/inveniosoftware/dictdiffer).
import dictdiffer
a_dict = {
'a': 'foo',
'b': 'bar',
'd': 'barfoo'
}
b_dict = {
'a': 'foo',
'b': 'BAR',
'c': 'foobar'
}
for diff in list(dictdiffer.diff(a_dict, b_dict)):
print diff
A diff is a tuple with the type of change, the changed value, and the path to the entry.
('change', 'b', ('bar', 'BAR'))
('add', '', [('c', 'foobar')])
('remove', '', [('d', 'barfoo')])
The simplest thing would be to check the timestamp of the table files on the disk. For example, You can check under your data directory
cd /var/lib/mysql/<mydatabase>
ls -lhtr *.ibd
This should give you the list of all tables with the table when it was last modified the oldest time, first.
I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved. note using Lavalite framework. before:
public function Activity($id)
{
$data=getData();
return
$this->response->title('title')
->layout('layout')
->data(compact('data'))
->view('view')
->output();
}
after code looks like:
try {
$attributes = $request->all();
//do something
return $this->response->message('')
->code(204)
->status('success')
->url('url'. $data->id)
->redirect();
} catch (Exception $e) {
return $this->response->message($e->getMessage())
->code(400)
->status('error')
->url('nothing Wrong')
->redirect()
}
this worked for me
#testdiv {
border-left: 1px solid;
}
A little late to the game on this post, but I found this way to be pretty flexible / efficient
select
s1.id
,s1.name
,s1.city
from
stuff s1
,stuff s2
Where
s1.id <> s2.id
and s1.name = s2.name
and s1.city = s2.city
If you're using StringEntity
try this, using your choice of character encoding. It handles foreign characters as well.
I use this to sort the users, so the permitted hosts are more easy to spot:
mysql> SELECT User,Host FROM mysql.user ORDER BY User,Host;
another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.
Is this what you are looking for? Otherwise, let me know and I will remove this post.
Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect
Demo: http://www.stoimen.com/jquery.client.plugin/
This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.
For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html
And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js
They use regular CSS.
Just use your regular font family like this:
font-family: 'Open Sans', sans-serif;
Now you decide what "weight" the font should have by adding
for semi-bold
font-weight:600;
for bold (700)
font-weight:bold;
for extra bold (800)
font-weight:800;
Like this its fallback proof, so if the google font should "fail" your backup font Arial/Helvetica(Sans-serif) use the same weight as the google font.
Pretty smart :-)
Note that the different font weights have to be specifically imported via the link tag url (family query param of the google font url) in the header.
For example the following link will include both weights 400 and 700:
<link href='fonts.googleapis.com/css?family=Comfortaa:400,700'; rel='stylesheet' type='text/css'>
The icon file is added to your project as a content file.
Here you go:
$( table ).delegate( '.tr_clone_add', 'click', function () {
var thisRow = $( this ).closest( 'tr' )[0];
$( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});
Live demo: http://jsfiddle.net/RhjxK/4/
Update: The new way of delegating events in jQuery is
$(table).on('click', '.tr_clone_add', function () { … });
Created a .r file and saved it in Desktop together with a sample_10000.csv file.
Once trying to read it
heisenberg <- read.csv(file="sample_100000.csv")
was getting the same error as you
heisenberg <- read.csv(file="sample_10000") Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file 'sample_10000': No such file or directory
I knew at least two ways to fix this, one using the absolute path and the other changing the working directory.
I fixed it adding the absolute path to the file, more precisely
heisenberg <- read.csv(file="C:/Users/tiago/Desktop/sample_100000.csv")
This error shows up because RStudio has a specific working directory defined which isn't necessarily the place the .r file is at.
So, to fix using this approach I've gone to Session > Set Working Directory > Chose Directory (CTRL + Shift + H) and selected Desktop, where the .csv file was at. That way running the following command also worked
heisenberg <- read.csv(file="sample_100000.csv")
this code working for socketError 11004 and 10060......
# -*- encoding:UTF-8 -*-
__author__ = 'ACE'
import requests
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TimeOutModel(QThread):
Existed = pyqtSignal(bool)
TimeOut = pyqtSignal()
def __init__(self, fun, timeout=500, parent=None):
"""
@param fun: function or lambda
@param timeout: ms
"""
super(TimeOutModel, self).__init__(parent)
self.fun = fun
self.timeer = QTimer(self)
self.timeer.setInterval(timeout)
self.timeer.timeout.connect(self.time_timeout)
self.Existed.connect(self.timeer.stop)
self.timeer.start()
self.setTerminationEnabled(True)
def time_timeout(self):
self.timeer.stop()
self.TimeOut.emit()
self.quit()
self.terminate()
def run(self):
self.fun()
bb = lambda: requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip")
a = QApplication([])
z = TimeOutModel(bb, 500)
print 'timeout'
a.exec_()
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName();
and hit return.
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary
For those whose want created or modified user detail along with the time using JPA and Spring Data can follow this. You can add @CreatedDate
,@LastModifiedDate
,@CreatedBy
and @LastModifiedBy
in the base domain. Mark the base domain with @MappedSuperclass
and @EntityListeners(AuditingEntityListener.class)
like shown below:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseDomain implements Serializable {
@CreatedDate
private Date createdOn;
@LastModifiedDate
private Date modifiedOn;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String modifiedBy;
}
Since we marked the base domain with AuditingEntityListener
we can tell JPA about currently logged in user. So we need to provide an implementation of AuditorAware and override getCurrentAuditor()
method. And inside getCurrentAuditor()
we need to return the currently authorized user Id.
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication == null ? Optional.empty() : Optional.ofNullable(authentication.getName());
}
}
In the above code if Optional
is not working you may using older spring data. In that case try changing Optional
with String
.
Now for enabling the above Audtior implementation use the code below
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
@Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
Now you can extend the BaseDomain
class to all of your entity class where you want the created and modified date & time along with user Id
If anyone struggle with that problem using docker + nginx, it could be permissions. Nginx logs shown error:
2019/12/16 08:54:58 [crit] 6#6: *23 open() "/var/tmp/nginx/fastcgi/4/00/0000000004" failed (13: Permission denied) while reading upstream, client: 172.24.0.2, server: test.loc, request: "GET /login HTTP/1.1", upstream: "fastcgi://172.28.0.2:9001", host: "test.loc"
Run inside nginx container(path might vary):
chown -R www-data:www-data /var/tmp/nginx/
In case of SQL Server, this should work
SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond
To solve this issue more globally, here is another way using a directive:
import { Directive, HostListener, ElementRef } from "@angular/core";
@Directive({
selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
constructor(elementRef: ElementRef) {}
@HostListener("click", ["$event"])
onClick(event: MouseEvent) {
event.preventDefault();
let url: string = (<any>event.currentTarget).getAttribute("href");
if (url && url.indexOf("http") === -1) {
url = `//${url}`;
}
window.open(url, "_blank");
}
}
then it's as simple as using it like this:
<a [href]="url" hrefExternalUrl> Link </a>
and don't forget to declare the directive in your module.
CSS properties should be set by cssText
property or setAttribute
method.
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
Styles should not be set by assigning a string directly to the style
property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style
attribute returns a CSSStyleDeclaration
object which is also read-only.
All You have to do is git push origin master
, where origin
is the default name (alias) of Your remote repository and master
is the remote branch You want to push Your changes to.
You may also want to check these out:
Shorter version:
$('#multiselect1').multiselect({
...
onChange: function() {
console.log($('#multiselect1').val());
}
});
GIT uses colored output by default but on some system like as CentOS it is not enabled . You can enable it like this
git config --global color.ui true
git config --global color.ui false
git config --global color.ui auto
You can choose your required command from here .
Here --global is optional to apply action for every repository in your system . If you want to apply coloring for current repository only then you can do something like this -
git config color.ui true
For WebAPI, check out this link: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
Basically, add this code to your Application_Start
:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
Minimal runnable example
Main.java
public class Main {
public native int square(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().square(2));
}
}
Main.c
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_square(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and run:
sudo apt-get install build-essential openjdk-7-jdk
export JAVA_HOME='/usr/lib/jvm/java-7-openjdk-amd64'
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
Output:
4
Tested on Ubuntu 14.04 AMD64. Also worked with Oracle JDK 1.8.0_45.
Example on GitHub for you to play with.
Underscores in Java package / file names must be escaped with _1
in the C function name as mentioned at: Invoking JNI functions in Android package name containing underscore
Interpretation
native
allows you to:
This could be used to:
with the tradeoff of lower portability.
It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?
Analogous native extension APIs are also present in many other "VM languages" for the same reasons, e.g. Python, Node.js, Ruby.
Android NDK
The concept is exact the same in this context, except that you have to use Android boilerplate to set it up.
The official NDK repository contains "canonical" examples such as the hello-jni app:
In you unzip
an .apk
with NDK on Android O, you can see the pre-compiled .so
that corresponds to the native code under lib/arm64-v8a/libnative-lib.so
.
TODO confirm: furthermore, file /data/app/com.android.appname-*/oat/arm64/base.odex
, says it is a shared library, which I think is the AOT precompiled .dex corresponding to the Java files in ART, see also: What are ODEX files in Android? So maybe the Java is actually also run via a native
interface?
Example in the OpenJDK 8
Let's find find where Object#clone
is defined in jdk8u60-b27.
We will conclude that it is implemented with a native
call.
First we find:
find . -name Object.java
which leads us to jdk/src/share/classes/java/lang/Object.java#l212:
protected native Object clone() throws CloneNotSupportedException;
Now comes the hard part, finding where clone is amidst all the indirection. The query that helped me was:
find . -iname object.c
which would find either C or C++ files that might implement Object's native methods. It leads us to jdk/share/native/java/lang/Object.c#l47:
static JNINativeMethod methods[] = {
...
{"clone", "()Ljava/lang/Object;", (void *)&JVM_Clone},
};
JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
(*env)->RegisterNatives(env, cls,
methods, sizeof(methods)/sizeof(methods[0]));
}
which leads us to the JVM_Clone
symbol:
grep -R JVM_Clone
which leads us to hotspot/src/share/vm/prims/jvm.cpp#l580:
JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
JVMWrapper("JVM_Clone");
After expanding a bunch of macros, we come to the conclusion that this is the definition point.
As Sotirios explains, you can not use the ParameterizedTypeReference
, but ParameterizedTypeReference is used only to provide Type
to the object mapper, and as you have the class that is removed when type erasure happens, you can create your own ParameterizedType
and pass that to RestTemplate
, so that the object mapper can reconstruct the object you need.
First you need to have the ParameterizedType interface implemented, you can find an implementation in Google Gson project here.
Once you add the implementation to your project, you can extend the abstract ParameterizedTypeReference
like this:
class FakeParameterizedTypeReference<T> extends ParameterizedTypeReference<T> {
@Override
public Type getType() {
Type [] responseWrapperActualTypes = {MyClass.class};
ParameterizedType responseWrapperType = new ParameterizedTypeImpl(
ResponseWrapper.class,
responseWrapperActualTypes,
null
);
return responseWrapperType;
}
}
And then you can pass that to your exchange function:
template.exchange(
uri,
HttpMethod.POST,
null,
new FakeParameterizedTypeReference<ResponseWrapper<T>>());
With all the type information present object mapper will properly construct your ResponseWrapper<MyClass>
object
Use <button>
element instead of <input type=button />
In a function:
a += 1
will be interpreted by the compiler as assign to a => Create local variable a
, which is not what you want. It will probably fail with a a not initialized
error since the (local) a has indeed not been initialized:
>>> a = 1
>>> def f():
... a += 1
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
You might get what you want with the (very frowned upon, and for good reasons) global
keyword, like so:
>>> def f():
... global a
... a += 1
...
>>> a
1
>>> f()
>>> a
2
In general however, you should avoid using global variables which become extremely quickly out of hand. And this is especially true for multithreaded programs, where you don't have any synchronization mechanism for your thread1
to know when a
has been modified. In short: threads are complicated, and you cannot expect to have an intuitive understanding of the order in which events are happening when two (or more) threads work on the same value. The language, compiler, OS, processor... can ALL play a role, and decide to modify the order of operations for speed, practicality or any other reason.
The proper way for this kind of thing is to use Python sharing tools (locks and friends), or better, communicate data via a Queue instead of sharing it, e.g. like this:
from threading import Thread
from queue import Queue
import time
def thread1(threadname, q):
#read variable "a" modify by thread 2
while True:
a = q.get()
if a is None: return # Poison pill
print a
def thread2(threadname, q):
a = 0
for _ in xrange(10):
a += 1
q.put(a)
time.sleep(1)
q.put(None) # Poison pill
queue = Queue()
thread1 = Thread( target=thread1, args=("Thread-1", queue) )
thread2 = Thread( target=thread2, args=("Thread-2", queue) )
thread1.start()
thread2.start()
thread1.join()
thread2.join()
As Ennui mentioned, IE 10 supports the -ms
prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:
display: -ms-flexbox
instead of display: -ms-flex
flex
values, like flex: 0 1 auto
to avoid ambiguitySo the final updated code is...
.flexbox form {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flexbox;
display: -o-flex;
display: flex;
/* Direction defaults to 'row', so not really necessary to specify */
-webkit-flex-direction: row;
-moz-flex-direction: row;
-ms-flex-direction: row;
-o-flex-direction: row;
flex-direction: row;
}
.flexbox form input[type=submit] {
width: 31px;
}
.flexbox form input[type=text] {
width: auto;
/* Flex should have 3 values which is shorthand for
<flex-grow> <flex-shrink> <flex-basis> */
-webkit-flex: 1 1 auto;
-moz-flex: 1 1 auto;
-ms-flex: 1 1 auto;
-o-flex: 1 1 auto;
flex: 1 1 auto;
/* I don't think you need 'display: flex' on child elements * /
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
/**/
}
passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.
Adding onKeyPress will work onChange in Text Field.
<TextField
onKeyPress={(ev) => {
console.log(`Pressed keyCode ${ev.key}`);
if (ev.key === 'Enter') {
// Do code here
ev.preventDefault();
}
}}
/>
just try this one:
1)Share a folder with full permission in your computer
2) in your SQL server : control panel -> administrative tools -> services -> right click on all SQL services
on log on tab should start with your domain administrator
3) in maintenance wizard of sql server place the back up location and folder (\yourcomputername\sharedfoldernam)
I did remote backup on 8 server of sql server 2008 in our company
EL interprets ${class.name}
as described - the name becomes getName() on the assumption you are using explicit or implicit methods of generating getter/setters
You can override this behavior by explicitly identifying the name as a function:
${class.name()}
This calls the function name() directly without modification.
Microsoft Example Rnd Function
https://msdn.microsoft.com/en-us/library/f7s023d2%28v=vs.90%29.aspx
1- Initialize the random-number generator.
Randomize()
2 - Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))
I did all of these steps and nothing helped me. And what I need, it's just to run my app via IIS Express...
Hope it helps.
and
is the same as &&
but with lower precedence. They both use short-circuit evaluation.
WARNING: and
even has lower precedence than =
so you'll usually want to avoid and
. An example when and
should be used can be found in the Rails Guide under "Avoiding Double Render Errors".
I have used this simple code, and it works!
for (int i = 0; i < N * N; i++)
{
Thread.Sleep(50);
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
(float)10.25, FontStyle.Bold),
Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
}
It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#
I used this code, and it does work.
Create a Random object with a seed and get the array random by doing:
public static final int ARRAY_LENGTH = 20;
byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);
I got the same issue but Sometimes, the most dificult issue get simple answer.
I recheck the manifest permisions and there WAS_NOT write permision shame of me!!!
This could be done running a simple find
command:
find * -maxdepth 0 -exec mv {} PRE_{} \;
The above command will prefix all files and folders in the current directory with PRE_
.
this is my solution:
public Bitmap Blend(Bitmap topImage1, Bitmap bottomImage1, PorterDuff.Mode Type) {
Bitmap workingBitmap = Bitmap.createBitmap(topImage1);
Bitmap topImage = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Bitmap workingBitmap2 = Bitmap.createBitmap(bottomImage1);
Bitmap bottomImage = workingBitmap2.copy(Bitmap.Config.ARGB_8888, true);
Rect dest = new Rect(0, 0, bottomImage.getWidth(), bottomImage.getHeight());
new BitmapFactory.Options().inPreferredConfig = Bitmap.Config.ARGB_8888;
bottomImage.setHasAlpha(true);
Canvas canvas = new Canvas(bottomImage);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Type));
paint.setFilterBitmap(true);
canvas.drawBitmap(topImage, null, dest, paint);
return bottomImage;
}
usage :
imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.SCREEN));
or
imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.OVERLAY));
and the results :
This issue might be helpful for you, it explains how to achieve TPUStrategy
, a popular functionality of tf.contrib
in TF<2.0.
So, in TF 1.X you could do the following:
resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.contrib.distribute.initialize_tpu_system(resolver)
strategy = tf.contrib.distribute.TPUStrategy(resolver)
And in TF>2.0, where tf.contrib
is deprecated, you achieve the same by:
tf.config.experimental_connect_to_host('grpc://' + os.environ['COLAB_TPU_ADDR'])
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver)
Another simple example using ImageView to toggle visibility with less code, because of single InputType assign we need only equality operator:
EditText inputPassword = (EditText) findViewById(R.id.loginPassword);
ImageView inputPasswordShow = (ImageView) findViewById(R.id.imagePasswordShow);
inputPasswordShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(inputPassword.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
inputPassword.setInputType( InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
}else {
inputPassword.setInputType( InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
}
inputPassword.setSelection(inputPassword.getText().length());
}
});
Replacing :
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
With :
InputType.TYPE_CLASS_TEXT
Will give the same result but shorter word.
This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.
When selecting Run As..., go into the run configurations.
On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).
Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.
I used to use Firebug, until Internet Explorer 8 came out. I'm not a huge fan of Internet Explorer, but after spending some time with the built-in developer tools, which includes a really nice debugger, it seems pointless to use anything else. I have to tip my hat to Microsoft they did a fantastic job on this tool.
If you have seaborn
installed, an easier method that does not require you to perform pivot
:
import seaborn as sns
sns.lineplot(data=df, x='x', y='y', hue='color')
For PHP 7 and Ubuntu 14.04 the procedure is follows. Since PHP 7 is not in the official Ubuntu PPAs you likely installed it through Ondrej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). Go to /etc/php/7.0/fpm and edit php.ini, uncomment to following line:
extension=php_xmlrpc.dll
Then simply install php7.0-xml:
sudo apt-get install php7.0-xml
And restart PHP:
sudo service php7.0-fpm restart
And restart Apache:
sudo service apache2 restart
If you are on a later Ubuntu version where PHP 7 is included, the procedure is most likely the same as well (except adding any 3rd party repository).
Although the other answers solve the OP's problem, they are all overkill and do not explain why he or she is experiencing this issue.
The key is this line, "I close putty, then I cannot reach the address"
When you are logged into your remote host on Putty you have started an SSH linux process and all commands typed from that SSH session will be executed as children of said process.
Your problem is that when you close Putty you are exiting the SSH session which kills that process and any active child processes. When you close putty you inadvertently kill your server because you ran it in the foreground. To avoid this behavior run the server in the background by appending & to your command:
node /srv/www/MyUserAccount/server/server.js &
The problem here is a lack of linux knowledge and not a question about node. For some more info check out: http://linuxconfig.org/understanding-foreground-and-background-linux-processes
UPDATE:
As others have mentioned, the node server may still die when exiting the terminal. A common gotcha I have come across is that even though the node process is running in bg, it's stdout and stderr is still pointed at the terminal. This means that if the node server writes to console.log or console.error it will receive a broken pipe error and crash. This can be avoided by piping the output of your process:
node /srv/www/MyUserAccount/server/server.js > stdout.txt 2> stderr.txt &
If the problem persists then you should look into things like tmux or nohup, which are still more robust than node specific solutions, because they can be used to run all types of processes (databases, logging services, other languages).
A common mistake that could cause the server to exit is that after running the nohup node your_path/server.js &
you simply close the Putty terminal by a simple click. You should use exit
command instead, then your node server will be up and running.
Practice safe computing. Simply go up one level in the hierarchy and don't use a wildcard expression:
cd ..; rm -rf -- <dir-to-remove>
The two dashes --
tell rm
that <dir-to-remove>
is not a command-line option, even when it begins with a dash.
Libpng-1.6 is more stringent about checking ICC profiles than previous versions. You can ignore the warning. To get rid of it, remove the iCCP chunk from the PNG image.
Some applications treat warnings as errors; if you are using such an application you do have to remove the chunk. You can do that with any of a variety of PNG editors such as ImageMagick's
convert in.png out.png
To remove the invalid iCCP chunk from all of the PNG files in a folder (directory), you can use mogrify
from ImageMagick:
mogrify *.png
This requires that your ImageMagick was built with libpng16. You can easily check it by running:
convert -list format | grep PNG
If you'd like to find out which files need to be fixed instead of blindly processing all of them, you can run
pngcrush -n -q *.png
where the -n
means don't rewrite the files and -q
means suppress most of the output except for warnings. Sorry, there's no option yet in pngcrush to suppress everything but the warnings.
Binary Releases of ImageMagick are here
For Android Projects (Android Studio) navigate into res
folder.
For example:
C:\{your_project_folder}\app\src\main\res\drawable-hdpi\mogrify *.png
It's compiling because printf
isn't type safe, since it uses variable arguments in the C sense1. printf
has no option for std::string
, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.
The easiest way to fix this, since you're using C++, is printing it normally with std::cout
, since std::string
supports that through operator overloading:
std::cout << "Follow this command: " << myString;
If, for some reason, you need to extract the C-style string, you can use the c_str()
method of std::string
to get a const char *
that is null-terminated. Using your example:
#include <iostream>
#include <string>
#include <stdio.h>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString.c_str()); //note the use of c_str
cin.get();
return 0;
}
If you want a function that is like printf
, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format
.
[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf
, that means a string with encoded type information like %d
meaning int
. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.
It exists, but it's hard to search for. I think most people call it the "splat" operator.
It's in the documentation as "Unpacking argument lists".
You'd use it like this: foo(*values)
. There's also one for dictionaries:
d = {'a': 1, 'b': 2}
def foo(a, b):
pass
foo(**d)
just for modifying certain property from object collection you could directly use forEach with a collection as follows
collection.forEach(c -> c.setXyz(c.getXyz + "a"))
You can set the state of the checkbox based on the value:
$('#your-checkbox').prop('checked', value == 1);
Just to phrase things differently from the great answers above, as that has helped me get an intuitive understanding of negative margins:
A negative margin on an element allows it to eat up the space of its parent container.
Adding a (positive) margin on the bottom doesn't allow the element to do that - it only pushes back whatever element is below.
From the spec, §15.9.1.1:
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.
Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.
The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000)
, which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).
Even array2.extend(array1)
will work.
I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:
fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
The solution from @VonC on this thread didn't work for me.
The solution from this Fabian Lee's article solved it for me:
openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt
If you want to launch SMS Composing activity from some of your other activity and you also have to pass a phone number and SMS text, then use this code:
Uri sms_uri = Uri.parse("smsto:+92xxxxxxxx");
Intent sms_intent = new Intent(Intent.ACTION_SENDTO, sms_uri);
sms_intent.putExtra("sms_body", "Good Morning ! how r U ?");
startActivity(sms_intent);
Note: here the sms_body
and smsto:
is keys for recognizing the text and phone no at SMS compose activity, so be careful here.
So for resuming...
If you have the IntelliJ Ultimate the correct answer is the one provided by Daniel Bubenheim
But if you don't, create in Run->Edit Configurations and in Configuration tab add the next Environment variable:
SPRING_PROFILES_ACTIVE=profilename
And to execute the jar do:
java -jar -Dspring.profiles.active=profilename XXX.jar
This is the way Visual Studio is designed: One solution, one Visual Studio (VS) instance.
Besides switching between solutions in one VS instance, you can also open another VS instance and open your other solution with that one. Next to solutions there are as you said "projects". You can have multiple projects within one solution and therefore view many projects at the same time.
To Achieve ellipses for the text use the Text property numberofLines={1} which will automatically truncate the text with an ellipsis you can specify the ellipsizeMode as "head", "middle", "tail" or "clip" By default it is tail
Now that the question is clearer, you can just do this in one grep
grep -R --include "*bills*" "put" .
With relevant flags
-R, -r, --recursive
Read all files under each directory, recursively; this is
equivalent to the -d recurse option.
--include=GLOB
Search only files whose base name matches GLOB (using wildcard
matching as described under --exclude).
* Don't change anything to Listen : keep it as it is..
1) Open httpd.conf of Apache server (backup first) Look for the the following :
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Allow from all
#Deny from all
</Directory>
and also this
<Directory "cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
2) Now From taskbar :
Click on wamp icon > Apache > Apache modules > apache_rewrite (enable this module)
And Ya Also Activate "Put Online" From same taskbar icon
You need to allow port request from windows firewall setting.
(Windows 7)
Go to control panel > windows firewall > advance setting (on left sidebar)
then
Right click on inbound rules -> add new rule -> port -> TCP (Specific port 80 - if your localhost wok on this port) -> Allow the connections -> Give a profile name -> ok
Now Restart all the services of Apache server & you are done..
Date and time formats are well described below
SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns
There could be n
Number of formats you can possibly make. ex - dd/MM/yyyy
or YYYY-'W'ww-u
or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.
G
- Era designator (AD)y
- Year (1996; 96)Y
- Week Year (2009; 09)M
- Month in year (July; Jul; 07)w
- Week in year (27)W
- Week in month (2)D
- Day in year (189)d
- Day in month (10)F
- Day of week in month (2)E
- Day name in week (Tuesday; Tue)u
- Day number of week (1 = Monday, ..., 7 = Sunday)a
- AM/PM markerH
- Hour in day (0-23)k
- Hour in day (1-24)K
- Hour in am/pm (0-11)h
- Hour in am/pm (1-12)m
- Minute in hour (30)s
- Second in minute (55)S
- Millisecond (978)z
- General time zone (Pacific Standard Time; PST; GMT-08:00)Z
- RFC 822 time zone (-0800)X
- ISO 8601 time zone (-08; -0800; -08:00)To parse:
2000-01-23T04:56:07.000+0000
Use:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
To complete the response of the other users:
For this I have created an "WinHttp.WinHttpRequest.5.1" object.
Send a post request with some data from Excel using VBA:
Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")
Send a get request with token authentication from Excel using VBA:
Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send
You can convert the double
value into a int
value.
int x = (int) y
where y is your double variable. Then, printing x
does not give decimal places (15000
instead of 15000.0
).
Kruskal time complexity worst case is O(E log E),this because we need to sort the edges. Prim time complexity worst case is O(E log V) with priority queue or even better, O(E+V log V) with Fibonacci Heap. We should use Kruskal when the graph is sparse, i.e.small number of edges,like E=O(V),when the edges are already sorted or if we can sort them in linear time. We should use Prim when the graph is dense, i.e number of edges is high ,like E=O(V²).
Steps to manually configure DNS:
You can access Network and Sharing center by right clicking on the Network icon on the taskbar.
Now choose adapter settings from the side menu.
This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.
In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.
Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.
Select ‘use the following DNS address’ option. Now fill the following fields as given here.
Preferred DNS server: 208.67.222.222
Alternate DNS server : 208.67.220.220
This is an available Open DNS address. You may also use google DNS server addresses.
After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.
You have to add this DNS server address in the router configuration also (by referring the router manual for more information).
Refer : for above method & alternative
If none of this works, then open command prompt(Run as Administrator) and run these:
ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit
Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).
Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue
I've just came across the same problem and found the chrome extension Open IE.
That's the only one what works for me (Chrome V46 & V52). The only disadvantefge is, that you need to install an additional program, means you need admin rights.
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
you can use the following.
$("#selector").datepicker({
maxDate: 0
});
I've tried many of the previous answers, really nothing works for me but this solution did:
https://getbootstrap.com/docs/3.3/javascript/#dismiss-on-next-click
They recommend to use anchor tag not button and take care of role="button" + data-trigger="focus" + tabindex="0" attributes.
Ex:
<a tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover"
data-trigger="focus" title="Dismissible popover" data-content="amazing content">
Dismissible popover</a>
Maybe it will be to complex for this question but it surely do the job for you. I have created two classes to handle not only array insertion but also querying the database, updating and deleting files. "MySqliConnection" class is used to create only one instance of db connection (to prevent duplication of new objects).
<?php
/**
*
* MySQLi database connection: only one connection is allowed
*/
class MySqliConnection{
public static $_instance;
public $_connection;
public function __construct($host, $user, $password, $database){
$this->_connection = new MySQLi($host, $user, $password, $database);
if (isset($mysqli->connect_error)) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
}
/*
* Gets instance of connection to database
* @return (MySqliConnection) Object
*/
public static function getInstance($host, $user, $password, $database){
if(!self::$_instance){
self::$_instance = new self($host, $user, $password, $database); //if no instance were created - new one will be initialize
}
return self::$_instance; //return already exsiting instance of the database connection
}
/*
* Prevent database connection from bing copied while assignig the object to new wariable
* @return (MySqliConnection) Object
*/
public function getConnection(){
return $this->_connection;
}
/*
* Prevent database connection from bing copied/duplicated while assignig the object to new wariable
* @return nothing
*/
function __clone(){
}
}
/*// CLASS USE EXAMPLE
$db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
$mysqli = $db->getConnection();
$sql_query = 'SELECT * FROM users;
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['ID'];
}
*/
The second "TableManager" class is little bit more complex. It also make use of the MySqliConnection class which I posted above. So you would have to include both of them in your project. TableManager will allow you to easy make insertion updates and deletions. Class have separate placeholder for read and write.
<?php
/*
* DEPENDENCIES:
* include 'class.MySqliConnection.inc'; //custom class
*
*/
class TableManager{
private $lastQuery;
private $lastInsertId;
private $tableName;
private $tableIdName;
private $columnNames = array();
private $lastResult = array();
private $curentRow = array();
private $newPost = array();
/*
* Class constructor
* [1] (string) $tableName // name of the table which you want to work with
* [2] (string) $tableIdName // name of the ID field which will be used to delete and update records
* @return void
*/
function __construct($tableName, $tableIdName){
$this->tableIdName = $tableIdName;
$this->tableName = $tableName;
$this->getColumnNames();
$this->curentRow = $this->columnNames;
}
public function getColumnNames(){
$sql_query = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = "'.$this->tableName.'"';
$mysqli = $this->connection();
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->columnNames[$row['COLUMN_NAME']] = null;
}
}
/*
* Used by a Constructor to set native parameters or virtual array curentRow of the class
* [1] (array) $v
* @return void
*/
function setRowValues($v){
if(!is_array($v)){
$this->curentRow = $v;
return true;
}
foreach ($v as $a => $b) {
$method = 'set'.ucfirst($a);
if(is_callable(array($this, $method))){
//if method is callable use setSomeFunction($k, $v) to filter the value
$this->$method($b);
}else{
$this->curentRow[$a] = $b;
}
}
}
/*
* Used by a constructor to set native parameters or virtual array curentRow of the class
* [0]
* @return void
*/
function __toString(){
var_dump($this);
}
/*
* Query Database for information - Select column in table where column = somevalue
* [1] (string) $column_name // name od a column
* [2] (string) $quote_pos // searched value in a specified column
* @return void
*/
public function getRow($column_name = false, $quote_post = false){
$mysqli = $this->connection();
$quote_post = $mysqli->real_escape_string($quote_post);
$this->tableName = $mysqli->real_escape_string($this->tableName);
$column_name = $mysqli->real_escape_string($column_name);
if($this->tableName && $column_name && $quote_post){
$sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$column_name.' = "'.$quote_post.'"';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
if($this->tableName && $column_name && !$quote_post){
$sql_query = 'SELECT '.$column_name.' FROM '.$this->tableName.'';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[] = $row;
$this->setRowValues($row);
}
}
if($this->tableName && !$column_name && !$quote_post){
$sql_query = 'SELECT * FROM '.$this->tableName.'';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
}
/*
* Connection class gets instance of db connection or if not exsist creats one
* [0]
* @return $mysqli
*/
private function connection(){
$this->lastResult = "";
$db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
$mysqli = $db->getConnection();
return $mysqli;
}
/*
* ...
* [1] (string) $getMe
* @return void
*/
function __get($getMe){
if(isset($this->curentRow[$getMe])){
return $this->curentRow[$getMe];
}else{
throw new Exception("Error Processing Request - No such a property in (array) $this->curentRow", 1);
}
}
/*
* ...
* [2] (string) $setMe, (string) $value
* @return void
*/
function __set($setMe, $value){
$temp = array($setMe=>$value);
$this->setRowValues($temp);
}
/*
* Dumps the object
* [0]
* @return void
*/
function dump(){
echo "<hr>";
var_dump($this);
echo "<hr>";
}
/*
* Sets Values for $this->newPost array which will be than inserted by insertNewPost() function
* [1] (array) $newPost //array of avlue that will be inserted to $this->newPost
* @return bolean
*/
public function setNewRow($arr){
if(!is_array($arr)){
$this->newPost = $arr;
return false;
}
foreach ($arr as $k => $v) {
if(array_key_exists($k, $this->columnNames)){
$method = 'set'.ucfirst($k);
if(is_callable(array($this, $method))){
if($this->$method($v) == false){ //if something go wrong
$this->newPost = array(); //empty the newPost array and return flase
throw new Exception("There was a problem in setting up New Post parameters. [Cleaning array]", 1);
}
}else{
$this->newPost[$k] = $v;
}
}else{
$this->newPost = array(); //empty the newPost array and return flase
throw new Exception("The column does not exsist in this table. [Cleaning array]", 1);
}
}
}
/*
* Inserts new post held in $this->newPost
* [0]
* @return bolean
*/
public function insertNewRow(){
// check if is set, is array and is not null
if(isset($this->newPost) && !is_null($this->newPost) && is_array($this->newPost)){
$mysqli = $this->connection();
$count_lenght_of_array = count($this->newPost);
// preper insert query
$sql_query = 'INSERT INTO '.$this->tableName.' (';
$i = 1;
foreach ($this->newPost as $key => $value) {
$sql_query .=$key;
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
$i = 1;
$sql_query .=') VALUES (';
foreach ($this->newPost as $key => $value) {
$sql_query .='"'.$value.'"';
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
$sql_query .=')';
var_dump($sql_query);
if($mysqli->query($sql_query)){
$this->lastInsertId = $mysqli->insert_id;
$this->lastQuery = $sql_query;
}
$this->getInsertedPost($this->lastInsertId);
}
}
/*
* getInsertedPost function query the last inserted id and assigned it to the object.
* [1] (integer) $id // last inserted id from insertNewRow fucntion
* @return void
*/
private function getInsertedPost($id){
$mysqli = $this->connection();
$sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = "'.$id.'"';
$result = $mysqli->query($sql_query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
/*
* getInsertedPost function query the last inserted id and assigned it to the object.
* [0]
* @return bolean // if deletion was successful return true
*/
public function deleteLastInsertedPost(){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$this->lastInsertId.'';
$result = $mysqli->query($sql_query);
if($result){
$this->lastResult[$this->lastInsertId] = "deleted";
return true;
}else{
throw new Exception("We could not delete last inserted row by ID [{$mysqli->errno}] {$mysqli->error}");
}
var_dump($sql_query);
}
/*
* deleteRow function delete the row with from a table based on a passed id
* [1] (integer) $id // id of the table row to be delated
* @return bolean // if deletion was successful return true
*/
public function deleteRow($id){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$id.'';
$result = $mysqli->query($sql_query);
if($result){
$this->lastResult[$this->lastInsertId] = "deleted";
return true;
}else{
return false;
}
var_dump($sql_query);
}
/*
* deleteAllRows function deletes all rows from a table
* [0]
* @return bolean // if deletion was successful return true
*/
public function deleteAllRows(){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.'';
$result = $mysqli->query($sql_query);
if($result){
return true;
}else{
return false;
}
}
/*
* updateRow function updates all values to object values in a row with id
* [1] (integer) $id
* @return bolean // if deletion was successful return true
*/
public function updateRow($update_where = false){
$id = $this->curentRow[$this->tableIdName];
$mysqli = $this->connection();
$updateMe = $this->curentRow;
unset($updateMe[$this->tableIdName]);
$count_lenght_of_array = count($updateMe);
// preper insert query
$sql_query = 'UPDATE '.$this->tableName.' SET ';
$i = 1;
foreach ($updateMe as $k => $v) {
$sql_query .= $k.' = "'.$v.'"';
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
if($update_where == false){
//update row only for this object id
$sql_query .=' WHERE '.$this->tableIdName.' = '.$this->curentRow[$this->tableIdName].'';
}else{
//add your custom update where query
$sql_query .=' WHERE '.$update_where.'';
}
var_dump($sql_query);
if($mysqli->query($sql_query)){
$this->lastQuery = $sql_query;
}
$result = $mysqli->query($sql_query);
if($result){
return true;
}else{
return false;
}
}
}
/*TO DO
1 insertPost(X, X) write function to isert data and in to database;
2 get better query system and display data from database;
3 write function that displays data of a object not databsae;
object should be precise and alocate only one instance of the post at a time.
// Updating the Posts to curent object $this->curentRow values
->updatePost();
// Deleting the curent post by ID
// Add new row to database
*/
/*
USE EXAMPLE
$Post = new TableManager("post_table", "ID"); // New Object
// Getting posts from the database based on pased in paramerters
$Post->getRow('post_name', 'SOME POST TITLE WHICH IS IN DATABASE' );
$Post->getRow('post_name');
$Post->getRow();
MAGIC GET will read current object $this->curentRow parameter values by refering to its key as in a varible name
echo $Post->ID.
echo $Post->post_name;
echo $Post->post_description;
echo $Post->post_author;
$Task = new TableManager("table_name", "table_ID_name"); // creating new TableManager object
$addTask = array( //just an array [colum_name] => [values]
'task_name' => 'New Post',
'description' => 'New Description Post',
'person' => 'New Author',
);
$Task->setNewRow($addTask); //preper new values for insertion to table
$Task->getRow('ID', '12'); //load value from table to object
$Task->insertNewRow(); //inserts new row
$Task->dump(); //diplays object properities
$Task->person = "John"; //magic __set() method will look for setPerson(x,y) method firs if non found will assign value as it is.
$Task->description = "John Doe is a funny guy"; //magic __set() again
$Task->task_name = "John chellange"; //magic __set() again
$test = ($Task->updateRow("ID = 5")) ? "WORKS FINE" : "ERROR"; //update cutom row with object values
echo $test;
$test = ($Task->updateRow()) ? "WORKS FINE" : "ERROR"; //update curent data loaded in object
echo $test;
*/
you can use custom gallery control.. check this https://github.com/kilaka/ImageViewZoom use galleryTouch class from this..