uint32_t
is defined in the standard, in
<cstdint>
synopsis [cstdint.syn]namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
Additionally, for our Android friends (API Level 8):
import android.util.Base64
...
Base64.encodeToString(bytes, Base64.DEFAULT);
The key is to give the anchor links a display property of "block" and a width property of 100%.
Making list-items clickable (example):
HTML:
<ul>
<li><a href="">link1</a></li>
<li><a href="">link2</a></li>
<li><a href="">link3</a></li>
</ul>
CSS:
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
ul li a {
display: block;
width: 100%;
text-decoration: none;
padding: 5px;
}
ul li a:hover {
background-color: #ccc;
}
If you are looking for something easier:
public MyTextView extends TextView{
public void resize(String text, float textViewWidth, float textViewHeight) {
Paint p = new Paint();
Rect bounds = new Rect();
p.setTextSize(1);
p.getTextBounds(text, 0, text.length(), bounds);
float widthDifference = (textViewWidth)/bounds.width();
float heightDifference = (textViewHeight);
textSize = Math.min(widthDifference, heightDifference);
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.
You simply need to specify on which tables to apply the DELETE
.
Delete only the deadline
rows:
DELETE `deadline` FROM `deadline` LEFT JOIN `job` ....
Delete the deadline
and job
rows:
DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....
Delete only the job
rows:
DELETE `job` FROM `deadline` LEFT JOIN `job` ....
When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics
object outside the paint()
/paintComponent()
/etc. methods.
However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics()
method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage
instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel
's paintComponent()
, you simply need to draw the BufferedImage
instance unto the JPanel
. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.
You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent
. One way to do so is to serialize it into a JSON string:
var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json
Now all you need to do is pass the string to the post method.
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+
var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
You can use a CASE statement...however why don't you just create a table with an integer for ages between 0 and 150, a varchar for the written out age and then you can just join on that
If you're just doing this in either SQL Server Management Studio or sqlcmd.exe
, you can use the fact that the batch separator allows you to repeat the batch:
CREATE TABLE Number (N INT IDENTITY(1,1) PRIMARY KEY NOT NULL);
GO
INSERT INTO Number DEFAULT VALUES;
GO 100000
This will insert 100000 records into the Numbers
table using the default value of the next identity.
It's slow. It compares to METHOD 1 in @KM.'s answer, which is the slowest of the examples. However, it's about as code light as it gets. You could speed it up somewhat by adding the primary key constraint after the insert batch.
Some tips:
Have fun :-)
The syntax error is just due to a missing alias for the subquery:
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) mySubQuery /* Alias */
It is possible to use patterns in a .gitignore
file. See the gitignore man page. The pattern */target/*
should ignore any directory named target and anything under it. Or you may try */target/**
to ignore everything under target.
Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:
<div style="text-align:center;">
<div style="border:1px solid #000; display:inline-block;">Div 1</div>
<div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>
This is the best for www
and for HTTPS, for proxy and no proxy users.
RewriteEngine On
### WWW & HTTPS
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### WWW & HTTPS
I suggest you to see "How do I run a bat file in the background from another bat file?"
Also, good answer (of using start
command) was given in "Parallel execution of shell processes" question page here;
But my recommendation is to use PowerShell. I believe it will perfectly suit your needs.
PHP mail()
command does not support authentication. Your options:
On the client side you can add and remove websites to be displayed in Compatibility View from Compatibility View Settings window of IE:
Tools-> Compatibility View Settings
#collect
is actually an alias for #map
. That means the two methods can be used interchangeably, and effect the same behavior.
--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
is now in the neil
group, so webgui
can call set role neil
. However, webgui
did not inherit neil
's permissions.
Later, login as webgui:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
does not need superuser
permission for this.
You want to set role
at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}
You can also set the options --log-fd if you just want to read your logs with a less. For example :
valgrind --log-fd=1 ls | less
IE assumes that the clicking of a link heralds a new navigation where the current page contents will be replaced. As part of the process for perparing for that it halts the code that animates the GIFs. I doubt there is anything you can do about it (unless you aren't actually navigating in which case use return false in the onclick event).
The answer from Matt Fear was the most effective IMHO. The following is just a PowerShell script for those in windows to only remove files from their git repo that matches their exclusion list.
# Get files matching exclusionsfrom .gitignore
# Excluding comments and empty lines
$ignoreFiles = gc .gitignore | ?{$_ -notmatch "#"} | ?{$_ -match "\S"} | % {
$ignore = "*" + $_ + "*"
(gci -r -i $ignore).FullName
}
$ignoreFiles = $ignoreFiles| ?{$_ -match "\S"}
# Remove each of these file from Git
$ignoreFiles | % { git rm $_}
git add .
If a method doesn't return anything, it's either one of the following
Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.
void DeductFromBalance( dAmount )
can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount
Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.
void OnAccountDebit( dAmount ) // emails account holder with info
can be tested by verifying if the email is being sent
Post more details about your actual method and people will be able to answer better.
Update: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.
string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );
String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check this thread for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like
InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );
Instead of playing with tags, I took different approach. Made delegate for my subclass of UITableViewCell(OptionButtonsCell) and added an indexPath var. From my button in storyboard I connected @IBAction to the OptionButtonsCell and there I send delegate method with the right indexPath to anyone interested. In cell for index path I set current indexPath and it works :)
Let the code speak for itself:
Swift 3 Xcode 8
OptionButtonsTableViewCell.swift
import UIKit
protocol OptionButtonsDelegate{
func closeFriendsTapped(at index:IndexPath)
}
class OptionButtonsTableViewCell: UITableViewCell {
var delegate:OptionButtonsDelegate!
@IBOutlet weak var closeFriendsBtn: UIButton!
var indexPath:IndexPath!
@IBAction func closeFriendsAction(_ sender: UIButton) {
self.delegate?.closeFriendsTapped(at: indexPath)
}
}
MyTableViewController.swift
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, OptionButtonsDelegate {...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "optionCell") as! OptionButtonsTableViewCell
cell.delegate = self
cell.indexPath = indexPath
return cell
}
func closeFriendsTapped(at index: IndexPath) {
print("button tapped at index:\(index)")
}
do it the simpler way,
direc=$(basename `pwd`)
Or use the shell
$ direc=${PWD##*/}
You could use a radio button/checkbox and set it to hide the button in css and then give it a label with an image.
input[type="radio"] {display: none}
input[type="radio"] + label span {display: block}
Then on the page:
<input type="radio" name="emotion" id="mysubmitradio" />
<label for="mysubmitradio"><img src="images/f.jpg" />
<span>if you need it</span></label>
And then set it to submit using javascript:
document.forms["myform"].submit();
I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;
SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;
Result: Paddy O'Reilly
Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!
<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>
You might be trying to access a control inside a control, maybe a GridView or DetailsView.
Try using something like this:
empsalary = Convert.ToInt32(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);
The following method can be used to get the formatted string of the date which is passed in to it. It'll format the date to say 1st,2nd,3rd,4th .. using SimpleDateFormat in Java. eg:- 1st of September 2015
public String getFormattedDate(Date date){
Calendar cal=Calendar.getInstance();
cal.setTime(date);
//2nd of march 2015
int day=cal.get(Calendar.DATE);
switch (day % 10) {
case 1:
return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
case 2:
return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
case 3:
return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
default:
return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
}
Yes, you can... If a then a, else if b then if c then c(b), else b, else null
a ? a : (b ? (c ? c(b) : b) : null)
a
? a
: b
? c
? c(b)
: b
: null
Ternary operator ?:
used as inline if-else is right associative. In short this means that the rightmost ?
gets fed first and it takes exactly one closest operand on the left and two, with a :
, on the right.
Practically speaking, consider the following statement (same as above):
a ? a : b ? c ? c(b) : b : null
The rightmost ?
gets fed first, so find it and its surrounding three arguments and consecutively expand to the left to another ?
.
a ? a : b ? c ? c(b) : b : null
^ <---- RTL
1. |1-?-2----:-3|
^ <-
2. |1-?|--2---------|:-3---|
^ <-
3.|1-?-2-:|--3--------------------|
result: a ? a : (b ? (c ? c(b) : b) : null)
- Term
a
is read.
Node:a
- Nonterminal
?
is read.
Node:a ?
- Term
a
is read.
Node:a ? a
- Nonterminal
:
is read.
Node:a ? a :
- Term
b
is read.
Node:a ? a : b
- Nonterminal
?
is read, triggering the right-associativity rule. Associativity decides:
node:a ? a : (b ?
- Term
c
is read.
Node:a ? a : (b ? c
- Nonterminal
?
is read, re-applying the right-associativity rule.
Node:a ? a : (b ? (c ?
- Term
c(b)
is read.
Node:a ? a : (b ? (c ? c(b)
- Nonterminal
:
is read.
Node:a ? a : (b ? (c ? c(b) :
- Term
b
is read.
Node:a ? a : (b ? (c ? c(b) : b
- Nonterminal
:
is read. The ternary operator?:
from previous scope is satisfied and the scope is closed.
Node:a ? a : (b ? (c ? c(b) : b) :
- Term
null
is read.
Node:a ? a : (b ? (c ? c(b) : b) : null
- No tokens to read. Close remaining open parenthesis.
#Result is:a ? a : (b ? (c ? c(b) : b) : null)
The ugly oneliner from above could (and should) be rewritten for readability as:
(Note that the indentation does not implicitly define correct closures as brackets () do.)
a
? a
: b
? c
? c(b)
: b
: null
for example
return a + some_lengthy_variable_name > another_variable
? "yep"
: "nop"
Mozilla: JavaScript Conditional Operator
Wiki: Operator Associativity
var a = 0 // 1
var b = 20
var c = null // x=> {console.log('b is', x); return true} // return true here!
a
&& a
|| b
&& c
&& c(b) // if this returns false, || b is processed
|| b
|| null
Using logical operators as in this example is ugly and wrong, but this is where they shine...
This approach comes with subtle limitations as explained in the link below. For proper solution, see Nullish coalescing in Bonus2.
function f(mayBeNullOrFalsy) {
var cantBeNull = mayBeNullOrFalsy || 42 // "default" value
var alsoCantBe = mayBeNullOrFalsy ? mayBeNullOrFalsy : 42 // ugly...
..
}
false && (anything) // is short-circuit evaluated to false.
true || (anything) // is short-circuit evaluated to true.
Logical operators
Null coalescence
Short-circuit evaluation
developer.mozilla.org~Nullish_coalescing_operator
function f(mayBeNullOrUndefined, another) {
var cantBeNullOrUndefined = mayBeNullOrUndefined ?? 42
another ??= 37 // nullish coalescing self-assignment
another = another ?? 37 // same effect
..
}
Stage 4 finished proposal https://github.com/tc39/proposal-optional-chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
// before
var street = user.address && user.address.street
// after
var street = user.address?.street
// combined with Nullish coalescing
// before
var street = user.address
? user.address.street
: "N/A"
// after
var street = user.address?.street ?? "N/A"
// arrays
obj.someArray?.[index]
// functions
obj.someMethod?.(args)
The POSIX standard has its own method to get file size.
Include the sys/stat.h
header to use the function.
stat(3)
.st_size
property.Note: It limits the size to 4GB
. If not Fat32
filesystem then use the 64bit version!
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat info;
stat(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char** argv)
{
struct stat64 info;
stat64(argv[1], &info);
// 'st' is an acronym of 'stat'
printf("%s: size=%ld\n", argv[1], info.st_size);
}
The ANSI C doesn't directly provides the way to determine the length of the file.
We'll have to use our mind. For now, we'll use the seek approach!
#include <stdio.h>
int main(int argc, char** argv)
{
FILE* fp = fopen(argv[1]);
int f_size;
fseek(fp, 0, SEEK_END);
f_size = ftell(fp);
rewind(fp); // to back to start again
printf("%s: size=%ld", (unsigned long)f_size);
}
If the file is
stdin
or a pipe. POSIX, ANSI C won't work.
It will going return0
if the file is a pipe orstdin
.Opinion: You should use POSIX standard instead. Because, it has 64bit support.
OK here is what worked for me! I have a button on my left Nav. If you click it it will open a window and that window will load a document. After loading the document I want print the document then close the popup window immediately.
contentDiv.focus();
contentDiv.contentWindow.print();
contentDiv.contentWindow.onfocus = function() {
window.close();
};
Why does this work?
Well, after printing you set the onfocus event to close the window. The print popup will load so quickly that the onfocus event will not get a chance to trigger until you 1)print 2) cancel the print. Once you regain focus on the window, the window will close!
I hope that will work for you
You'll get a lot of information in Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes or Portable PHP password hashing framework.
The goal is to hash the password with something slow, so someone getting your password database will die trying to brute force it (a 10 ms delay to check a password is nothing for you, a lot for someone trying to brute force it). Bcrypt is slow and can be used with a parameter to choose how slow it is.
Here is my updated solution to this issue.
/* Sticky footer styles
-------------------------------------------------- */
html {
position: relative;
min-height: 100%;
}
body {
/* Margin bottom by footer height */
margin-bottom: 60px;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
/* Set the fixed height of the footer here */
height: 60px;
background-color: #f5f5f5;
border-top: 1px solid #eee;
text-align: center;
}
.site-footer-links {
font-size: 12px;
line-height: 1.5;
color: #777;
padding-top: 20px;
display: block;
text-align: center;
float: center;
margin: 0;
list-style: none;
}
And use it like this:
<div class="footer">
<div class="site-footer">
<ul class="site-footer-links">
<li>© Zee and Company<span></span></li>
</ul>
</div>
</div>
Or
html, body {
height: 100%;
}
.page-wrap {
min-height: 100%;
/* equal to footer height */
margin-bottom: -142px;
}
.page-wrap:after {
content: "";
display: block;
}
.site-footer, .page-wrap:after {
height: 142px;
}
.site-footer {
background: orange;
}
This is how I solved
<a href="#" >
<button type="button" class="btn btn-info">Button Text</button>
</a>
for future reference :
As of Babel version 7.0.0-beta.55 stage presets have been removed
refer blog https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
async await can be still be used by
https://babeljs.io/docs/en/babel-plugin-transform-async-to-generator#usage
installation
npm install --save-dev @babel/plugin-transform-async-to-generator
usage in .babelrc
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
and using babel polyfill https://babeljs.io/docs/en/babel-polyfill
installation
npm install --save @babel/polyfill
webpack.config.js
module.exports = {
entry: ["@babel/polyfill", "./app/js"],
};
In Java 8 you can simply do
ZonedDateTime.now().toInstant().toEpochMilli()
returns : the number of milliseconds since the epoch of 1970-01-01T00:00:00Z
Using Integer.toHexString(...)
is a good answer. But personally prefer to use String.format(...)
.
Try this sample as a test.
byte[] values = new byte[64];
Arrays.fill(values, (byte)8); //Fills array with 8 just for test
String valuesStr = "";
for(int i = 0; i < values.length; i++)
valuesStr += String.format("0x%02x", values[i] & 0xff) + " ";
valuesStr.trim();
Use the CX register to count the loops
mov cx, 3 startloop: cmp cx, 0 jz endofloop push cx loopy: Call ClrScr pop cx dec cx jmp startloop endofloop: ; Loop ended ; Do what ever you have to do here
This simply loops around 3 times calling ClrScr
, pushing the CX register onto the stack, comparing to 0, jumping if ZeroFlag is set then jump to endofloop
. Notice how the contents of CX is pushed/popped on/off the stack to maintain the flow of the loop.
Use this code
using System.Threading;
// ...
Thread.Sleep(50);
/usr/sbin/ifconfig -a | awk 'BEGIN { count=0; } { if ( $1 ~ /inet/ ) { count++; if( count==2 ) { print $2; } } }'
This will list down the exact ip address for the machine
Official Documentation on facebook developer site:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Also known as Frozen Binaries but not the same as as the output of a true compiler- they run byte code through a virtual machine (PVM). Run the same as a compiled program just larger because the program is being compiled along with the PVM. Py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraties; programs that use the pygame game programming toolkit; win32com client programs; and more. The Stackless Python system is a standard CPython implementation variant that does not save state on the C language call stack. This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. Other systems of study that are working on future development: Pyrex is working on the Cython system, the Parrot project, the PyPy is working on replacing the PVM altogether, and of course the founder of Python is working with Google to get Python to run 5 times faster than C with the Unladen Swallow project. In short, py2exe is the easiest and Cython is more efficient for now until these projects improve the Python Virtual Machine (PVM) for standalone files.
I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.
private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className + ".html";
ExtentReports report;
ExtentTest test;
@BeforeMethod
// initialise report variables
report = new ExtentReports(outputFolder + outputFile);
test = report.startTest(className);
// more setup code
@Test
// test method code with log statements
@AfterMethod
// takeScreenShot returns the relative path and filename for the image
String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".
This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.
Chris
String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);
As a fixed length string (VARCHAR(n) or however MySQL calls it). A hash has always a fixed length of for example 12 characters (depending on the hash algorithm you use). So a 20 char password would be reduced to a 12 char hash, and a 4 char password would also yield a 12 char hash.
Drop the parentheses and commas:
myBackupFunction ".." "..." "xx"
And the function should look like this:
function myBackupFunction() {
# Here $1 is the first parameter, $2 the second, etc.
}
Example:
use: android:textStyle="bold"
<TextView
android:id="@+id/txtVelocidade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/txtlatitude"
android:layout_centerHorizontal="true"
android:layout_marginBottom="34dp"
android:textStyle="bold"
android:text="Aguardando GPS"
android:textAppearance="?android:attr/textAppearanceLarge" />
@jasonk - if you want to have "or" then negate all conditions since (A and B) <=> ~(~A or ~B)
but if you have values other than boolean try using type converters:
<MultiDataTrigger.Conditions>
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource conditionConverter}">
<Binding Path="Name" />
<Binding Path="State" />
</MultiBinding>
</Condition.Binding>
<Setter Property="Background" Value="Cyan" />
</Condition>
</MultiDataTrigger.Conditions>
you can use the values in Convert method any way you like to produce a condition which suits you.
Docker Compose does not support the deploy
key. It's only respected when you use your version 3 YAML file in a Docker Stack.
This message is printed when you add the deploy
key to you docker-compose.yml
file and then run docker-compose up -d
WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use
docker stack deploy
to deploy to a swarm.
The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:
Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.
AFAIK, the only way this could be done is by using the state=directory
option.
While template
module supports most of copy
options, which in turn supports most file
options, you can not use something like state=directory
with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf
is a directory ? or would it mean that {{project_root}}/conf/
should be created first.
So I don't think this is possible right now without adding a previous file
task.
- file:
path: "{{project_root}}/conf"
state: directory
recurse: yes
// a wrapper closure around executing a string
// can take either a string or a list of strings (for arguments with spaces)
// prints all output, complains and halts on error
def runCommand = { strList ->
assert ( strList instanceof String ||
( strList instanceof List && strList.each{ it instanceof String } ) \
)
def proc = strList.execute()
proc.in.eachLine { line -> println line }
proc.out.close()
proc.waitFor()
print "[INFO] ( "
if(strList instanceof List) {
strList.each { print "${it} " }
} else {
print strList
}
println " )"
if (proc.exitValue()) {
println "gave the following error: "
println "[ERROR] ${proc.getErrorStream()}"
}
assert !proc.exitValue()
}
To configure bash aliases, it's the same as if you were on a Unix platform: put them in a .bashrc
in your home:
cd
echo alias ll=\'ls -l\' >> .bashrc
To have this change taken into account you should then either source this file (ie: run source .bashrc
) or restart your terminal
(In some cases* you can find equivalent for .bashrc
file in C:\Users\<username>\AppData\Local\GitHub\PortableGit_\etc\profile.d\aliases.sh.
And you should add aliases in aliases.sh.
)
(*this case is when you install Git for Windows GUI release from https://git-scm.com/download/win that contains GitBash)
First, have program 1 write the string to stdout
(as if you'd like it to appear in screen). Then the second program should read a string from stdin
, as if a user was typing from a keyboard. then you run:
$ program_1 | program_2
try this. It will solve your problem.
var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);
Borrowed and improved Marcus Downing's answer. Tested and works in Firefox 3 and Opera 9. Supports multiple lines, too.
ol {
counter-reset: item;
margin-left: 0;
padding-left: 0;
}
li {
display: block;
margin-left: 3.5em; /* Change with margin-left on li:before. Must be -li:before::margin-left + li:before::padding-right. (Causes indention for other lines.) */
}
li:before {
content: counter(item) ")"; /* Change 'item' to 'item, upper-roman' or 'item, lower-roman' for upper- and lower-case roman, respectively. */
counter-increment: item;
display: inline-block;
text-align: right;
width: 3em; /* Must be the maximum width of your list's numbers, including the ')', for compatability (in case you use a fixed-width font, for example). Will have to beef up if using roman. */
padding-right: 0.5em;
margin-left: -3.5em; /* See li comments. */
}
If you are looking for a number that is bigger than all others:
Method 1:
float('inf')
Method 2:
import sys
max = sys.maxsize
If you are looking for a number that is smaller than all others:
Method 1:
float('-inf')
Method 2:
import sys
min = -sys.maxsize - 1
Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.
Finally this worked for me
private String buildBasicAuthorizationString(String username, String password) {
String credentials = username + ":" + password;
return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
}
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
i've solved this issue with these steps: expand your project, right click "JRE System Library" > Properties > choose 3rd option "Workspace default JRE" > OK . Hope it help you too
Maybe you can use a file, write to file inside function, read from file after it. I have changed e
to an array. In this example blanks are used as separator when reading back the array.
#!/bin/bash
declare -a e
e[0]="first"
e[1]="secondddd"
function test1 () {
e[2]="third"
e[1]="second"
echo "${e[@]}" > /tmp/tempout
echo hi
}
ret=$(test1)
echo "$ret"
read -r -a e < /tmp/tempout
echo "${e[@]}"
echo "${e[0]}"
echo "${e[1]}"
echo "${e[2]}"
Output:
hi
first second third
first
second
third
This happens if you initialized a new github repo with README
and/or LICENSE
file
git remote add origin [//your github url]
//pull those changes
git pull origin master
// or optionally, 'git pull origin master --allow-unrelated-histories' if you have initialized repo in github and also committed locally
//now, push your work to your new repo
git push origin master
Now you will be able to push your repository to github. Basically, you have to merge those new initialized files with your work. git pull
fetches and merges for you. You can also fetch and merge if that suits you.
You cannot put comments inside UWP XAML tags. Your syntax is right.
TO DO:
<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
<!-- Cool comment -->
NOT TO DO:
<xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib"/>
I know this is an older thread however I needed to write a function that returned the first blank row WITHIN a range. All of the code I found online actually searches the entire row (even the cells outside of the range) for a blank row. Data in ranges outside the search range was triggering a used row. This seemed to me to be a simple solution:
Function FirstBlankRow(ByVal rngToSearch As Range) As Long
Dim R As Range
Dim C As Range
Dim RowIsBlank As Boolean
For Each R In rngToSearch.Rows
RowIsBlank = True
For Each C In R.Cells
If IsEmpty(C.Value) = False Then RowIsBlank = False
Next C
If RowIsBlank Then
FirstBlankRow = R.Row
Exit For
End If
Next R
End Function
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
If you have ids in both tables, the following works:
update table2
set value = (select value from table1 where table1.id = table2.id)
Perhaps a better approach is a join:
update table2
set value = table1.value
from table1
where table1.id = table2.id
Note that this syntax works in SQL Server but may be different in other databases.
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
[k for (k, v) in i.iteritems() if v == 0]
Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0}
is perfectly legal.
If you want ordering you either need to use a list or a OrderedDict instance instead:
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
It means you should use logging framework like logback or log4j and instead of printing exceptions directly:
e.printStackTrace();
you should log them using this frameworks' API:
log.error("Ops!", e);
Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.
I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).
# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase
And a good way to find out where a branch started is to do a svn log
it and find the first one on the branch (the last one listed when doing):
svn log --stop-on-copy svn://some/repo/branch/some-branch
So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.
There might be a semicolon or bracket missing a line before your pasted line.
It seems fine to me; every string is allowed as an array index.
Instead of using pull-right
class, it is better to use text-right
class in the column, because pull-right
creates problems sometimes while resizing the page.
This can happen due to a different language in the phone for which your code doesn't have the asset for. For example your preference.xml is placed in xml-en and you are trying to run your app in a phone which has French selected, the app will crash.
pydoc is fantastic for generating documentation, but the documentation has to be written in the first place. You must have docstrings in your source code as was mentioned by RocketDonkey in the comments:
"""
This example module shows various types of documentation available for use
with pydoc. To generate HTML documentation for this module issue the
command:
pydoc -w foo
"""
class Foo(object):
"""
Foo encapsulates a name and an age.
"""
def __init__(self, name, age):
"""
Construct a new 'Foo' object.
:param name: The name of foo
:param age: The ageof foo
:return: returns nothing
"""
self.name = name
self.age = age
def bar(baz):
"""
Prints baz to the display.
"""
print baz
if __name__ == '__main__':
f = Foo('John Doe', 42)
bar("hello world")
The first docstring provides instructions for creating the documentation with pydoc. There are examples of different types of docstrings so you can see how they look when generated with pydoc.
Here is a practical example of Anchor tag with different
If you use Java 8 or above, you can rely on the Stream API to do such thing:
public static boolean containsItemFromArray(String inputString, String[] items) {
// Convert the array of String items as a Stream
// For each element of the Stream call inputString.contains(element)
// If you have any match returns true, false otherwise
return Arrays.stream(items).anyMatch(inputString::contains);
}
Assuming that you have a big array of big String
to test you could also launch the search in parallel by calling parallel()
, the code would then be:
return Arrays.stream(items).parallel().anyMatch(inputString::contains);
Each answer is 5 6 years old, so bit outdated or depreciated. Let's talk in 2020.
simple-node-logger is simple multi-level logger for console, file, and rolling file appenders. Features include:
levels: trace, debug, info, warn, error and fatal levels (plus all and off)
flexible appender/formatters with default to HH:mm:ss.SSS LEVEL message add appenders to send output to console, file, rolling file, etc
change log levels on the fly
domain and category columns
overridable format methods in base appender
stats that track counts of all log statements including warn, error, etc
You can easily use it in any nodejs web application:
// create a stdout console logger
const log = require('simple-node-logger').createSimpleLogger();
or
// create a stdout and file logger
const log = require('simple-node-logger').createSimpleLogger('project.log');
or
// create a custom timestamp format for log statements
const SimpleNodeLogger = require('simple-node-logger'),
opts = {
logFilePath:'mylogfile.log',
timestampFormat:'YYYY-MM-DD HH:mm:ss.SSS'
},
log = SimpleNodeLogger.createSimpleLogger( opts );
or
// create a file only file logger
const log = require('simple-node-logger').createSimpleFileLogger('project.log');
or
// create a rolling file logger based on date/time that fires process events
const opts = {
errorEventName:'error',
logDirectory:'/mylogfiles', // NOTE: folder must exist and be writable...
fileNamePattern:'roll-<DATE>.log',
dateFormat:'YYYY.MM.DD'
};
const log = require('simple-node-logger').createRollingFileLogger( opts );
Messages can be logged by
log.info('this is logged info message')
log.warn('this is logged warn message')//etc..
PLUS POINT: It can send logs to console or socket. You can also append to log levels.
This is the most effective and easy way to handle logs functionality.
I've found the solution.
I used: outline:none;
in the CSS and it seems to have worked. Thanks for the help anyway. :)
In Java 8,
IntStream.range(0,jsonArray.length()).mapToObj(i->jsonArray.getString(i)).collect(Collectors.toList())
The dataset:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
Now you can convert the data frame into a matrix and use the barplot
function.
barplot(as.matrix(dat))
I found this page 10 years (!) after the original post, and needed the answer as vanilla js instead of AJAX. I figured it out with the help of @gargAman's answer.
Use an appropriate selector to assign your button to a variable, e.g.
document.getElementById('myButton')
then
myButton.addEventListener('click', function(e) {
e.preventDefault();
// do cool stuff
});
I should note that my html looks like this (specifically, I am not using type="Submit"
in my button and action=""
in my form:
<form method="POST" action="" id="myForm">
<!-- form fields -->
<button id="myButton" class="btn-submit">Submit</button>
</form>
Python-3.x:
"aabc".count("a")
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
I try to avoid floating elements unless the design really needs it. Because you have floated the <li>
they are out of normal flow.
If you add .navigation { text-align:center; }
and change .navigation li { float: left; }
to .navigation li { display: inline-block; }
then entire navigation will be centred.
One caveat to this approach is that display: inline-block;
is not supported in IE6 and needs a workaround to make it work in IE7.
Note that callback syntax is deprecated:
Deprecation Notice
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Here a modernized solution using the promise
interface
$.ajax({url: "...", cache: false}).done(function( data ) {
// data contains result
}).fail(function(err){
// error
});
I think, this could be done without IIS URL Rewrite module. <httpRedirect>
supports wildcards, so you can configure it this way:
<system.webServer>
<httpRedirect enabled="true">
<add wildcard="/" destination="/menu_1/MainScreen.aspx" />
</httpRedirect>
</system.webServer>
Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects
In the CSS all you have to do is put url(logical path to the image file)
List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.
Since Docker 1.5 you can now expose a range of ports to other linked containers using:
The Dockerfile EXPOSE command:
EXPOSE 7000-8000
or The Docker run command:
docker run --expose=7000-8000
Or instead you can publish a range of ports to the host machine via Docker run command:
docker run -p 7000-8000:7000-8000
Using sed can also be elegant in this situation. Example (replace line with matched group "yyy" from line):
$ cat testfile
xxx yyy zzz
yyy xxx zzz
$ cat testfile | sed -r 's#^.*(yyy).*$#\1#g'
yyy
yyy
Relevant manual page: https://www.gnu.org/software/sed/manual/sed.html#Back_002dreferences-and-Subexpressions
Add following option in jboss in bin/standalone.conf.bat
set "JAVA_OPTS=-Xms1G -Xmx1G -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=1024m"
The warning is issued since you are using backslashes in your strings. If you want to avoid the message, type this command "set standard_conforming_strings=on;". Then use "E" before your string including backslashes that you want postgresql to intrepret.
You can also do the following,to import datetime
from datetime import datetime as dt
dt.strptime(date, '%Y-%m-%d')
You can add the following to each image you don't want to be draggable, (inside the img
tag):
onmousedown="return false;"
e.g.
img src="Koala.jpg" onmousedown="return false;"
Instead of using:
self.present(viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?)
you can use:
self.navigationController?.pushViewController(viewController: UIViewController, animated: Bool)
There aren't many JavaScript decoders.
There is one at http://www.webqr.com/index.html
The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.
I'm sticking with DbVisualizer Free until something better comes along.
EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this
Ok, for @AndrewS solution to work with v7 appCompat library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/saved_badge"
someNamespace:showAsAction="always"
android:icon="@drawable/shape_notification" />
</menu>
.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.saved_badge);
MenuItemCompat.setActionView(item, R.layout.feed_update_count);
View view = MenuItemCompat.getActionView(item);
notifCount = (Button)view.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
}
private void setNotifCount(int count){
mNotifCount = count;
supportInvalidateOptionsMenu();
}
The rest of the code is the same.
I always use requestAnimationFrame()
to jump over internal post-event mechanisms and this works perfectly in Firefox. Haven't tested in Chrome.
$("input[type=text]").on('focus', function() {
requestAnimationFrame(() => $(this).select());
});
Slightly off topic, but in case some people (like me, when I first found this thread) might be interested in capturing log output via SLF4J, commons-testing's JUnit @Rule
might help:
public class FooTest {
@Rule
public final ExpectedLogs logs = new ExpectedLogs() {{
captureFor(Foo.class, LogLevel.WARN);
}};
@Test
public void barShouldLogWarning() {
assertThat(logs.isEmpty(), is(true)); // Nothing captured yet.
// Logic using the class you are capturing logs for:
Foo foo = new Foo();
assertThat(foo.bar(), is(not(nullValue())));
// Assert content of the captured logs:
assertThat(logs.isEmpty(), is(false));
assertThat(logs.contains("Your warning message here"), is(true));
}
}
Disclaimer:
log4j
, log4j2
and logback
are available at the moment, but I am happy to add more.I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error
The FLAWED version
import threading
import time
# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []
def add():
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output when ERROR
Exception in thread Thread-63:
Traceback (most recent call last):
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
l.remove(i)
ValueError: list.remove(x): x not in list
Version that uses locks
import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
with lock:
for i in range(count):
l.append(i)
time.sleep(0.0001)
def remove():
with lock:
for i in range(count):
l.remove(i)
time.sleep(0.0001)
t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()
print(l)
Output
[] # Empty list
Conclusion
As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another
The code doesn't work because elapsed variable in getElapsedTimeSecs()
is not a float
or double
.
select cast (height as decimal)/10 as HeightDecimal
I am using Windows 10 Home edition.
I tried various combination,
netsh wlan show drivers
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=allow ssid=happy key=12345678
netsh wlan start hostednetwork
and also,
Control Panel\Network and Internet\Network Connections\Ethernet Properties\Sharing\Internet Connection Sharing\Allow other network users to connect through this computer Internet connection...
But still cannot activate WiFi hotspot.
While I have given up, somehow I click on Network icon on the taskbar, suddenly I see the buttons:
[ Wi-Fi ] [ Airplane Mode ] [ Mobile hotspot ]
Just like how our mobile phone can enable Mobile hotspot, Windows 10 has Mobile hotspot build-in. Just click on [ Mobile hotspot ] button and it works.
The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.
dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is
P(dBm) = 10 · log10( P(W) / 1mW )
where
P(dBm) = Power expressed in dBm P(W) = the absolute power measured in Watts mW = milliWatts log10 = log to base 10
From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.
There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.
Your actual question was "does the - sign count?"
The answer is yes, it does.
-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.
Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.
How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.
From PHP:
function OutputJs($Content)
{
ob_start();
echo $Content;
$expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere
header("Content-type: x-javascript");
header('Content-Length: ' . ob_get_length());
header('Cache-Control: max-age='.$expires.', must-revalidate');
header('Pragma: public');
header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');
ob_end_flush();
return;
}
works for me.
As a developer you'll probably quickly run into the situation that you don't want files cached, in which case see Help with aggressive JavaScript caching
If you use a CompletableFuture (introduced in Java 8) or a SettableFuture (from Google Guava), you can make your test finish as soon as it's done, rather than waiting a pre-set amount of time. Your test would look something like this:
CompletableFuture<String> future = new CompletableFuture<>();
executorService.submit(new Runnable() {
@Override
public void run() {
future.complete("Hello World!");
}
});
assertEquals("Hello World!", future.get());
Git comes with a couple of GUI clients that helps you visualize this. Open GitGUI and go to menu Repository > Visualize All Branch History
Try running cmd as administrator (in the menu that pops up after right-clicking) and/or entering "pip" alone and then
I'm using the following in VC++ and it works like a charm for me.
CA2CT(charText)
This is actually a documented feature, and can be found here
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
You can add a shebang line the to the top of the script:
#!/usr/bin/env python2.7
But that will only work when executing as ./my_program.py
.
If you execute as python my_program.py
, then the whatever Python version that which python
returns will be used.
In re: to virtualenv use: virtualenv -p /usr/bin/python3.2
or whatever to set it up to use that Python executable.
I ran into this same situation (in my case with a date value in a custom PHP field in a Drupal view), and what worked for me was using intval instead of strtotime to turn the value into an integer - because it basically was a timestamp, but in the form of a string rather than an integer. Obviously that won't be the case for everyone, but it might be worth a try.
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
Install Oracle's MySql.Data
NuGet package.
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Data
{
public class DBConnection
{
private DBConnection()
{
}
public string Server { get; set; }
public string DatabaseName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private MySqlConnection Connection { get; set;}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
public bool IsConnect()
{
if (Connection == null)
{
if (String.IsNullOrEmpty(databaseName))
return false;
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
Connection = new MySqlConnection(connstring);
Connection.Open();
}
return true;
}
public void Close()
{
Connection.Close();
}
}
}
Example:
var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}
I'm maybe a little bit late but I'm currently trying to develop a program which can brute force a password protected zip archive. First I tried all commands I found in the internet to extract it through cmd... But it never worked....Every time I tried it, the cmd output said, that the key was wrong but it was right. I think they just disenabled this function in a current version.
What I've done to Solve the problem was to download an older 7zip version(4.?) and to use this for extracting through cmd.
This is the command: "C:/Program Files (86)/old7-zip/7z.exe" x -pKey "C:/YOURE_ZIP_PATH"
The first value("C:/Program Files (86)/old7-zip/7z.exe") has to be the path where you have installed the old 7zip to. The x is for extract and the -p For you're password. Make sure you put your password without any spaces behind the -p! The last value is your zip archive to extract. The destination where the zip is extracted to will be the current path of cmd. You can change it with: cd YOURE_PATH
Now I let execute this command through java with my password trys. Then I check the error output stream of cmd and if it is null-> then the password is right!
For Hibernate you can use the jackson-datatype-hibernate project to accommodate JSON serialization/deserialization with lazy-loaded objects.
For example,
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonDatatypeHibernate5Configuration {
// Register Jackson Hibernate5 Module to handle JSON serialization of lazy-loaded entities
// Any beans of type com.fasterxml.jackson.databind.Module are automatically
// registered with the auto-configured Jackson2ObjectMapperBuilder
// https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper
@Bean
public Module hibernate5Module() {
Hibernate5Module hibernate5Module = new Hibernate5Module();
hibernate5Module.enable( Hibernate5Module.Feature.FORCE_LAZY_LOADING );
hibernate5Module.disable( Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION );
return hibernate5Module;
}
}
In 32 bit format system the hexadecimal value 0xff
represents 00000000000000000000000011111111
that is 255(15*16^1+15*16^0)
in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
I did it a different way to what I was wanting to do...gave me the result I needed. I chose not to submit the form, rather just get the value of the text field and use it in the javascript and then reset the text field. Sorry if I bothered anyone with this question.
Basically just did this:
var search = document.getElementById('search').value;
document.getElementById('search').value = "";
Please, see oficial encode()
and decode()
documentation from codecs
library. utf-8
is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1
or utf_32
.
This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.
change it to:
$(function () {
var specialElementHandlers = {
'#editor': function (element,renderer) {
return true;
}
};
$('#cmd').click(function () {
var doc = new jsPDF();
doc.fromHTML(
$('#target').html(), 15, 15,
{ 'width': 170, 'elementHandlers': specialElementHandlers },
function(){ doc.save('sample-file.pdf'); }
);
});
});
and it will work.
git checkout BranchB
git merge BranchA
git push origin BranchB
This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.
Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.
Make sure you are in the branch where you want to copy all the changes to. git merge
will take the branch you specify and merge it with the branch you are currently in.
Assuming that your table name is city
and your existing Primary Key is pk_city
, you should be able to do the following:
ALTER TABLE city
DROP CONSTRAINT pk_city;
ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);
Make sure that there are no records where time
is NULL
, otherwise you won't be able to re-create the constraint.
expr(1)
has a substr subcommand:
expr substr <string> <start-index> <length>
This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).
Use:
db.emails.count({sent_at: null})
Which counts all emails whose sent_at property is null or is not set. The above query is same as below.
db.emails.count($or: [
{sent_at: {$exists: false}},
{sent_at: null}
])
No.
If the user is sophisticated or determined enough to:
then they are probably sophisticated or determined enough to:
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
After updating PHP to 7.3, PHP scripts where run with www-data instead of $USER like before.
I needed to reinstall and activate PHP-FPM :
sudo apt-get install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo service apache2 restart
sudo a2enconf php7.3-fpm
sudo service apache2 restart
To ensure everything was ok for Virtualmin, i used the Re-Check Configuration wizard /virtual-server/check.cgi
, under Vitualmin/System Settings.
After that, Apache/PHP was downloading php files instead of running them. So i needed to edit /etc/apache2/mods-available/php7.3.conf
to comment the row SetHandler application/x-httpd-php
like below :
<FilesMatch ".+\.ph(ar|p|tml)$">
# SetHandler application/x-httpd-php
</FilesMatch>
After restarting Apache, it solved my issue, hope this help.
Take care of browser cache too.
My system :
Ubuntu 16.04.6 LTS
Webmin version 1.932
Usermin version 1.780
Virtualmin version 6.08
Apache version 2.4.41
PHP versions 7.3.12
PHP-FPM 7.3.12 Server
I am not very sure whether it will make any difference in performance of my API.
Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async
" considerations in my article on async
ASP.NET.
I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.
As far as the code goes, this is not asynchronous:
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
return Task.FromResult(response);
}
You'd need a truly asynchronous implementation to get the scalability benefits of async
:
public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Or (if your logic in this method really is just a pass-through):
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync
). Then let the async
trickle up, making your controller actions asynchronous as the last step.
And under no circumstances should you use Task.Run
in this scenario.
You cannot initialize an array to '0' like that
int cipher[Array_size][Array_size]=0;
You can either initialize all the values in the array as you declare it like this:
// When using different values
int a[3] = {10,20,30};
// When using the same value for all members
int a[3] = {0};
// When using same value for all members in a 2D array
int a[Array_size][Array_size] = { { 0 } };
Or you need to initialize the values after declaration. If you want to initialize all values to 0 for example, you could do something like:
for (int i = 0; i < Array_size; i++ ) {
a[i] = 0;
}
I was having the same problem. It seems that passing Me.ComboBox1.Value
as an argument for the Vlookup
function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.
Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False)
Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>)
.
So it would end up being
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False)
Strange as it may sound, it works for me.
Hope this helps.
You need to convert your image to a numpy array this way:
import numpy
import PIL
img = PIL.Image.open("foo.jpg").convert("L")
imgarr = numpy.array(img)
You can use the Math.abs(number) function. It returns a positive number.
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.timezone,data.datetime,data.dst));
_x000D_
Depends on what you need.
In this case I suggest:
SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;
because there are few fields and the execution time of DISTINCT
is lower than the execution of GROUP BY
.
In other cases, for example where there are many fields, I prefer:
SELECT * FROM buy GROUP BY date ORDER BY date DESC;
I think @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
should work.
You need to write it like
string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
Response.Write(email + " is correct");
else
Response.Write(email + " is incorrect");
Be warned that this will fail if:
There is a subdomain after the @
symbol.
You use a TLD with a length greater than 3, such as .info
??!
is a trigraph that translates to |
. So it says:
!ErrorHasOccured() || HandleError();
which, due to short circuiting, is equivalent to:
if (ErrorHasOccured())
HandleError();
Guru of the Week (deals with C++ but relevant here), where I picked this up.
Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.
From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):
The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.
An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)
A linker takes all these object files and combines them to form one executable (assuming that it can, ie: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c
is a common "just compile; don't link" option.)
You can also get through it by the code below:
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
For me
grep -b "searchsomething" *.log
worked as I wanted
Operator precedence in python
You can see that not X
has higher precedence than and
. Which means that the not
only apply to the first part (u0 <= u)
.
Write:
if not (u0 <= u and u < u0+step):
or even
if not (u0 <= u < u0+step):
If you have to use the same page as the action, you cannot use onSubmit="window.close();"
as it will close the window before the response is received. You have to dinamycally output a JS snippet that closes the window after the SQL data is processed. It would however be far more elegant to use another page as the form action.
I should like to contribute the modern answer. The SimpleDateFormat
class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat
and its friend Date
are now considered long outdated, so don’t use them anymore.
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
String dateformat = "2012-11-17T00:00:00.000-05:00";
OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
String monthYear = dateTime.format(monthFormatter);
System.out.println(monthYear);
Output:
11/2012
I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.
SimpleDateFormat.format
cannot accept a String
argument, also when the parameter type is declared to be Object
.mm/yyyy
. Lowercase mm
os for minute of the hour. You need uppercase MM
for month.m
in monthYear
(also because java.time includes a MonthYear
class with uppercase M
, so to avoid confusion).java.time
.Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
This will give you the date in 24 hour format.
Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));
Check the manual for mysql_fetch_object()
. It returns an object, not an array of objects.
I'm guessing you want something like this
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
$sidemenus[] = $sidemenu;
}
Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ)
does what you assumed mysql_fetch_object()
to do
To answer the original question: here is how you decode utf-8 in javascript:
http://ecmanaut.blogspot.ca/2006/07/encoding-decoding-utf8-in-javascript.html
Specifically,
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
We have been using this in our production code for 6 years, and it has worked flawlessly.
Note, however, that escape() and unescape() are deprecated. See this.
If I'm not mistaken this is usually handled via a timeout.
Another method to try out.
Also select
could be replaced when you set the initial column into a Range object. Performance wise it helps.
Dim rng as Range
Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.
'-- here is your loop
i = 1
Do
'-- do something: e.g. show the address of the column that you are currently in
Msgbox rng.offset(0,i).Address
i = i + 1
Loop Until i > 10
** Two methods to get the column name using column number**
code
colName = Split(Range.Offset(0,i).Address, "$")(1)
code
Function myColName(colNum as Long) as String
myColName = Left(Range(0, colNum).Address(False, False), _
1 - (colNum > 10))
End Function
If you need to create multiple columns at once:
Create the dataframe:
import pandas as pd
df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
Create the function:
def fab(row):
return row['A'] * row['B'], row['A'] + row['B']
Assign the new columns:
df['newcolumn'], df['newcolumn2'] = zip(*df.apply(fab, axis=1))
There are a set of available properties to all Maven projects.
From Introduction to the POM:
project.basedir
: The directory that the current project resides in.
This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml
file. If your POM is located inside /path/to/project/pom.xml
then this property will evaluate to /path/to/project
.
Some properties are also inherited from the Super POM, which is the case for project.build.directory
. It is the value inside the <project><build><directory>
element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory
, it is:
The directory where all files generated by the build are placed. The default value is
target
.
This is the directory that will hold every generated file by the build.
This maybe a bit off topic.
I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.
fwrite(fopen('php://stdout', 'w'), var_export($object, true));
As of Xcode 8, you can define class properties in Obj-C. This has been added to interoperate with Swift's static properties.
Objective-C now supports class properties, which interoperate with Swift type properties. They are declared as: @property (class) NSString *someStringProperty;. They are never synthesized. (23891898)
Here is an example
@interface YourClass : NSObject
@property (class, nonatomic, assign) NSInteger currentId;
@end
@implementation YourClass
static NSInteger _currentId = 0;
+ (NSInteger)currentId {
return _currentId;
}
+ (void)setCurrentId:(NSInteger)newValue {
_currentId = newValue;
}
@end
Then you can access it like this:
YourClass.currentId = 1;
val = YourClass.currentId;
Here is a very interesting explanatory post I used as a reference to edit this old answer.
2011 Answer: (don't use this, it's terrible)
If you really really don't want to declare a global variable, there another option, maybe not very orthodox :-), but works... You can declare a "get&set" method like this, with an static variable inside:
+ (NSString*)testHolder:(NSString*)_test {
static NSString *test;
if(_test != nil) {
if(test != nil)
[test release];
test = [_test retain];
}
// if(test == nil)
// test = @"Initialize the var here if you need to";
return test;
}
So, if you need to get the value, just call:
NSString *testVal = [MyClass testHolder:nil]
And then, when you want to set it:
[MyClass testHolder:testVal]
In the case you want to be able to set this pseudo-static-var to nil, you can declare testHolder
as this:
+ (NSString*)testHolderSet:(BOOL)shouldSet newValue:(NSString*)_test {
static NSString *test;
if(shouldSet) {
if(test != nil)
[test release];
test = [_test retain];
}
return test;
}
And two handy methods:
+ (NSString*)test {
return [MyClass testHolderSet:NO newValue:nil];
}
+ (void)setTest:(NSString*)_test {
[MyClass testHolderSet:YES newValue:_test];
}
Hope it helps! Good luck.
Check this code to:
@Override
protected void onDestroy() {
// closing Entire Application
android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// <uses-permission
// android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
// The directory is now empty so delete it
return dir.delete();
}
I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.
Dockerfile
...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash
Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.
Swift Version :
// Attributed String for Label
let plainText = "Apkia"
let styledText = NSMutableAttributedString(string: plainText)
// Set Attribuets for Color, HyperLink and Font Size
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSLinkAttributeName:NSURL(string: "http://apkia.com/")!, NSForegroundColorAttributeName: UIColor.blueColor()]
styledText.setAttributes(attributes, range: NSMakeRange(0, plainText.characters.count))
registerLabel.attributedText = styledText
In ES6, it is good to use for - of loop. You can get index in for of like this
for (let [index, val] of array.entries()) {
// your code goes here
}
Note that Array.entries()
returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
For System.Timers.Timer:
See Brian Gideon's answer below
MSDN Documentation on Timers states:
The System.Threading.Timer class makes callbacks on a ThreadPool thread and does not use the event model at all.
So indeed the timer elapses on a different thread.
You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.
Extract from Android Developer Guide link above:
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
widget['bg'] = '#000000'
or
widget['background'] = '#000000'
would also work as hex-valued colors are also accepted.
Try This one:: Libav in Linux
Installation: run command
sudo apt-get install libav-tools
Video conversion command::Go to folder contains the video and run in terminal
avconv -i oldvideo.flv -ar 22050 convertedvideo.mp4
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
The best way doing this - especially if you're adding more than one condition - is:
$values = array(...); // array of your values
$qb->andWhere('where', $qb->expr()->in('r.winner', $values));
If your array of values contains strings, you can't use the setParameter method with an imploded string, because your quotes will be escaped!
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
since some minor explanations were missing
Use @Deprecated
annotation on the method like this
/**
* @param basePrice
*
* @deprecated reason this method is deprecated <br/>
* {will be removed in next version} <br/>
* use {@link #setPurchasePrice()} instead like this:
*
*
* <blockquote><pre>
* getProduct().setPurchasePrice(200)
* </pre></blockquote>
*
*/
@Deprecated
public void setBaseprice(int basePrice) {
}
<br/>
{@link #setPurchasePrice()}
Altova's DiffDog has free 30-day trial and should do what you're looking for:
The Instant
class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC.
So, formatter can't print a date because date always printed for concrete time zone.
You should set time zone to formatter and all will be fine, like this :
Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");
Invoke the sqlite3
utility on the database file, and use its special dot commands:
.tables
will list tables.schema [tablename]
will show the CREATE statement(s) for a table or tablesThere are many other useful builtin dot commands -- see the documentation at http://www.sqlite.org/sqlite.html, section Special commands to sqlite3.
Example:
sqlite> entropy:~/Library/Mail>sqlite3 Envelope\ Index
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
addresses ews_folders subjects
alarms feeds threads
associations mailboxes todo_notes
attachments messages todos
calendars properties todos_deleted_log
events recipients todos_server_snapshot
sqlite> .schema alarms
CREATE TABLE alarms (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, alarm_id,
todo INTEGER, flags INTEGER, offset_days INTEGER,
reminder_date INTEGER, time INTEGER, argument,
unrecognized_data BLOB);
CREATE INDEX alarm_id_index ON alarms(alarm_id);
CREATE INDEX alarm_todo_index ON alarms(todo);
Note also that SQLite saves the schema and all information about tables in the database itself, in a magic table named sqlite_master, and it's also possible to execute normal SQL queries against that table. For example, the documentation link above shows how to derive the behavior of the .schema
and .tables
commands, using normal SQL commands (see section: Querying the database schema).
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
Add a method to your page class like this:
public string YesNo(bool active)
{
return active ? "Yes" : "No";
}
And then in your TemplateField
you Bind
using this method:
<%# YesNo(Active) %>
From Language DDL & UDF of Hive
NVL(value, default value)
Returns default value if value is null else returns value
that worked for me after clearing selection, BeginEdit and change the girdview rows and end the Edit Mode.
if (dgvDetails.RowCount > 0)
{
dgvDetails.ClearSelection();
dgvDetails.BeginEdit(true);
foreach (DataGridViewRow dgvr in dgvDetails.Rows)
{
dgvr.Cells["cellName"].Value = true;
}
dgvDetails.EndEdit();
}
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
Perhaps not a "builtin", but I consider it builtin. anyways just use numpy
import numpy
prod_sum = numpy.prod(some_list)
This:
document.getElementById('myField').onblur();
works because your element (the <input>
) has an attribute called "onblur" whose value is a function. Thus, you can call it. You're not telling the browser to simulate the actual "blur" event, however; there's no event object created, for example.
Elements do not have a "blur" attribute (or "method" or whatever), so that's why the first thing doesn't work.
If you use addToBackStack()
, you can use following code.
List<Fragment> fragments = fragmentManager.getFragments();
activeFragment = fragments.get(fragments.size() - 1);
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
Override toString()
method in Student
class as below:
@Override
public String toString() {
return ("StudentName:"+this.getStudentName()+
" Student No: "+ this.getStudentNo() +
" Email: "+ this.getEmail() +
" Year : " + this.getYear());
}
var str = "I'm a very^ we!rd* Str!ng.";
$('body').html(str.replace(/[^a-z0-9\s]/gi, " ").replace(/^\s+|\s+$|\s+(?=\s)/g, "").replace(/[_\s]/g, "-").toLowerCase());
First regex remove special characters with spaces than remove extra spaces from string and the last regex replace space with "-"
I will give you a solution implementing selectionSort algorithm ,it is simple and effective
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
function selection_Sort(num) {
//console.log(num);
var temp, index;
for (var i = 0; i <= num.length - 1; i++) {
index = i;
for (var j = i + 1; j <= num.length - 1; j++) {
// you can use first_nom/last_nom,any way you choose to sort
if (num[j]. last_nom < num[index]. last_nom) {
index = j;
}
}
//below is the swapping part
temp = num[i]. last_nom;
num[i]. last_nom = num[index]. last_nom;
num[index]. last_nom = temp;
};
console.log(num);
return num;
}
selection_Sort(objs);
Great to see such great answers
Create a wrapper around properties and assume your A value has keys A.1, A.2, etc. Then when asked for A your wrapper will read all the A.* items and build the list. HTH
The TimeSpan constructor allows you to pass in seconds. Simply declare a variable of type TimeSpan amount of seconds. Ex:
TimeSpan span = new TimeSpan(0, 0, 500);
span.ToString();
This is based on my solution for FreeCodeCamp's Bonfire "Title Case", which requires you to first convert the given string to all lower case and then convert every character proceeding a space to upper case.
Without using regex:
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}
When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png)
can be problematic if PDF output is required.
The knitr function include_graphics
knitr::include_graphics('/path/to/image.png')
is a more portable alternative
that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.
As suggested by Nineroad Installing WindowBuilder as the default editor for files with a *.java extention fixed this issue for me.
In Eclipse, navigate to Help > Install New Software
Add http://archive.eclipse.org/windowbuilder/WB/release/R201309271200/4.3 to the "Work with" path, select all components suggested, and install WindowBuilder.
Once complete, Eclipse will request restart. Once restarted, within Eclipse navigate to Window > Preferences. In The Preferences dialogue-box navigate to General > Editor > File Associations. Under "File Associations" list, be sure to select *.java file types. The bottom window (labeled "Associated Editors") should have WindowBuilder as an option. Select WindowBuilder and click "Default" to the right, to set WindowBuilder as your default *.java file editor.
This fixed the SWT error for me.
Note: Eclipse Version: Kepler Service Release 2 Windows 7 64-bit
In addition to potame's answer, if you do want to escape using a CDATA block.
If you put your text in a CDATA block then you don't need to use escaping. In that case you can use all characters in the following range:
Note: On top of that, you're not allowed to use the ]]>
character sequence. Because it would match the end of the CDATA block.
If there are still invalid characters (e.g. control characters), then probably it's better to use some kind of encoding (e.g. base64).
I found a space in one of the header (titles) on the Excel sheet. Once I removed the space before the name, it went smoothly.
Here is an out of the box future proof date snippet. Firefox defaults to jquery ui datepicker. Otherwise HTML5 datepicker is used. If FF ever support HTML5 type="date" the script will simply be redundant. Dont forget the three dependencies are needed in the head tag.
<script>
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link rel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--Form element uses HTML 5 type="date"-->
<div class="form-group row">
<label for="date" class="col-sm-2 col-form-label"Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="date" id="date" placeholder="date">
</div>
</div>
<!--if the user is using FireFox it
autoconverts type='date' into type='text'. If the type is text the
script below will assign the jquery ui datepicker with options-->
<script>
$(function()
{
var elem = document.createElement('input');
elem.setAttribute('type', 'date');
if ( elem.type === 'text' )
{
$('#date').datepicker();
$( "#date" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
}
});
<div ng-repeat="file in files" ng-class="!$last ? 'class-for-last' : 'other'">
{{file.name}}
</div>
That works for me! Good luck!
Answer above did not work for me on Chrome. The change event was been fired after I clicked out of the field somewhere, which did not help because the datepicker window is also closed too when you click out of the field.
I did use this code and it worked pretty well. You can place it after calling .datepicker();
HTML
<input type="text" class="datepicker-input" placeholder="click to show datepicker" />
JavaScript
$(".datepicker-input").each(function() {
$(this).datepicker();
});
$(".datepicker-input").click(function() {
$(".datepicker-days .day").click(function() {
$('.datepicker').hide();
});
});
I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient, because implementing encodeWithCoder and initWithCoder is super boring!
To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"
To save a custom object into NSUserDefaults:
#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];
To get custom obj from NSUserDefaults:
user = [defaults rm_customObjectForKey:@"SAVED_DATA"];
You can try this. :) simple solution!
=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")
df.write.mode('overwrite').parquet("/output/folder/path")
works if you want to overwrite a parquet file using python. This is in spark 1.6.2. API may be different in later versions
As definition of "Foo" has lot's of meanings:
bar, and baz are often compounded together to make such words as foobar, barbaz, and foobaz. www.nationmaster.com/encyclopedia/Metasyntactic-variable
Major concepts in CML, usually mapped directly onto XMLElements (to be discussed later). wwmm.ch.cam.ac.uk/blogs/cml/
Measurement of the total quantity of pasture in a paddock, expressed in kilograms of pasture dry matter per hectare (kg DM/ha) www.lifetimewool.com.au/glossary.aspx
Forward Observation Officer. An artillery officer who remained with infantry and tank battalions to set up observation posts in the front lines from which to observe enemy positions and radio the coordinates of targets to the guns further in the rear. members.fortunecity.com/lniven/definition.htm
is the first metasyntactic variable commonly used. It is sometimes combined with bar to make foobar. This suggests that foo may have originated with the World War II slang term fubar, as an acronym for fucked/fouled up beyond all recognition, although the Jargon File makes a pretty good case ... explanation-guide.info/meaning/Metasyntactic-variable.html
Foo is a metasyntactic variable used heavily in computer science to represent concepts abstractly and can be used to represent any part of a ... en.wikipedia.org/wiki/FOo
Foo is the world of dreams (no its not) in Obert Skye's Leven Thumps series. Although it has many original inhabitants, most of its current dwellers are from Reality, and are known as nits. ... en.wikipedia.org/wiki/Foo (place)
Also foo’. Representation of fool (foolish person), in a Mr. T accent en.wiktionary.org/wiki/foo
Resource: google