I prefer using the selector and I apply it on the document.
This binds itself on the document and will be applicable to the elements that will be rendered after page load.
For example:
$(document).on("click", 'selector', function() {
// Your code here
});
The date you are parsing is in ISO 8601 format.
In Java 7 the pattern to read and apply the timezone suffix should read yyyy-MM-dd'T'HH:mm:ssX
It works for me, when i add following code in app.module.ts
@NgModule({ ..., imports: [ AppRoutingModule ], ... })
Just add data-html="true"
<a href="#" title="Some long text <br/> Second line text \n Third line text" data-html="true">Hover me</a>
With integers, it's preference.
If the loop variable is a class/object, it can make a difference (only profiling can tell you if it's a significant difference), because the post-increment version requires that you create a copy of that object that gets discarded.
If creating that copy is an expensive operation, you're paying that expense once for every time you go through the loop, for no reason at all.
If you get into the habit of always using ++i
in for loops, you don't need to stop and think about whether what you're doing in this particular situation makes sense. You just always are.
I modifie this list and add a List to the samples try this
Pseudocode
Sample {
List<String> values;
List<String> getList() {
return values}
}
for(Sample s : list) {
if(s.getString.getList.contains("three") {
return s;
}
}
Since favorites is an array, you just need to splice it off and save the document.
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var favorite = new Schema({
cn: String,
favorites: Array
});
module.exports = mongoose.model('Favorite', favorite);
exports.deleteFavorite = function (req, res, next) {
if (req.params.callback !== null) {
res.contentType = 'application/javascript';
}
// Changed to findOne instead of find to get a single document with the favorites.
Favorite.findOne({cn: req.params.name}, function (error, doc) {
if (error) {
res.send(null, 500);
} else if (doc) {
var records = {'records': doc};
// find the delete uid in the favorites array
var idx = doc.favorites ? doc.favorites.indexOf(req.params.deleteUid) : -1;
// is it valid?
if (idx !== -1) {
// remove it from the array.
doc.favorites.splice(idx, 1);
// save the doc
doc.save(function(error) {
if (error) {
console.log(error);
res.send(null, 500);
} else {
// send the records
res.send(records);
}
});
// stop here, otherwise 404
return;
}
}
// send 404 not found
res.send(null, 404);
});
};
And in the meantime, there's a C source code library that will do all this for you, redirecting stdout or stderr. But the cool part is that it lets you assign as many callback functions as you want to the intercepted streams, allowing you then to very easily send a single message to multiple destinations, a DB, a text file, etc.
On top of that, it makes it trivial to create new streams that look and behave the same as stdout and stderr, where you can redirect these new streams to multiple locations as well.
look for U-Streams C library on *oogle.
add this to your css
.table-vcenter td {
vertical-align: middle!important;
}
then add to the class to your table:
<table class="table table-hover table-striped table-vcenter">
If you know the height, you can use absolute positioning with a negative margin-top
like so:
#Login {
width:400px;
height:400px;
position:absolute;
top:50%;
left:50%;
margin-left:-200px; /* width / -2 */
margin-top:-200px; /* height / -2 */
}
Otherwise, there's no real way to vertically center a div with just CSS
perlfaq5: How do I select a random line from a file? Here's a reservoir-sampling algorithm from the Camel Book:
perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;' file
This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.
Try
$waffles = foo($waffles);
Or pass the array by reference, like suggested in the other answers.
In addition, you can add new elements to an array without writing the index, e.g.
$waffles = array(1,2,3); // filling on initialization
or
$waffles = array();
$waffles[] = 1;
$waffles[] = 2;
$waffles[] = 3;
On a sidenote, if you want to sum all values in an array, use array_sum()
You're looking for the onclose event.
see: https://developer.mozilla.org/en/DOM/window.onclose
note that not all browsers support this (for example firefox 2)
To get all the lines of the file loaded into the variable, Delayed Expansion is needed, so do the following:
SETLOCAL EnableDelayedExpansion
for /f "Tokens=* Delims=" %%x in (version.txt) do set Build=!Build!%%x
There is a problem with some special characters, though especially ;
, %
and !
The following is more thorough:
var DEBUG = false;
if(!DEBUG){
if(!window.console) window.console = {};
var methods = ["log", "debug", "warn", "info"];
for(var i=0;i<methods.length;i++){
console[methods[i]] = function(){};
}
}
This will zero out the common methods in the console if it exists, and they can be called without error and virtually no performance overhead. In the case of a browser like IE6 with no console, the dummy methods will be created to prevent errors. Of course there are many more functions in Firebug, like trace, profile, time, etc. They can be added to the list if you use them in your code.
You can also check if the debugger has those special methods or not (ie, IE) and zero out the ones it does not support:
if(window.console && !console.dir){
var methods = ["dir", "dirxml", "trace", "profile"]; //etc etc
for(var i=0;i<methods.length;i++){
console[methods[i]] = function(){};
}
}
I was having the issue finding my debug apk. Android Studio 0.8.6 did not show the apk or even the output folder at project/project/build/. When I checked the same path project/project/build/ from windows folder explorer, I found the "output" folder there and the debug apk inside it.
you can integrate to LDAP or AD as well. It works well.
Why not do it with one method call:
File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });
which will do the newline for you, and allow you to insert multiple lines at once if you want.
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
function callMethod() {
//your logic should be here and make sure your logic code note returing function
return false;
}
</script>
Put in the URL bar and then click enter:
javascript:alert(document.title);
You can select and copy the text from the alert depending on the website and the web browser you are using.
None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.
In the instance below I want to ensure the OutletRef field is unique:
public class ApplicationDbContext : IdentityDbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Outlet>()
.HasIndex(o => new { o.OutletRef });
}
}
This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.
Another way is to use np.place
which does in-place replacement and works with multidimentional arrays:
import numpy as np
# create 2x3 array with numbers 0..5
arr = np.arange(6).reshape(2, 3)
# replace 0 with -10
np.place(arr, arr == 0, -10)
I found that user controls can exist in the same project.
As others have mentioned, AutoToolboxPopulate must be set to True.
Create the desired user control.
Select Build Solution.
If the new user control doesn't show up in the toolbox, close/open Visual Studio.
If the user controls still aren't showing up in the toolbox, right click on the toolbox and select Reset Toolbox. Then select Build Solution. If they still aren't there, restart Visual Studio.
There must not be any build errors when the solution is built, otherwise new toolbox items will not be added to the toolbox.
This could be complicated way of doing
String newString = new String(oldString);
This shortens the String is the underlying char[] used is much longer.
However more specifically it will be checking that every character can be UTF-8 encoded.
There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?
Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'
String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));
prints
false
The ~
selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):
The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.
Consider the following example:
.a ~ .b {_x000D_
background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
<li class="b">1st</li>_x000D_
<li class="a">2nd</li>_x000D_
<li>3rd</li>_x000D_
<li class="b">4th</li>_x000D_
<li class="b">5th</li>_x000D_
</ul>
_x000D_
.a ~ .b
matches the 4th and 5th list item because they:
.b
elements .a
.a
in HTML source order.Likewise, .check:checked ~ .content
matches all .content
elements that are siblings of .check:checked
and appear after it.
Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).
This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit
(of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.
As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.
N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.
As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction
[\s-[\r\n]]
or, including Eiríkr Útlendi's solution, you get
[\s\u3000-[\r\n]]
How about:
df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x
To do all these operations in one-liner:
setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))
#[1] name age gender
#<0 rows> (or 0-length row.names)
Or
data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))
Suppose an autofac setting like the following:
public class AutofacContractResolver : DefaultContractResolver
{
private readonly IContainer _container;
public AutofacContractResolver(IContainer container)
{
_container = container;
}
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
// use Autofac to create types that have been registered with it
if (_container.IsRegistered(objectType))
{
contract.DefaultCreator = () => _container.Resolve(objectType);
}
return contract;
}
}
Then, suppose your class is like this:
public class TaskController
{
private readonly ITaskRepository _repository;
private readonly ILogger _logger;
public TaskController(ITaskRepository repository, ILogger logger)
{
_repository = repository;
_logger = logger;
}
public ITaskRepository Repository
{
get { return _repository; }
}
public ILogger Logger
{
get { return _logger; }
}
}
Therefore, the usage of the resolver in deserialization could be like:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<TaskRepository>().As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogService(new DateTime(2000, 12, 12))).As<ILogger>();
IContainer container = builder.Build();
AutofacContractResolver contractResolver = new AutofacContractResolver(container);
string json = @"{
'Logger': {
'Level':'Debug'
}
}";
// ITaskRespository and ILogger constructor parameters are injected by Autofac
TaskController controller = JsonConvert.DeserializeObject<TaskController>(json, new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Console.WriteLine(controller.Repository.GetType().Name);
You can see more details in http://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm
For Visible:
document.getElementById("test").style.visibility="visible";
For Invisible:
document.getElementById("test").style.visibility="hidden";
You can use below code to get all the privileges list from all users.
select * from dba_sys_privs
use dependency maven:
groupId: net.sf.extcos
artifactId: extcos
version: 0.4b
then use this code :
ComponentScanner scanner = new ComponentScanner();
Set classes = scanner.getClasses(new ComponentQuery() {
@Override
protected void query() {
select().from("com.leyton").returning(allExtending(DynamicForm.class));
}
});
In Angular 6, I found this simpler way:
navigate(["/yourpage", { "someParamName": "paramValue"}]);
Then in the constructor or in ngInit
you can directly use:
let value = this.route.snapshot.params.someParamName;
Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:
You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.
Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.
-onedaywhen yesterday
Here is an example where #table constraints can prevent bad data which is not the case in CTE's
DECLARE @BadData TABLE (
ThisID int
, ThatID int );
INSERT INTO @BadData
( ThisID
, ThatID
)
VALUES
( 1, 1 ),
( 1, 2 ),
( 2, 2 ),
( 1, 1 );
IF OBJECT_ID('tempdb..#This') IS NOT NULL
DROP TABLE #This;
CREATE TABLE #This (
ThisID int NOT NULL
, ThatID int NOT NULL
UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
AS (SELECT *
FROM @BadData)
SELECT *
FROM This_CTE;
import string
import random
n = 10
p = ''
while (string.ascii_uppercase not in p) and (string.ascii_lowercase not in p) and (string.digits not in p):
for _ in range(n):
state = random.randint(0, 2)
if state == 0:
p = p + chr(random.randint(97, 122))
elif state == 1:
p = p + chr(random.randint(65, 90))
else:
p = p + str(random.randint(0, 9))
break
print(p)
This code generates a sequence with size n which at least contain an uppercase, lowercase, and a digit. By using the while loop, we have guaranteed this event.
This is my solution with stack
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
final themeColor = new Color(0xfff5a623);
final primaryColor = new Color(0xff203152);
final greyColor = new Color(0xffaeaeae);
final greyColor2 = new Color(0xffE8E8E8);
class LoadindScreen extends StatefulWidget {
LoadindScreen({Key key, this.title}) : super(key: key);
final String title;
@override
LoginScreenState createState() => new LoginScreenState();
}
class LoginScreenState extends State<LoadindScreen> {
SharedPreferences prefs;
bool isLoading = false;
Future<Null> handleSignIn() async {
setState(() {
isLoading = true;
});
prefs = await SharedPreferences.getInstance();
var isLoadingFuture = Future.delayed(const Duration(seconds: 3), () {
return false;
});
isLoadingFuture.then((response) {
setState(() {
isLoading = response;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: Stack(
children: <Widget>[
Center(
child: FlatButton(
onPressed: handleSignIn,
child: Text(
'SIGN IN WITH GOOGLE',
style: TextStyle(fontSize: 16.0),
),
color: Color(0xffdd4b39),
highlightColor: Color(0xffff7f7f),
splashColor: Colors.transparent,
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0)),
),
// Loading
Positioned(
child: isLoading
? Container(
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
),
color: Colors.white.withOpacity(0.8),
)
: Container(),
),
],
));
}
}
here is some code for more robust imcrop ( a bit like in matlab )
def imcrop(img, bbox):
x1,y1,x2,y2 = bbox
if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
return img[y1:y2, x1:x2, :]
def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
img = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
(np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
y1 += np.abs(np.minimum(0, y1))
y2 += np.abs(np.minimum(0, y1))
x1 += np.abs(np.minimum(0, x1))
x2 += np.abs(np.minimum(0, x1))
return img, x1, x2, y1, y2
I tried using disabled along with click event. Below is the snippet , the accepted answer also worked perfectly fine , I am adding this answer to give an example how it can be used with disabled and click properties.
<button (click)="!planNextDisabled && planNext()" [disabled]="planNextDisabled"></button>
Any approach should give you roughly same number. It is always a good idea to allocate the heap using -X..m
-X..x
for all generations. You can then guarantee and also do ps to see what parameters were passed and hence being used.
For actual memory usages, you can roughly compare VIRT (allocated and shared) and RES (actual used) compare against the jstat values as well:
For Java 8, see jstat for these values actually mean. Assuming you run a simple class with no mmap or file processing.
$ jstat -gccapacity 32277
NGCMN NGCMX NGC S0C S1C EC OGCMN OGCMX OGC OC MCMN MCMX MC CCSMN CCSMX CCSC YGC FGC
215040.0 3433472.0 73728.0 512.0 512.0 67072.0 430080.0 6867968.0 392704.0 392704.0 0.0 1083392.0 39680.0 0.0 1048576.0 4864.0 7225 2
$ jstat -gcutil 32277
S0 S1 E O M CCS YGC YGCT FGC FGCT GCT
6.25 0.00 7.96 18.21 98.01 95.29 7228 30.859 2 0.173 31.032
Max:
NGCMX + S0C + S1C + EC + OGCMX + MCMX + CCSMX
3433472 + 512 + 512 + 67072 + 6867968 + 1083392 + 1048576 = 12 GB
(roughly close and below to VIRT memory)
Max(Min, Used):
215040 + 512 + 512 + 67072 + 430080 + 39680 + 4864 = ~ 1GB
(roughly close to RES memory)
"Don't quote me on this" but VIRT mem is roughly close to or more than Max memory allocated but as long as memory being used is free/available in physical memory, JVM does not throw memory exception. In fact, max memory is not even checked against physical memory on JVM startup even with swap off on OS. A better explanation of what Virtual memory really used by a Java process is discussed here.
I tried the accepted answer, it did not work.
However the simple way to do it is below:-
<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>
Enjoy!!
info frame
to show the stack frame info
To read the memory at given addresses you should take a look at x
x/x $esp
for hex x/d $esp
for signed x/u $esp
for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip
etc.
To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:
def foo():
if bar:
print "bar"
print "baz" # ends the if and foo at the same time
The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.
Lines with no statement, no matter the indentation, does not matter
def foo():
print "The line below has no indentation"
print "Still part of foo"
But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:
def foo():
print "Still correct"
print "Error because there is no block at this indentation"
Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.
BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.
To pass arguments to the jar:
java -jar myjar.jar one two
You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf
file of a JAR).
String one = args[0];
String two = args[1];
Schema is a container of objects. It is owned by a user.
You can create a new queue item to do your removing of the class:
$("#div").addClass("error").delay(1000).queue(function(next){
$(this).removeClass("error");
next();
});
Or using the dequeue method:
$("#div").addClass("error").delay(1000).queue(function(){
$(this).removeClass("error").dequeue();
});
The reason you need to call next
or dequeue
is to let jQuery know that you are done with this queued item and that it should move on to the next one.
Full disclosure, I am one of the maintainers of pdfminer.six.
Nowadays, there are multiple api's to extract text from a PDF, depending on your needs. Behind the scenes, all of these api's use the same logic for parsing and analyzing the layout.
(All the examples assume your PDF file is called example.pdf)
Commandline
If you want to extract text just once you can use the commandline tool pdf2txt.py:
$ pdf2txt.py example.pdf
High-level api
If you want to extract text with Python, you can use the high-level api. This approach is the go-to solution if you want to extract text programmatically from many PDF's.
from pdfminer.high_level import extract_text
text = extract_text('example.pdf')
Composable api
There is also a composable api that gives a lot of flexibility in handling the resulting objects. For example, you can implement your own layout algorithm using that. This method is suggested in the other answers, but I would only recommend this when you need to customize the way pdfminer.six behaves.
from io import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
output_string = StringIO()
with open('example.pdf', 'rb') as in_file:
parser = PDFParser(in_file)
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
device = TextConverter(rsrcmgr, output_string, laparams=LAParams())
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.create_pages(doc):
interpreter.process_page(page)
print(output_string.getvalue())
I just figured out that json_encode
does only escape \n
if it's used within single quotes.
echo json_encode("Hello World\n");
// results in "Hello World\n"
And
echo json_encode('Hello World\n');
// results in "Hello World\\\n"
I notice that recent Oracle client installers change file permissions.
I had Oracle 12.0.1 32 bit client installed for a year. I recently installed Oracle 12.0.1 64 bit client. The Oracle install change ALL file permissions in the 32 bit folders.
My application suddenly failed to run.
I used PROCMON.EXE (https://docs.microsoft.com/en-us/sysinternals/downloads/) and noticed that permission was denied opening OCI.DLL
I changed the permissions for everything in the Oracle client folders and application works as expected.
To make changes to sudo from putty/bash:
This was written in 2000, not sure if the state of the art in porn detection has advanced at all, but I doubt it.
http://www.dansdata.com/pornsweeper.htm
PORNsweeper seems to have some ability to distinguish pictures of people from pictures of things that aren't people, as long as the pictures are in colour. It is less successful at distinguishing dirty pictures of people from clean ones.
With the default, medium sensitivity, if Human Resources sends around a picture of the new chap in Accounts, you've got about a 50% chance of getting it. If your sister sends you a picture of her six-month-old, it's similarly likely to be detained.
It's only fair to point out amusing errors, like calling the Mona Lisa porn, if they're representative of the behaviour of the software. If the makers admit that their algorithmic image recogniser will drop the ball 15% of the time, then making fun of it when it does exactly that is silly.
But PORNsweeper only seems to live up to its stated specifications in one department - detection of actual porn. It's half-way decent at detecting porn, but it's bad at detecting clean pictures. And I wouldn't be surprised if no major leaps were made in this area in the near future.
Custom SerDe might be a way to do it. Or you could use some kind of mediation process with regex_replace:
create table tableB as
select
columnA
regexp_replace(description, '\\t', '') as description
from tableA
;
It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)
git pull origin master
for me that simple call solved those error messages:
I've added yet another JavaScript serializer repo to GitHub.
Rather than take the approach of serializing and deserializing JavaScript objects to an internal format the approach here is to serialize JavaScript objects out to native JavaScript. This has the advantage that the format is totally agnostic from the serializer, and the object can be recreated simply by calling eval().
This Should work Making it Round to 2 Point
int a=53214
parseFloat(Math.round(a* 100) / 100).toFixed(2);
I know this question was already answered, but this is what I use:
using (FileStream fStream = File.OpenRead(filename)) {
return GetHash<MD5>(fStream)
}
Where GetHash:
public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
StringBuilder sb = new StringBuilder();
MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
using (T crypt = (T) create.Invoke(null, null)) {
byte[] hashBytes = crypt.ComputeHash(stream);
foreach (byte bt in hashBytes) {
sb.Append(bt.ToString("x2"));
}
}
return sb.ToString();
}
Probably not the best way, but it can be handy.
Just simply the css style using white-space:nowrap
works very well to avoid text wrapping in cells. And ofcourse you can use the text-overflow:ellipsis
and overflow:hidden
for truncating text with ellipsis effect.
<td style="white-space:nowrap">Cell Value</td>
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
This is the shortest way.
var now = new Date().toLocaleTimeString();
console.log(now)
Here is also a way through string manipulation that was not mentioned.
var now = new Date()
console.log(now.toString().substr(16,8))
Here is a function that works with jQuery (for height only, not width):
function setHeight(jq_in){
jq_in.each(function(index, elem){
// This line will work with pure Javascript (taken from NicB's answer):
elem.style.height = elem.scrollHeight+'px';
});
}
setHeight($('<put selector here>'));
Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.
awk 'BEGIN { print strftime("%c", 1271603087); }'
There is a chance that application pool created for you application by default is version 2. So although you see a handler for .svc extension in the list it does not work and treat it as static file. All you need is to open application pool properties and switch it to version 4.
I'd do it this way:
grid1.DataContext = dt.AsEnumerable().Where(x => x < 10).AsEnumerable().CopyToDataTable().AsDataView();
and do whatever query i want between the two AsEnumerable(). If you don't need space for query, you can just do directly this:
grid1.DataContext = dt.AsDataView();
make sure your folder permissions are set so that a directory listing is allowed then just point your anchor to that folder using chmod 701 (that might be risky though) for example
<a href="./downloads/folder_i_want_to_display/" >Go to downloads page</a>
make sure that you have no index.html any index file on that directory
Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems
Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:
For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:
<html> <head> <title>Test Page</title> </head> <body> <h2>Data Collection</h2><p> <form action="process.php" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" name="Name"/></td> </tr> <tr> <td>Age:</td> <td><input type="text" name="Age"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit"/> </td> </tr> </table> </form> </body> </html>
This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:
<?php
print "Your name is ". $Name;
print "<br />";
print "You are ". $Age . " years old";
print "<br />"; $old = 25 + $Age;
print "In 25 years you will be " . $old . " years old";
?>
As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.
Additional JavaScript Example
This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.
Note: document.getElementById("fname").value
gets the object with the ID
tag that equals fname
and then pulls it's value
- which in this case is the text in the First Name textbox.
<html>
<head>
<script type="text/javascript">
function ExampleJS(){
var jFirst = document.getElementById("fname").value;
var jLast = document.getElementById("lname").value;
alert("Your name is: " + jFirst + " " + jLast);
}
</script>
</head>
<body>
<FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">
First name: <input type="text" id="fname" name="firstname" /><br />
Last name: <input type="text" id="lname" name="lastname" /><br />
<input name="Submit" type="submit" value="Update" />
</FORM>
</body>
</html>
Simply go to /opt/lampp/var/mysql
There You can find your database
name.
Open that folder. Remove if any files in it
Now come to phpmyadmin
and drop that database
SELECT SCOPE_IDENTITY()
after the insert statement
Please refer the following links
The following works in all browsers, but as always there are caveats.
Background:
"URL Shortcuts" are OS dependent. The following solution is for MS Windows due to a lack of standards between environments.
If you require linux support for the solution below, please see this article.
* I have no connection to the article, YMMV.
URL shortcuts come in two forms:
Files with .URL extensions are text based. Can be dynamically generated.
[InternetShortcut]
URL=file:///D:/
Files with .LNK extension are binary. They can be generated dynamically, but require iShelLinkInterface implementer. This is complicated by default OS restrictions, which rightfully prevent an IIS process from reaching Shell.
.URL is the recommended solution, as dynamic generation is viable across Web Languages/Frameworks and allows for a KISS implementation.
Overview/Recap:
Solution:
Provide a downloadable link (.URL or .LNK) to the resource. Browser behavior will be explained at end of post.
Option 1: Produce a .lnk file and save it to the server. Due to the binary nature of the .LNK file, this is not the recommended solution, but a pre-generated file should be viable.
Option 2: Produce a .url file and either save it to the server or dynamically generate
it. In my situation, I am dynamically creating the .URL file.
Solution Details (.URL):
Add .url to the available MIME types in your web server.
For IIS open the site, choose MIME Types, and add the following:
File name Extension= .url
MIME type: application/internet-shortcut
Per @cremax ... For Webkit Browsers like Chrome on Apache Servers add this code to .htaccess or http.config:
SetEnvIf Request_URI ".url$" requested_url=url Header add Content-Disposition "attachment" env=requested_url
The .url file is a text file formatted as follows (again, this can be dynamically generated).
File Contents:
[InternetShortcut]
URL=file:///D:
Provide a link to the script that generates the .url file, or to the file itself.
If you've simply uploaded a .url file to your server, add the following to your HTML:
<a href="URIShortcut.url">Round-About Linking</a>
Browser Dependent Behavior
Chrome: Download/Save file.url then open
In Chrome, this behavior can be augmented by choosing the "Always open files of this type" option.
FireFox: Download/Save file.url then open
Internet Explorer: Click “Open” and go straight to directory (no need to save shortcut)
Internet Explorer has the preferred behavior, but Chrome and Firefox are at least serviceable.
A more modern version of kaiido's answer using fetch would be:
function toObjectUrl(url) {
return fetch(url)
.then((response)=> {
return response.blob();
})
.then(blob=> {
return URL.createObjectURL(blob);
});
}
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Edit: As pointed out in the comments this will return an object url which points to a file in your local system instead of an actual DataURL so depending on your use case this might not be what you need.
You can look at the following answer to use fetch and an actual dataURL: https://stackoverflow.com/a/50463054/599602
One use: test some code that should raise an exception.
try:
this_should_raise_TypeError()
except TypeError:
pass
except:
assert False, "Raised the wrong exception type"
else:
assert False, "Didn't raise any exception"
(This code should be abstracted into a more generic test in practice.)
#include
has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.
You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.
Spring MVC and Spring Boot are well described in other answers, and so without repeating that, let me jump straight to the specifics. Spring Boot and Spring MVC are not comparable or mutually exclusive. If you want to do web application development using Spring, you would use Spring MVC anyway. Your question then becomes whether to use Spring Boot or not.
For developing common Spring applications or starting to learn Spring, I think using Spring Boot would be recommended. It considerably eases the job, is production ready and is rapidly being widely adopted.
I have seen sometimes beginners asking this question because in STS (Spring Tool Suite) there are two wizards: one for creating a Spring Boot project, and another for creating a Spring MVC project. So, my recommendation would be to create a Spring Boot project and choose Web as a module in that.
Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:
Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.
Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.
If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.
Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.
Simple answer NO.
However you can achieve something similar by running the following version using bind variables:
SELECT * FROM Employees WHERE EmployeeID = :EmpIDVar
Once you run the query above in SQL Developer you will be prompted to enter value for the bind variable EmployeeID.
I don't understand why some people are suggesting using cross apply
or outer apply
to convert the xml into a table of values. For me, that just brought back way too much data.
Here's my example of how you'd create an xml
object, then turn it into a table.
(I've added spaces in my xml string, just to make it easier to read.)
DECLARE @str nvarchar(2000)
SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Mike</firstName>'
SET @str = @str + ' <lastName>Gledhill</lastName>'
SET @str = @str + ' <age>31</age>'
SET @str = @str + ' </user>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Mark</firstName>'
SET @str = @str + ' <lastName>Stevens</lastName>'
SET @str = @str + ' <age>42</age>'
SET @str = @str + ' </user>'
SET @str = @str + ' <user>'
SET @str = @str + ' <firstName>Sarah</firstName>'
SET @str = @str + ' <lastName>Brown</lastName>'
SET @str = @str + ' <age>23</age>'
SET @str = @str + ' </user>'
SET @str = @str + '</users>'
DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML)
-- Iterate through each of the "users\user" records in our XML
SELECT
x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)
And here's the output:
I found the easiest way to do this, is by setting the cornerRadius to half of the height of the view.
button.layer.cornerRadius = button.bounds.size.height/2
Yes you can negate the test as SiegeX has already pointed out.
However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:
[[ ":$PATH:" != *":$1:"* ]]
Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.
from numpy.polynomial import Polynomial
p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())
p
uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with
pnormal = p.convert(domain=(-1, 1))
you can set tintColor of UIBarItem :
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.magentaColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState:.Selected)
Below steps helped me fix this.
rm -rf env-name
python3 -m venv env-aide
Have you seen FlexSlider from WooThemes? I've used it on several recent projects with great success. It's touch enabled too so it will work on both mouse-based browsers as well as touch-based browsers in iOS and Android.
subprocess.check_output() returns bytes.
so you need to convert '\n' to bytes as well:
f.write (plaintext + b'\n')
hope this helps
Create a <div>
element that contains your loading message, give the <div>
an ID, and then when your content has finished loading, hide the <div>
:
$("#myElement").css("display", "none");
...or in plain JavaScript:
document.getElementById("myElement").style.display = "none";
You mean you want to show a javascript alert when a button is clicked on a PHP generated page?
echo('<button type="button" onclick="alert(\'Alrt Text!\');">My Button</button>');
Would do that
Query to add column with comment are :
alter table table_name
add( "NISFLAG" NUMBER(1,0) )
comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'
commit;
Make sure your designer version and targetSdkVersion both is same. Example : If your targetSdkVersion is 22 then change your designer version also 22, so this problem do not occur.
I do it this way. Precise? Maybe or maybe not. Try it
<html>
<head>
<title> Age Calculator</title>
</head>
<input type="date" id="startDate" value="2000-01-01">
<input type="date" id="endDate" value="2020-01-01">
<button onclick="getAge(new Date(document.getElementById('startDate').value), new Date(document.getElementById('endDate').value))">Check Age</button>
<script>
function getAge (startDate, endDate) {
var diff = endDate-startDate
var age = new Date(new Date("0000-01-01").getTime()+diff)
var years = age.getFullYear()
var months = age.getMonth()
var days = age.getDate()
console.log(years,"years",months,"months",days-1,"days")
return (years+"years "+ months+ "months"+ days,"days")
}
</script>
</html>
This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.
<Window.Resources>
<local:WidthConverter x:Key="widthConverter"/>
</Window.Resources>
<Grid>
<Grid>
<StackPanel VerticalAlignment="Center" Orientation="Vertical" >
<Viewbox Margin="100,0,100,0">
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
</Viewbox>
<TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
</StackPanel>
</Grid>
</Grid>
Converter
[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value*.7;
return width; // columnsCount;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
When in doubt, read the documentation:
filename = "C:\Temp\vblist.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
WScript.Echo f.ReadLine
Loop
f.Close
You've misunderstood how character classes are used:
$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
does the same as your regex (assuming you didn't mean to remove '
characters from your strings).
Edit: The +
allows several of those "special characters" to match at once, so it should also be faster.
This code is correct but if you entered a lot of space (' ') instead of null or empty string return false.
To correct this use regular expresion (this code below check if the variable is null or empty or blank the same as org.apache.commons.lang.StringUtils.isNotBlank) :
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${not empty description}">
<c:set var="description" value="${fn:replace(description, ' ', '')}" />
<c:if test="${not empty description}">
The description is not blank.
</c:if>
</c:if>
havent tried but this might help
$(document).ready(function(){
r=0;s=-1;
$(a).click(function(){
v=$(this).html();
$(a).each(function(){
if($(this).html()==v)
return;
else ++r;
$(div).each(function(){
if(s==r)
$(div).appendTo($(".target"));
++S;
});
});
});
});
File: Info.plist
For Camera:
<key>NSCameraUsageDescription</key>
<string>You can take photos to document your job.</string>
For Photo Library, you will want this one to allow app user to browse the photo library.
<key>NSPhotoLibraryUsageDescription</key>
<string>You can select photos to attach to reports.</string>
Probably there's something wrong with the input values for X and/or T. The function from the question works ok:
import numpy as np
from math import e
def sigmoid(X, T):
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])
print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))
Result:
[[15 16]
[ 5 10]]
[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]
[[ 0.99999969 0.99999989]
[ 0.99330715 0.9999546 ]]
Probably it's the dtype of your input arrays. Changing X to:
X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)
Gives:
Traceback (most recent call last):
File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
print sigmoid(X, T)
File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp
I wrote an article on this on my blog: http://www.ebenmonney.com/blog/how-to-implement-remember-me-functionality-using-token-based-authentication-and-localstorage-in-a-web-application .
Using a library I created storageManager
you can achieve this as follows:
storageManager.savePermanentData('data', 'key'): //saves permanent data
storageManager.saveSyncedSessionData('data', 'key'); //saves session data to all opened tabs
storageManager.saveSessionData('data', 'key'); //saves session data to current tab only
storageManager.getData('key'); //retrieves data
There are other convenient methods as well to handle other scenarios as well
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
function method1(){_x000D_
var dfd = new $.Deferred();_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 1"); _x000D_
method2(dfd); _x000D_
}, 5000);_x000D_
return dfd.promise();_x000D_
}_x000D_
_x000D_
function method2(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 2"); _x000D_
method3(dfd); _x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method3(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 3"); _x000D_
dfd.resolve();_x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method4(){ _x000D_
console.log("Inside Method - 4"); _x000D_
}_x000D_
_x000D_
var call = method1();_x000D_
_x000D_
$.when(call).then(function(cb){_x000D_
method4();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Using git version 1.7.9.5 there is no "remove" command for remote. Use "rm" instead.
$ git remote rm upstream
$ git remote add upstream https://github.com/Foo/repos.git
or, as noted in the previous answer, set-url works.
I don't know when the command changed, but Ubuntu 12.04 shipped with 1.7.9.5.
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
I was pretty sure that you need to specify the NOLOCK
for each JOIN
in the query. But my experience was limited to SQL Server 2005.
When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:
[SQL Server 2008 R2]
All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
[SQL Server 2005]
In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
Additionally, point to note - and this applies to both 2005 and 2008:
The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the
OPTION (EXPAND VIEWS)
query hint.
Try this:
$(function() {
$("#type").change(function() {
if ($(this).val() === 'parcel') $("#row_dim").show();
else $("#row_dim").hide();
}
}
$.ajax({
url:href,
type:'get',
success: function(data){
console.log($(data));
}
});
This console log gets an array like object: [meta, title, ,], very strange
You can use JavaScript:
var doc = document.documentElement.cloneNode()
doc.innerHTML = data
$content = $(doc.querySelector('#content'))
It behaves the way you want if called as a function:
>>> def test():
... a = iter(list(range(10)))
... for i in a:
... print(i)
... next(a)
...
>>> test()
0
2
4
6
8
Try to use JSONP
in your Ajax call. It will bypass the Same Origin Policy.
http://learn.jquery.com/ajax/working-with-jsonp/
Try example
$.ajax({
url: "https://api.dailymotion.com/video/x28j5hv?fields=title",
dataType: "jsonp",
success: function( response ) {
console.log( response ); // server response
}
});
Try this one for data...
function get_album_data() {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' );
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$query = $this->db->get ();
return $query->result ();
}
while for datum try this...
function get_album_datum($album_id) {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' );
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$this->db->where ( 'album.album_id', $album_id);
$query = $this->db->get ();
return $query->row();
}7
855788
I solved this by clearing all the plots in the console and then making sure the plot area was large enough to accommodate what I was creating.
I was getting this error while posting a FormData object because I was not setting up the ajax call correctly. Setup below fixed my issue.
var myformData = new FormData();
myformData.append('leadid', $("#leadid").val());
myformData.append('date', $(this).val());
myformData.append('time', $(e.target).prev().val());
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
url: 'include/ajax.php',
success: function (response) {
$("#subform").html(response).delay(4000).hide(1);
}
});
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
See the print documentation for all the exciting details!
Update for Python 3.x (7.5 years later)
That last line should now be:
print("%0*d" % (width, x))
I.e. print()
is now a function, not a statement. Note that I still prefer the Old School printf()
style because, IMNSHO, it reads better, and because, um, I've been using that notation since January, 1980. Something ... old dogs .. something something ... new tricks.
Follow these steps to create CSR (Code Signing Identity):
On your Mac, go to the folder 'Applications' ? 'Utilities' and open 'Keychain Access.'
Go to 'Keychain Access' ? Certificate Assistant ? Request a Certificate from a Certificate Authority. ?
Fill out the information in the Certificate Information window as specified below and click "Continue."
• In the User Email Address field, enter the email address to identify with this certificate
• In the Common Name field, enter your name
• In the Request group, click the "Saved to disk" option
?
Save the file to your hard drive.
Use this CSR (.certSigningRequest) file to create project/application certificates and profiles, in Apple developer account.
<?php
require_once ( 'username.php' );
if (isset($_POST['textfield'])) {
echo username();
return;
}
echo '
<form name="form1" method="post" action="">
<p>
<label>
<input type="text" name="textfield" id="textfield">
</label>
</p>
<p>
<label>
<input type="submit" name="button" id="button" value="Submit">
</label>
</p>
</form>';
?>
You need to run the function in the page the form is sent to.
This is more general than .NET and Windows. Managed is an environment where you have automatic memory management, garbage collection, type safety, ... unmanaged is everything else. So for example .NET is a managed environment and C/C++ is unmanaged.
Here's another way to do it :) The concept is to create a clip-path polygon with the wave as one side.
This approach is fairly flexible. You can change the position (left, right, top or bottom) in which the wave appears, change the wave function to any function(t) which maps to [0,1]). The polygon can also be used for shape-outside, which lets text flow around the wave when in 'left' or 'right' orientation.
At the end, an example you can uncomment which demonstrates animating the wave.
_x000D_
_x000D_
function PolyCalc(f /*a function(t) from [0, infinity) => [0, 1]*/, _x000D_
s, /*a slice function(y, i) from y [0,1] => [0, 1], with slice index, i, in [0, n]*/_x000D_
w /*window size in seconds*/,_x000D_
n /*sample size*/,_x000D_
o /*orientation => left/right/top/bottom - the 'flat edge' of the polygon*/ _x000D_
) _x000D_
{_x000D_
this.polyStart = "polygon(";_x000D_
this.polyLeft = this.polyStart + "0% 0%, "; //starts in the top left corner_x000D_
this.polyRight = this.polyStart + "100% 0%, "; //starts in the top right corner_x000D_
this.polyTop = this.polyStart + "0% 0%, "; // starts in the top left corner_x000D_
this.polyBottom = this.polyStart + "0% 100%, ";//starts in the bottom left corner_x000D_
_x000D_
var self = this;_x000D_
self.mapFunc = s;_x000D_
this.func = f;_x000D_
this.window = w;_x000D_
this.count = n;_x000D_
var dt = w/n; _x000D_
_x000D_
switch(o) {_x000D_
case "top":_x000D_
this.poly = this.polyTop; break;_x000D_
case "bottom":_x000D_
this.poly = this.polyBottom; break;_x000D_
case "right":_x000D_
this.poly = this.polyRight; break;_x000D_
case "left":_x000D_
default:_x000D_
this.poly = this.polyLeft; break;_x000D_
}_x000D_
_x000D_
this.CalcPolygon = function(t) {_x000D_
var p = this.poly;_x000D_
for (i = 0; i < this.count; i++) {_x000D_
x = 100 * i/(this.count-1.0);_x000D_
y = this.func(t + i*dt);_x000D_
if (typeof self.mapFunc !== 'undefined')_x000D_
y=self.mapFunc(y, i);_x000D_
y*=100;_x000D_
switch(o) {_x000D_
case "top": _x000D_
p += x + "% " + y + "%, "; break;_x000D_
case "bottom":_x000D_
p += x + "% " + (100-y) + "%, "; break;_x000D_
case "right":_x000D_
p += (100-y) + "% " + x + "%, "; break;_x000D_
case "left":_x000D_
default:_x000D_
p += y + "% " + x + "%, "; break; _x000D_
}_x000D_
}_x000D_
_x000D_
switch(o) { _x000D_
case "top":_x000D_
p += "100% 0%)"; break;_x000D_
case "bottom":_x000D_
p += "100% 100%)";_x000D_
break;_x000D_
case "right":_x000D_
p += "100% 100%)"; break;_x000D_
case "left":_x000D_
default:_x000D_
p += "0% 100%)"; break;_x000D_
}_x000D_
_x000D_
return p;_x000D_
}_x000D_
};_x000D_
_x000D_
var text = document.querySelector("#text");_x000D_
var divs = document.querySelectorAll(".wave");_x000D_
var freq=2*Math.PI; //angular frequency in radians/sec_x000D_
var windowWidth = 1; //the time domain window which determines the range from [t, t+windowWidth] that will be evaluated to create the polygon_x000D_
var sampleSize = 60;_x000D_
divs.forEach(function(wave) {_x000D_
var loc = wave.classList[1];_x000D_
_x000D_
var polyCalc = new PolyCalc(_x000D_
function(t) { //The time domain wave function_x000D_
return (Math.sin(freq * t) + 1)/2; //sine is [-1, -1], so we remap to [0,1]_x000D_
},_x000D_
function(y, i) { //slice function, takes the time domain result and the slice index and returns a new value in [0, 1] _x000D_
return MapRange(y, 0.0, 1.0, 0.65, 1.0); //Here we adjust the range of the wave to 'flatten' it out a bit. We don't use the index in this case, since it is irrelevant_x000D_
},_x000D_
windowWidth, //1 second, which with an angular frequency of 2pi rads/sec will produce one full period._x000D_
sampleSize, //the number of samples to make, the larger the number, the smoother the curve, but the more pionts in the final polygon_x000D_
loc //the location_x000D_
);_x000D_
_x000D_
var polyText = polyCalc.CalcPolygon(0);_x000D_
wave.style.clipPath = polyText;_x000D_
wave.style.shapeOutside = polyText;_x000D_
wave.addEventListener("click",function(e) {document.querySelector("#polygon").innerText = polyText;});_x000D_
});_x000D_
_x000D_
function MapRange(value, min, max, newMin, newMax) {_x000D_
return value * (newMax - newMin)/(max-min) + newMin;_x000D_
}_x000D_
_x000D_
//Animation - animate the wave by uncommenting this section_x000D_
//Also demonstrates a slice function which uses the index of the slice to alter the output for a dampening effect._x000D_
/*_x000D_
var t = 0;_x000D_
var speed = 1/180;_x000D_
_x000D_
var polyTop = document.querySelector(".top");_x000D_
_x000D_
var polyTopCalc = new PolyCalc(_x000D_
function(t) {_x000D_
return (Math.sin(freq * t) + 1)/2;_x000D_
},_x000D_
function(y, i) { _x000D_
return MapRange(y, 0.0, 1.0, (sampleSize-i)/sampleSize, 1.0);_x000D_
},_x000D_
windowWidth, sampleSize, "top"_x000D_
);_x000D_
_x000D_
function animate() {_x000D_
var polyT = polyTopCalc.CalcPolygon(t); _x000D_
t+= speed;_x000D_
polyTop.style.clipPath = polyT; _x000D_
requestAnimationFrame(animate);_x000D_
}_x000D_
_x000D_
requestAnimationFrame(animate);_x000D_
*/
_x000D_
div div {_x000D_
padding:10px;_x000D_
/*overflow:scroll;*/_x000D_
}_x000D_
_x000D_
.left {_x000D_
height:100%;_x000D_
width:35%;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
.right {_x000D_
height:200px;_x000D_
width:35%;_x000D_
float:right;_x000D_
}_x000D_
_x000D_
.top { _x000D_
width:100%;_x000D_
height: 200px; _x000D_
}_x000D_
_x000D_
.bottom {_x000D_
width:100%;_x000D_
height:200px;_x000D_
}_x000D_
_x000D_
.green {_x000D_
background:linear-gradient(to bottom, #b4ddb4 0%,#83c783 17%,#52b152 33%,#008a00 67%,#005700 83%,#002400 100%); _x000D_
} _x000D_
_x000D_
.mainContainer {_x000D_
width:100%;_x000D_
float:left;_x000D_
}_x000D_
_x000D_
#polygon {_x000D_
padding-left:20px;_x000D_
margin-left:20px;_x000D_
width:100%;_x000D_
}
_x000D_
<div class="mainContainer">_x000D_
_x000D_
<div class="wave top green">_x000D_
Click to see the polygon CSS_x000D_
</div>_x000D_
_x000D_
<!--div class="wave left green">_x000D_
</div-->_x000D_
<!--div class="wave right green">_x000D_
</div--> _x000D_
<!--div class="wave bottom green"></div--> _x000D_
</div>_x000D_
<div id="polygon"></div>
_x000D_
If you use the history,then Router put everything into the location from the history,such as:
this.props.location.pathname;
this.props.location.query;
get it?
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
else:
print("Now I'll see if I can break your score...")
ans = False
break
Your statement matches any string that contains a letter or digit anywhere, even if it contains other non-alphanumeric characters. Try this:
SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$';
^
and $
require the entire string to match rather than just any portion of it, and +
looks for 1 or more alphanumberic characters.
You could also use a named character class if you prefer:
SELECT * FROM table WHERE column REGEXP '^[[:alnum:]]+$';
RxJS Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections.
For example, RxJS defines operators such as map()
, filter()
, concat()
, and flatMap()
.
You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.
The pipe()
function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).
Actually was searching the internet for a solution to this for a while. And the accepted answer gives the good "by the book" answer. But I didn't want to accept that so I kept searching and found this:
http://jsbin.com/eqape/1601/edit - Live Example
This example pulls in the proper styles and adds the functionality requested at the same time, complete with space to write add your own functionality on each header click. Also allows multiple divs to be in between the "h3"s.
$("#notaccordion").addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset")
.find("h3")
.addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom")
.hover(function() { $(this).toggleClass("ui-state-hover"); })
.prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>')
.click(function() {
$(this).find("> .ui-icon").toggleClass("ui-icon-triangle-1-e ui-icon-triangle-1-s").end()
.next().toggleClass("ui-accordion-content-active").slideToggle();
return false;
})
.next()
.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom")
.hide();
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Toggle Panels (not accordion) using ui-accordion styles</title>
<!-- jQuery UI | http://jquery.com/ http://jqueryui.com/ http://jqueryui.com/docs/Theming -->
<style type="text/css">body{font:62.5% Verdana,Arial,sans-serif}</style>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
</head>
<body>
<h1>Toggle Panels</h1>
<div id="notaccordion">
<h3><a href="#">Section 1</a></h3>
<div class="content">
Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
</div>
<h3><a href="#">Section 2</a></h3>
<div>
Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
suscipit faucibus urna.
</div>
<h3><a href="#">Section 3</a></h3>
<div class="top">
Top top top top
</div>
<div class="content">
Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
<ul>
<li>List item one</li>
<li>List item two</li>
<li>List item three</li>
</ul>
</div>
<div class="bottom">
Bottom bottom bottom bottom
</div>
<h3><a href="#">Section 4</a></h3>
<div>
Cras dictum. Pellentesque habitant morbi tristique senectus et netus
et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
mauris vel est.
Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
inceptos himenaeos.
</div>
</div>
</body>
</html>`
.bbg {
/* The image used */
background-image: url('...');
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<!doctype html>
<html class="h-100">
.
.
.
<body class="bbg">
</body>
.
.
.
</html>
Using the "Add Service Reference" tool in Visual Studio, you can insert the address as:
file:///path/to/wsdl/file.wsdl
And it will load properly.
The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.
The difference between die()
and exit()
in PHP is their origin.
exit()
is from exit()
in C.die()
is from die
in Perl.die()
and exit()
are equivalent functions.
PHP Manual for die
:
This language construct is equivalent to
exit()
.
PHP Manual for exit
:
Note: This language construct is equivalent to
die()
.
PHP Manual for List of Function Aliases:
die()
and exit()
are different in other languages but in PHP they are identical.
From Yet another PHP rant:
...As a C and Perl coder, I was ready to answer, "Why, exit() just bails off the program with a numeric exit status, while die() prints out the error message to stderr and exits with EXIT_FAILURE status." But then I remembered we're in messy-syntax-land of PHP.
In PHP, exit() and die() are identical.
The designers obviously thought "Hmm, let's borrow exit() from C. And Perl folks probably will like it if we take die() as is from Perl too. Oops! We have two exit functions now! Let's make it so that they both can take a string or integer as an argument and make them identical!"
The end result is that this didn't really make things any "easier", just more confusing. C and Perl coders will continue to use exit() to toss an integer exit value only, and die() to toss an error message and exit with a failure. Newbies and PHP-as-a-first-language people will probably wonder "umm, two exit functions, which one should I use?" The manual doesn't explain why there's exit() and die().
In general, PHP has a lot of weird redundancy like this - it tries to be friendly to people who come from different language backgrounds, but while doing so, it creates confusing redundancy.
git rebase -i master
you will get the editor vm open and msgs something like this
Pick 2994283490 commit msg1
f 7994283490 commit msg2
f 4654283490 commit msg3
f 5694283490 commit msg4
#Some message
#
#some more
Here I have changed pick for all the other commits to "f" (Stands for fixup).
git push -f origin feature/feature-branch-name-xyz
this will fixup all the commits to one commit and will remove all the other commits . I did this and it helped me.
in AndroidStudio or idea
add "VM Options" Config
“-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005”
remember "address"
You may want to check out my library called DCKit. It's written on the latest version of Swift.
You'd be able to make a rounded corner button/text field from the Interface builder directly:
It also has many other cool features, such as text fields with validation, controls with borders, dashed borders, circle and hairline views etc.
Use rowspan
if you want to extend cells down and colspan
to extend across.
You can use str()
to cast it, or formatters:
"ME%d.txt" % (num,)
I had this issue as well (Error: Could not find or load main class test.Test). I'll explain this relatively basically since I know I would have appreciated someone doing that when I was looking for my answer.
When I right-clicked on the project (left hand side of the screen unless you got rid of the projects tab) and went to properties and then run, the main class had the projectname.classname, which is what confused me. For example, I created a project "test" to test this out, and when I went to
(right-click) test or Source Packages -> properties -> run -> main class
had Test.test in that field, which is what the problem was. the class is test, not Test.test, so I clicked browse to its right, and the only thing in the list to select from was test, and when I selected that and tried rerunning it, it finally worked.
Additionally, I found that when you create a new project in Netbeans, one of the things it originally gives you (in my case of the project named test) is package test;. If you are having this problem, then like me, you probably originally got rid of that line seeing it as just another line of code you didn't need. That line of code is what enabled your main class which in my case was Test.test to find the main class *test from that.
Perhaps using the "~" selector of CSS?
.myclass {
background: red;
}
.myclass~.myclass {
background: yellow;
}
.myclass~.myclass~.myclass {
background: green;
}
See my example on jsfiddle
First, disabling the index during the deletion would be helpful.
Try with a MERGE INTO statement :
1) create a temp table with IDs and an additional column from TABLE1 and test with the following
MERGE INTO table1 src
USING (SELECT id,col1
FROM test_merge_delete) tgt
ON (src.id = tgt.id)
WHEN MATCHED THEN
UPDATE
SET src.col1 = tgt.col1
DELETE
WHERE src.id = tgt.id
You must have used the object, released it ("disconnect"), and used it again. Release object only after you're finished with it, or when calling Form_Closing
.
A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input unsorted array. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.
However, any given sorting algo which is not stable can be modified to be stable. There can be sorting algo specific ways to make it stable, but in general, any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison operation so that the comparison of two keys considers position as a factor for objects with equal keys.
References: http://www.math.uic.edu/~leon/cs-mcs401-s08/handouts/stability.pdf http://en.wikipedia.org/wiki/Sorting_algorithm#Stability
With spool:
set heading off
set arraysize 1
set newpage 0
set pages 0
set feedback off
set echo off
set verify off
variable cd varchar2(10);
variable d number;
declare
ab varchar2(10) := 'Raj';
a number := 10;
c number;
begin
c := a+10;
select ab,c into :cd,:d from dual;
end;
SPOOL
select :cd,:d from dual;
SPOOL OFF
EXIT;
For those who like boost:
boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");
// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);
// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);
Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use
using namespace boost::filesystem
if you do not like those long type names
In regards to iterative variable names, I like making dynamic variables using Template literals. Every Tom, Dick, and Harry uses the array-style, which is fine. Until you're working with arrays and dynamic variables, oh boy! Eye-bleed overload. Since Template literals have limited support right now, eval()
is even another option.
v0 = "Variable Naught";
v1 = "Variable One";
for(i = 0; i < 2; i++)
{//console.log(i) equivalent is console.log(`${i}`)
dyV = eval(`v${i}`);
console.log(`v${i}`); /* => v0; v1; */
console.log(dyV); /* => Variable Naught; Variable One; */
}
When I was hacking my way through the APIs I made this little looping snippet to see behavior depending on what was done with the Template literals compared to say, Ruby. I liked Ruby's behavior more; needing to use eval()
to get the value is kind of lame when you're used to getting it automatically.
_0 = "My first variable"; //Primitive
_1 = {"key_0":"value_0"}; //Object
_2 = [{"key":"value"}] //Array of Object(s)
for (i = 0; i < 3; i++)
{
console.log(`_${i}`); /* var
* => _0 _1 _2 */
console.log(`"_${i}"`); /* var name in string
* => "_0" "_1" "_2" */
console.log(`_${i}` + `_${i}`); /* concat var with var
* => _0_0 _1_1 _2_2 */
console.log(eval(`_${i}`)); /* eval(var)
* => My first variable
Object {key_0: "value_0"}
[Object] */
}
Easier still: return a pointer to a string that's been malloc'd with strdup.
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return strdup(&word[0]);
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
If you use the track by
option, the value
attribute is correctly written, e.g.:
<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
<select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>
produces:
<select>
<option value="" selected="selected"></option>
<option value="15">one</option>
<option value="20">two</option>
</select>
This works:
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
It will produce:
'abcdgxre'
You can also use a delimiter like a comma to produce:
'a,b,c,d,g,x,r,e'
By using:
','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
The problem was that the file access permission was wrong.
I changed the permissions of the directory and it worked.
This is bit tricky
Now a days most of website new techniques to save websites from scraping
1st Technique
Ctrl+U this will show you Page Source
2nd Technique
This one is small hack if the website has ajax like functionality.
Just Hover the mouse key on inspect element untill whole screen becomes just right click then and copy element
That's it you are good to go.
To expand a little on the other answers:
In the line:
def wrapper(func, *args):
The * next to args
means "take the rest of the parameters given and put them in a list called args
".
In the line:
func(*args)
The * next to args
here means "take this list called args and 'unwrap' it into the rest of the parameters.
So you can do the following:
def wrapper1(func, *args): # with star
func(*args)
def wrapper2(func, args): # without star
func(*args)
def func2(x, y, z):
print x+y+z
wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])
In wrapper2
, the list is passed explicitly, but in both wrappers args
contains the list [1,2,3]
.
Why does it implement its methods? How can it implement its methods when an interface can't contain method body? How can it implement the methods when it extends the other interface and not implement it? What is the purpose of an interface implementing another interface?
Interface does not implement the methods of another interface but just extends them.
One example where the interface extension is needed is: consider that you have a vehicle interface with two methods moveForward
and moveBack
but also you need to incorporate the Aircraft which is a vehicle but with some addition methods like moveUp
, moveDown
so
in the end you have:
public interface IVehicle {
bool moveForward(int x);
bool moveBack(int x);
};
and airplane:
public interface IAirplane extends IVehicle {
bool moveDown(int x);
bool moveUp(int x);
};
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.
Here are some density constants, source:
There are, in addition to the standard densities, 5 Intermediate ones. Taking into account this fact, the following code will be a complete working example:
float density = getResources().getDisplayMetrics().density;
if (density == 0.75f)
{
// LDPI
}
else if (density >= 1.0f && density < 1.5f)
{
// MDPI
}
else if (density == 1.5f)
{
// HDPI
}
else if (density > 1.5f && density <= 2.0f)
{
// XHDPI
}
else if (density > 2.0f && density <= 3.0f)
{
// XXHDPI
}
else
{
// XXXHDPI
}
Alternatively, you can find density constants using the densityDpi
:
int densityDpi = getResources().getDisplayMetrics().densityDpi;
switch (densityDpi)
{
case DisplayMetrics.DENSITY_LOW:
// LDPI
break;
case DisplayMetrics.DENSITY_MEDIUM:
// MDPI
break;
case DisplayMetrics.DENSITY_TV:
case DisplayMetrics.DENSITY_HIGH:
// HDPI
break;
case DisplayMetrics.DENSITY_XHIGH:
case DisplayMetrics.DENSITY_280:
// XHDPI
break;
case DisplayMetrics.DENSITY_XXHIGH:
case DisplayMetrics.DENSITY_360:
case DisplayMetrics.DENSITY_400:
case DisplayMetrics.DENSITY_420:
// XXHDPI
break;
case DisplayMetrics.DENSITY_XXXHIGH:
case DisplayMetrics.DENSITY_560:
// XXXHDPI
break;
}
gem uninstall -aIx
and
bundle install
worked for me.
Allocate memory to hold chars.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct PString {
char *chars;
int (*length)(PString *self);
} PString;
int length(PString *self) {
return strlen(self->chars);
}
PString *initializeString(int n) {
PString *str = malloc(sizeof(PString));
str->chars = malloc(sizeof(char) * n);
str->length = length;
str->chars[0] = '\0'; //add a null terminator in case the string is used before any other initialization.
return str;
}
int main() {
PString *p = initializeString(30);
strcpy(p->chars, "Hello");
printf("\n%d", p->length(p));
return 0;
}
WhatsApp Inc. does not provide an open API but a reverse-engineered library is made available on GitHub by the team Venomous on the GitHub. This however according to my knowledge is made possible in PHP. You can check the link here: https://github.com/venomous0x/WhatsAPI
Hope this helps
If you need the entire table structure (not just the basic data layout), use Task>Script Table As>Create To>New Query Window
and run in your new database. Then you can copy the data at your leisure.
a bit more smart (python 3) way:
def printvars():
tmp = globals().copy()
[print(k,' : ',v,' type:' , type(v)) for k,v in tmp.items() if not k.startswith('_') and k!='tmp' and k!='In' and k!='Out' and not hasattr(v, '__call__')]
Regular Expression for 0 to 100 with the decimal point.
^100(\.[0]{1,2})?|([0-9]|[1-9][0-9])(\.[0-9]{1,2})?$
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class Average {
public static void main(String [] args) {
String test1= JOptionPane.showInputDialog("Please input mark for test 1: ");
String test2= JOptionPane.showInputDialog("Please input mark for test 2: ");
String test3= JOptionPane.showInputDialog("Please input mark for test 3: ");
int int1 = Integer.parseInt(test1);
int int2 = Integer.parseInt(test2);
int int3 = Integer.parseInt(test3);
SortedSet<Integer> set = new TreeSet<>();
set.add(int1);
set.add(int2);
set.add(int3);
Integer [] intArray = set.toArray(new Integer[3]);
JFrame frame = new JFrame();
JOptionPane.showInternalMessageDialog(frame.getContentPane(), String.format("Result %f", (intArray[1] + intArray[2]) / 2.0));
}
}
It depends on what your local OS is.
If your local OS is Unix-like, then try:
scp username@remoteHost:/remote/dir/file.txt /local/dir/
If your local OS is Windows ,then you should use pscp.exe
utility.
For example, below command will download file.txt from remote to D:
disk of local machine.
pscp.exe username@remoteHost:/remote/dir/file.txt d:\
It seems your Local OS is Unix, so try the former one.
For those who don't know what pscp.exe
is and don't know where it is, you can always go to putty
official website to download it. And then open a CMD prompt, go to the pscp.exe directory where you put it. Then execute the command as provided above
I was using corporate VPN connection. It was the reason why I couldn't send email from my application. It works if I disconnect from VPN.
I also tried to work with an SQL-IN-like thing - querying against an Entity Data Model. My approach is a string builder to compose a big OR-expression. That's terribly ugly, but I'm afraid it's the only way to go right now.
Now well, that looks like this:
Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
while(productIds.Count > 0)
{
sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
entities.Products.Name, productIds.Dequeue());
}
}
Working with GUIDs in this context: As you can see above, there is always the word "GUID" before the GUID ifself in the query string fragments. If you don't add this, ObjectQuery<T>.Where
throws the following exception:
The argument types 'Edm.Guid' and 'Edm.String' are incompatible for this operation., near equals expression, line 6, column 14.
Found this in MSDN Forums, might be helpful to have in mind.
Matthias
... looking forward for the next version of .NET and Entity Framework, when everything get's better. :)
Try escaping the single quote with a single quote:
Replace(@strip, '''', '')
The Distinct()
is going to mess up the ordering, so you'll have to the sorting after that.
var uniqueColors =
(from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name).Distinct().OrderBy(name=>name);
You could have searched just for whereIn
function in the core to see that. Here you are. This must answer all your questions
/**
* Add a "where in" clause to the query.
*
* @param string $column
* @param mixed $values
* @param string $boolean
* @param bool $not
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
$type = $not ? 'NotIn' : 'In';
// If the value of the where in clause is actually a Closure, we will assume that
// the developer is using a full sub-select for this "in" statement, and will
// execute those Closures, then we can re-construct the entire sub-selects.
if ($values instanceof Closure)
{
return $this->whereInSub($column, $values, $boolean, $not);
}
$this->wheres[] = compact('type', 'column', 'values', 'boolean');
$this->bindings = array_merge($this->bindings, $values);
return $this;
}
Look that it has a third boolean param. Good luck.
in case you need to use a bool param, you need just to assign the default value.
func test(WithFlag flag: Bool = false){.....}
then you can use without or with the param:
test() //here flag automatically has the default value: false
test(WithFlag: true) //here flag has the value: true
Find list of Nearby Bluetooth Devices:
Find Screenshot for the same.
MainActivity.java:
public class MainActivity extends ActionBarActivity {
private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
@Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
listView.setAdapter(new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
}
};
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bluetoothdemo.MainActivity" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"/>
</RelativeLayout>
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Note:
Please make sure that you ask Location permission to your user and turn GPS On.
Reason: From Android 6.0 you need Location permission for Bluetooth Discovery.
More reference:
Done
I'd just use zip
:
In [1]: from pandas import *
In [2]: def calculate(x):
...: return x*2, x*3
...:
In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
In [4]: df
Out[4]:
a b
0 1 2
1 2 3
2 3 4
In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
In [6]: df
Out[6]:
a b A1 A2
0 1 2 2 3
1 2 3 4 6
2 3 4 6 9
If you've checked all the things from the above answers (which are common mistakes) and you're sure that your view is at the location in the exceptions, then you may need to restart Visual Studio.
:(
I have used these convenience methods before:
- (CGRect)getScreenFrameForCurrentOrientation {
return [self getScreenFrameForOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
- (CGRect)getScreenFrameForOrientation:(UIInterfaceOrientation)orientation {
CGRect fullScreenRect = [[UIScreen mainScreen] bounds];
// implicitly in Portrait orientation.
if (UIInterfaceOrientationIsLandscape(orientation)) {
CGRect temp = CGRectZero;
temp.size.width = fullScreenRect.size.height;
temp.size.height = fullScreenRect.size.width;
fullScreenRect = temp;
}
if (![[UIApplication sharedApplication] statusBarHidden]) {
CGFloat statusBarHeight = 20; // Needs a better solution, FYI statusBarFrame reports wrong in some cases..
fullScreenRect.size.height -= statusBarHeight;
}
return fullScreenRect;
}
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
I ran into this very problem trying to send mail with javax.mail from a web application in a web server running Java 7. Internal mail server destinations failed with "network unreachable", despite telnet and ping working from the same host, and while external mail servers worked. I tried
System.setProperty("java.net.preferIPv4Stack" , "true");
in the code, but that failed. So the parameter value was probably cached earlier by the system. Setting the VM argument
-Djava.net.preferIPv4Stack=true
in the web server startup script worked.
One further bit of evidence: in a very small targeted test program, setting the system property in the code did work. So the parameter is probably cached when the first Socket is used, probably not just as the JVM starts.
Looks to me like you are not dealing properly with your Initialization Vector (IV). It's been a long time since I last read about AES, IVs and block chaining, but your line
IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
does not seem to be OK. In the case of AES, you can think of the initialization vector as the "initial state" of a cipher instance, and this state is a bit of information that you can not get from your key but from the actual computation of the encrypting cipher. (One could argue that if the IV could be extracted from the key, then it would be of no use, as the key is already given to the cipher instance during its init phase).
Therefore, you should get the IV as a byte[] from the cipher instance at the end of your encryption
cipherOutputStream.close();
byte[] iv = encryptCipher.getIV();
and you should initialize your Cipher
in DECRYPT_MODE
with this byte[] :
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Then, your decryption should be OK. Hope this helps.
According to the HTML specification you can't access the elements of the Canvas. You can get its context, and draw in it manipulate it, but that is all.
BUT, you can put both the Canvas and the html element in the same div with a aposition: relative
and then set the canvas and the other element to position: absolute
.
This ways they will be on the top of each other. Then you can use the left
and right
CSS properties to position the html element.
If the element doesn't shows up, maybe the canvas is before it, so use the z-index
CSS property to bring it before the canvas.
You're looking for dir to return the directory contents.
To loop over the results, you can simply do the following:
dirlist = dir('.');
for i = 1:length(dirlist)
dirlist(i)
end
This should give you output in the following format, e.g.:
name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []
It seems to be a known issue. You can instruct m2e to ignore this.
Option 1: pom.xml
Add the following inside your <build/>
tag:
<pluginManagement>
<plugins>
<!-- Ignore/Execute plugin execution -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<!-- copy-dependency plugin -->
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[1.0.0,)</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins></pluginManagement>
You will need to do Maven... -> Update Project Configuration on your project after this.
Read more: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#m2e_maven_plugin_coverage_status
Option 2: Global Eclipse Override
To avoid changing your POM files, the ignore override can be applied to the whole workspace via Eclipse settings.
Save this file somewhere on the disk: https://gist.github.com/maksimov/8906462
In Eclipse/Preferences/Maven/Lifecycle Mappings
browse to this file and click OK:
According to this SO link you can print a specific div with
w=window.open();
w.document.write(document.getElementsByClassName('report_left_inner')[0].innerH??TML);
w.print();
w.close();
For some reason IntelliJ (at least in version 2019.1.2) ignores dependencies in local .m2
directory. None of above solutions worked for me. The only thing finally forced IntelliJ to discover local dependencies was:
pom.xml
(not on a project directory)Open as Project
Delete Existing Project and Import
To make sure you get the call backs after the user enters text, set the delegate inside the configuration handler. textField.delegate = self
Swift 3 & 4 (iOS 10 - 11):
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
textField.placeholder = "Enter text:"
textField.isSecureTextEntry = true // for password input
})
self.present(alert, animated: true, completion: nil)
In Swift (iOS 8-10):
override func viewDidAppear(animated: Bool) {
var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Enter text:"
textField.secureTextEntry = true
})
self.presentViewController(alert, animated: true, completion: nil)
}
In Objective-C (iOS 8):
- (void) viewDidLoad
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Click" style:UIAlertActionStyleDefault handler:nil]];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Enter text:";
textField.secureTextEntry = YES;
}];
[self presentViewController:alert animated:YES completion:nil];
}
FOR iOS 5-7:
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
NOTE: Below doesn't work with iOS 7 (iOS 4 - 6 Works)
Just to add another version.
- (void)viewDidLoad{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Preset Saving..." message:@"Describe the Preset\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
UITextField *textField = [[UITextField alloc] init];
[textField setBackgroundColor:[UIColor whiteColor]];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleLine;
textField.frame = CGRectMake(15, 75, 255, 30);
textField.placeholder = @"Preset Name";
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
[textField becomeFirstResponder];
[alert addSubview:textField];
}
then I call [alert show];
when I want it.
The method that goes along
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString* detailString = textField.text;
NSLog(@"String is: %@", detailString); //Put it on the debugger
if ([textField.text length] <= 0 || buttonIndex == 0){
return; //If cancel or 0 length string the string doesn't matter
}
if (buttonIndex == 1) {
...
}
}
I'll add a couple of index types
BITMAP - when you have very low number of different possible values, very fast and doesn't take up much space
PARTITIONED - allows the index to be partitioned based on some property usually advantageous on very large database objects for storage or performance reasons.
FUNCTION/EXPRESSION indexes - used to pre-calculate some value based on the table and store it in the index, a very simple example might be an index based on lower() or a substring function.
git pull origin master --allow-unrelated-histories
You might want to use this if your histories doesnt match and want to merge it anyway..
refer here
At first, you need to add :
after the IP address to indicate the path is following:
scp magento.tar.gz [email protected]:/var/www
I don't think you need to sudo
the scp
. In this case it doesn't affect the remote machine, only the local command.
Then if your user
@xx.x.x.xx doesn't have write access to /var/www
then you need to do it in 2 times:
Copy to remote server in your home folder (:
represents your remote home folder, use :subfolder/
if needed, or :/home/user/
for full path):
scp magento.tar.gz [email protected]:
Then SSH and move the file:
ssh [email protected]
sudo mv magento.tar.gz /var/www
You can try Context.getApplicationInfo().dataDir
if you want the package's persistent data folder.
getFilesDir()
returns a subroot of this.
i was looking for the same and found the answer,
solution is to use the styled map, on below link you can create your custom styles through wizard and test is at the same time google map style wizard
you can check all available options : here
here is my sample code which creates boundary for states and hide all the road and there labels.
var styles = [
{
"featureType": "administrative.province",
"elementType": "geometry.stroke",
"stylers": [
{ "visibility": "on" },
{ "weight": 2.5 },
{ "color": "#24b0e2" }
]
},{
"featureType": "road",
"elementType": "geometry",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "administrative.locality",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "road",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
];
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': "rajasthan"
}, (results, status)=> {
var mapOpts = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
scrollwheel: false,
styles:styles,
center: results[0].geometry.location,
zoom:6
}
map = new google.maps.Map(document.getElementById("map"), mapOpts);
});
without much ado:
this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
parameter '..' makes navigation one level up, i.e. parent :)
For python 3.6
class SomeClass:
def attr_list(self, should_print=False):
items = self.__dict__.items()
if should_print:
[print(f"attribute: {k} value: {v}") for k, v in items]
return items
Also note that if your using the git flow system and your feature branch might be called
feature/mobile_additions
and with a git remote called stagingtwo, then the command to push to heroku would be
git push stagingtwo feature/mobile_additions:master
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "A");
multimap.put(1, "B");
multimap.put(1, "C");
multimap.put(1, "A");
multimap.put(2, "A");
multimap.put(2, "B");
multimap.put(2, "C");
multimap.put(3, "A");
System.out.println(multimap.get(1));
System.out.println(multimap.get(2));
System.out.println(multimap.get(3));
Output is:
[A,B,C,A]
[A,B,C]
[A]
Note: we need to import library files.
http://www.java2s.com/Code/Jar/g/Downloadgooglecollectionsjar.htm
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
or https://commons.apache.org/proper/commons-collections/download_collections.cgi
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;
If you can add another wrapping div "block3" you could do something like this.
<html>
<head>
<style type="text/css">
.block1 {color:red;width:120px;border:1px solid green; height: 100px;}
.block3 {float:left; width:10px;}
.block2 {color:blue;width:70px;border:2px solid black;position:relative;float:right;}
</style>
</head>
<body>
<div class='block1'>
<div class='block3'>
<p>text1</p>
<p>text2</p>
</div>
<div class='block2'>block2</DIV>
</div>
</body>
</html>
In Java 8 you can do it like this:
import java.util.*;
import java.util.stream.*;
List<JsonNode> datasets = StreamSupport
.stream(datasets.get("datasets").spliterator(), false)
.collect(Collectors.toList())
numba
module for speed up.On big datasets (500k >
) pd.cut
can be quite slow for binning data.
I wrote my own function in numba
with just in time compilation, which is roughly 16x
faster:
from numba import njit
@njit
def cut(arr):
bins = np.empty(arr.shape[0])
for idx, x in enumerate(arr):
if (x >= 0) & (x < 1):
bins[idx] = 1
elif (x >= 1) & (x < 5):
bins[idx] = 2
elif (x >= 5) & (x < 10):
bins[idx] = 3
elif (x >= 10) & (x < 25):
bins[idx] = 4
elif (x >= 25) & (x < 50):
bins[idx] = 5
elif (x >= 50) & (x < 100):
bins[idx] = 6
else:
bins[idx] = 7
return bins
cut(df['percentage'].to_numpy())
# array([5., 5., 7., 5.])
Optional: you can also map it to bins as strings:
a = cut(df['percentage'].to_numpy())
conversion_dict = {1: 'bin1',
2: 'bin2',
3: 'bin3',
4: 'bin4',
5: 'bin5',
6: 'bin6',
7: 'bin7'}
bins = list(map(conversion_dict.get, a))
# ['bin5', 'bin5', 'bin7', 'bin5']
Speed comparison:
# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)
dfbig.shape
# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())
# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)
# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
hive> show partitions table_name;
See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).
BEGIN RSA PRIVATE KEY
is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY
is PKCS#8 and indicates that the key type is included in the key data itself. From the link:
The unencrypted PKCS#8 encoded data starts and ends with the tags:
-----BEGIN PRIVATE KEY----- BASE64 ENCODED DATA -----END PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
PrivateKeyInfo ::= SEQUENCE { version Version, algorithm AlgorithmIdentifier, PrivateKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL }
So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.
As opposed to BEGIN RSA PRIVATE KEY
, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY
is PKCS#1
:
RSA Private Key file (PKCS#1)
The RSA private key PEM file is specific for RSA keys.
It starts and ends with the tags:
-----BEGIN RSA PRIVATE KEY----- BASE64 ENCODED DATA -----END RSA PRIVATE KEY-----
Within the base64 encoded data the following DER structure is present:
RSAPrivateKey ::= SEQUENCE { version Version, modulus INTEGER, -- n publicExponent INTEGER, -- e privateExponent INTEGER, -- d prime1 INTEGER, -- p prime2 INTEGER, -- q exponent1 INTEGER, -- d mod (p-1) exponent2 INTEGER, -- d mod (q-1) coefficient INTEGER, -- (inverse of q) mod p otherPrimeInfos OtherPrimeInfos OPTIONAL }
Use a DecimalFormatter:
double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));
Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.
Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).
The easiest way to do this is writing a copy constructor in the MyClass class.
Something like this:
namespace Example
{
class MyClass
{
public int val;
public MyClass()
{
}
public MyClass(MyClass other)
{
val = other.val;
}
}
}
The second constructor simply accepts a parameter of his own type (the one you want to copy) and creates a new object assigned with the same value
class Program
{
static void Main(string[] args)
{
MyClass objectA = new MyClass();
MyClass objectB = new MyClass(objectA);
objectA.val = 10;
objectB.val = 20;
Console.WriteLine("objectA.val = {0}", objectA.val);
Console.WriteLine("objectB.val = {0}", objectB.val);
Console.ReadKey();
}
}
output:
objectA.val = 10
objectB.val = 20
It happened to me using pip package, then I solved it like below:
1) First of all uninstall pip using python command
$python -m pip uninstall pip
2) Then reinstall pip package using easy_install command
$easy_install pip
3) Finally, try again pip command on command line directly, install any package
$pip install pylint
or only execute pip command
$pip
Regarding this part:
When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.
The easiest solution is to avoid the problem entirely by properly configuring Notepad++.
Try Settings
-> Preferences
-> New document
-> Encoding
-> choose UTF-8
without BOM, and check Apply to opened ANSI files
.
That way all the opened ANSI files will be treated as UTF-8 without BOM.
For explanation what's going on, read the comments below this answer.
To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.
FYI according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta global attributes are valid which means the id
attribute can be used with getElementById
.
There are many ways to speed up Android Studio.
Speed up gradle build time.
1.Go to Project gradle.properties file and remove comment from both line.
2.copy gradle.properties file to your .gradle folder so that you don't need to setup for every project.
Enable Work Offline so that Android studio/Gradle don't need to check for newer file over internet every time.
A very simple way is to add the image as a background to a DIV then load an empty transparent gif set to the same size as the DIV in the foreground. that keeps the less determined out. They cant get the background without viewing the code and copying the URL and right clicking just downloads the transparent gif.
Map
is an interface; HashMap
is a particular implementation of that interface.
HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.
you can test this:
let newString = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:
select
A.*
from
table_A A
inner join table_B B
on A.id = B.id
where
B.tag = 'chair'
That WHERE clause I would like to be:
WHERE B.tag = A.<col_name>
or, in my specific case:
WHERE B.val BETWEEN A.val1 AND A.val2
More detailed:
Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.
In pom.xml make sure packaging is set to war
like <packaging>war</packaging>
,not to jar or any thing else.
This is a simple question but the answer is surprisingly complex. The short answer is you can do what you're trying to do with std::bind1st
or boost::bind
. The longer answer is below.
The compiler is correct to suggest you use &CLoggersInfra::RedundencyManagerCallBack
. First, if RedundencyManagerCallBack
is a member function, the function itself doesn't belong to any particular instance of the class CLoggersInfra
. It belongs to the class itself. If you've ever called a static class function before, you may have noticed you use the same SomeClass::SomeMemberFunction
syntax. Since the function itself is 'static' in the sense that it belongs to the class rather than a particular instance, you use the same syntax. The '&' is necessary because technically speaking you don't pass functions directly -- functions are not real objects in C++. Instead you're technically passing the memory address for the function, that is, a pointer to where the function's instructions begin in memory. The consequence is the same though, you're effectively 'passing a function' as a parameter.
But that's only half the problem in this instance. As I said, RedundencyManagerCallBack
the function doesn't 'belong' to any particular instance. But it sounds like you want to pass it as a callback with a particular instance in mind. To understand how to do this you need to understand what member functions really are: regular not-defined-in-any-class functions with an extra hidden parameter.
For example:
class A {
public:
A() : data(0) {}
void foo(int addToData) { this->data += addToData; }
int data;
};
...
A an_a_object;
an_a_object.foo(5);
A::foo(&an_a_object, 5); // This is the same as the line above!
std::cout << an_a_object.data; // Prints 10!
How many parameters does A::foo
take? Normally we would say 1. But under the hood, foo really takes 2. Looking at A::foo's definition, it needs a specific instance of A in order for the 'this' pointer to be meaningful (the compiler needs to know what 'this' is). The way you usually specify what you want 'this' to be is through the syntax MyObject.MyMemberFunction()
. But this is just syntactic sugar for passing the address of MyObject
as the first parameter to MyMemberFunction
. Similarly, when we declare member functions inside class definitions we don't put 'this' in the parameter list, but this is just a gift from the language designers to save typing. Instead you have to specify that a member function is static to opt out of it automatically getting the extra 'this' parameter. If the C++ compiler translated the above example to C code (the original C++ compiler actually worked that way), it would probably write something like this:
struct A {
int data;
};
void a_init(A* to_init)
{
to_init->data = 0;
}
void a_foo(A* this, int addToData)
{
this->data += addToData;
}
...
A an_a_object;
a_init(0); // Before constructor call was implicit
a_foo(&an_a_object, 5); // Used to be an_a_object.foo(5);
Returning to your example, there is now an obvious problem. 'Init' wants a pointer to a function that takes one parameter. But &CLoggersInfra::RedundencyManagerCallBack
is a pointer to a function that takes two parameters, it's normal parameter and the secret 'this' parameter. That's why you're still getting a compiler error (as a side note: If you've ever used Python, this kind of confusion is why a 'self' parameter is required for all member functions).
The verbose way to handle this is to create a special object that holds a pointer to the instance you want and has a member function called something like 'run' or 'execute' (or overloads the '()' operator) that takes the parameters for the member function, and simply calls the member function with those parameters on the stored instance. But this would require you to change 'Init' to take your special object rather than a raw function pointer, and it sounds like Init is someone else's code. And making a special class for every time this problem comes up will lead to code bloat.
So now, finally, the good solution, boost::bind
and boost::function
, the documentation for each you can find here:
boost::bind docs, boost::function docs
boost::bind
will let you take a function, and a parameter to that function, and make a new function where that parameter is 'locked' in place. So if I have a function that adds two integers, I can use boost::bind
to make a new function where one of the parameters is locked to say 5. This new function will only take one integer parameter, and will always add 5 specifically to it. Using this technique, you can 'lock in' the hidden 'this' parameter to be a particular class instance, and generate a new function that only takes one parameter, just like you want (note that the hidden parameter is always the first parameter, and the normal parameters come in order after it). Look at the boost::bind
docs for examples, they even specifically discuss using it for member functions. Technically there is a standard function called [std::bind1st][3]
that you could use as well, but boost::bind
is more general.
Of course, there's just one more catch. boost::bind
will make a nice boost::function for you, but this is still technically not a raw function pointer like Init probably wants. Thankfully, boost provides a way to convert boost::function's to raw pointers, as documented on StackOverflow here. How it implements this is beyond the scope of this answer, though it's interesting too.
Don't worry if this seems ludicrously hard -- your question intersects several of C++'s darker corners, and boost::bind
is incredibly useful once you learn it.
C++11 update: Instead of boost::bind
you can now use a lambda function that captures 'this'. This is basically having the compiler generate the same thing for you.