With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
With the example given in the question, it would look like this
plot.savefig(f'hanning{num}.pdf')
Keep it Simple
Adding Floating Action Button using TextView by giving rounded xml background.
- Add compile com.android.support:design:23.1.1
to gradle file
Circle Xml is
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/colorPrimary"/>
<size
android:width="30dp"
android:height="30dp"/>
</shape>
Layout xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="5"
>
<RelativeLayout
android:id="@+id/viewA"
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1.6"
android:background="@drawable/contact_bg"
android:gravity="center_horizontal|center_vertical"
>
</RelativeLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="3.4"
android:orientation="vertical"
android:padding="16dp"
android:weightSum="10"
>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Name"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:id="@+id/name"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="Ritesh Kumar Singh"
android:singleLine="true"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Phone"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:id="@+id/number"
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="8283001122"
android:textSize="22dp"
android:textColor="@android:color/black"
android:singleLine="true"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Email"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="[email protected]"
android:textSize="22dp"
android:singleLine="true"
android:textColor="@android:color/black"
android:padding="3dp"
/>
</LinearLayout>
<LinearLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1"
android:weightSum="4"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:text="City"
android:textSize="22dp"
android:textColor="@android:color/black"
android:padding="3dp"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:text="Panchkula"
android:textSize="22dp"
android:textColor="@android:color/black"
android:singleLine="true"
android:padding="3dp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/floating"
android:transitionName="@string/transition_name_circle"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="16dp"
android:clickable="false"
android:background="@drawable/circle"
android:elevation="10dp"
android:text="R"
android:textSize="40dp"
android:gravity="center"
android:textColor="@android:color/black"
app:layout_anchor="@id/viewA"
app:layout_anchorGravity="bottom"/>
</android.support.design.widget.CoordinatorLayout>
I always use
cxt.fillStyle = "rgb(255, 255, 255)";
cxt.fillRect(0, 0, canvas.width, canvas.height);
For a custom color, and
ctx.clearRect(0, 0, canvas.width, canvas.height);
For making the canvas transparent when clearing
Code updated for Swift 3
Swift code
import UIKit
class ViewController: UIViewController {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
@IBOutlet weak var myBlueSubview: UIView!
@IBAction func showButtonTapped(sender: UIButton) {
activityIndicator.startAnimating()
}
@IBAction func hideButtonTapped(sender: UIButton) {
activityIndicator.stopAnimating()
}
override func viewDidLoad() {
super.viewDidLoad()
// set up activity indicator
activityIndicator.center = CGPoint(x: myBlueSubview.bounds.size.width/2, y: myBlueSubview.bounds.size.height/2)
activityIndicator.color = UIColor.yellow
myBlueSubview.addSubview(activityIndicator)
}
}
Notes
You can center the activity indicator in middle of the screen by adding it as a subview to the root view
rather than myBlueSubview
.
activityIndicator.center = CGPoint(x: self.view.bounds.size.width/2, y: self.view.bounds.size.height/2)
self.view.addSubview(activityIndicator)
You can also create the UIActivityIndicatorView
in the Interface Builder. Just drag an Activity Indicator View onto the storyboard and set the properties. Be sure to check Hides When Stopped. Use an outlet to call startAnimating()
and stopAnimating()
. See this tutorial.
Remember that the default color of the LargeWhite
style is white. So if you have a white background you can't see it, just change the color to black or whatever other color you want.
activityIndicator.color = UIColor.black
A common use case would be while a background task runs. Here is an example:
// start animating before the background task starts
activityIndicator.startAnimating()
// background task
DispatchQueue.global(qos: .userInitiated).async {
doSomethingThatTakesALongTime()
// return to the main thread
DispatchQueue.main.async {
// stop animating now that background task is finished
self.activityIndicator.stopAnimating()
}
}
Although adding something to nodejs module is possible, it seems to be not the best way (if you try to run your code on other computer, the program will crash with the same error, obviously).
I would rather set max listeners number in your own code:
var options = {uri:headingUri, headers:headerData, maxRedirects:100};
request.setMaxListeners(0);
request.get(options, function (error, response, body) {
}
If you know the number of columns at compile time, it's pretty simple:
#define COLS ...
...
size_t rows;
// get number of rows
T (*ap)[COLS] = malloc(sizeof *ap * rows); // ap is a *pointer to an array* of T
You can treat ap
like any 2D array:
ap[i][j] = x;
When you're done you deallocate it as
free(ap);
If you don't know the number of columns at compile time, but you're working with a C99 compiler or a C2011 compiler that supports variable-length arrays, it's still pretty simple:
size_t rows;
size_t cols;
// get rows and cols
T (*ap)[cols] = malloc(sizeof *ap * rows);
...
ap[i][j] = x;
...
free(ap);
If you don't know the number of columns at compile time and you're working with a version of C that doesn't support variable-length arrays, then you'll need to do something different. If you need all of the elements to be allocated in a contiguous chunk (like a regular array), then you can allocate the memory as a 1D array, and compute a 1D offset:
size_t rows, cols;
// get rows and columns
T *ap = malloc(sizeof *ap * rows * cols);
...
ap[i * rows + j] = x;
...
free(ap);
If you don't need the memory to be contiguous, you can follow a two-step allocation method:
size_t rows, cols;
// get rows and cols
T **ap = malloc(sizeof *ap * rows);
if (ap)
{
size_t i = 0;
for (i = 0; i < cols; i++)
{
ap[i] = malloc(sizeof *ap[i] * cols);
}
}
ap[i][j] = x;
Since allocation was a two-step process, deallocation also needs to be a two-step process:
for (i = 0; i < cols; i++)
free(ap[i]);
free(ap);
I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY
We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"
--
To make content itself clickable:
HTML
<input type="checkbox" id="activate-div">
<label for="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
</label>
CSS
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked ~ label
.my-div{background-color:#000}
To make button change content:
HTML
<input type="checkbox" id="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
<label for="activate-div">
//MY BUTTON STUFF
</label>
CSS
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked +
.my-div{background-color:#000}
Hope it helps!!
page-break-inside: avoid; definitely does not work in webkit, in fact has been a known issue for 5+ years now https://bugs.webkit.org/show_bug.cgi?id=5097
As far as my research has gone, there is no known method to accomplish this (I am working on figuring out my own hack)
The advice I can give you is, to accomplish this functionality in FF, wrap the content that you don;t want to break ever inside a DIV (or any container) with overflow: auto (just be careful not to cause weird scroll bars to show up by sizing the container too small).
Sadly, FF is the only browser I managed to accomplish this in, and webkit is the one I am more worried about.
Simple python code!
def format_us_currency(value):
value=str(value)
if value.count(',')==0:
b,n,v='',1,value
value=value[:value.rfind('.')]
for i in value[::-1]:
b=','+i+b if n==3 else i+b
n=1 if n==3 else n+1
b=b[1:] if b[0]==',' else b
value=b+v[v.rfind('.'):]
return '$'+(value.rstrip('0').rstrip('.') if '.' in value else value)
df.iloc[0].head(1)
- First data set only from entire first row.df.iloc[0]
- Entire First row in column.From version 9.1.4 you only need to import ReactiveFormsModule
I'm assuming you want all three of those as part of the selection criteria. You'll need a few statements in your where but they will be similar to the link your question contained.
SELECT *
FROM MyTable
WHERE [dateColumn] > '3/1/2009' AND [dateColumn] <= DATEADD(day,1,'3/31/2009')
--make it inclusive for a datetime type
AND DATEPART(hh,[dateColumn]) >= 6 AND DATEPART(hh,[dateColumn]) <= 22
-- gets the hour of the day from the datetime
AND DATEPART(dw,[dateColumn]) >= 3 AND DATEPART(dw,[dateColumn]) <= 5
-- gets the day of the week from the datetime
Hope this helps.
In Java Class:
public class EnumTest{
//Other property link
private String name;
....
public enum Status {
ACTIVE,NEWLINK, BROADCASTED, PENDING, CLICKED, VERIFIED, AWARDED, INACTIVE, EXPIRED, DELETED_BY_ADMIN;
}
private Status statusobj ;
//Getter and Setters
}
So now POJO and enum obj is created. Now EnumTest you will set in session object using in the servlet or controller class session.setAttribute("enumTest", EnumTest );
In JSP Page
<c:if test="${enumTest.statusobj == 'ACTIVE'}">
//TRUE??? THEN PROCESS SOME LOGIC
In FirstActivity:
Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);
In SecondActivity
In onCreate()
String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");
I would like to suggest a solution if you need to sort more than 2 lists in sync:
def SortAndSyncList_Multi(ListToSort, *ListsToSync):
y = sorted(zip(ListToSort, zip(*ListsToSync)))
w = [n for n in zip(*y)]
return list(w[0]), tuple(list(a) for a in zip(*w[1]))
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
I have solve this problem by just deleting .gradle folder within my application project..
Delete folder .gradle from your project no need to delete main .gradle folder which is located at C:\Users\<username>
Didn't see anyone offer my usual go-to for this:
less +F <file>
ctrl + c
/<search term>
<enter>
shift + f
I prefer this, because you can use ctrl + c
to stop and navigate through the file whenever, and then just hit shift + f
to return to the live, streaming search.
SHOW CREATE TABLE bar;
you will get a create statement for that table, edit the table name, or anything else you like, and then execute it.
This will allow you to copy the indexes and also manually tweak the table creation.
You can also run the query within a program.
if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
I would recommend using Wireshark, which has a "Follow TCP Stream" option that makes it very easy to see the full requests and responses for a particular TCP connection. If you would prefer to use the command line, you can try tcpflow, a tool dedicated to capturing and reconstructing the contents of TCP streams.
Other options would be using an HTTP debugging proxy, like Charles or Fiddler as EricLaw suggests. These have the advantage of having specific support for HTTP to make it easier to deal with various sorts of encodings, and other features like saving requests to replay them or editing requests.
You could also use a tool like Firebug (Firefox), Web Inspector (Safari, Chrome, and other WebKit-based browsers), or Opera Dragonfly, all of which provide some ability to view the request and response headers and bodies (though most of them don't allow you to see the exact byte stream, but instead how the browsers parsed the requests).
And finally, you can always construct requests by hand, using something like telnet, netcat, or socat to connect to port 80 and type the request in manually, or a tool like htty to help easily construct a request and inspect the response.
I don't think this is a timing issue around a null application context
Try extending Application within your app (or just use it if you already have)
public class MyApp extends Application
Make the instance available as a private singleton. This is never null
private static MyApp appInstance;
Make a static helper in MyApp (which will use the singleton)
public static void showProgressDialog( CharSequence title, CharSequence message )
{
prog = ProgressDialog.show(appInstance, title, message, true); // Never Do This!
}
BOOM!!
Also, check out android engineer's answer here: WindowManager$BadTokenException
One cause of this error may be trying to display an application window/dialog through a Context that is not an Activity.
Now, i agree, it does not make sense that the method takes a Context param, instead of Activity..
For the vast majority[1] of visitors here, the correct and simplest answer to the question "How do I list all remote branches in Git 1.7+?" is:
git branch -r
For a small minority[1] git branch -r
does not work. If git branch -r
does not work try:
git ls-remote --heads <remote-name>
If git branch -r
does not work, then maybe as Cascabel says "you've modified the default refspec, so that git fetch
and git remote update
don't fetch all the remote
's branches".
[1] As of the writing of this footnote 2018-Feb, I looked at the comments and see that the git branch -r
works for the vast majority (about 90% or 125 out of 140).
If git branch -r
does not work, check git config --get remote.origin.fetch
contains a wildcard (*
) as per this answer
While debugging, when you hit a break-point.
CTRL+ALT+C
I try this solution, but only works for me like a RaisePropertyChange("SourceGroupeGridView") when collection changed, that fired for each item add or changed.
The problem is in:
public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(args);
}
NotifyCollectionChangedAction.Reset this action make a complete rebind of all items in groupedgrid, is equivalent at RaisePropertyChanged. When you use it all groups of gridview refreshed.
IF you, only want to refresh in UI the group of the new item, you don't use Reset action, you will need simulate a Add action in itemproperty with something like this:
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var index = this.IndexOf((T)sender);
this.RemoveAt(index);
this.Insert(index, (T)sender);
var a = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, sender);
OnCollectionChanged(a);
}
Sorry by my english, and thanks for the base code :), I hope this helps someone ^_^
Enjoi!!
Since you imported the project as a General Project, it does not have the java nature and that is the problem.
Add the below lines in the .project file of your workspace and refresh.
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
Here is a simple example:
ThreadTest.java
public class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0, 3, 300);
MyThread t2 = new MyThread(1, 3, 300);
MyThread t3 = new MyThread(2, 3, 300);
t1.start();
t2.start();
t3.start();
}
}
MyThread.java
public class MyThread extends Thread
{
private int startIdx, nThreads, maxIdx;
public MyThread(int s, int n, int m)
{
this.startIdx = s;
this.nThreads = n;
this.maxIdx = m;
}
@Override
public void run()
{
for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
{
System.out.println("[ID " + this.getId() + "] " + i);
}
}
}
And some output:
[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23
An explanation - Each MyThread
object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1
does index 0, 3, 6, 9, etc.
Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:
MyThread.java
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
And the output:
[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7
Now you can see each thread executing, giving up control early, and the next executing.
Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.
In the non-Express version of VS, the import libray name is specfied in the project settings here:
Configuration Properties/Linker/Advanced/Import Library
I assume it's the same in Express (if it even provides the ability to configure the name).
If you have your private key(s) in ~/.ssh and have added them to https://github.com/settings/ssh, but still are unable to commit to a Github repo added via ssh, make sure they are added to your ssh-agent:
ssh-add -k ~/.ssh/[PRIVATE_KEY]
You can add multiple private keys for multiple servers (e.g. Bitbucket & GitHub) and it will use the correct one when dealing with git.
You should try to use: getpeername function.
now when the connection is down you will get in errno: ENOTCONN - The socket is not connected. which means for you DOWN.
else (if no other failures) there the return code will 0 --> which means UP.
resources: man page: http://man7.org/linux/man-pages/man2/getpeername.2.html
The way I've handled it so far: in UITextFieldDelegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
// text hasn't changed yet, you have to compute the text AFTER the edit yourself
let updatedString = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range, withString: string)
// do whatever you need with this updated string (your code)
// always return true so that changes propagate
return true
}
Swift4 version
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
return true
}
Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.
Yes, otherwise it wouldn't be called "deprecated"
Unless stated otherwise in docs, it should be the same as before
No, but if there were problems in v1 they aren't about to fix them
Try this:
select * from artists where name like "A%" or name like "B%" or name like "C%"
(Expanding on the accepted answer...)
I needed to:
jpg
image and an animated gif
, and, I accomplished this by creating a "secondary" .htaccess
file in the sub-folder where the images are located.
The file contains only one line:
AddHandler application/x-httpd-lsphp .jpg .jpeg .gif
In the same folder, I placed the two 'original' image files (we'll call them orig.jpg
and orig.gif
), as well as two variations of the [simplified] script below (saved as myimage.jpg
and myimage.gif
)...
<?php
error_reporting(0); //hide errors (displaying one would break the image)
//get user IP and the pseudo-image's URL
if(isset($_SERVER['REMOTE_ADDR'])) {$ip =$_SERVER['REMOTE_ADDR'];}else{$ip= '(unknown)';}
if(isset($_SERVER['REQUEST_URI'])) {$url=$_SERVER['REQUEST_URI'];}else{$url='(unknown)';}
//log the visit
require_once('connect.php'); //file with db connection info
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn->connect_error) { //if connected then save mySQL record
$conn->query("INSERT INTO imageclicks (image, ip) VALUES ('$url', '$ip');");
$conn->close(); //(datetime is auto-added to table with default of 'now')
}
//display the image
$imgfile='orig.jpg'; // or 'orig.gif'
header('Content-Type: image/jpeg'); // or 'image/gif'
header('Content-Length: '.filesize($imgfile));
header('Cache-Control: no-cache');
readfile($imgfile);
?>
The images render (or animate) normally and can be called in any of the normal ways for images (like an <img>
tag), and will save a record of the visiting IP, while invisible to the user.
I recommend not using WebClient.DownloadString
. This is because (at least in .NET 3.5) DownloadString is not smart enough to use/remove the BOM, should it be present. This can result in the BOM (
) incorrectly appearing as part of the string when UTF-8 data is returned (at least without a charset) - ick!
Instead, this slight variation will work correctly with BOMs:
string ReadTextFromUrl(string url) {
// WebClient is still convenient
// Assume UTF8, but detect BOM - could also honor response charset I suppose
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
return textReader.ReadToEnd();
}
}
Here's a way to create a flexible generator that allows you to add some rules:
function generatePassword(length, rules) {
if (!length || length == undefined) {
length = 8;
}
if (!rules || rules == undefined) {
rules = [
{chars: "abcdefghijklmnopqrstuvwxyz", min: 3}, // As least 3 lowercase letters
{chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 2}, // At least 2 uppercase letters
{chars: "0123456789", min: 2}, // At least 2 digits
{chars: "!@#$&*?|%+-_./:;=()[]{}", min: 1} // At least 1 special char
];
}
var allChars = "", allMin = 0;
rules.forEach(function(rule) {
allChars += rule.chars;
allMin += rule.min;
});
if (length < allMin) {
length = allMin;
}
rules.push({chars: allChars, min: length - allMin});
var pswd = "";
rules.forEach(function(rule) {
if (rule.min > 0) {
pswd += shuffleString(rule.chars, rule.min);
}
});
return shuffleString(pswd);
}
function shuffleString(str, maxlength) {
var shuffledString = str.split('').sort(function(){return 0.5-Math.random()}).join('');
if (maxlength > 0) {
shuffledString = shuffledString.substr(0, maxlength);
}
return shuffledString;
}
var pswd = generatePassword(15, [
{chars: "abcdefghijklmnopqrstuvwxyz", min: 4}, // As least 4 lowercase letters
{chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 1}, // At least 1 uppercase letters
{chars: "0123456789", min: 3}, // At least 3 digits
{chars: "!@#$&*?|%+-_./:;=()[]{}", min: 2} // At least 2 special chars
]);
console.log(pswd, pswd.length);
It's important to write full class path in the xml. I got 'Error inflating class' when only subclass's name was written in.
For others like me:
There was once an example in the SSL source in the directory demos/ssl/
with example code in C++. Now it's available only via the history:
https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl
You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.
Certificates: .pem in demos/certs/apps/
: https://github.com/openssl/openssl/tree/master/demos/certs/apps
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
By pretty-print, I assume you mean indented, like so
{
"data": 1234
}
rather than
{"data":1234}
The easiest way to do this is with MarshalIndent
, which will let you specify how you would like it indented via the indent
argument. Thus, json.MarshalIndent(data, "", " ")
will pretty-print using four spaces for indentation.
The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:
<form action="http://someotherserver.com">
and there is no javascript involved in posting the form, then the same origin policy is not applicable.
See wikipedia for more information
Using
Dim myarray As Variant
works but
Dim myarray As String
doesn't so I sitck to Variant
if you want only the background-image
to be affected, you can use a linear gradient to do that, just like this:
background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(IMAGE_URL);
If you want it darker, make the alpha value higher, else you want it lighter, make alpha lower
Actually, you only need to use the default
argument to add_argument
as in this test.py
script:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--example', default=1)
args = parser.parse_args()
print(args.example)
test.py --example
% 1
test.py --example 2
% 2
Details are here.
You cannot assign an rvalue to an rvalue.
if (strcmp("hello", "hello") = 0)
is wrong. Suggestions:
if (strcmp("hello", "hello") == 0)
^
=
is the assign operator.
==
is the equal to operator.
I know many new programmers are confused with this fact.
In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:
#include <string>
#include <iostream>
#include <fstream>
int main() {
std::ifstream input("filename.txt");
std::string line;
while( std::getline( input, line ) ) {
std::cout<<line<<'\n';
}
return 0;
}
This program reads each line from a file and echos it to the console.
For C you're probably looking at using fgets
, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:
#include <stdio.h>
int main() {
char line[1024];
FILE *fp = fopen("filename.txt","r");
//Checks if file is empty
if( fp == NULL ) {
return 1;
}
while( fgets(line,1024,fp) ) {
printf("%s\n",line);
}
return 0;
}
With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.
auto
is not a valid value for padding
property, the only thing you can do is take out padding: 0;
from the *
declaration, else simply assign padding
to respective property block.
If you remove padding: 0;
from * {}
than browser will apply default styles to your elements which will give you unexpected cross browser positioning offsets by few pixels, so it is better to assign padding: 0;
using *
and than if you want to override the padding, simply use another rule like
.container p {
padding: 5px;
}
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
May be it helps some one, On Android i had same issue but i figured it out by using
setTimeout
inside
document.ready
so it worked for me secondly you have to increase the timeout just incase if user allow his location after few seconds, so i kept it to 60000 mili seconds (1 minute) allowing my success function to call if user click on allow button within 1 minute.
In case anyone has similar problems, I used the default sudo apt-get installs for the relevant packages and here are the correct settings:
JAVA_HOME=/usr/lib/jvm/java-7-openjdk-i386
and
MAVEN_HOME=/usr/share/maven2
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....
and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...
May be this will help some one. I have my proxy setup in python script but keep getting the error mentioned in the question.
Below is the piece of block which will take my username and password as a constant in the beginning.
if (use_proxy):
proxy = req.ProxyHandler({'https': proxy_url})
auth = req.HTTPBasicAuthHandler()
opener = req.build_opener(proxy, auth, req.HTTPHandler)
req.install_opener(opener)
If you are using corporate laptop and if you did not connect to Direct Access or office VPN then the above block will throw error. All you need to do is to connect to your org VPN and then execute your python script.
Thanks
If you use setState
inside componentDidUpdate
it updates the component, resulting in a call to componentDidUpdate
which subsequently calls setState
again resulting in the infinite loop. You should conditionally call setState
and ensure that the condition violating the call occurs eventually e.g:
componentDidUpdate: function() {
if (condition) {
this.setState({..})
} else {
//do something else
}
}
In case you are only updating the component by sending props to it(it is not being updated by setState, except for the case inside componentDidUpdate), you can call setState
inside componentWillReceiveProps
instead of componentDidUpdate
.
too many ) parenthesis remove one of them.
Its better if you can have RDM (Redis Desktop Manager). You can connect to your redis server by creating a new connection in RDM.
Once its connected you can check the live data, also you can play around with any redis command.
Opening a cli in RDM.
1) Right click on the connection you will see a console option, just click on it a new console window will open at the bottom of RDM.
Coming back to your question FLUSHALL is the command, you can simply type FLUSHALL in the redis cli.
Moreover if you want to know about any redis command and its proper usage, go to link below. https://redis.io/commands.
You have to be careful with what you want to do, because it is not just about to get the time.
The batch has internal variables to represent the date and the tme: %DATE% %TIME%. But they dependent on the Windows Locale.
%Date%:
%TIME%:
Now, how long your script will work and when? For example, if it will be longer than a day and does pass the midnight it will definitely goes wrong, because difference between 2 timestamps between a midnight is a negative value! You need the date to find out correct distance between days, but how you do that if the date format is not a constant? Things with %DATE% and %TIME% might goes worser and worser if you continue to use them for the math purposes.
The reason is the %DATE% and %TIME% are exist is only to show a date and a time to user in the output, not to use them for calculations. So if you want to make correct distance between some time values or generate some unique value dependent on date and time then you have to use something different and accurate than %DATE% and %TIME%.
I am using the wmic windows builtin utility to request such things (put it in a script file):
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE`) do if "%%i" == "LocalDateTime" echo.%%j
or type it in the cmd.exe console:
for /F "usebackq tokens=1,2 delims==" %i in (`wmic os get LocalDateTime /VALUE`) do @if "%i" == "LocalDateTime" echo.%j
The disadvantage of this is a slow performance in case of frequent calls. On mine machine it is about 12 calls per second.
If you want to continue use this then you can write something like this (get_datetime.bat):
@echo off
rem Description:
rem Independent to Windows locale date/time request.
rem Drop last error level
cd .
rem drop return value
set "RETURN_VALUE="
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if "%%i" == "LocalDateTime" set "RETURN_VALUE=%%j"
if not "%RETURN_VALUE%" == "" (
set "RETURN_VALUE=%RETURN_VALUE:~0,18%"
exit /b 0
)
exit /b 1
Now, you can parse %RETURN_VALUE% somethere in your script:
call get_datetime.bat
set "FILE_SUFFIX=%RETURN_VALUE:.=_%"
set "FILE_SUFFIX=%FILE_SUFFIX:~8,2%_%FILE_SUFFIX:~10,2%_%FILE_SUFFIX:~12,6%"
echo.%FILE_SUFFIX%
While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.
<p style="margin-bottom:3cm;">This is the first question?</p>
This is a work in progress, but this is what I don't understand:
ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
Log.i(TAG, " memoryInfo.availMem " + memoryInfo.availMem + "\n" );
Log.i(TAG, " memoryInfo.lowMemory " + memoryInfo.lowMemory + "\n" );
Log.i(TAG, " memoryInfo.threshold " + memoryInfo.threshold + "\n" );
List<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
Map<Integer, String> pidMap = new TreeMap<Integer, String>();
for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses)
{
pidMap.put(runningAppProcessInfo.pid, runningAppProcessInfo.processName);
}
Collection<Integer> keys = pidMap.keySet();
for(int key : keys)
{
int pids[] = new int[1];
pids[0] = key;
android.os.Debug.MemoryInfo[] memoryInfoArray = activityManager.getProcessMemoryInfo(pids);
for(android.os.Debug.MemoryInfo pidMemoryInfo: memoryInfoArray)
{
Log.i(TAG, String.format("** MEMINFO in pid %d [%s] **\n",pids[0],pidMap.get(pids[0])));
Log.i(TAG, " pidMemoryInfo.getTotalPrivateDirty(): " + pidMemoryInfo.getTotalPrivateDirty() + "\n");
Log.i(TAG, " pidMemoryInfo.getTotalPss(): " + pidMemoryInfo.getTotalPss() + "\n");
Log.i(TAG, " pidMemoryInfo.getTotalSharedDirty(): " + pidMemoryInfo.getTotalSharedDirty() + "\n");
}
}
Why isn't the PID mapped to the result in activityManager.getProcessMemoryInfo()? Clearly you want to make the resulting data meaningful, so why has Google made it so difficult to correlate the results? The current system doesn't even work well if I want to process the entire memory usage since the returned result is an array of android.os.Debug.MemoryInfo objects, but none of those objects actually tell you what pids they are associated with. If you simply pass in an array of all pids, you will have no way to understand the results. As I understand it's use, it makes it meaningless to pass in more than one pid at a time, and then if that's the case, why make it so that activityManager.getProcessMemoryInfo() only takes an int array?
We use a lot of Action delegate functionality in tests. When we need to build some default object and later need to modify it. I made little example. To build default person (John Doe) object we use BuildPerson()
function. Later we add Jane Doe too, but we modify her birthdate and name and height.
public class Program
{
public static void Main(string[] args)
{
var person1 = BuildPerson();
Console.WriteLine(person1.Firstname);
Console.WriteLine(person1.Lastname);
Console.WriteLine(person1.BirthDate);
Console.WriteLine(person1.Height);
var person2 = BuildPerson(p =>
{
p.Firstname = "Jane";
p.BirthDate = DateTime.Today;
p.Height = 1.76;
});
Console.WriteLine(person2.Firstname);
Console.WriteLine(person2.Lastname);
Console.WriteLine(person2.BirthDate);
Console.WriteLine(person2.Height);
Console.Read();
}
public static Person BuildPerson(Action<Person> overrideAction = null)
{
var person = new Person()
{
Firstname = "John",
Lastname = "Doe",
BirthDate = new DateTime(2012, 2, 2)
};
if (overrideAction != null)
overrideAction(person);
return person;
}
}
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime BirthDate { get; set; }
public double Height { get; set; }
}
In your situation I think your partner is correct. What's nice about rebasing is that to the outsider your changes look like they all happened in a clean sequence all by themselves. This means
You can still continue to push your private development branch to the remote repository for the sake of backup but others should not treat that as a "public" branch since you'll be rebasing. BTW, an easy command for doing this is git push --mirror origin
.
The article Packaging software using Git does a fairly nice job explaining the trade offs in merging versus rebasing. It's a little different context but the principals are the same -- it basically comes down to whether your branches are public or private and how you plan to integrate them into the mainline.
For IntelliJ 13, there is a checkbox in Editor's page in IDE Settings
EDIT: For IntelliJ 14, the option has been moved to Editor > General page. It's the last option in the "Other" group. (For Mac the option is under the menu "IntelliJ Idea" > "Preferences").
EDIT: For IntelliJ 16, it's the second-to-last option in Editor > General > Other.
EDIT: For IntelliJ Ultimate 2016.1, it's been moved to Editor > General > Code Completion.
EDIT: For IntelliJ Ultimate 2017.2, aka IntelliJ IDEA 2017.2.3, there are actually two options:
EDIT: For IntelliJ Ultimate 2020.3, the first option is now located under Editor > Code Editing > Quick Documentation > Show quick documentation on mouse move
function slugify(text){
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
*based on https://gist.github.com/mathewbyrne/1280286
now you can transform this string:
Barack_Obama ?????_????? ~!@#$%^&*()+/-+?><:";'{}[]\|`
into:
barack_obama-?????_?????
applying to your code:
$("#Restaurant_Name").keyup(function(){
var Text = $(this).val();
Text = slugify(Text);
$("#Restaurant_Slug").val(Text);
});
I Found Solution Of You Question But In Stack Not Allow to Upload Video See the link below it show better explain
I know it's an old question, but I needed this solution too, and I acme with another solution.
I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:
HOST=`hostname --fqdn`
Then, I used it across my entrypoint script:
echo "Value: $HOST"
Hope this helps
In addition to @Marek's comment about not including fixed==TRUE
, you also need to not have the spaces in your regular expression. It should be "A1|A9|A6"
.
You also mention that there are lots of patterns. Assuming that they are in a vector
toMatch <- c("A1", "A9", "A6")
Then you can create your regular expression directly using paste
and collapse = "|"
.
matches <- unique (grep(paste(toMatch,collapse="|"),
myfile$Letter, value=TRUE))
Just an alternative:
ls -lAR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
grep -v '^d'
will exclude the directories.
Here is my Suggestion:
First:
1. Add display: block or table
2. Add position: relative
3. Add width:(percentage also works fine)
Second:
if above trick not works then you have to add float:none;
2016 update:
You can create a new stacking context, as seen on Coderwall:
<div style="transform: translate3d(0,0,0);overflow:hidden">
<img style="position:fixed; ..." />
</div>
Which refers to http://dev.w3.org/csswg/css-transforms/#transform-rendering
For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.
webView.clearCache(true)
appFormWebView.clearFormData()
appFormWebView.clearHistory()
appFormWebView.clearSslPreferences()
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()
WebStorage.getInstance().deleteAllData()
event.target
returns the DOM element, so you can retrieve any property/ attribute that has a value; so, to answer your question more specifically, you will always be able to retrieve nodeName
, and you can retrieve href
and id
, provided the element has a href
and id
defined; otherwise undefined
will be returned.
However, inside an event handler, you can use this
, which is set to the DOM element as well; much easier.
$('foo').bind('click', function () {
// inside here, `this` will refer to the foo that was clicked
});
I had some errors during installation. Just in case somebody has this too. Despite that I already was sitting under admin user, but not root.
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/PIL'
Storing debug log for failure in /Users/wzbozon/Library/Logs/pip.log
Adding "sudo" solved the problem, with sudo it worked:
~/Documents/mv-server: $ sudo pip install Pillow
Also you can download and execute the install.bat file in 'ODAC112030Xcopy.zip' from 64-bit Oracle Data Access Components (ODAC) Downloads. This resolved my problem.
You have to use an image to change the actual size or form of the bullet itself:
You can use a background image with appropriate padding to nudge content so it doesn't overlap:
list-style-image:url(bigger.gif);
or
background-image: url(images/bullet.gif);
Alternate solution. I prefer this for the brevity and code simplicity.
(function () {
alert("I am here");
})();
This is an anonymous function, where the name is not specified. What happens here is that, the function is defined and executed together. Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.
Actually the correct answer is on http://jsfiddle.net/HDakN/
Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete
$("#phone").mask("(99) 9999-9999?9");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 5 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );
var lastfour = last.substr(1,4);
var first = $(this).val().substr( 0, 9 );
$(this).val( first + move + '-' + lastfour );
}
});?
Try this:
> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
Code Value
1 A 1
2 B 2
1.1 A 1
1.2 A 1
I updated my android SDK to the latest version (API 19). When I tried to run the emulator with phonegap 3, the build was successful but it ran the same issue.
In the AVD manager there was an existent device, nevertheless, its parameters were all unknown. Surely this occurs because I uninstalled the old sdk version (API 17) that returns a second error while attempting to remove the device. With the message: "device is already running"
To solve the issue, I went to the AVD's location in ~/.android/avd/ and removed manually the device directory.avd and device.ini file. Finally, in the the device manager I created a new AVD provided by the newest API.
This allowed phonegap to build and run the emulator succesfully
I hope this helps
Good day
Include <ctime>
and use the time
function.
simple use "accept" and "required" in and avoiding so much typical and unwanted coding.
You have two choices:
Use fileno()
to obtain the file descriptor associated with the stdio
stream pointer
Don't use <stdio.h>
at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write()
call won't even return until the lower-level IO has completed (in theory).
For device-level IO I'd say it's pretty unusual to use stdio
. I'd strongly recommend using the lower-level open()
, read()
and write()
functions instead (based on your later reply):
int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);
HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers
Yes, it is the right way.
You could use the image in the resource file just using the path:
<Image Source="..\Media\Image.png" />
You must set the build action of the image file to "Resource".
package com.app;
public class SiftNumberAndEvenNumber {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5};
int arr1[] = new int[arr.length];
int shiftAmount=3;
for(int i = 0; i < arr.length; i++){
int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
arr1[newLocation] = arr[i];
}
for(int i=0;i<arr1.length;i++) {
if(i==arr1.length-1) {
System.out.print(arr1[i]);
}else {
System.out.print(arr1[i]+",");
}
}
System.out.println();
for(int i=0;i<arr1.length;i++) {
if(arr1[i]%2==0) {
System.out.print(arr1[i]+" ");
}
}
}
}
Because the range for floats is greater than that of integers -- returning an integer could overflow
update T1
set T1.COST2=T1.TOT_COST+2.000,
T1.COST3=T1.TOT_COST+2.000,
T1.COST4=T1.TOT_COST+2.000,
T1.COST5=T1.TOT_COST+2.000,
T1.COST6=T1.TOT_COST+2.000,
T1.COST7=T1.TOT_COST+2.000,
T1.COST8=T1.TOT_COST+2.000,
T1.COST9=T1.TOT_COST+2.000,
T1.COST10=T1.TOT_COST+2.000,
T1.COST11=T1.TOT_COST+2.000,
T1.COST12=T1.TOT_COST+2.000,
T1.COST13=T1.TOT_COST+2.000
from DBRMAST T1
inner join DBRMAST t2 on t2.CODE=T1.CODE
If you want to have control over where they are placed separate from source code order:
<div id="NW"></div>
<div id="NE"></div>
<div id="SE"></div>?
<div id="SW"></div>
html, body { height:100%; margin:0; padding:0 }
div { position:fixed; width:50%; height:50% }
#NW { top:0; left:0; background:orange }
#NE { top:0; left:50%; background:blue }
#SW { top:50%; left:0; background:green }
#SE { top:50%; left:50%; background:red } ?
Note: if you want padding on your regions, you'll need to set the box-sizing
to border-box
:
div {
/* ... */
padding:1em;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
…otherwise your "50%" width and height become "50% + 2em", which will lead to visual overlaps.
You might include the implementation of itoa in your project.
Here's itoa modified to work with std::string: http://www.strudel.org.uk/itoa/
The best way to drop your database in Mongoose depends on which version of Mongoose you are using. If you are using a version of Mongoose that 4.6.4 or newer, then this method added in that release is likely going to work fine for you:
mongoose.connection.dropDatabase();
In older releases this method did not exist. Instead, you were to use a direct MongoDB call:
mongoose.connection.db.dropDatabase();
However, if this was run just after the database connection was created, it could possibly fail silently. This is related to the connection actually be asynchronous and not being set up yet when the command happens. This is not normally a problem for other Mongoose calls like .find()
, which queue until the connection is open and then run.
If you look at the source code for the dropDatabase()
shortcut that was added, you can see it was designed to solve this exact problem. It checks to see if the connection is open and ready. If so, it fires the command immediately. If not, it registers the command to run when the database connection has opened.
Some of the suggestions above recommend always putting your dropDatabase
command in the open
handler. But that only works in the case when the connection is not open yet.
Connection.prototype.dropDatabase = function(callback) {
var Promise = PromiseProvider.get();
var _this = this;
var promise = new Promise.ES6(function(resolve, reject) {
if (_this.readyState !== STATES.connected) {
_this.on('open', function() {
_this.db.dropDatabase(function(error) {
if (error) {
reject(error);
} else {
resolve();
}
});
});
} else {
_this.db.dropDatabase(function(error) {
if (error) {
reject(error);
} else {
resolve();
}
});
}
});
if (callback) {
promise.then(function() { callback(); }, callback);
}
return promise;
};
Here's a simple version of the above logic that can be used with earlier Mongoose versions:
// This shim is backported from Mongoose 4.6.4 to reliably drop a database
// http://stackoverflow.com/a/42860208/254318
// The first arg should be "mongoose.connection"
function dropDatabase (connection, callback) {
// readyState 1 === 'connected'
if (connection.readyState !== 1) {
connection.on('open', function() {
connection.db.dropDatabase(callback);
});
} else {
connection.db.dropDatabase(callback);
}
}
Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.
The Windows console normaly uses CP850 encoding and not utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters -¦
instead of a degree °
.
Demonstration (using python 2.7 in a windows console):
deg = u'\xb0` # utf code for degree
print deg.encode('utf8')
effectively outputs -¦
.
Fix: just force the correct encoding (or better use unicode):
local_encoding = 'cp850' # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg
or if you use a source file that explicitely defines an encoding:
# -*- coding: utf-8 -*-
local_encoding = 'cp850' # adapt for other encodings
print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)
Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate
as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:
AudioServicesAddSystemSoundCompletion (
kSystemSoundID_Vibrate,
NULL,
NULL,
MyAudioServicesSystemSoundCompletionProc,
NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Then you define your callback function to replay the vibrate sound again:
#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
);
#pragma mark AudioService callback function implementation
// Callback that gets called after we finish buzzing, so we
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
) {
if (iShouldKeepBuzzing) { // Your logic here...
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
//Unregister, so we don't get called again...
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
}
The functions with an s
take string parameters. The others take file
streams.
VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.
It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.
this one is working for me also for internet explorer:
<div class="col imagebox" [ngStyle]="bkUrl"></div>
...
@Input() background = '571x450img';
bkUrl = {};
ngOnInit() {
this.bkUrl = this.getBkUrl();
}
getBkUrl() {
const styles = {
'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
};
console.log(styles);
return styles;
}
Open report in Report designer
Go to View menu -> Report data
The problem seems to happen when you have an alias the same name as the objects property. Hibernate seems to pick up the alias and use it in the sql. I found this documented here and here, and I believe it to be a bug in Hibernate, although I am not sure that the Hibernate team agrees.
Either way, I have found a simple work around that works in my case. Your mileage may vary. The details are below, I tried to simplify the code for this sample so I apologize for any errors or typo's:
Criteria criteria = session.createCriteria(MyClass.class)
.setProjection(Projections.projectionList()
.add(Projections.property("sectionHeader"), "sectionHeader")
.add(Projections.property("subSectionHeader"), "subSectionHeader")
.add(Projections.property("sectionNumber"), "sectionNumber"))
.add(Restrictions.ilike("sectionHeader", sectionHeaderVar)) // <- Problem!
.setResultTransformer(Transformers.aliasToBean(MyDTO.class));
Would produce this sql:
select
this_.SECTION_HEADER as y1_,
this_.SUB_SECTION_HEADER as y2_,
this_.SECTION_NUMBER as y3_,
from
MY_TABLE this_
where
( lower(y1_) like ? )
Which was causing an error: java.sql.SQLException: ORA-00904: "Y1_": invalid identifier
But, when I changed my restriction to use "this", like so:
Criteria criteria = session.createCriteria(MyClass.class)
.setProjection(Projections.projectionList()
.add(Projections.property("sectionHeader"), "sectionHeader")
.add(Projections.property("subSectionHeader"), "subSectionHeader")
.add(Projections.property("sectionNumber"), "sectionNumber"))
.add(Restrictions.ilike("this.sectionHeader", sectionHeaderVar)) // <- Problem Solved!
.setResultTransformer(Transformers.aliasToBean(MyDTO.class));
It produced the following sql and my problem was solved.
select
this_.SECTION_HEADER as y1_,
this_.SUB_SECTION_HEADER as y2_,
this_.SECTION_NUMBER as y3_,
from
MY_TABLE this_
where
( lower(this_.SECTION_HEADER) like ? )
Thats, it! A pretty simple fix to a painful problem. I don't know how this fix would translate to the query by example problem, but it may get you closer.
An empty array is defined by omitting values, like so:
v=[[],[]]
a=[]
b=[1,2]
a.push(b)
b==a[0]
readdir() does that.
Check http://perldoc.perl.org/functions/readdir.html
opendir(DIR, $some_dir) || die "can't opendir $some_dir: $!";
@dots = grep { /^\./ && -f "$some_dir/$_" } readdir(DIR);
closedir DIR;
4 steps
npm install dotenv --save
Next add the following line to your app.
require('dotenv').config()
Then create a .env
file at the root directory of your application and add the variables to it.
// contents of .env
REACT_APP_API_KEY = 'my-secret-api-key'
.env
to your .gitignore
file so that Git ignores it and it never ends up on GitHub.If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_
for it to work.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/
NOTE - Need to restart application after adding variable in .env file.
Reference - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f
You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants.kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file. The constants known at compile time must be marked with const
.
So, in this case, it should be:
const val MY_CONST = "something"
and then you can import the constant using:
import package_name.MY_CONST
You can refer to this link
If you are using windows 7, make sure you install jdk-xxxx-windows-x64.exe. http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html I had previously installed 32 bit instead of 64 bit version hence it was installed in program files x(86) folder. But if you install 64 bit sdk setup, its installed in program files folder. Then set the JAVA_HOME='C:\Program Files\Java\jdk1.8.0_65' It should work fine.
This depends on a lot of things, such as what is the size of the file, what is its type (text/binary) etc. Some time ago I benchmarked the following function against versions using streambuf iterators - it was about twice as fast:
unsigned int FileRead( std::istream & is, std::vector <char> & buff ) {
is.read( &buff[0], buff.size() );
return is.gcount();
}
void FileRead( std::ifstream & ifs, string & s ) {
const unsigned int BUFSIZE = 64 * 1024; // reasoable sized buffer
std::vector <char> buffer( BUFSIZE );
while( unsigned int n = FileRead( ifs, buffer ) ) {
s.append( &buffer[0], n );
}
}
Try this out. Hope this helps
<div id="single" dir="rtl">
<div class="common">Single</div>
</div>
<div id="both" dir="ltr">
<div class="common">Both</div>
</div>
#single, #both{
width: 100px;
height: 100px;
overflow: auto;
margin: 0 auto;
border: 1px solid gray;
}
.common{
height: 150px;
width: 150px;
}
You can try the following tutorial, it may help you to move forward:
All logging output is handled by the handlers; just add a logging.StreamHandler()
to the root logger.
Here's an example configuring a stream handler (using stdout
instead of the default stderr
) and adding it to the root logger:
import logging
import sys
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
Here it is in C# (lat and long in radians):
double CalculateGreatCircleDistance(double lat1, double long1, double lat2, double long2, double radius)
{
return radius * Math.Acos(
Math.Sin(lat1) * Math.Sin(lat2)
+ Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(long2 - long1));
}
If your lat and long are in degrees then divide by 180/PI to convert to radians.
Instead of '\' or another character on the keyboard, you can also use special characters that aren't on the keyboard. Depending o your use case this might be necessary, if you don't want user input to accidentally be used as an escape character.
This should solve your problem, you should try to run the following below:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
This will get you count:
get-alias | measure
You can work with the result as with object:
$m = get-alias | measure
$m.Count
And if you would like to have aliases in some variable also, you can use Tee-Object:
$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases
Some more info on Measure-Object cmdlet is on Technet.
Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)
select convert_tz(now(),@@session.time_zone,'+05:30')
replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994
to format into desired time format, eg:
select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p')
you will get similar to this -> Dec 17 2014 10:39:56 AM
If your instance is down, you are look for version information in alert.log
Or another crude way is to look into Oracle binary, If DB in hosted on Linux, try strings on Oracle binary.
strings -a $ORACLE_HOME/bin/oracle |grep RDBMS | grep RELEASE
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
The below snippet works fine for me(I used the size())
String itemId;
for (int i = 0; i < itemList.size(); i++) {
JSONObject itemObj = (JSONObject)itemList.get(i);
itemId=(String) itemObj.get("ItemId");
System.out.println(itemId);
}
If it is wrong to use use size() kindly advise
I have solved this issue as follows:
removed from chrome extension and install ext again. It will work ISA
For anyone just looking to replace the extra ' ' (space) if day is less than 10 then use:
#define BUILD_DATE (char const[]) { __DATE__[0], __DATE__[1], __DATE__[2], __DATE__[3], (__DATE__[4] == ' ' ? '0' : __DATE__[4]), __DATE__[5], __DATE__[6], __DATE__[7], __DATE__[8], __DATE__[9], __DATE__[10], __DATE__[11] }
Output: Sep 06 2019
----------
element.all(by.id('locregion')).then(function(Item)
{
// Item[x] = > // x is [0,1,2,3]element you want to click
Item[0].click(); //first item
Item[3].click(); // fourth item
expect(Item[0].getText()).toEqual('Ranjans Mobile Testing')
});
I use $(date +"%Y-%m-%d")
or $(date +"%Y-%m-%d %T")
with time and hours.
Try this:
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<Man> Men = new List<Man>();
Man m1 = new Man();
m1.Number = "+1-9169168158";
m1.Message = "Hello Bob from 1";
m1.UniqueCode = "0123";
m1.State = 0;
Man m2 = new Man();
m2.Number = "+1-9296146182";
m2.Message = "Hello Bob from 2";
m2.UniqueCode = "0125";
m2.State = 0;
Men.AddRange(new Man[] { m1, m2 });
string result = JsonConvert.SerializeObject(Men);
Console.WriteLine(result);
List<Man> NewMen = JsonConvert.DeserializeObject<List<Man>>(result);
foreach(Man m in NewMen) Console.WriteLine(m.Message);
}
}
public class Man
{
public string Number{get;set;}
public string Message {get;set;}
public string UniqueCode {get;set;}
public int State {get;set;}
}
I too faced the similar issue , not solved after adding the command in eclipse.ini file. My root cause is different. I was experimenting on sequence diagrams using objectaid. This is throwing an exception and disturbed my workspace. You may have different issue when working on new plugins. Better you check the log file located in your project work-space C:\path\to\workspace\.metadata\.log
You can use wc -l
to figure out the total # of lines.
You can then combine head
and tail
to get at the range you want. Let's assume the log is 40,000 lines, you want the last 1562 lines, then of those you want the first 838. So:
tail -1562 MyHugeLogFile.log | head -838 | ....
Or there's probably an easier way using sed
or awk
.
To pass multiple headers in a curl request you simply add additional -H
or --header
to your curl command.
Example
//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL
//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json' https://www.example.com
Going Further
For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:
For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.
$ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
$ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com
result = bytes.fromhex(some_hex_string)
Most programs will check the $EDITOR
environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.
~/.bashrc
file:export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"
echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc
If you are using zsh, use ~/.zshrc
instead of ~/.bashrc
.
You can skip the container or background image with pure css arrow:
select {
/* make arrow and background */
background:
linear-gradient(45deg, transparent 50%, blue 50%),
linear-gradient(135deg, blue 50%, transparent 50%),
linear-gradient(to right, skyblue, skyblue);
background-position:
calc(100% - 21px) calc(1em + 2px),
calc(100% - 16px) calc(1em + 2px),
100% 0;
background-size:
5px 5px,
5px 5px,
2.5em 2.5em;
background-repeat: no-repeat;
/* styling and reset */
border: thin solid blue;
font: 300 1em/100% "Helvetica Neue", Arial, sans-serif;
line-height: 1.5em;
padding: 0.5em 3.5em 0.5em 1em;
/* reset */
border-radius: 0;
margin: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
-webkit-appearance:none;
-moz-appearance:none;
}
Sample here
In the Facebook app control panel make sure you have a forward slash on the end of any specified URL if you are only specifying a folder name
i.e.
Page Tab URL: http://mypagetabserver.com/custom_tab/
You can definitely use num1 = (20 if someBoolValue else num1) if you want.
Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions. Windows doesn't not have (need?) this.
Yes, windows don't have sudo
on its terminal. Try using pip
instead.
pip
using the steps here.pip install [package name]
on the terminal. In this case, it may be pdfkit
or wkhtmltopdf
.Slicing of arrays is done with [first:last+1]
.
One trick I tend to use a lot of is to indicate extra information with ellipses. So, if your field is one hundred characters, I would use:
if len(s) <= 100:
print s
else:
print "%s..."%(s[:97])
And yes, I know ()
is superfluous in this case for the %
formatting operator, it's just my style.
It is most accurate to say that methods with a Bang! are the more dangerous or surprising version. There are many methods that mutate without a Bang such as .destroy
and in general methods only have bangs where a safer alternative exists in the core lib.
For instance, on Array we have .compact
and .compact!
, both methods mutate the array, but .compact!
returns nil instead of self if there are no nil's in the array, which is more surprising than just returning self.
The only non-mutating method I've found with a bang is Kernel
's .exit!
which is more surprising than .exit
because you cannot catch SystemExit
while the process is closing.
Rails and ActiveRecord continues this trend in that it uses bang for more 'surprising' effects like .create!
which raises errors on failure.
<?php
spl_autoload_register(function ($classname){
// for security purpose
//your class name should match the name of your class "file.php"
$classname = str_replace("..", "", $classname);
require_once __DIR__.DIRECTORY_SEPARATOR.("classes/$classname.class.php");
});
try {
$new = new Class1();
} catch (Exception $e) {
echo "error = ". $e->getMessage();
}
?>
Here is the solution I found on Hibernate 4.1.9. I had to pass a parameter to my query that can have value NULL sometimes. So I passed the using:
setParameter("orderItemId", orderItemId, new LongType())
After that, I use the following where clause in my query:
where ((:orderItemId is null) OR (orderItem.id != :orderItemId))
As you can see, I am using the Query.setParameter(String, Object, Type) method, where I couldn't use the Hibernate.LONG that I found in the documentation (probably that was on older versions). For a full set of options of type parameter, check the list of implementation class of org.hibernate.type.Type interface.
Hope this helps!
What about gethostname()?
Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.
Do You have Internal Connection or External Connection. If you did Internal Connection then try this:
"Data Source=.\SQLEXPRESS;AttachDbFilename="Your PAth .mdf";Integrated Security=True;User Instance=True";
Historical Note: This was written at the time of PHP4. This is what we call "legacy code" now.
I have left this answer for historical purposes - but some of the methods are now deprecated, DES encryption method is not a recommended practice, etc.
I have not updated this code for two reasons: 1) I no longer work with encryption methods by hand in PHP, and 2) this code still serves the purpose it was intended for: to demonstrate the minimum, simplistic concept of how encryption can work in PHP.
If you find a similarly simplistic, "PHP encryption for dummies" kind of source that can get people started in 10-20 lines of code or less, let me know in comments.
Beyond that, please enjoy this Classic Episode of early-era PHP4 minimalistic encryption answer.
Ideally you have - or can get - access to the mcrypt PHP library, as its certainly popular and very useful a variety of tasks. Here's a run down of the different kinds of encryption and some example code: Encryption Techniques in PHP
//Listing 3: Encrypting Data Using the mcrypt_ecb Function
<?php
echo("<h3> Symmetric Encryption </h3>");
$key_value = "KEYVALUE";
$plain_text = "PLAINTEXT";
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT);
echo ("<p><b> Text after encryption : </b>");
echo ( $encrypted_text );
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT);
echo ("<p><b> Text after decryption : </b>");
echo ( $decrypted_text );
?>
A few warnings:
1) Never use reversible, or "symmetric" encryption when a one-way hash will do.
2) If the data is truly sensitive, like credit card or social security numbers, stop; you need more than any simple chunk of code will provide, but rather you need a crypto library designed for this purpose and a significant amount of time to research the methods necessary. Further, the software crypto is probably <10% of security of sensitive data. It's like rewiring a nuclear power station - accept that the task is dangerous and difficult and beyond your knowledge if that's the case. The financial penalties can be immense, so better to use a service and ship responsibility to them.
3) Any sort of easily implementable encryption, as listed here, can reasonably protect mildly important information that you want to keep from prying eyes or limit exposure in the case of accidental/intentional leak. But seeing as how the key is stored in plain text on the web server, if they can get the data they can get the decryption key.
Be that as it may, have fun :)
NameSpace
using System.Resources;
using System.Diagnostics;
Method
private static bool IsDebug()
{
object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false);
if ((customAttributes != null) && (customAttributes.Length == 1))
{
DebuggableAttribute attribute = customAttributes[0] as DebuggableAttribute;
return (attribute.IsJITOptimizerDisabled && attribute.IsJITTrackingEnabled);
}
return false;
}
If the command should work with both tabs and spaces as the delimiter I would use awk
:
awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile
As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for
loop:
awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile
If you want to use cut
, you need to use the -f
option:
cut -f100-105 myfile > outfile
If the field delimiter is different from TAB
you need to specify it using -d
:
cut -d' ' -f100-105 myfile > outfile
Check the man page for more info on the cut command.
You can do with the following command at the time of running docker
docker run [OPTIONS] --add-host example.com:127.0.0.1 <your-image-name>:<your tag>
Here I am mapping example.com
to localhost 127.0.0.1
and its working.
CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.
Button.module.css
.error {
background-color: red;
}
another-stylesheet.css
.error {
color: red;
}
Button.js
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}
Copied directly from this answer:
You could write a script in any language you want to automate this (even using nodejs) and then just install a shortcut to that script in the user's %appdata%\Microsoft\Windows\Start Menu\Programs\Startup folder
I had a problem which I have just managed to solve so I am sharing it as it may help someone.
I have a UITableView and added the methods shown to enable swipe to delete:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
}
}
I am working on an update that allows me to put the table into edit mode and enables multiselect. To do that I added the code from Apple's TableMultiSelect sample. Once I got that working I found that my swipe the delete function had stopped working.
It turns out that adding the following line to viewDidLoad was the issue:
self.tableView.allowsMultipleSelectionDuringEditing = YES;
With this line in, the multiselect would work but the swipe to delete wouldn't. Without the line it was the other way around.
The fix:
Add the following method to your viewController:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
self.tableView.allowsMultipleSelectionDuringEditing = editing;
[super setEditing:editing animated:animated];
}
Then in your method that puts the table into editing mode (from a button press for example) you should use:
[self setEditing:YES animated:YES];
instead of:
[self.tableView setEditing:YES animated:YES];
This means that multiselect is only enabled when the table is in editing mode.
I feel like there should be a no javascript solution, but how is this?
$(window).resize(function() {
$('#content').height($(window).height() - 46);
});
$(window).trigger('resize');
<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>
<!--Insert more code here-->
<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">
Next time you ask a question here, include more detail and what you have tried.
Following Justin's example, the command below works in Postgres:
alter table foo alter column col2 set default 'bar';
THE new @RestController annotation in Spring4+, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
import React, { Component } from 'react';
import { Image } from 'react-native';
class Images extends Component {
constructor(props) {
super(props);
this.state = {
images: {
'./assets/RetailerLogo/1.jpg': require('../../../assets/RetailerLogo/1.jpg'),
'./assets/RetailerLogo/2.jpg': require('../../../assets/RetailerLogo/2.jpg'),
'./assets/RetailerLogo/3.jpg': require('../../../assets/RetailerLogo/3.jpg')
}
}
}
render() {
const { images } = this.state
return (
<View>
<Image
resizeMode="contain"
source={ images['assets/RetailerLogo/1.jpg'] }
style={styles.itemImg}
/>
</View>
)}
}
You can check undefined object using below code.
ReactObject === 'undefined'
Do you actually need more information than plain IEnumerable
gives you? Just cast it to that and use foreach
with it. I face exactly the same situation in some bits of Protocol Buffers, and I've found that casting to IEnumerable
(or IList
to access it like a list) works very well.
I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache
.
I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage
which will help others who may want to use localStorage
instead of localCache
for caching.
Ajax Call:
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: url,
data: '{"Id":"' + Id + '"}',
cache: true, //It must "true" if you want to cache else "false"
//async: false,
success: function (data) {
var resData = JSON.parse(data);
var Info = resData.Info;
if (Info) {
customerName = Info.FirstName;
}
},
error: function (xhr, textStatus, error) {
alert("Error Happened!");
}
});
To store data into localStorage:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
var success = originalOptions.success || $.noop,
url = originalOptions.url;
options.cache = false; //remove jQuery cache as we have our own localStorage
options.beforeSend = function () {
if (localStorage.getItem(url)) {
success(localStorage.getItem(url));
return false;
}
return true;
};
options.success = function (data, textStatus) {
var responseData = JSON.stringify(data.responseJSON);
localStorage.setItem(url, responseData);
if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
};
}
});
If you want to remove localStorage, use following statement wherever you want:
localStorage.removeItem("Info");
Hope it helps others!
CREATE view vw_sppb_part_listsource as
select row_number() over (partition by sppb_part.init_id order by sppb_part.sppb_part_id asc ) as idx, * from (
select
part.SPPB_PART_ID
, 0 as is_rev
, part.part_number
, part.init_id
from t_sppb_init_part part
left join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
where prev.SPPB_PART_ID is null
union
select
part.SPPB_PART_ID
, 1 as is_rev
, prev.part_number
, part.init_id
from t_sppb_init_part part
inner join t_sppb_init_partrev prev on ( part.SPPB_PART_ID = prev.SPPB_PART_ID )
) sppb_part
will restart idx when it comes to different init_id
If you want a relative link to your wiki page on GitHub, use this:
Read here: [Some other wiki page](path/to/some-other-wiki-page)
If you want a link to a file in the repository, let us say, to reference some header file, and the wiki page is at the root of the wiki, use this:
Read here: [myheader.h](../tree/master/path/to/myheader.h)
The rationale for the last is to skip the "/wiki" path with "../", and go to the master branch in the repository tree without specifying the repository name, that may change in the future.
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
You can query the INFORMATION_SCHEMA tables
system view:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';
If no rows returned, then the table doesn't exist.
There are multiple right answers here. I don't see the VIM version of it so here it is. Open your file in VIM, check the bottom status line for example, execute set ff=dos
(for CRLF) or set ff=unix
(for LF).
The @japf answer above is working fine and in my case I wanted to change the mouse cursor from a Spinning Wheel back to the normal Arrow once the CEF Browser finished loading the page. In case it can help someone, here is the code:
private void Browser_LoadingStateChanged(object sender, CefSharp.LoadingStateChangedEventArgs e) {
if (!e.IsLoading) {
// set the cursor back to arrow
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() => Mouse.OverrideCursor = Cursors.Arrow));
}
}
Try this...
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
public class StopwatchTest {
public static void main(String[] args) throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
Thread.sleep(1000 * 60);
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("Time in milliseconds "+millis);
System.out.println("that took: " + stopwatch);
}
}
A sidenote to consider, you can store arrays in Postgres.
Visibility Scopes with Abstract Examples :: Makes easy Understanding
This visibility of a property or method is defined by pre-fixing declaration of one of three keyword (Public, protected and private)
Public : If a property or method is defined as public, it means it can be both access and manipulated by anything that can refer to object.
Protected : when a property or method visibility is set to protected members can only be access within the class itself and by inherited & inheriting classes. (Inherited:- a class can have all the properties and methods of another class).
Private : When a property or method visibility is set to private, only the class that has the private members can access those methods and properties(Internally within the class), despite of whatever class relation there maybe.
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Just for completeness: a build might be slow because the build system is being stupid as well as because the compiler is taking a long time to do its work.
Read Recursive Make Considered Harmful (PDF) for a discussion of this topic in Unix environments.
Worth mentioning that there are many different solutions which offer two way binding and play really nicely.
I have had a pleasant experience with this model binder - https://github.com/theironcook/Backbone.ModelBinder. which gives sensible defaults yet a lot of custom jquery selector mapping of model attributes to input elements.
There is a more extended list of backbone extensions/plugins on github
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.
I just edited the Project Name in csproj file of the Project & it Worked...!
Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00
. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.
If you don't like nested list comprehensions, you can make use of the map function as well,
>>> from pprint import pprint
>>> l = l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]
>>> pprint(l)
[['40', '20', '10', '30'],
['20', '20', '20', '20', '20', '30', '20'],
['30', '20', '30', '50', '10', '30', '20', '20', '20'],
['100', '100'],
['100', '100', '100', '100', '100'],
['100', '100', '100', '100']]
>>> float_l = [map(float, nested_list) for nested_list in l]
>>> pprint(float_l)
[[40.0, 20.0, 10.0, 30.0],
[20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0],
[30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0],
[100.0, 100.0],
[100.0, 100.0, 100.0, 100.0, 100.0],
[100.0, 100.0, 100.0, 100.0]]
There is the GeoLocation API, but browser support is rather thin on the ground at present. Most sites that care about such things use a GeoIP database (with the usual provisos about the inaccuracy of such a system). You could also look at third party services requiring user cooperation such as FireEagle.
The way it's often done is as follows:
I find that this pattern comes up pretty frequently.
What's interesting about this method is that it allows one to insert N
elements into an empty array one-by-one in amortized O(N)
time without knowing N
in advance.
(Comment)
I can't comment yet, so posting here... I just tried the above OSK.EXE debug trick but regedit instantly closes when I save the filled "C:\windows\system32\cmd.exe" into the already created Debugger key so Microsoft is actively working to block native ways to do this. It is really weird because other things do not trigger this.
Using task scheduler does create a SYSTEM CMD but it is in the system environment and not displayed within a human user profile so this is also now defunct (though it is logical).
Currently on Microsoft Windows [Version 10.0.20201.1000]
So, at this point it has to be third party software that mediates this and further tricks are being more actively sealed by Microsoft these days.
In my case this works fine:
from pyspark_llap import HiveWarehouseSession
hive = HiveWarehouseSession.session(spark).build()
hive.setDatabase("DatabaseName")
df = spark.read.format("csv").option("Header",True).load("/user/csvlocation.csv")
df.write.format(HiveWarehouseSession().HIVE_WAREHOUSE_CONNECTOR).option("table",<tablename>).save()
Done!!
You can read the Data, let you give as "Employee"
hive.executeQuery("select * from Employee").show()
For more details use this URL: https://docs.cloudera.com/HDPDocuments/HDP3/HDP-3.1.5/integrating-hive/content/hive-read-write-operations.html
textBox1.Text = "Line1" + Environment.NewLine + "Line2";
Also the markup needs to include TextMode="MultiLine" (otherwise it shows text as one line)
<asp:TextBox ID="multitxt" runat="server" TextMode="MultiLine" ></asp:TextBox>
I experienced the same problem and following solution solved this problem. You should try the following solution.
sudo mkdir -p /data/db
sudo chown -R 'username' /data/db
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert($(myContent).text());
That results in hello world. Does that answer your question?
http://jsfiddle.net/D2tEf/ for an example
How about the ole goto statement (i know, i know, but it works just fine here ;)
DECLARE
v_attr char(88);
CURSOR SELECT_USERS IS
SELECT id FROM USER_TABLE
WHERE USERTYPE = 'X';
BEGIN
FOR user_rec IN SELECT_USERS LOOP
BEGIN
SELECT attr INTO v_attr
FROM ATTRIBUTE_TABLE
WHERE user_id = user_rec.id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- user does not have attribute, continue loop to next record.
goto end_loop;
END;
<<end_loop>>
null;
END LOOP;
END;
Just put end_loop at very end of loop of course. The null can be substituted with a commit maybe or a counter increment maybe, up to you.
//installing jquerynpm install jquery --save
//installing type defintion for the jquerytypings install dt~jquery --global --save
//adding jquery library into build configuration file as specified(in "angular-cli-build.js" file)
vendorNpmFiles: [
.........
.........
'jquery/dist/jquery.min.js'
]
//run the build to add the jquery library in the build ng build
//adding the relative path configuration(in system-config.js)
/** Map relative paths to URLs. */
const map: any = {
.....,
.......,
'jquery': 'vendor/jquery/dist'
};
/** User packages configuration. */
const packages: any = {
......,
'jquery':{ main: 'jquery.min',
format: 'global',
defaultExtension: 'js'}};
//import the jquery library in your component file
import 'jquery';
below is the code snipppet of my sample component
import { Component } from '@angular/core';
import 'jquery';
@Component({
moduleId: module.id,
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
list:Array<number> = [90,98,56,90];
title = 'app works!';
isNumber:boolean = jQuery.isNumeric(89)
constructor(){}
}
Try following code;
DropDownList1.Items.Add(new ListItem(txt_box1.Text));
You could use DATE_ADD : (or ADDDATE with INTERVAL
)
UPDATE table SET date = DATE_ADD(date, INTERVAL 1 YEAR)
I am using django with postgres in Docker containers. in the docker-compose file, add the following:
db:
image: postgres:10-alpine
environment:
- POSTGRES_DB=app
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=supersecretpassword
**ports:
- "6543:5432"**
which will add accessible port by your local machine. for myself, I connected DBeaver to it. this will prevent port clashes between your app request and local machine request. at first, I got a message saying that the port 5432 is in use (which is by django app) so I couldn't access by pgAdmin or DBeaver.
<div id="divmobile" style="position: fixed; background-color: transparent;
z-index: 1; bottom:5%; right: 0px; width: 50px; text-align:center;" class="div-mobile">
The following are equivalent and result in a two dimensional array:
$array = array(
array(0, 1, 2),
array(3, 4, 5),
);
or
$array = array();
$array[] = array(0, 1, 2);
$array[] = array(3, 4, 5);
simply click
'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'
and run the below query is :
Query:alter Table 'TableName' drop constraint PK__TableName__30242045
Put your if condition inside resize
function:
var windowsize = $(window).width();
$(window).resize(function() {
windowsize = $(window).width();
if (windowsize > 440) {
//if the window is greater than 440px wide then turn on jScrollPane..
$('#pane1').jScrollPane({
scrollbarWidth:15,
scrollbarMargin:52
});
}
});
Here is one that works for plain-text with some server side processing:
public string RotateHtmltext(string innerHtml)
{
const string TRANSFORMTEXT = "transform: rotate(90deg);";
const string EXTRASTYLECSS = "<style type='text/css'>.r90 {"
+ "-webkit-" + TRANSFORMTEXT
+ "-moz-" + TRANSFORMTEXT
+ "-o-" + TRANSFORMTEXT
+ "-ms-" + TRANSFORMTEXT
+ "" + TRANSFORMTEXT
+ "width:1em;line-height:1ex}</style>";
const string WRAPPERDIV = "<div style='display: table-cell; vertical-align: middle;'>";
var newinnerHtml = string.Join("</div>"+WRAPPERDIV, Regex.Split(innerHtml, @"<br */?>").Reverse());
newinnerHtml = Regex.Replace(newinnerHtml, @"((?:<[^>]*>)|(?:[^<]+))",
match => match.Groups[1].Value.StartsWith("<")
? match.Groups[1].Value
: string.Join("", match.Groups[1].Value.ToCharArray().Select(x=>"<div class='r90'>"+x+"</div>")),
RegexOptions.Singleline);
return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + "</div>";
}
which gives something like:
<style type="text/css">.r90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
width: 1em;
line-height: 1ex;
}</style>
<div style="display: table-cell; vertical-align: middle;">
<div class="r90">p</div>
<div class="r90">o</div>
<div class="r90">s</div>
</div><div style="display: table-cell; vertical-align: middle;">
<div class="r90">(</div>
<div class="r90">A</div>
<div class="r90">b</div>
<div class="r90">s</div>
<div class="r90">)</div>
</div>
Using the ${#VAR}
syntax will calculate the number of characters in a variable.
https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
The workaround is to use a reverse proxy running on your 'source' host and forwarding to your target server, such as Fiddler:
Link here: http://docs.telerik.com/fiddler/configure-fiddler/tasks/usefiddlerasreverseproxy
Or an Apache Reverse proxy...
I suggest you to update your SDK and start new project and recompile everything you have. It seems you have some inner program errors. Or you are missing package.
And ofc do what Abdijeek said.
If you successfully rebased against remote branch and can not git rebase --abort
you still can do some tricks to save your work and don't have forced pushes.
Suppose your current branch that was rebased by mistake is called your-branch
and is tracking origin/your-branch
git branch -m your-branch-rebased
# rename current branchgit checkout origin/your-branch
# checkout to latest state that is known to origingit checkout -b your-branch
git log your-branch-rebased
, compare to git log your-branch
and define commits that are missing from your-branch
git cherry-pick COMMIT_HASH
for every commit in your-branch-rebased
remote/your-branch
and you should push only your-branch
Please use this command
git rm -rf --cached .
git add .
Sometimes .gitignore files don't work even though they're correct. The reason Git ignores files is that they are not added to the repository. If you added a file that you want to ignore before, it will be tracked by Git, and any skipping matching rules will be skipped. Git does this because the file is already part of the repository.
There is a schema called INFORMATION_SCHEMA
schema which contains a set of views on tables from the SYS schema that you can query to get what you want.
A major upside of the INFORMATION_SCHEMA
is that the object names are very query friendly and user readable. The downside of the INFORMATION_SCHEMA
is that you have to write one query for each type of object.
The Sys schema may seem a little cryptic initially, but it has all the same information (and more) in a single spot.
You'd start with a table called SysObjects (each database has one) that has the names of all objects and their types.
One could search in a database as follows:
Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
and [Name] like '%YourObjectName%'
Now, if you wanted to restrict this to only search for tables and stored procs, you would do
Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
and [Name] like '%YourObjectName%'
and Type in ('U', 'P')
If you look up object types, you will find a whole list for views, triggers, etc.
Now, if you want to search for this in each database, you will have to iterate through the databases. You can do one of the following:
If you want to search through each database without any clauses, then use the sp_MSforeachdb as shown in an answer here.
If you only want to search specific databases, use the "USE DBName" and then search command.
You will benefit greatly from having it parameterized in that case. Note that the name of the database you are searching in will have to be replaced in each query (DatabaseOne, DatabaseTwo...). Check this out:
Declare @ObjectName VarChar (100)
Set @ObjectName = '%Customer%'
Select 'DatabaseOne' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseOne.Sys.Objects
Where 1=1
and [Name] like @ObjectName
and Type in ('U', 'P')
UNION ALL
Select 'DatabaseTwo' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseTwo.Sys.Objects
Where 1=1
and [Name] like @ObjectName
and Type in ('U', 'P')
UNION ALL
Select 'DatabaseThree' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseThree.Sys.Objects
Where 1=1
and [Name] like @ObjectName
and Type in ('U', 'P')
var stringToSplit = "0, 10, 20, 30, 100, 200";
// To parse your string
var elements = test.Split(new[]
{ ',' }, System.StringSplitOptions.RemoveEmptyEntries);
// To Loop through
foreach (string items in elements)
{
// enjoy
}
This doesn't seem to be relevant in this case, but in case others face this problem --- make sure that if you installed 32 bit version of Eclipse, you also installed 32 bit version of JRE. Similarly, if you installed 64 bit version of Eclipse, you need 64 bit version of JRE in your Windows. Otherwise you will see the above error message as well.
In VB.NET:
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184")
In C#:
System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString("http://api.hostip.info/?ip=68.180.206.184");
:not
selector:
input:not([type]), input[type='text'], input[type='password'] {
/* style here */
}
Support: in Internet Explorer 9 and higher
This will do the trick for you:
foreach (int indexChecked in checkedListBox1.CheckedIndices)
{
string itemtxt = checkedListBox11.Items[indexChecked];
}
It will return whatever string value is in the checkedlistbox items.
git reflog show
should show you the history of HEAD. You can use that to figure out where you were before the pull
. Then you can reset
your HEAD
to that commit.
Edit:
Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs
See the working example: http://jsfiddle.net/U6aKT/
<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>
Above solutions will work only if its a string. Input type date, gives you output in javascript date object in some cases like if you use angular or so. That's why some people are getting error like "TypeError: str.split is not a function". It's a date object, so you should use functions of Date object in javascript to manipulate it. Example here:
var date = $scope.dateObj ;
//dateObj is data bind to the ng-modal of input type dat.
console.log(date.getFullYear()); //this will give you full year eg : 1990
console.log(date.getDate()); //gives you the date from 1 to 31
console.log(date.getMonth() + 1); //getMonth will give month from 0 to 11
Check the following link for reference: