In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:
mtcars[, -which(names(mtcars) == "carb")] #only works on a single column
mtcars[, names(mtcars) != "carb"] #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")]
mtcars[, -match(c("carb", "mpg"), names(mtcars))]
mtcars2 <- mtcars; mtcars2$hp <- NULL #lost column (risky)
library(gdata)
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE)
Generally I use:
mtcars[, !names(mtcars) %in% c("carb", "mpg")]
because I feel it's safe and efficient.
Here is another alternative that I insert at top of the Python files in tests
folder:
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:
y = [s for s in x if len(s) == 2]
try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.
The terms resource and endpoint are often used synonymously. But in fact they do not mean the same thing.
The term endpoint is focused on the URL that is used to make a request.
The term resource is focused on the data set that is returned by a request.
Now, the same resource can often be accessed by multiple different endpoints.
Also the same endpoint can return different resources, depending on a query string.
Let us see some examples:
Have a look at the following examples of different endpoints:
/api/companies/5/employees/3
/api/v2/companies/5/employees/3
/api/employees/3
They obviously could all access the very same resource in a given API.
Also an existing API could be changed completely. This could lead to new endpoints that would access the same old resources using totally new and different URLs:
/api/employees/3
/new_api/staff/3
If your endpoint returns a collection, you could implement searching/filtering/sorting using query strings. As a result the following URLs all use the same endpoint (/api/companies
), but they can return different resources (or resource collections, which by definition are resources in themselves):
/api/companies
/api/companies?sort=name_asc
/api/companies?location=germany
/api/companies?search=siemens
You can pass a mutable container datatype into a function, and it can contain anything you want.
If you need a different functionality, name the functions differently, or if you need the same interface, just write an interface function (or method) that calls the functions appropriately based on the data received.
It took a while to me to get adjusted to this coming from Java, but it really isn't a "big handicap".
You can use the DATE_ADD()
function:
... WHERE DATE(DATE_ADD(eventdate, INTERVAL -1 DAY)) = CURRENT_DATE
It can also be used in the SELECT
statement:
SELECT DATE_ADD('2010-05-11', INTERVAL 1 DAY) AS Tomorrow;
+------------+
| Tomorrow |
+------------+
| 2010-05-12 |
+------------+
1 row in set (0.00 sec)
This is the default working setup https://www.youtube.com/watch?v=XiD7JTCBdpI
Use Connection Method: standard TCP/IP over ssh
Then ssh hostname: 127.0.0.1:2222
SSH Username: vagrant password vagrant
MySQL Hostname: localhost
Username: homestead password:secret
This is my solution, alhamdulillah it worked.
Reference: https://docs.microsoft.com/en-US/troubleshoot/iis/http-error-405-website
Per the Javadoc:
Returns the value of a request parameter as a String, or null if the parameter does not exist.
Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse
into the URL to enable logging, without needing to specify &log=true
. In this case, the value will be an empty String (""
).
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
I can't remember where I came across this script, but I've been using it with XCloner to move my WP multisites.
<?php
// Setup the associative array for replacing the old string with new string
$replace_array = array( 'FIND' => 'REPLACE', 'FIND' => 'REPLACE');
$mysql_link = mysql_connect( 'localhost', 'USERNAME', 'PASSWORD' );
if( ! $mysql_link) {
die( 'Could not connect: ' . mysql_error() );
}
$mysql_db = mysql_select_db( 'DATABASE', $mysql_link );
if(! $mysql_db ) {
die( 'Can\'t select database: ' . mysql_error() );
}
// Traverse all tables
$tables_query = 'SHOW TABLES';
$tables_result = mysql_query( $tables_query );
while( $tables_rows = mysql_fetch_row( $tables_result ) ) {
foreach( $tables_rows as $table ) {
// Traverse all columns
$columns_query = 'SHOW COLUMNS FROM ' . $table;
$columns_result = mysql_query( $columns_query );
while( $columns_row = mysql_fetch_assoc( $columns_result ) ) {
$column = $columns_row['Field'];
$type = $columns_row['Type'];
// Process only text-based columns
if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
// Process all replacements for the specific column
foreach( $replace_array as $old_string => $new_string ) {
$replace_query = 'UPDATE ' . $table .
' SET ' . $column . ' = REPLACE(' . $column .
', \'' . $old_string . '\', \'' . $new_string . '\')';
mysql_query( $replace_query );
}
}
}
}
}
mysql_free_result( $columns_result );
mysql_free_result( $tables_result );
mysql_close( $mysql_link );
echo 'Done!';
?>
grep
For non-greedy match in grep
you could use a negated character class. In other words, try to avoid wildcards.
For example, to fetch all links to jpeg files from the page content, you'd use:
grep -o '"[^" ]\+.jpg"'
To deal with multiple line, pipe the input through xargs
first. For performance, use ripgrep
.
See this picture. :)
import --> const --> var --> init()
If a package imports other packages, the imported packages are initialized first.
Current package's constant initialized then.
Current package's variables are initialized then.
Finally, init()
function of current package is called.
A package can have multiple init functions (either in a single file or distributed across multiple files) and they are called in the order in which they are presented to the compiler.
A package will be initialised only once even if it is imported from multiple packages.
It's pretty simple, take a look at the code below:
The form:
<form action="result.php" method="post">
Answer 1 <input type="radio" name="ans" value="ans1" /><br />
Answer 2 <input type="radio" name="ans" value="ans2" /><br />
Answer 3 <input type="radio" name="ans" value="ans3" /><br />
Answer 4 <input type="radio" name="ans" value="ans4" /><br />
<input type="submit" value="submit" />
</form>
PHP code:
<?php
$answer = $_POST['ans'];
if ($answer == "ans1") {
echo 'Correct';
}
else {
echo 'Incorrect';
}
?>
There is a php library (pdfparser) that does exactly what you want.
project website
github
https://github.com/smalot/pdfparser
Demo page/api
After including pdfparser in your project you can get all text from mypdf.pdf
like so:
<?php
$parser = new \installpath\PdfParser\Parser();
$pdf = $parser->parseFile('mypdf.pdf');
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf
?>
Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).
Have a look at these methods:
byte [] StructureToByteArray(object obj)
{
int len = Marshal.SizeOf(obj);
byte [] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
void ByteArrayToStructure(byte [] bytearray, ref object obj)
{
int len = Marshal.SizeOf(obj);
IntPtr i = Marshal.AllocHGlobal(len);
Marshal.Copy(bytearray,0, i,len);
obj = Marshal.PtrToStructure(i, obj.GetType());
Marshal.FreeHGlobal(i);
}
This is a shameless copy of another thread which I found upon Googling!
Update : For more details, check the source
It's entirely possible in browser-side javascript.
The easy way:
The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,
), but that's no biggie. This would take all the fun out though.
The hard way:
If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer()
. This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.
There are two methods:
btoa
or similar
I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.
What I do now:
The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):
function uint8ToString(buf) {
var i, length, out = '';
for (i = 0, length = buf.length; i < length; i += 1) {
out += String.fromCharCode(buf[i]);
}
return out;
}
From there, just do:
var base64 = btoa(uint8ToString(yourUint8Array));
Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:
window.open("data:application/octet-stream;base64," + base64);
This will download it as a file.
Other info:
To get the data as a Uint8Array, look at the MDN docs:
If you are looking for a particular type of element that is further away than the immediate parent, you can use a function that goes up the DOM until it finds one, or doesn't:
// Find first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
Only need to set it to
DateTime.Now.Date
Console.WriteLine(DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Console.Read();
It shows
"2017-04-08 00:00:00"
on my machine.
LATEST UPDATE: Please ignore the function below, @SurasinTancharoen managed to alert me that it is broken at n = 53
.
For those who are interested, here are other broken values just below n = 200
:
END OF UPDATE
The function below is provided by Microsoft:
Function ConvertToLetter(iCol As Integer) As String
Dim iAlpha As Integer
Dim iRemainder As Integer
iAlpha = Int(iCol / 27)
iRemainder = iCol - (iAlpha * 26)
If iAlpha > 0 Then
ConvertToLetter = Chr(iAlpha + 64)
End If
If iRemainder > 0 Then
ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
End If
End Function
Source: How to convert Excel column numbers into alphabetical characters
APPLIES TO
Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.
EDIT
In This example, all you need to do is add this line:
gallery.setSelection(1);
after setting the adapter to gallery object, that is this line:
gallery.setAdapter(new ImageAdapter(this));
UPDATE1
Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.
UPDATE2:
I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.
findByInventoryIdIn(List<Long> inventoryIdList)
should do the trick.
The HTTP request parameter format would be like so:
Yes ?id=1,2,3
No ?id=1&id=2&id=3
The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn
is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn
and IsNotIn
.
Install ejs if it is not.
npm install ejs
Then after just paste below two lines in your main file. (like app.js, main.js)
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
What even is ‘children’?
The React docs say that you can use
props.children
on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.My simple explanation of what
this.props.children
does is that it is used to display whatever you include between the opening and closing tags when invoking a component.A simple example:
Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no
this
keyword so just useprops.children
const Picture = (props) => {
return (
<div>
<img src={props.src}/>
{props.children}
</div>
)
}
This component contains an
<img>
that is receiving someprops
and then it is displaying{props.children}
.Whenever this component is invoked
{props.children}
will also be displayed and this is just a reference to what is between the opening and closing tags of the component.
//App.js
render () {
return (
<div className='container'>
<Picture key={picture.id} src={picture.src}>
//what is placed here is passed as props.children
</Picture>
</div>
)
}
Instead of invoking the component with a self-closing tag
<Picture />
if you invoke it will full opening and closing tags<Picture> </Picture>
you can then place more code between it.This de-couples the
<Picture>
component from its content and makes it more reusable.
Reference: A quick intro to React’s props.children
Use tolist()
:
import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]
Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)
You should use formControlName="surveyType"
on an input
and not on a div
I was also disappointed by the lack of type a function can throw, but I get it now thanks to @rickster and I'll summarize it like this: let's say we could specify the type a function throws, we would have something like this:
enum MyError: ErrorType { case ErrorA, ErrorB }
func myFunctionThatThrows() throws MyError { ...throw .ErrorA...throw .ErrorB... }
do {
try myFunctionThatThrows()
}
case .ErrorA { ... }
case .ErrorB { ... }
The problem is that even if we don't change anything in myFunctionThatThrows, if we just add an error case to MyError:
enum MyError: ErrorType { case ErrorA, ErrorB, ErrorC }
we are screwed because our do/try/catch is no longer exhaustive, as well as any other place where we called functions that throw MyError
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
Try =index(ARRAY, ROW, COLUMN)
where: Array: select the whole sheet Row, Column: Your row and column references
That should be easier to understand to those looking at the formula.
If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html
If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/
Jon's disassemblies show, that the difference between the two versions is that the fast version uses a pair of registers (esi,edi
) to store one of the local variables where the slow version doesn't.
The JIT compiler makes different assumptions regarding register use for code that contains a try-catch block vs. code which doesn't. This causes it to make different register allocation choices. In this case, this favors the code with the try-catch block. Different code may lead to the opposite effect, so I would not count this as a general-purpose speed-up technique.
In the end, it's very hard to tell which code will end up running the fastest. Something like register allocation and the factors that influence it are such low-level implementation details that I don't see how any specific technique could reliably produce faster code.
For example, consider the following two methods. They were adapted from a real-life example:
interface IIndexed { int this[int index] { get; set; } }
struct StructArray : IIndexed {
public int[] Array;
public int this[int index] {
get { return Array[index]; }
set { Array[index] = value; }
}
}
static int Generic<T>(int length, T a, T b) where T : IIndexed {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
static int Specialized(int length, StructArray a, StructArray b) {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
One is a generic version of the other. Replacing the generic type with StructArray
would make the methods identical. Because StructArray
is a value type, it gets its own compiled version of the generic method. Yet the actual running time is significantly longer than the specialized method's, but only for x86. For x64, the timings are pretty much identical. In other cases, I've observed differences for x64 as well.
The most rank answer in this post work, however its is CSV file. It is not actual Excel file. Therefore, you will get a warning when you are opening a file.
The best solution I found on the web is using CloseXML https://github.com/closedxml/closedxml You need to Open XML as well.
dt = city.GetAllCity();//your datatable
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
I created .pfx file from .key and .pem files.
Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx
That's not the direct answer but still maybe it helps out someone else.
I know this an old question but I just wanted to add if you would like to easily change the height of a UITextField from inside IB then simply change that UITextfield's border type to anything other than the default rounded corner type. Then you can stretch or change height attributes easily from inside the editor.
class Clock {
String time;
void setTime (String t) {
time = t;
}
String getTime() {
return time;
}
}
class ClockTestDrive {
public static void main (String [] args) {
Clock c = new Clock;
c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod);
}
}
When you run the program, program starts in mains,
setTime()
is called by the object c time
is set to the value passed by getTime()
is called by object ctod
and tod
get printed out If your using the RichFaces library you can also use the tag rich:spacer which will add an "invisible" image with a given length and height. Usually much easier and prettier than to add tons of nbsp;.
Where you want your space to show you simply add:
<rich:spacer height="1" width="2" />
The solution is pretty easy actually:
<button style="border:1px solid black; background-color: transparent;">Test</button>
This is doing an inline style. You're defining the border to be 1px, solid line, and black in color. The background color is then set to transparent.
UPDATE
Seems like your ACTUAL question is how do you prevent the border after clicking on it. That can be resolved with a CSS pseudo selector: :active
.
button {
border: none;
background-color: transparent;
outline: none;
}
button:focus {
border: none;
}
You don't need the date
validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA
validator, which uses dd/mm/yyyy format as you need.
Just like the date
validator, your code for dateGreaterThan
and dateLessThan
calls new Date
for input string and has the same issue parsing dates. You can use a function like this to parse the date:
function parseDMY(value) {
var date = value.split("/");
var d = parseInt(date[0], 10),
m = parseInt(date[1], 10),
y = parseInt(date[2], 10);
return new Date(y, m - 1, d);
}
You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.
<input type="text" name="idtest" value="<?php echo $idtest; ?>" >
Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.
In the meantime (since version 3.2, in the year 2013, thanks to SEC-2298) the authentication can be injected into MVC methods using the annotation @AuthenticationPrincipal:
@Controller
class Controller {
@RequestMapping("/somewhere")
public void doStuff(@AuthenticationPrincipal UserDetails myUser) {
}
}
In your unit test you can obviously call this Method directly. In integration tests using org.springframework.test.web.servlet.MockMvc
you can use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user()
to inject the user like this:
mockMvc.perform(get("/somewhere").with(user(myUserDetails)));
This will however just directly fill the SecurityContext. If you want to make sure that the user is loaded from a session in your test, you can use this:
mockMvc.perform(get("/somewhere").with(sessionUser(myUserDetails)));
/* ... */
private static RequestPostProcessor sessionUser(final UserDetails userDetails) {
return new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(final MockHttpServletRequest request) {
final SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())
);
request.getSession().setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext
);
return request;
}
};
}
This worked for me:
SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;
There's no ALTER COLUMN in sqlite.
I believe your only option is to:
This other Stackoverflow answer explains the process in details
Path changes appear to be persistent if you set the SHELL variable in your makefile first:
SHELL := /bin/bash
PATH := bin:$(PATH)
test all:
x
I don't know if this is desired behavior or not.
This problem can also be solved by selecting first row from each group where the group are the columns based on which we want to select unique values (in the example shared it is just 1st column).
Using base R :
subset(df, ave(V2, V1, FUN = seq_along) == 1)
# V1 V2 V3 V4 V5
#1 platform_external_dbus 202 16 google 1
In dplyr
library(dplyr)
df %>% group_by(V1) %>% slice(1L)
Or using data.table
library(data.table)
setDT(df)[, .SD[1L], by = V1]
If we need to find out unique rows based on multiple columns just add those column names in grouping part for each of the above answer.
data
df <- structure(list(V1 = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = "platform_external_dbus", class = "factor"),
V2 = c(202L, 202L, 202L, 202L, 202L), V3 = c(16L, 16L, 16L,
16L, 16L), V4 = structure(c(1L, 4L, 3L, 5L, 2L), .Label = c("google",
"hughsie", "localhost", "space-ghost.verbum", "users.sourceforge"
), class = "factor"), V5 = c(1L, 1L, 1L, 8L, 1L)), class = "data.frame",
row.names = c(NA, -5L))
Implement division without divison operator: You will need to include subtraction. But then it is just like you do it by hand (only in the basis of 2). The appended code provides a short function that does exactly this.
uint32_t udiv32(uint32_t n, uint32_t d) {
// n is dividend, d is divisor
// store the result in q: q = n / d
uint32_t q = 0;
// as long as the divisor fits into the remainder there is something to do
while (n >= d) {
uint32_t i = 0, d_t = d;
// determine to which power of two the divisor still fits the dividend
//
// i.e.: we intend to subtract the divisor multiplied by powers of two
// which in turn gives us a one in the binary representation
// of the result
while (n >= (d_t << 1) && ++i)
d_t <<= 1;
// set the corresponding bit in the result
q |= 1 << i;
// subtract the multiple of the divisor to be left with the remainder
n -= d_t;
// repeat until the divisor does not fit into the remainder anymore
}
return q;
}
Reviving an old question, but I wanted to post an iteration on @adeneo's answer. That answer is completely general, but for this use case it could be more efficient (it's slow on my machine with an array of a few thousand objects). If you know the specific properties of the objects you need to compare, just compare them directly:
var sl = standardsList;
var out = [];
for (var i = 0, l = sl.length; i < l; i++) {
var unique = true;
for (var j = 0, k = out.length; j < k; j++) {
if ((sl[i].Grade === out[j].Grade) && (sl[i].Domain === out[j].Domain)) {
unique = false;
}
}
if (unique) {
out.push(sl[i]);
}
}
console.log(sl.length); // 10
console.log(out.length); // 5
To elaborate on the other answers provided, this is my solution (placed in an Activity):
@Override
public void onBackPressed(){
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
Applications that require intensive memory access eg. image manipulation are usually better off written in unmanaged environment (C++) than managed (C#). Optimized inner loops with pointer arithmetics are much easier to have control of in C++. In C# you might need to resort to unsafe code to even get near the same performance.
If you prefer to use a class name, by all means use a class name.
className={completed ? 'text-strike' : null}
You may also find the classnames package helpful. With it, your code would look like this:
className={classNames({ 'text-strike': completed })}
There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.
POSTSCRIPT [06-AUG-2019]
Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.
What other folks posted here mainly worked, but using onchange
doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput
. My code (mainly borrowing from MC9000):
HTML
<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">
JS
function setTwoNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(2);
};
Here's a quick and dirty ctypes tutorial.
First, write your C library. Here's a simple Hello world example:
#include <stdio.h>
void myprint(void);
void myprint()
{
printf("hello world\n");
}
Now compile it as a shared library (mac fix found here):
$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c
# or... for Mac OS X
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c
Then, write a wrapper using ctypes:
import ctypes
testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()
Now execute it:
$ python testlibwrapper.py
And you should see the output
Hello world
$
If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib
or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL()
.
This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.
PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6')
. If you're on another OS, things might change a little bit (or quite a lot).
See also here: http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/06/26/fun-with-dbcc-chekident.aspx
This is documented behavior, why do you run CHECKIDENT if you recreate the table, in that case skip the step or use TRUNCATE (if you don't have FK relationships)
I was experiencing the same issue.. I already had 4 controllers going and working just fine but when I added this one it returned "The requested resource does not support HTTP method 'GET'". I tried everything here and in a couple other relevant articles but was indifferent to the solution since, as Dan B. mentioned in response to the answer, I already had others working fine.
I walked away for a while, came back, and immediately realized that when I added the Controller it was nested under the "Controller" class and not "ApiController" class that my other Controllers were under. I'm assuming I chose the wrong scaffolding option to build the .cs file in Visual Studio. So I included the System.Web.Http namespace, changed the parent class, and everything works without the additional attributes or routing.
You could use SQL.js which is the SQLlite lib compiled to JavaScript and store the database in the local storage introduced in HTML5.
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact. This has the following 2 consequences:
Although @ruakh gave a good answer, I will add some alternatives for completeness:
You could in fact use even var Omega = 'Ω'
in JavaScript, but only if your JavaScript code is:
onclick="var Omega = 'Ω';
alert(Omega)"
or script
element inside an XHTML (or XHTML + XML) document
served with an XML content type.In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like Ω
are recognized. The restrictions make this an impractical approach in most cases.
You can also enter the O character as such, as in var Omega = 'O'
, but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.
Using the \u
notation, as in var Omega = '\u03A9'
, works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff
, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)
You can also construct a character using the String.fromCharCode()
method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937)
or in hexadecimal as in var Omega = String.fromCharCode(0x3A9)
. This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.
if you omit the format
attribute from the attr
element, you can use it to reference a class from XML layouts.
Refactor > Rename
worksFind Usages
worksdon't specify a format
attribute in .../src/main/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
....
<attr name="give_me_a_class"/>
....
</declare-styleable>
</resources>
use it in some layout file .../src/main/res/layout/activity__main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<SomeLayout
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- make sure to use $ dollar signs for nested classes -->
<MyCustomView
app:give_me_a_class="class.type.name.Outer$Nested/>
<MyCustomView
app:give_me_a_class="class.type.name.AnotherClass/>
</SomeLayout>
parse the class in your view initialization code .../src/main/java/.../MyCustomView.kt
class MyCustomView(
context:Context,
attrs:AttributeSet)
:View(context,attrs)
{
// parse XML attributes
....
private val giveMeAClass:SomeCustomInterface
init
{
context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
{
try
{
// very important to use the class loader from the passed-in context
giveMeAClass = context::class.java.classLoader!!
.loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
.newInstance() // instantiate using 0-args constructor
.let {it as SomeCustomInterface}
}
finally
{
recycle()
}
}
}
On Controller
$data = ModelName::select('name')->get()->toArray();
return view('viewtemplatename')->with('yourVariableName', $data);
On Blade file
@if(isset($yourVariableName))
//do you work here
@endif
Here's what you can do using font-awesome library.
button.btn.add::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
font-family: fontAwesome;_x000D_
content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
In order to create an array of objects, the objects need a constructor that doesn't take any paramters (that creates a default form of the object, eg. with both strings empty). This is what the error message means. The compiler automatically generates a constructor which creates an empty object unless there are any other constructors.
If it makes sense for the array elements to be created empty (in which case the members acquire their default values, in this case, empty strings), you should:
-Write an empty constructor:
class name {
public:
string first;
string last;
name() { }
name(string a, string b){
first = a;
last = b;
}
};
-Or, if you don't need it, remove the existing constructor.
If an "empty" version of your class makes no sense, there is no good solution to provide initialisation paramters to all the elements of the array at compile time. You can:
init()
function which does the real initialisationvector
, and on initialisation create the objects and insert them into the vector
, either using vector::insert
or a loop, and trust that not doing it at compile time doesn't matter.std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
`
A lock should be considered to use, such as threading.Lock
. See lock-objects for more info.
The accepted answer CAN print 10 by thread1, which is not what you want. You can run the following code to understand the bug more easily.
def thread1(threadname):
while True:
if a % 2 and not a % 2:
print "unreachable."
def thread2(threadname):
global a
while True:
a += 1
Using a lock can forbid changing of a
while reading more than one time:
def thread1(threadname):
while True:
lock_a.acquire()
if a % 2 and not a % 2:
print "unreachable."
lock_a.release()
def thread2(threadname):
global a
while True:
lock_a.acquire()
a += 1
lock_a.release()
If thread using the variable for long time, coping it to a local variable first is a good choice.
With node.js version >= v10.13.0, fs.readdirSync will return an array of fs.Dirent objects if withFileTypes
option is set to true
.
So you can use,
const fs = require('fs')
const directories = source => fs.readdirSync(source, {
withFileTypes: true
}).reduce((a, c) => {
c.isDirectory() && a.push(c.name)
return a
}, [])
For those working in Titanium Studio, the item is a little different: It's under the "Titanium Studio" Themes tab.
The color to change is the "Selection" one in the top right.
# or even faster copy paste answer if you have sudo on the host
sudo su - postgres -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"
Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.
If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.
Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.
The answer depends on the complexity of the algorithms used in the program. I came up with a method to calculate the optimal number of threads by making two measurements of processing times Tn and Tm for two arbitrary number of threads ‘n’ and ‘m’. For linear algorithms, the optimal number of threads will be N = sqrt ( (mn(Tm*(n-1) – Tn*(m-1)))/(nTn-mTm) ) .
Please read my article regarding calculations of the optimal number for various algorithms: pavelkazenin.wordpress.com
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
The solution proposed here worked for me:
Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
val i = Intent(this, NewActivity::class.java)
// set the new task and clear flags
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(i)
However, it requires API level >= 11.
Only set the width
or height
, and it will scale the other automatically. And yes you can use a percentage.
The first part can be done, but requires JavaScript, so might not work for all users.
I prefer this solution:
df = spark.table(selected_table).filter(condition)
counter = df.count()
df = df.select([(counter - count(c)).alias(c) for c in df.columns])
1 additional caveat (besides the answer by kanaka/peter): if you use WSS, and the server certificate is not acceptable to the browser, you may not get any browser rendered dialog (like it happens for Web pages). This is because WebSockets is treated as a so-called "subresource", and certificate accept / security exception / whatever dialogs are not rendered for subresources.
Using Transformer Factory:-
public static String printSoapMessage(final SOAPMessage soapMessage) throws TransformerFactoryConfigurationError,
TransformerConfigurationException, SOAPException, TransformerException
{
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
// Format it
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
final Source soapContent = soapMessage.getSOAPPart().getContent();
final ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
final StreamResult result = new StreamResult(streamOut);
transformer.transform(soapContent, result);
return streamOut.toString();
}
Make sure to put:
imageView.translatesAutoresizingMaskIntoConstraints = false
Your image view will not show if you don't put that, don't ask me why.
Another way to add a default namespace to an XML Document before feeding it to JAXB is to use JDom:
Like this:
public class XMLObjectFactory {
private static Namespace DEFAULT_NS = Namespace.getNamespace("http://tempuri.org/");
public static Object createObject(InputStream in) {
try {
SAXBuilder sb = new SAXBuilder(false);
Document doc = sb.build(in);
setNamespace(doc.getRootElement(), DEFAULT_NS, true);
Source src = new JDOMSource(doc);
JAXBContext context = JAXBContext.newInstance("org.tempuri");
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement root = unmarshaller.unmarshal(src);
return root.getValue();
} catch (Exception e) {
throw new RuntimeException("Failed to create Object", e);
}
}
private static void setNamespace(Element elem, Namespace ns, boolean recurse) {
elem.setNamespace(ns);
if (recurse) {
for (Object o : elem.getChildren()) {
setNamespace((Element) o, ns, recurse);
}
}
}
ExecuteScalar()
is what you need here
why not pull the data directly out of the data source.
DataBinder.Eval(e.Row.DataItem, "ColumnName")
Assuming your json object from your GET request looks like the one you posted above simply do:
let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
Or am I missing something that prevents you from doing it this way?
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:
columns = ['Y'+str(i) for year in range(1967, 2011)]
df.groupby('Country')[columns].agg('sum')
Nobody mentioned the ability to use them in switch
statements; I'll throw that in as well.
This allows arbitrarily complex enums to be used in a clean way without using instanceof
, potentially confusing if
sequences, or non-string/int switching values. The canonical example is a state machine.
git will show changes in commits that affect the index, such as git rm
. It does not store a log of all git commands you execute.
However, a large number of git commands affect the index in some way, such as creating a new branch. These changes will show up in the commit history, which you can view with git log
.
However, there are destructive changes that git can't track, such as git reset
.
So, to answer your question, git does not store an absolute history of git
commands you've executed in a repository. However, it is often possible to interpolate what command you've executed via the commit history.
whoami's answer is the correct one. Using the properties as suggested I was unable to get this to work (using Spring Boot 1.5.3.RELEASE)
I'm adding my answer since it's a complete configuration class so it might help someone using Spring Boot:
@Configuration
@Log4j
public class SwatDataBaseConfig {
@Value("${swat.decrypt.location}")
private String fileLocation;
@Value("${swat.datasource.url}")
private String dbURL;
@Value("${swat.datasource.driver-class-name}")
private String driverName;
@Value("${swat.datasource.username}")
private String userName;
@Value("${swat.datasource.password}")
private String hashedPassword;
@Bean
public DataSource primaryDataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setUrl(dbURL);
poolProperties.setUsername(userName);
poolProperties.setPassword(password);
poolProperties.setDriverClassName(driverName);
poolProperties.setTestOnBorrow(true);
poolProperties.setValidationQuery("SELECT 1");
poolProperties.setValidationInterval(0);
DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
return ds;
}
}
Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?
First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and Ubuntu)
__usage="
Usage: $(basename $0) [OPTIONS]
Options:
-l, --level <n> Something something something level
-n, --nnnnn <levels> Something something something n
-h, --help Something something something help
-v, --version Something something something version
"
Then I can simply use it as
echo "$__usage"
or even better, when parsing parameters, I can just echo it there in a one-liner:
levelN=${2:?"--level: n is required!""${__usage}"}
First, it's always worth noting that git reset --hard
is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status
is clean (that is, empty) before using it.
Initially you say the following:
So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:
That's incorrect. Git only records the state of the files when you stage them (with git add
) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add
to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)
In your question you then go on to ask the following:
When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro
How do I then revert the files on my hard drive back to that previous commit?
If you do git reset --hard <SOME-COMMIT>
then Git will:
master
) back to point at <SOME-COMMIT>
.<SOME-COMMIT>
.HEAD
points to your current branch (or current commit), so all that git reset --hard HEAD
will do is to throw away any uncommitted changes you have.
So, suppose the good commit that you want to go back to is f414f31
. (You can find that via git log
or any history browser.) You then have a few different options depending on exactly what you want to do:
git reset --hard f414f31
. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31
will no longer be in the history of your master
branch.Create a new commit that represents exactly the same state of the project as f414f31
, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:
git reset --hard f414f31
git reset --soft HEAD@{1}
git commit -m "Reverting to the state of the project at f414f31"
It may be worth getting into the habit of using printf
rather then echo
on the command line.
In this example it doesn't give much benefit but it can be more useful with more complex output.
FOO="BAR * BAR"
printf %s "$FOO"
The preferred modern method is to use addEventListener
either by adding the event listener direct to the element or to a parent of the elements (delegated).
An example, using delegated events, might be
var box = document.getElementById('box');_x000D_
_x000D_
document.getElementById('buttons').addEventListener('click', function(evt) {_x000D_
var target = evt.target;_x000D_
if (target.id === 'yes') {_x000D_
box.style.backgroundColor = 'red';_x000D_
} else if (target.id === 'no') {_x000D_
box.style.backgroundColor = 'green';_x000D_
} else {_x000D_
box.style.backgroundColor = 'purple';_x000D_
}_x000D_
}, false);
_x000D_
#box {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background-color: red;_x000D_
}_x000D_
#buttons {_x000D_
margin-top: 50px;_x000D_
}
_x000D_
<div id='box'></div>_x000D_
<div id='buttons'>_x000D_
<button id='yes'>yes</button>_x000D_
<button id='no'>no</button>_x000D_
<p>Click one of the buttons above.</p>_x000D_
</div>
_x000D_
First I did alias setup on bash / zsh profile.
alias composer="php /usr/local/bin/composer.phar"
Then I moved composer.phar to /usr/local/bin/
cd /usr/local/bin
mv composer.phar composer
Then made composer executable by running
sudo chmod +x composer
You may also combine cut
and paste
:
paste <(cut -f2 file.txt) <(cut -f1 file.txt)
via comments: It's possible to avoid bashisms and remove one instance of cut by doing:
paste file.txt file.txt | cut -f2,3
Additionally for what was said, if you want integer powers of two, then 1 << x
(or 1L << x
) is a faster way to calculate 2x than Math.pow(2,x)
or a multiplication loop, and is guaranteed to give you an int
(or long
) result.
It only uses the lowest 5 (or 6) bits of x
(i.e. x & 31
(or x & 63
)), though, shifting between 0 and 31 (or 63) bits.
If you only need the standard functionality of hide only with visibility:hidden to keep the current layout you can use the callback function of hide to alter the css in the tag. Hide docs in jquery
An example :
$('#subs_selection_box').fadeOut('slow', function() {
$(this).css({"visibility":"hidden"});
$(this).css({"display":"block"});
});
This will use the normal cool animation to hide the div, but after the animation finish you set the visibility to hidden and display to block.
An example : http://jsfiddle.net/bTkKG/1/
I know you didnt want the $("#aa").css() solution, but you did not specify if it was because using only the css() method you lose the animation.
For me the issue was because of Case sensitivity. I was using ~{fragments/Base}
instead of ~{fragments/base}
(The name of the file was base.html
)
My development environment was windows but the server hosting the application was Linux so I was not seeing this issue during development since windows' paths are not case sensitive.
This can be simplified by completely skipping the where object and the $users declaration. All you need is:
Code
get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv
You can use following:
angular.element(domElement).scope()
to get the current scope for the element
angular.element(domElement).injector()
to get the current app injector
angular.element(domElement).controller()
to get a hold of the ng-controller instance.
Hope that might help
To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.
Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.
From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:
E:first-child
, E:hover
, E > F
(Child combinator), E + F
(Adjacent sibling combinator), E ~ F
(General sibling combinator). This unfortunately means resorting to workarounds like inline styles.white-space
won't work.background-image
property won't work.height
, width
, and the max-
versions are either not usable or have bugs for certain elements.display
, float
s and position
are all out).In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.
PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top
" where you probably meant to use vertical-align
. Also: cell-padding
for td
s doesn't exist.
sprintf('%.2f', number)
is a cryptic, but very powerful way of formatting numbers. The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf
can format any number almost any way you like, and lots more.
Full sprintf documentation: http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf
Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.
First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.
Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :
xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"
Run notepad as administrator then open extension.vsixmanifest
in the destination directory just created.
Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio
element and change the Version
attribute, as @brainslugs83 said in comments):
<SupportedProducts>
<VisualStudio Version="11.0">
<Edition>VSTS</Edition>
<Edition>VSTD</Edition>
<Edition>Pro</Edition>
<Edition>VCSExpress</Edition>
<Edition>VPDExpress</Edition>
</VisualStudio>
</SupportedProducts>
Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.
You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
This has been tested for Windows Games, but not WP7 or Xbox games.
[Edit] According Jowsty, this works also for XBox 360 Games.
[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.
There are many way you can do this. Those are given bellow:
Suppose your original number is given bellow: double number = 2354548.235;
Using NumberFormat
and Rounding mode
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
DecimalFormat decimalFormatter = (DecimalFormat) nf;
decimalFormatter.applyPattern("#,###,###.##");
decimalFormatter.setRoundingMode(RoundingMode.CEILING);
String fString = decimalFormatter.format(number);
System.out.println(fString);
Using String formatter
System.out.println(String.format("%1$,.2f", number));
In all cases the output will be: 2354548.24
Note:
During rounding you can add RoundingMode
in your formatter. Here are some Rounding mode given bellow:
decimalFormat.setRoundingMode(RoundingMode.CEILING);
decimalFormat.setRoundingMode(RoundingMode.FLOOR);
decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
decimalFormat.setRoundingMode(RoundingMode.UP);
Here are the imports:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
The best way to handle this would be to terminate your infinite loop with a proper condition.
But since you asked for the exception handling:
Try to use two catches. Your EOFException is expected, so there seems to be no problem when it occures. Any other exception should be handled.
...
} catch (EOFException e) {
// ... this is fine
} catch(IOException e) {
// handle exception which is not expected
e.printStackTrace();
}
As others have noted, in the instance you are asking about it is the destructor for class Stack
.
But taking your question exactly as it appears in the title:
In c++ what does a tilde “~” before a function name signify?
there is another situation. In any context except immediately before the name of a class (which is the destructor context), ~
is the one's complement (or bitwise not) operator. To be sure it does not come up very often, but you can imagine a case like
if (~getMask()) { ...
which looks similar, but has a very different meaning.
The two are not exactly the same. I couldn't remember the exact differences, but they are outlined very well in What's quicker and better to determine if an array key exists in PHP?.
The common consensus seems to be to use isset whenever possible, because it is a language construct and therefore faster. However, the differences should be outlined above.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>
use this method from everywhere with a context
private static String getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
return stringBuffer.toString();
}
Since Hibernate ORM 5.2.10, you can do it likee this:
Object unproxiedEntity = Hibernate.unproxy(proxy);
Before Hibernate 5.2.10. the simplest way to do that was to use the unproxy method offered by Hibernate internal PersistenceContext
implementation:
Object unproxiedEntity = ((SessionImplementor) session)
.getPersistenceContext()
.unproxy(proxy);
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
My heavily commented vimrc, with readline-esque (emacs) keybindings:
if version >= 700
"------ Meta ------"
" clear all autocommands! (this comment must be on its own line)
autocmd!
set nocompatible " break away from old vi compatibility
set fileformats=unix,dos,mac " support all three newline formats
set viminfo= " don't use or save viminfo files
"------ Console UI & Text display ------"
set cmdheight=1 " explicitly set the height of the command line
set showcmd " Show (partial) command in status line.
set number " yay line numbers
set ruler " show current position at bottom
set noerrorbells " don't whine
set visualbell t_vb= " and don't make faces
set lazyredraw " don't redraw while in macros
set scrolloff=5 " keep at least 5 lines around the cursor
set wrap " soft wrap long lines
set list " show invisible characters
set listchars=tab:>·,trail:· " but only show tabs and trailing whitespace
set report=0 " report back on all changes
set shortmess=atI " shorten messages and don't show intro
set wildmenu " turn on wild menu :e <Tab>
set wildmode=list:longest " set wildmenu to list choice
if has('syntax')
syntax on
" Remember that rxvt-unicode has 88 colors by default; enable this only if
" you are using the 256-color patch
if &term == 'rxvt-unicode'
set t_Co=256
endif
if &t_Co == 256
colorscheme xoria256
else
colorscheme peachpuff
endif
endif
"------ Text editing and searching behavior ------"
set nohlsearch " turn off highlighting for searched expressions
set incsearch " highlight as we search however
set matchtime=5 " blink matching chars for .x seconds
set mouse=a " try to use a mouse in the console (wimp!)
set ignorecase " set case insensitivity
set smartcase " unless there's a capital letter
set completeopt=menu,longest,preview " more autocomplete <Ctrl>-P options
set nostartofline " leave my cursor position alone!
set backspace=2 " equiv to :set backspace=indent,eol,start
set textwidth=80 " we like 80 columns
set showmatch " show matching brackets
set formatoptions=tcrql " t - autowrap to textwidth
" c - autowrap comments to textwidth
" r - autoinsert comment leader with <Enter>
" q - allow formatting of comments with :gq
" l - don't format already long lines
"------ Indents and tabs ------"
set autoindent " set the cursor at same indent as line above
set smartindent " try to be smart about indenting (C-style)
set expandtab " expand <Tab>s with spaces; death to tabs!
set shiftwidth=4 " spaces for each step of (auto)indent
set softtabstop=4 " set virtual tab stop (compat for 8-wide tabs)
set tabstop=8 " for proper display of files with tabs
set shiftround " always round indents to multiple of shiftwidth
set copyindent " use existing indents for new indents
set preserveindent " save as much indent structure as possible
filetype plugin indent on " load filetype plugins and indent settings
"------ Key bindings ------"
" Remap broken meta-keys that send ^[
for n in range(97,122) " ASCII a-z
let c = nr2char(n)
exec "set <M-". c .">=\e". c
exec "map \e". c ." <M-". c .">"
exec "map! \e". c ." <M-". c .">"
endfor
""" Emacs keybindings
" first move the window command because we'll be taking it over
noremap <C-x> <C-w>
" Movement left/right
noremap! <C-b> <Left>
noremap! <C-f> <Right>
" word left/right
noremap <M-b> b
noremap! <M-b> <C-o>b
noremap <M-f> w
noremap! <M-f> <C-o>w
" line start/end
noremap <C-a> ^
noremap! <C-a> <Esc>I
noremap <C-e> $
noremap! <C-e> <Esc>A
" Rubout word / line and enter insert mode
noremap <C-w> i<C-w>
noremap <C-u> i<C-u>
" Forward delete char / word / line and enter insert mode
noremap! <C-d> <C-o>x
noremap <M-d> dw
noremap! <M-d> <C-o>dw
noremap <C-k> Da
noremap! <C-k> <C-o>D
" Undo / Redo and enter normal mode
noremap <C-_> u
noremap! <C-_> <C-o>u<Esc><Right>
noremap! <C-r> <C-o><C-r><Esc>
" Remap <C-space> to word completion
noremap! <Nul> <C-n>
" OS X paste (pretty poor implementation)
if has('mac')
noremap v :r!pbpaste<CR>
noremap! v <Esc>v
endif
""" screen.vim REPL: http://github.com/ervandew/vimfiles
" send paragraph to parallel process
vmap <C-c><C-c> :ScreenSend<CR>
nmap <C-c><C-c> mCvip<C-c><C-c>`C
imap <C-c><C-c> <Esc><C-c><C-c><Right>
" set shell region height
let g:ScreenShellHeight = 12
"------ Filetypes ------"
" Vimscript
autocmd FileType vim setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4
" Shell
autocmd FileType sh setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4
" Lisp
autocmd Filetype lisp,scheme setlocal equalprg=~/.vim/bin/lispindent.lisp expandtab shiftwidth=2 tabstop=8 softtabstop=2
" Ruby
autocmd FileType ruby setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
" PHP
autocmd FileType php setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4
" X?HTML & XML
autocmd FileType html,xhtml,xml setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
" CSS
autocmd FileType css setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4
" JavaScript
" autocmd BufRead,BufNewFile *.json setfiletype javascript
autocmd FileType javascript setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
let javascript_enable_domhtmlcss=1
"------ END VIM-500 ------"
endif " version >= 500
Set a negative z-index
for the child, and remove the one set on the parent.
.parent {_x000D_
position: relative;_x000D_
width: 350px;_x000D_
height: 150px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
.parent2 {_x000D_
position: relative;_x000D_
width: 350px;_x000D_
height: 40px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
.child {_x000D_
position: relative;_x000D_
background-color: blue;_x000D_
height: 200px;_x000D_
}_x000D_
.wrapper {_x000D_
position: relative;_x000D_
background: green;_x000D_
height: 350px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">parent 1 parent 1_x000D_
<div class="child">child child child</div>_x000D_
</div>_x000D_
<div class="parent2">parent 2 parent 2_x000D_
</div>_x000D_
</div>
_x000D_
The most efficient way (before django 1.2) is this:
if orgs.count() == 0:
# no results
else:
# alrigh! let's continue...
(4+3)*(4*2) == 56
Note that PHP doesn't really support "nested functions", as in defined only in the scope of the parent function. All functions are defined globally. See the docs.
C# arrays are fixed length and always indexed. Go with Motti's solution:
int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List<int>.
List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
terms.Add(runs);
}
Neither int[] nor List<int> is an associative array -- that would be a Dictionary<> in C#. Both arrays and lists are dense.
Note that the Element::innerText
property will not contain the text which has been hidden by CSS style "display:none
" in Google Chrome (as well it will drop the content that has been masked by other CSS technics (including font-size:0, color:transparent, and a few other similar effects that cause the text not to be rendered in any visible way).
Other CSS properties are also considered :
<br \>
that generates an inline newline will also generate an newline in the value of innerText.But Element::textContent
will still contain ALL contents of inner text elements independantly of the applied CSS even if they are invisible. And no extra newlines or whitespaces will be generated in textContent, which just ignores all styles and the structure and inline/block or positioned types of inner elements.
A copy/paste operation using mouse selection will discard the hidden text in the plain-text format that is put in the clipboard, so it won't contain everything in the textContent
, but only what is within innerText
(after whitespace/newline generation as above).
Both properties are then supported in Google Chrome, but their content may then be different. Older browsers still included in innetText everything like what textContent now contains (but their behavior in relation with then generation of whitespaces/newlines was inconsistant).
jQuery will solve these inconsistencies between browsers using the ".text()" method added to the parsed elements it returns via a $() query. Internally, it solves the difficulties by looking into the HTML DOM, working only with the "node" level. So it will return something looking more like the standard textContent.
The caveat is that that this jQuery method will not insert any extra spaces or line breaks that may be visible on screen caused by subelements (like <br />
) of the content.
If you design some scripts for accessibility and your stylesheet is parsed for non-aural rendering, such as plugins used to communicate with a Braille reader, this tool should use the textContent if it must include the specific punctuation signs that are added in spans styled with "display:none" and that are typically included in pages (for example for superscripts/subscripts), otherwise the innerText will be very confusive on the Braille reader.
Texts hidden by CSS tricks are now typically ignored by major search engines (that will also parse the CSS of your HTML pages, and will also ignore texts that are not in contrasting colors on the background) using an HTML/CSS parser and the DOM property "innerText" exactly like in modern visual browsers (at least this invisible content will not be indexed so hidden text cannot be used as a trick to force the inclusion of some keywords in the page to check its content) ; but this hidden text will be stil displayed in the result page (if the page was still qualified from the index to be included in results), using the "textContent" property instead of the full HTML to strip the extra styles and scripts.
IF you assign some plain-text in any one of these two properties, this will overwrite the inner markup and styles applied to it (only the assigned element will keep its type, attributes and styles), so both properties will then contain the same content. However, some browsers will now no longer honor the write to innerText, and will only let you overwrite the textContent property (you cannot insert HTML markup when writing to these properties, as HTML special characters will be properly encoded using numeric character references to appear literally, if you then read the innerHTML
property after the assignment of innerText
or textContent
.
If you already have material-icons working in your web project, just need to update your reference in the html file and the used class for icons:
html reference:
Before
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
After
<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp"
rel="stylesheet" />
material icons class:
After that just check wich className are you using:
Before:
<i className="material-icons">weekend</i>
After:
<i className="material-icons-outlined">weekend</i>
that works for me... Pura vida!
This is probably what you need:
$text = str_replace(' ', '_', substr($text, 0, 10));
Try something like this:
$link = @new mysqli($this->host, $this->user, $this->pass)
$statement = $link->prepare($sqlStatement);
if(!$statement)
{
$this->debug_mode('query', 'error', '#Query Failed<br/>' . $link->error);
return false;
}
A simple solution is to use writeFile :
require("fs").writeFile(
somepath,
arr.map(function(v){ return v.join(', ') }).join('\n'),
function (err) { console.log(err ? 'Error :'+err : 'ok') }
);
While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.
Edit - this answer was for an earlier version of Charles. See @semicircle21 answer below for the proper steps for v3.10.x -- much easier than this approach too... :-)
For what it's worth here are the step by step instructions for this. They should apply equally well in iOS too:
You should then be able to see the SSL files in Charles. If you want to intercept and change the values you can use the "Map Local" tool which is really awesome:
One more trick, search photos by hashtags:
GET https://www.instagram.com/graphql/query/?query_hash=3e7706b09c6184d5eafd8b032dbcf487&variables={"tag_name":"nature","first":25,"after":""}
Where:
query_hash
- permanent value(i belive its hash of 17888483320059182, can be changed in future)
tag_name
- the title speaks for itself
first
- amount of items to get (I do not know why, but this value does not work as expected. The actual number of returned photos is slightly larger than the value multiplied by 4.5 (about 110 for the value 25, and about 460 for the value 100))
after
- id of the last item if you want to get items from that id. Value of end_cursor
from JSON response can be used here.
From ISO 8601 String to Java Date Object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf.parse("2013-09-29T18:46:19Z"); //prints-> Mon Sep 30 02:46:19 CST 2013
if you don't set TimeZone.getTimeZone("GMT")
then it will output Sun Sep 29 18:46:19 CST 2013
From Java Date Object to ISO 8601 String
And to convert Date
object to ISO 8601 Standard (yyyy-MM-dd'T'HH:mm:ss'Z'
) use following code
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date())); //-prints-> 2015-01-22T03:23:26Z
Also note that without ' '
at Z yyyy-MM-dd'T'HH:mm:ssZ
prints 2015-01-22T03:41:02+0000
This worked for me.
sudo adduser <username> www-data
sudo chown -R www-data:www-data /var/www
sudo chmod -R g+rwX /var/www
Then logout or reboot.
If SELinux
complains, try the following
sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www(/.*)?'
sudo restorecon -Rv '/var/www(/.*)?'
So, in an ideal world you'd have a spec for all pages in your site. You would also have a test infrastructure that could hit all your pages to test them.
You're presumably not in an ideal world. Why not do this...?
Create a mapping between the well known old URLs and the new ones. Redirect when you see an old URL. I'd possibly consider presenting a "this page has moved, it's new url is XXX, you'll be redirected shortly".
If you have no mapping, present a "sorry - this page has moved. Here's a link to the home page" message and redirect them if you like.
Log all redirects - especially the ones with no mapping. Over time, add mappings for pages that are important.
It's not an error. Javascript will gladly convert a number to a string when a string is expected (for example parseInt(42)
), but in this case there is nothing that expect the number to be a string.
Here's a makeLowerCase
function. :)
function makeLowerCase(value) {
return value.toString().toLowerCase();
}
There are two problems with your attempt.
First, you've used n+1
instead of i+1
, so you're going to return something like [5, 5, 5, 5]
instead of [1, 2, 3, 4]
.
Second, you can't for
-loop over a number like n
, you need to loop over some kind of sequence, like range(n)
.
So:
def naturalNumbers(n):
return [i+1 for i in range(n)]
But if you already have the range
function, you don't need this at all; you can just return range(1, n+1)
, as arshaji showed.
So, how would you build this yourself? You don't have a sequence to loop over, so instead of for
, you have to build it yourself with while
:
def naturalNumbers(n):
results = []
i = 1
while i <= n:
results.append(i)
i += 1
return results
Of course in real-life code, you should always use for
with a range
, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range
function first, just to use it for naturalNumbers
. (It's already pretty close.)
There is one more option, if you want to get clever.
If you have a list, you can slice it. For example, the first 5 elements of my_list
are my_list[:5]
. So, if you had an infinitely-long list starting with 1
, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count
or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice
. So:
from itertools import count, islice
def naturalNumbers(n):
return list(islice(count(1), n))
on CMD
type
ren *.* *.jpg
. will select all files, and rename to * (what ever name they have) plus extension to jpg
Add this to your Web Config
<system.web>
<httpRuntime executionTimeout="180" />
</system.web>
https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx
Optional TimeSpan attribute.
Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation element is False. To help to prevent shutting down the application while you are debugging, do not set this time-out to a large value.
The default is "00:01:50" (110 seconds).
You may also be missing using namespace std;
As answered by Ian L, I also use NPM to manage my scripts.
Example:
{_x000D_
"scripts": {_x000D_
"ios": "react-native run-ios --simulator=\"iPad Air 2\"",_x000D_
"devices": "xcrun simctl list devices"_x000D_
}_x000D_
}
_x000D_
This way, I can quickly get what I need:
npm run devices
npm run ios
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
async:false
= Code paused. (Other code waiting for this to finish.)async:true
= Code continued. (Nothing gets paused. Other code is not waiting.)As simple as this.
1.Use git reflog
to get all references update.
2.git reset <id_of_commit_to_which_you_want_restore>
I realize this isn't a part of the answer, but on that note, I also think the availability of stable plugins for platforms like NetBeans and Eclipse play a part in which tool is a better fit for the task, or rather, which tool is the best fit for "you". That is, unless you really want to do it the CLI-way.
Both Eclipse (and everything based on it) and NetBeans sometimes have issues with remote file systems (such as SSH) and external updates of files; which is yet another reason why you want whatever you choose to work "seamlessly".
I'm trying to answer this question for myself right now too .. and I've boiled down the candidates to Git or Mercurial .. thank you all for providing useful inputs on this topic without going religious.
One important point is that Swift's ==
on strings might not be equivalent to Objective-C's -isEqualToString:
. The peculiarity lies in differences in how strings are represented between Swift and Objective-C.
Just look on this example:
let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)
composed.utf16.count // 1
decomposed.utf16.count // 2
let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString
decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not
NSString
's are represented as a sequence of UTF–16 code units (roughly read as an array of UTF-16 (fixed-width) code units). Whereas Swift String
s are conceptually sequences of "Characters", where "Character" is something that abstracts extended grapheme cluster (read Character = any amount of Unicode code points, usually something that the user sees as a character and text input cursor jumps around).
The next thing to mention is Unicode. There is a lot to write about it, but here we are interested in something called "canonical equivalence". Using Unicode code points, visually the same "character" can be encoded in more than one way. For example, "Á" can be represented as a precomposed "Á" or as decomposed A + ?´ (that's why in example composed.utf16
and decomposed.utf16
had different lengths). A good thing to read on that is this great article.
-[NSString isEqualToString:]
, according to the documentation, compares NSStrings code unit by code unit, so:
[Á] != [A, ?´]
Swift's String ==
compares characters by canonical equivalence.
[ [Á] ] == [ [A, ?´] ]
In swift the above example will return true for Strings. That's why -[NSString isEqualToString:]
is not equivalent to Swift's String ==. Equivalent pure Swift comparison could be done by comparing String's UTF-16 Views:
decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same
Also, there is a difference between NSString == NSString
and String == String
in Swift. The NSString ==
will cause isEqual and UTF-16 code unit by code unit comparison, where as String ==
will use canonical equivalence:
decomposed == composed // true, Strings are equal
decomposed as NSString == composed as NSString // false, UTF-16 code units are not the same
And the whole example:
let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)
composed.utf16.count // 1
decomposed.utf16.count // 2
let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString
decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not
decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same
Here it is in TypeScript:
var trim: (input: string) => string = String.prototype.trim
? ((input: string) : string => {
return (input || "").trim();
})
: ((input: string) : string => {
return (input || "").replace(/^\s+|\s+$/g,"");
})
It will fall back to the regex if the native prototype is not available.
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
//more views
</androidx.constraintlayout.widget.ConstraintLayout>
In the above code, the basic need of tools:context is to tell which activity or fragment the layout file is associated with by default. So, you can specify the activity class name using the same dot prefix as used in Manifest file.
By doing so, the Android Studio will choose the necessary theme for the preview automatically and you don’t have to do the preview settings manually. As we all know that a layout file can be associated with several activities but the themes are defined in the Manifest file and these themes are associated with your activity. So, by adding tools:context in your layout file, the Android Studio preview will automatically choose the necessary theme for you.
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
var datetime = new Date();_x000D_
console.log(datetime.toISOString().slice(0,10));
_x000D_
If you are on windows and using mingw, gcc uses the win32 runtime, where printf needs %I64d
for a 64 bit integer. (and %I64u
for an unsinged 64 bit integer)
For most other platforms you'd use %lld
for printing a long long. (and %llu
if it's unsigned). This is standarized in C99.
gcc doesn't come with a full C runtime, it defers to the platform it's running on - so the general case is that you need to consult the documentation for your particular platform - independent of gcc.
There is no "absolute path for a file existing in the asset folder". The content of your project's assets/
folder are packaged in the APK file. Use an AssetManager
object to get an InputStream
on an asset.
For WebView
, you can use the file
Uri
scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/...
(note: three slashes) where the ellipsis is the path of the file from within the assets/
folder.
You can use Jquery's on method and listen for the scroll
event.
gnu tar v 1.26 the --exclude needs to come after archive file and backup directory arguments, should have no leading or trailing slashes, and prefers no quotes (single or double). So relative to the PARENT directory to be backed up, it's:
tar cvfz /path_to/mytar.tgz ./dir_to_backup --exclude=some_path/to_exclude
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
move the System.out statement to finally block.
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
$('img.conversation_img[alt="example"]')
.each(function(){
alert($(this).attr('src'))
});
This will display src attributes of all images of class 'conversation_img' with alt='example'
As others have pointed out, you can only use werkzeug.server.shutdown
from a request handler. The only way I've found to shut down the server at another time is to send a request to yourself. For example, the /kill
handler in this snippet will kill the dev server unless another request comes in during the next second:
import requests
from threading import Timer
from flask import request
import time
LAST_REQUEST_MS = 0
@app.before_request
def update_last_request_ms():
global LAST_REQUEST_MS
LAST_REQUEST_MS = time.time() * 1000
@app.route('/seriouslykill', methods=['POST'])
def seriouslykill():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
return "Shutting down..."
@app.route('/kill', methods=['POST'])
def kill():
last_ms = LAST_REQUEST_MS
def shutdown():
if LAST_REQUEST_MS <= last_ms: # subsequent requests abort shutdown
requests.post('http://localhost:5000/seriouslykill')
else:
pass
Timer(1.0, shutdown).start() # wait 1 second
return "Shutting down..."
If you know the size use this
No temporary variable used just to store user input
int main()
{
cout << "Hello World!\n";
int n;//input size
cin >> n;
vector<int>a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
//to verify output user input printed below
for (auto x : a) {
cout << x << " ";
}
return 0;
}
The JLS 5, Section 15.18.1.1 JLS 8 § 15.18.1 "String Concatenation Operator +", leading to JLS 8, § 5.1.11 "String Conversion", requires this operation to succeed without failure:
...Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
Let's look at the bytecode! The compiler takes your code:
String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"
and compiles it into bytecode as if you had instead written this:
String s = null;
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
System.out.println(s); // prints "nullhello"
(You can do so yourself by using javap -c
)
The append methods of StringBuilder
all handle null just fine. In this case because null
is the first argument, String.valueOf()
is invoked instead since StringBuilder does not have a constructor that takes any arbitrary reference type.
If you were to have done s = "hello" + s
instead, the equivalent code would be:
s = new StringBuilder("hello").append(s).toString();
where in this case the append method takes the null and then delegates it to String.valueOf()
.
Note: String concatenation is actually one of the rare places where the compiler gets to decide which optimization(s) to perform. As such, the "exact equivalent" code may differ from compiler to compiler. This optimization is allowed by JLS, Section 15.18.1.2:
To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
The compiler I used to determine the "equivalent code" above was Eclipse's compiler, ecj.
You can use
function echo(content) {
var e = document.createElement("p");
e.innerHTML = content;
document.currentScript.parentElement.replaceChild(document.currentScript, e);
}
which will replace the currently executing script who called the echo function with the text in the content argument.
I would use the #{}
constructor, as stated by the other answers.
I also want to point out there is a real subtlety here to watch out for here:
2.0.0p247 :001 > first_name = 'jim'
=> "jim"
2.0.0p247 :002 > second_name = 'bob'
=> "bob"
2.0.0p247 :003 > full_name = '#{first_name} #{second_name}'
=> "\#{first_name} \#{second_name}" # not what we expected, expected "jim bob"
2.0.0p247 :004 > full_name = "#{first_name} #{second_name}"
=> "jim bob" #correct, what we expected
While strings can be created with single quotes (as demonstrated by the first_name
and last_name
variables, the #{}
constructor can only be used in strings with double quotes.
An answer from 2020. The following code solves this. A lot of people new to selenium seem to have to get past this step. Install the chromedriver and put it inside a folder on your desktop. Also make sure to put the selenium python project in the same folder as where the chrome driver is located.
Change USER_NAME and FOLDER in accordance to your computer.
For Windows
driver = webdriver.Chrome(r"C:\Users\USER_NAME\Desktop\FOLDER\chromedriver")
For Linux/Mac
driver = webdriver.Chrome("/home/USER_NAME/FOLDER/chromedriver")
You should try this syntax - assuming you want to have @OrderID
as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
@OrderID INT
AS
BEGIN
DECLARE @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SELECT @OrderItemID = OrderItemID
FROM [OrderItem]
WHERE OrderID = @OrderID
SELECT @AppointmentID = AppoinmentID
FROM [Appointment]
WHERE OrderID = @OrderID
SELECT @PurchaseOrderID = PurchaseOrderID
FROM [PurchaseOrder]
WHERE OrderID = @OrderID
END
OF course, that only works if you're returning exactly one value (not multiple values!)
how to fetch the dropdown values from database and display in jsp:
Dynamically Fetch data from Mysql to (drop down) select option in Jsp. This post illustrates, to fetch the data from the mysql database and display in select option element in Jsp. You should know the following post before going through this post i.e :
How to Connect Mysql database to jsp.
How to create database in MySql and insert data into database. Following database is used, to illustrate ‘Dynamically Fetch data from Mysql to (drop down)
select option in Jsp’ :
id City
1 London
2 Bangalore
3 Mumbai
4 Paris
Following codes are used to insert the data in the MySql database. Database used is “City” and username = “root” and password is also set as “root”.
Create Database city;
Use city;
Create table new(id int(4), city varchar(30));
insert into new values(1, 'LONDON');
insert into new values(2, 'MUMBAI');
insert into new values(3, 'PARIS');
insert into new values(4, 'BANGLORE');
Here is the code to Dynamically Fetch data from Mysql to (drop down) select option in Jsp:
<%@ page import="java.sql.*" %>
<%ResultSet resultset =null;%>
<HTML>
<HEAD>
<TITLE>Select element drop down box</TITLE>
</HEAD>
<BODY BGCOLOR=##f89ggh>
<%
try{
//Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection =
DriverManager.getConnection
("jdbc:mysql://localhost/city?user=root&password=root");
Statement statement = connection.createStatement() ;
resultset =statement.executeQuery("select * from new") ;
%>
<center>
<h1> Drop down box or select element</h1>
<select>
<% while(resultset.next()){ %>
<option><%= resultset.getString(2)%></option>
<% } %>
</select>
</center>
<%
//**Should I input the codes here?**
}
catch(Exception e)
{
out.println("wrong entry"+e);
}
%>
</BODY>
</HTML>
You need to use v-bind:
or its alias :
. For example,
<a v-bind:href="'/job/'+ r.id">
or
<a :href="'/job/' + r.id">
The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:
...
...
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
<!-- place a FrameLayout (match_parent) as the last child -->
<FrameLayout
android:id="@+id/icon_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</TabHost>
in Java:
final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;
FrameLayout frameLayout = (FrameLayout) materialDialog
.findViewById(R.id.icon_frame_container);
frameLayout.setOnTouchListener(
new OnSwipeTouchListener(ShowCardActivity.this) {
As Mark mentioned, the previous statement should be ended in semi-colon. So you can use:
; DISABLE TRIGGER dbo.tr_name ON dbo.table_name
Using javascript you can style the scroll bars. Which works fine in IE as well as FF.
Check the below links
From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques
In your CSS, float the first div by left or right. Float the second div by left or right same as first. Apply clear: left
or right
the same as the above two divs for the second div.
For example:
#firstDiv {
float: left;
}
#secondDiv {
float: left;
clear: left;
}
For email templates, inline CSS is the properly used method to style:
<thead>
<tr style="color: #fff; background: black;">
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
conda create -n py27 python=2.7 ipykernel
source activate py27
pip install geocoder
import java.util.*;
public class Arrays2
{
public static void main(String[] args)
{
int small, row = 0, col = 0, z;
int[][] array = new int[5][5];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(100);
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println("\n");
for(int k = 0; k < array.length; k++)
{
for(int p = 0; p < array[k].length; p++)
{
small = array[k][p];
for(int i = k; i < array.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < array[i].length; z++)
{
if(array[i][z] <= small)
{
small = array[i][z];
row = i;
col = z;
}
}
}
array[row][col] = array[k][p];
array[k][p] = small;
System.out.print(array[k][p] + " ");
}
System.out.println();
}
}
}
Good Luck
It is looping, probably the problem is in the part of the print...
If you can't find the logic where the system prints, just add the folling where you want the content out:
for i in range(len(vs)):
print vs[i]
print fs[i]
print rs[i]
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
Look here for c#
https://msdn.microsoft.com/en-us/library/system.io.streamreader.currentencoding%28v=vs.110%29.aspx
string path = @"path\to\your\file.ext";
using (StreamReader sr = new StreamReader(path, true))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
//Test for the encoding after reading, or at least
//after the first read.
Console.WriteLine("The encoding used was {0}.", sr.CurrentEncoding);
Console.ReadLine();
Console.WriteLine();
}
Another alternative solution:
cat ~/.ssh/id_rsa.pub | xsel -i -b
From man xsel
:
-i, --input
read standard input into the selection.
-b, --clipboard
operate on the CLIPBOARD selection.
You can say Dispatcher Servlet acts as an entry and exit point for any request. Whenever a request comes it first goes to the Dispatcher Servlet(DS) where the DS then tries to identify its handler method ( the methods you define in the controller to handle the requests ), once the handler mapper (The DS asks the handler mapper) returns the controller the dispatcher servlet knows the controller which can handle this request and can now go to this controller to further complete the processing of the request. Now the controller can respond with an appropriate response and then the DS goes to the view resolver to identify where the view is located and once the view resolver tells the DS it then grabs that view and returns it back to you as the final response. I am adding an image which I took from YouTube from the channel Java Guides.
My app uses a ListView in portraint mode which is simply switches to Gallery in landscape mode. Both of them use one BaseAdapter. This looks like shown below.
setContentView(R.layout.somelayout);
orientation = getResources().getConfiguration().orientation;
if ( orientation == Configuration.ORIENTATION_LANDSCAPE )
{
Gallery gallery = (Gallery)findViewById( R.id.somegallery );
gallery.setAdapter( someAdapter );
gallery.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick( AdapterView<?> parent, View view,
int position, long id ) {
onClick( position );
}
});
}
else
{
setListAdapter( someAdapter );
getListView().setOnScrollListener(this);
}
To handle scrolling events I've inherited my own widget from Gallery and override onFling(). Here's the layout.xml:
<view
class="package$somegallery"
android:id="@+id/somegallery"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</view>
and code:
public static class somegallery extends Gallery
{
private Context mCtx;
public somegallery(Context context, AttributeSet attrs)
{
super(context, attrs);
mCtx = context;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
( (CurrentActivity)mCtx ).onScroll();
return super.onFling(e1, e2, velocityX, velocityY);
}
}
Write the code in your first activity .
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
//You can use String ,arraylist ,integer ,float and all data type.
intent.putExtra("Key","value");
startActivity(intent);
finish();
}
});
In secondActivity.class
String name = getIntent().getStringExtra("Key");
Use NULLIF(exp,0)
but in this way - NULLIF(ISNULL(exp,0),0)
NULLIF(exp,0)
breaks if exp is null
but NULLIF(ISNULL(exp,0),0)
will not break
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.
just make sure it built.
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
there's your bitmap as the screen saw it.
There are several issues:
elif option == 2:
and the subsequent elif
-else
should be aligned with the second if option == 1
, not with the for
.
The for x in range(x, 1, 1):
is missing a body.
Since "option 1 (count)" requires a second input, you need to call input()
for the second time. However, for sanity's sake I urge you to store the result in a second variable rather than repurposing option
.
The comparison in the first line of your code is probably meant to be an assignment.
You'll discover more issues once you're able to run your code (you'll need a couple more input()
calls, one of the range()
calls will need attention etc).
Lastly, please don't use the same variable as the loop variable and as part of the initial/terminal condition, as in:
for x in range(1, x, 1):
print x
It may work, but it is very confusing to read. Give the loop variable a different name:
for i in range(1, x, 1):
print i
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
On a MacBook Pro running Mavericks, sysctl -a | grep hw.cpu
will only return some cryptic details. Much more detailed and accessible information is revealed in the machdep.cpu
section, ie:
sysctl -a | grep machdep.cpu
In particular, for processors with HyperThreading
(HT), you'll see the total enumerated CPU count (logical_per_package
) as double that of the physical core count (cores_per_package
).
sysctl -a | grep machdep.cpu | grep per_package
You could store those objects on a database. If you don't want the overhead of a full blown database server you can use an embedded one like HSQLDB. Then you can use Hibernate or BeanKeeper (simpler to use) or other ORM to map objects to tables. You keep using the OO model and get the advanced storage and querying benefits from a database.
See in the android sdk directory.
In \platforms\android-X\data\res\values\themes.xml
:
<item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
<item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
In \platforms\android-X\data\res\values\styles.xml
:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
</style>
<style name="TextAppearance.Medium">
<item name="android:textSize">18sp</item>
</style>
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
TextAppearance.Large
means style is inheriting from TextAppearance
style, you have to trace it also if you want to see full definition of a style.
Link: http://developer.android.com/design/style/typography.html
I agree with @pkozlowski.opensource answer, but ng-clock class did't work for me for using with ng-repeat. so I would like to recommend you to use class for simple delimiter expression like {{name}} and ngCloak directive for ng-repeat.
<div class="ng-cloak">{{name}}<div>
and
<li ng-repeat="item in items" ng-cloak>{{item.name}}<li>
Easy way
# 1. Create a new remote branch A base on last master
# 2. Checkout A
# 3. Merge aq to A
ngSrc
is a native directive, so it seems you want a similar directive that modifies your div's background-image
style.
You could write your own directive that does exactly what you want. For example
app.directive('backImg', function(){
return function(scope, element, attrs){
var url = attrs.backImg;
element.css({
'background-image': 'url(' + url +')',
'background-size' : 'cover'
});
};
});?
Which you would invoke like this
<div back-img="<some-image-url>" ></div>
JSFiddle with cute cats as a bonus: http://jsfiddle.net/jaimem/aSjwk/1/
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
As far as I'm aware this isn't possible with HTML and CSS.
You could use Map.prototype.forEach((value, key, map) => void, thisArg?) : void
instead
Use it like this:
myMap.forEach((value: boolean, key: string) => {
console.log(key, value);
});
Here is the below code, it will return the Enum name from Enum value.
public enum Test {
PLUS("Plus One"), MINUS("MinusTwo"), TIMES("MultiplyByFour"), DIVIDE(
"DivideByZero");
private String operationName;
private Test(final String operationName) {
setOperationName(operationName);
}
public String getOperationName() {
return operationName;
}
public void setOperationName(final String operationName) {
this.operationName = operationName;
}
public static Test getOperationName(final String operationName) {
for (Test oprname : Test.values()) {
if (operationName.equals(oprname.toString())) {
return oprname;
}
}
return null;
}
@Override
public String toString() {
return operationName;
}
}
public class Main {
public static void main(String[] args) {
Test test = Test.getOperationName("Plus One");
switch (test) {
case PLUS:
System.out.println("Plus.....");
break;
case MINUS:
System.out.println("Minus.....");
break;
default:
System.out.println("Nothing..");
break;
}
}
}
select count(e.empno), d.deptno, d.dname
from emp e, dep d
where e.DEPTNO = d.DEPTNO
group by d.deptno, d.dname;
The advantages are that you can use functions like LEN
and LEFT
on nvarchar(max)
and you cannot do that against ntext
and text
. It is also easier to work with nvarchar(max)
than text
where you had to use WRITETEXT
and UPDATETEXT
.
Also, text
, ntext
, etc., are being deprecated (http://msdn.microsoft.com/en-us/library/ms187993.aspx)
This seems to work just fine:
import sys
print sys._getframe().f_back.f_code.co_name
You can't use CSS to disable autocomplete, but you can use HTML:
<input type="text" autocomplete="false" />
Technically you can replace false
with any invalid value and it'll work. This iOS the only solution I've found which also works in Edge.
This is just the XML Name Space declaration. We use this Name Space in order to specify that the attributes listed below, belongs to Android. Thus they starts with "android:"
You can actually create your own custom attributes. So to prevent the name conflicts where 2 attributes are named the same thing, but behave differently, we add the prefix "android:" to signify that these are Android attributes.
Thus, this Name Space declaration must be included in the opening tag of the root view of your XML file.
Sometimes, when I know that I am working with numbers, I use this logic (if result is not greater than zero
):
if (!$result['column']>0){
}
Even there exist an accepted answer, I'll like to demonstrate the following (with Python 2.7.2 and Numpy 1.6.0 on Vista):
In []: x= rand(1e5)
In []: %timeit isnan(x.min())
10000 loops, best of 3: 200 us per loop
In []: %timeit isnan(x.sum())
10000 loops, best of 3: 169 us per loop
In []: %timeit isnan(dot(x, x))
10000 loops, best of 3: 134 us per loop
In []: x[5e4]= NaN
In []: %timeit isnan(x.min())
100 loops, best of 3: 4.47 ms per loop
In []: %timeit isnan(x.sum())
100 loops, best of 3: 6.44 ms per loop
In []: %timeit isnan(dot(x, x))
10000 loops, best of 3: 138 us per loop
Thus, the really efficient way might be heavily dependent on the operating system. Anyway dot(.)
based seems to be the most stable one.
try this :
import zipfile
def un_zipFiles(path):
files=os.listdir(path)
for file in files:
if file.endswith('.zip'):
filePath=path+'/'+file
zip_file = zipfile.ZipFile(filePath)
for names in zip_file.namelist():
zip_file.extract(names,path)
zip_file.close()
path : unzip file's path
Drifting a bit, but it would be relatively easy to autofill the US City/State or CA City/Provence when the user enters her postal code using a lookup table.
Here's how you could do it if you could force people to bend to your will:
User enters: postal (zip) code
You fill: state, city (province, for Canada)
User starts to enter: streetname
You: autofill
You display: a range of allowed address numbers
User: enters the number
Done.
Here's how it is natural for people to do it:
User enters: address number
You: do nothing
User starts to enter: street name
You: autofill, drawing from a massive list of every street in the country
User enters: city
You: autofill
User enters: state/provence
You: is it worth autofilling a few chars?
You: autofill postal (zip) code, if you can (because some codes straddle cities).
Now you know why people charge $$$ to do this. :)
For the street address, consider there are two parts: numeric and streetname. If you have the zip code, then you can narrow down the available streets, but most people enter the numeric part first, which is backwa
If one has to call pd.Series.between(l,r)
repeatedly (for different bounds l
and r
), a lot of work is repeated unnecessarily. In this case, it's beneficial to sort the frame/series once and then use pd.Series.searchsorted()
. I measured a speedup of up to 25x, see below.
def between_indices(x, lower, upper, inclusive=True):
"""
Returns smallest and largest index i for which holds
lower <= x[i] <= upper, under the assumption that x is sorted.
"""
i = x.searchsorted(lower, side="left" if inclusive else "right")
j = x.searchsorted(upper, side="right" if inclusive else "left")
return i, j
# Sort x once before repeated calls of between()
x = x.sort_values().reset_index(drop=True)
# x = x.sort_values(ignore_index=True) # for pandas>=1.0
ret1 = between_indices(x, lower=0.1, upper=0.9)
ret2 = between_indices(x, lower=0.2, upper=0.8)
ret3 = ...
Benchmark
Measure repeated evaluations (n_reps=100
) of pd.Series.between()
as well as the method based on pd.Series.searchsorted()
, for different arguments lower
and upper
. On my MacBook Pro 2015 with Python v3.8.0 and Pandas v1.0.3, the below code results in the following outpu
# pd.Series.searchsorted()
# 5.87 ms ± 321 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# pd.Series.between(lower, upper)
# 155 ms ± 6.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# Logical expressions: (x>=lower) & (x<=upper)
# 153 ms ± 3.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
import numpy as np
import pandas as pd
def between_indices(x, lower, upper, inclusive=True):
# Assumption: x is sorted.
i = x.searchsorted(lower, side="left" if inclusive else "right")
j = x.searchsorted(upper, side="right" if inclusive else "left")
return i, j
def between_fast(x, lower, upper, inclusive=True):
"""
Equivalent to pd.Series.between() under the assumption that x is sorted.
"""
i, j = between_indices(x, lower, upper, inclusive)
if True:
return x.iloc[i:j]
else:
# Mask creation is slow.
mask = np.zeros_like(x, dtype=bool)
mask[i:j] = True
mask = pd.Series(mask, index=x.index)
return x[mask]
def between(x, lower, upper, inclusive=True):
mask = x.between(lower, upper, inclusive=inclusive)
return x[mask]
def between_expr(x, lower, upper, inclusive=True):
if inclusive:
mask = (x>=lower) & (x<=upper)
else:
mask = (x>lower) & (x<upper)
return x[mask]
def benchmark(func, x, lowers, uppers):
for l,u in zip(lowers, uppers):
func(x,lower=l,upper=u)
n_samples = 1000
n_reps = 100
x = pd.Series(np.random.randn(n_samples))
# Sort the Series.
# For pandas>=1.0:
# x = x.sort_values(ignore_index=True)
x = x.sort_values().reset_index(drop=True)
# Assert equivalence of different methods.
assert(between_fast(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_expr(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_fast(x, 0, 1, False).equals(between(x, 0, 1, False)))
assert(between_expr(x, 0, 1, False).equals(between(x, 0, 1, False)))
# Benchmark repeated evaluations of between().
uppers = np.linspace(0, 3, n_reps)
lowers = -uppers
%timeit benchmark(between_fast, x, lowers, uppers)
%timeit benchmark(between, x, lowers, uppers)
%timeit benchmark(between_expr, x, lowers, uppers)
One liner here
document.querySelector("meta[property='og:image']").getAttribute("content");
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
Java implementation in according Haversine formula
double calculateDistance(double latPoint1, double lngPoint1,
double latPoint2, double lngPoint2) {
if(latPoint1 == latPoint2 && lngPoint1 == lngPoint2) {
return 0d;
}
final double EARTH_RADIUS = 6371.0; //km value;
//converting to radians
latPoint1 = Math.toRadians(latPoint1);
lngPoint1 = Math.toRadians(lngPoint1);
latPoint2 = Math.toRadians(latPoint2);
lngPoint2 = Math.toRadians(lngPoint2);
double distance = Math.pow(Math.sin((latPoint2 - latPoint1) / 2.0), 2)
+ Math.cos(latPoint1) * Math.cos(latPoint2)
* Math.pow(Math.sin((lngPoint2 - lngPoint1) / 2.0), 2);
distance = 2.0 * EARTH_RADIUS * Math.asin(Math.sqrt(distance));
return distance; //km value
}
you can use ast.literal_eval()
>>> import ast
>>> s = "{'username':'dfdsfdsf'}"
>>> ast.literal_eval(s)
{'username': 'dfdsfdsf'}
I think you have deleted default .htaccess file inside the laravel public folder. upload the file it should fix your problem.