Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
I would like to add to the answers of BalusC and Pascal Thivent another common use of insertable=false, updatable=false
:
Consider a column that is not an id but some kind of sequence number. The responsibility for calculating the sequence number may not necessarily belong to the application.
For example, sequence number starts with 1000 and should increment by one for each new entity. This is easily done, and very appropriately so, in the database, and in such cases these configurations makes sense.
"The irony of JDBC is that, although the programming interfaces are portable, the SQL language is not. Despite the many attempts to standardize it, it is still rare to write SQL of any complexity that will run unchanged on two major database platforms. Even where the SQL dialects are similar, each database performs differently depending on the structure of the query, necessitating vendor-specific tuning in most cases."
..stolen from Pro JPA 2 Mastering the Java Persistence API, chapter 1, page 9
So, we might think of JDBC as the ultimate specification that abstracts away everything related to databases, but it isn't.
A quote from the JDBC specification, chapter 4.4, page 20:
The driver layer may mask differences between standard SQL:2003 syntax and the native dialect supported by the data source.
May is no guarantee that the driver will, and therefore we should provide the dialect in order to have a working application. In a best-case scenario, the application will work but might not run as effectively as it could if the persistence provider knew which dialect to use. In the case of Hibernate he will refuse to deploy your application unless you feed him the dialect.
The JDBC specification does not mention the word JPQL. JDBC is a standardized way of database access. Go read this JavaDoc and you will find that once the application can access the database, what must be fed into the JDBC compliant driver is vanilla = undecorated SQL.
It is worth noting that JPQL is a query language, not a data definition language (DDL). So even if we could feed the JDBC driver with JPQL, that would be of no use for the persistence provider during the phase of parsing the persistence.xml
file and setting up tables.
For your reference, here is an example for Hibernate and EclipseLink on how to specify a Java DB dialect in the persistence.xml file:
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect"/>
<property name="eclipselink.target-database" value="JavaDB"/>
In theory, the property has not been standardized and the JPA 2.1 specification says not a word about SQL dialects. So we're out of luck and must turn to vendor specific empirical studies and documentation thereof.
Hibernate refuse to accept a deployment archive that hasn't specified the property rendering the archive undeployable. Hibernate documentation says:
Always set the hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database.
So that is pretty clear. Do note that the dialects listed in the documentation are specifically targeting one or the other vendor. There is no "generic" dialect or anything like that. Given then that the property is an absolute requirement for a successful deployment, you would expect that the documentation of the WildFly application server which bundles Hibernate should say something, but it doesn't.
EclipseLink on the other hand is a bit more forgiving. If you don't provide the property, the deployment deploys (without warning too). EclipseLink documentation says:
Use the eclipselink.target-database property to specify the database to use, controlling custom operations and SQL generation for the specified database.
The talk is about "custom operations and SQL generation", meaning it is bit vague if you ask me. But one thing is clear: They don't say that the property is mandatory. Also note that one of the available values is "Database" which represent "a generic database" target. Hmm, what "dialect" would that be? SQL 2.0?? But then again, the property is called "target-database" and not "dialect" so maybe "Database" translates to no SQL at all lol. Moving on to the GlassFish server which bundles EclipseLink. Documentation (page "6-3") says:
You can specify the optional eclipselink.target-database property to guarantee that the database type is correct.
So GlassFish argues that the property is "optional" and the value added is a "guarantee" that I am actually using Java DB - in case I didn't know.
Copy-paste whatever you can find on google and pray to God.
It is there to specify another column as the default id column of the other table, e.g. consider the following
TableA
id int identity
tableb_key varchar
TableB
id int identity
key varchar unique
// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")
In my case, I used a keyword as a column name, which resulted in ERROR: operator does not exist: name = bigint
The solution was to use double quotes around the column name.
Here's a variant of the solution from @JoshuaUlrich that uses the correct size instead of a hard-coded size:
fileName <- 'foo.txt'
readChar(fileName, file.info(fileName)$size)
Note that readChar allocates space for the number of bytes you specify, so readChar(fileName, .Machine$integer.max)
does not work well...
You may probably do this way
var currentMonth = new Date().getMonth();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
for(var i = currentMonth-1 ; i<= 4; i++){
console.log(monthNames[i])// make it as an array of objects here
}
SELECT ID+1 "NEXTID"
FROM (
SELECT ID from TABLE1
WHERE ID>100 order by ID
) "X"
WHERE not exists (
SELECT 1 FROM TABLE1 t2
WHERE t2.ID=X.ID+1
)
LIMIT 1
Try using a div tag and block for span!
<div>
<span style="padding-right:3px; padding-top: 3px; display:block;">
<img class="manImg" src="images/ico_mandatory.gif"></img>
</span>
</div>
Below is an example where we can convert float value without any scientific notation.
DECLARE @Floater AS FLOAT = 100000003.141592653
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SET @Floater = @Floater * 10
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SET @Floater = @Floater * 100
SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
,STR(@Floater)
,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
SELECT LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
,FORMAT(@Floater, '')
In the above example, we can see that the format function is useful for us. FORMAT() function returns always nvarchar.
For a 2008 question, I thought I might add a more recent and up-to-date answer on how you could go about changing the colour of bullets in a list.
If you are willing to use external libraries, Font Awesome gives you scalable vector icons, and when combined with Bootstrap's helper classes (eg. text-success
), you can make some pretty cool and customisable lists.
I have expanded on the extract from the Font Awesome list examples page below:
Use
fa-ul
andfa-li
to easily replace default bullets in unordered lists.
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<ul class="fa-ul">_x000D_
<li><i class="fa-li fa fa-circle"></i>List icons</li>_x000D_
<li><i class="fa-li fa fa-check-square text-success"></i>can be used</li>_x000D_
<li><i class="fa-li fa fa-spinner fa-spin text-primary"></i>as bullets</li>_x000D_
<li><i class="fa-li fa fa-square text-danger"></i>in lists</li>_x000D_
</ul>
_x000D_
Font Awesome (mostly) supports IE8, and only supports IE7 if you use the older version 3.2.1.
For me brew postinstall python3
didn't work. I found this solution on the GitHub Homebrew issues page:
$ brew rm python
$ rm -rf /usr/local/opt/python
$ brew cleanup
$ brew install python3
In view.py Implement function like,
def download(request, id):
obj = your_model_name.objects.get(id=id)
filename = obj.model_attribute_name.path
response = FileResponse(open(filename, 'rb'))
return response
For all files (default setting for opened file): Settings/Preferences | Editor | General | Use soft wraps in editor
For currently opened file in editor: Menu | View | Active Editor | Use Soft Wraps
In latest IDE versions you can also access this option via context menu for the editor gutter area (the area with line numbers on the left side of the editor).
Search Everywhere
(Shift 2x times) or Help | Find Action...
( Ctrl + Shift+ A on Windows using Default keymap) can also be used to quickly change this option (instead of going into Settings/Preferences).
Make sure that all functions with non-void return type have a return
statement.
While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.
What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?
I can see the following issues with that SP, which may or may not relate to your problem:
)
after @BrandName
in your SELECT
(at the end)@CategoryID
or @BrandName
to anything anywhere (they're local variables, but you don't assign values to them)Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID
, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:
CREATE PROCEDURE AddBrand
@BrandName nvarchar(50),
@CategoryID int
AS
BEGIN
DECLARE @BrandID int
SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END
You would then call this like this:
EXEC AddBrand 'Gucci', 23
...assuming the brand name was 'Gucci' and category ID was 23.
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
@scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like @Dre's answer, with the parameterized query.
This is my way. I opened a file in DOS EOL and when I save the file, that will automatically convert to Unix EOL:
autocmd BufWrite * :set ff=unix
You can't return an XmlElement
or an XmlNode
, because those objects always and only exist within the context of an owning XmlDocument
.
XML serialization is a little easier than returning an XElement
, because all you have to do is mark properties with attributes and the serializer does all the XML generation for you. (Plus you get deserialization for free, assuming you have a parameterless constructor and, well, a bunch of other things.)
On the other hand, a) you have to create an XmlSerializer
to do it, b) dealing with collection properties isn't quite the no-brainer you might like it to be, and c) XML serialization is pretty dumb; you're out of luck if you want to do anything fancy with the XML you're generating.
In a lot of cases, those issues don't matter one bit. I for one would rather mark my properties with attributes than write a method.
All have given a very good explanation. I am still posting my answer just to give an example if that can help.
// break statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
break; // It will force to come out from the loop
}
lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
Here is the output:
0[Printed] 1[Printed] 2[Printed]
So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3
//continue statement
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue; // It will take the control to start point of loop
}
lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}
Here is the output:
0[Printed] 1[Printed] 2[Printed] 4[Printed]
So 3[Printed] will not be displayed as there is continue when i == 3
Difference between dp
and sp
units mentioned as "user's font size preference" by the answers copied from official documentation can be seen at run time by changing Settings->Accessibility->Large Text
option.
Large Text
option forces text to become 1.3
times bigger.
private static final float LARGE_FONT_SCALE = 1.3f;
This might be well of course vendor dependent since it lies in packages/apps/Settings.
In a case where you may be storing true / false as strings, such as in localStorage where the protocol flipped to multi object storage in 2009 & then flipped back to string only in 2011 - you can use JSON.parse to interpret to boolean on the fly:
this.sidebar = !JSON.parse(this.sidebar);
The padding options padx
and pady
of the grid
and pack
methods can take a 2-tuple that represent the left/right and top/bottom padding.
Here's an example:
import tkinter as tk
class MyApp():
def __init__(self):
self.root = tk.Tk()
l1 = tk.Label(self.root, text="Hello")
l2 = tk.Label(self.root, text="World")
l1.grid(row=0, column=0, padx=(100, 10))
l2.grid(row=1, column=0, padx=(10, 100))
app = MyApp()
app.root.mainloop()
A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.
Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.
For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.
xcopy e:\source_folder f:\destination_folder /e /i /h
The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.
I've just did a hard reset on wrong project. What saved my life was Eclipse's local history. IntelliJ Idea is said to have one, too, and so may your editor, it's worth checking:
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()
Popular solution is to append username and password in URL, like, http://username:[email protected]. However, if your username or password contains special character, then it may fail. So when you create the URL, make sure you encode those special characters.
String username = URLEncoder.encode(user, StandardCharsets.UTF_8.toString());
String password = URLEncoder.encode(pass, StandardCharsets.UTF_8.toString());
String url = “http://“ + username + “:” + password + “@website.com”;
driver.get(url);
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
You can also use Arrays.copyOfRange
.
Example:
public static void main(String[] args) {
int[] a = {1,2,3};
int[] b = Arrays.copyOfRange(a, 0, a.length);
a[0] = 5;
System.out.println(Arrays.toString(a)); // [5,2,3]
System.out.println(Arrays.toString(b)); // [1,2,3]
}
This method is similar to Arrays.copyOf
, but it's more flexible. Both of them use System.arraycopy
under the hood.
See:
One line answer:
IFS=$'\n'; for line in $(cat file.txt); do echo "$line" ; done
Table creation Syntax can be like:
Create table api_key(api_key_id INT NOT NULL IDENTITY(1,1)
PRIMARY KEY, date_added date DEFAULT
GetDate());
Insertion query syntax can be like:
Insert into api_key values(GETDATE());
Don't know if it's the best way but I'd do this:
=A1 & TEXT(A2,"mm/dd/yyyy")
That should format your date into your desired string.
Edit: That funny number you saw is the number of days between December 31st 1899 and your date. That's how Excel stores dates.
How about the following 3 statements?
-- change to your schema
ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;
-- check current schema
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;
-- generate drop table statements
SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';
COPY the RESULT and PASTE and RUN.
while Alexey Kukanov's answer may be more efficient, you can also iterate through a queue in a very natural manner, by popping each element from the front of the queue, then pushing it to the back:
#include <iostream>
#include <queue>
using namespace std;
int main() {
//populate queue
queue<int> q;
for (int i = 0; i < 10; ++i) q.push(i);
// iterate through queue
for (size_t i = 0; i < q.size(); ++i) {
int elem = std::move(q.front());
q.pop();
elem *= elem;
q.push(std::move(elem));
}
//print queue
while (!q.empty()) {
cout << q.front() << ' ';
q.pop();
}
}
output:
0 1 4 9 16 25 36 49 64 81
One is an interface (CharSequence
) while other is a concrete implementation of that interface (String
).
CharSequence animal = "cat" // `String` object presented as the interface `CharSequence`.
Just like ArrayList
is a List
, and HashMap
is a Map
, so too String
is a CharSequence
.
As an interface, normally the CharSequence
would be more commonly seen than String
, but some twisted history resulted in the interface being defined years after the implementation. So in older APIs we often see String
while in newer APIs we tend to see CharSequence
used to define arguments and return types.
Nowadays we know that generally an API/framework should focus on exporting interfaces primarily and concrete classes secondarily. But we did not always know this lesson so well.
The String
class came first in Java. Only later did they place a front-facing interface, CharSequence
.
A little history might help with understanding.
In its early days, Java was rushed to market a bit ahead of its time, due to the Internet/Web mania animating the industry. Some libraries were not as well thought-through as they should have been. String handling was one of those areas.
Also, Java was one of the earliest production-oriented non-academic Object-Oriented Programming (OOP) environments. The only successful real-world rubber-meets-the-road implementations of OOP before that was some limited versions of SmallTalk, then Objective-C with NeXTSTEP/OpenStep. So, many practical lessons were yet to be learned.
Java started with the String
class and StringBuffer
class. But those two classes were unrelated, not tied to each other by inheritance nor interface. Later, the Java team recognized that there should have been a unifying tie between string-related implementations to make them interchangeable. In Java 4 the team added the CharSequence
interface and retroactively implemented that interface on String and String Buffer, as well as adding another implementation CharBuffer
. Later in Java 5 they added StringBuilder
, basically a unsynchronized and therefore somewhat faster version of StringBuffer
.
So these string-oriented classes are a bit of a mess, and a little confusing to learn about. Many libraries and interfaces were built to take and return String
objects. Nowadays such libraries should generally be built to expect CharSequence
. But (a) String
seems to still dominate the mindspace, and (b) there may be some subtle technical issues when mixing the various CharSequence
implementations. With the 20/20 vision of hindsight we can see that all this string stuff could have been better handled, but here we are.
Ideally Java would have started with an interface and/or superclass that would be used in many places where we now use String
, just as we use the Collection
or List
interfaces in place of the ArrayList
or LinkedList
implementations.
The key difference about CharSequence
is that it is an interface, not an implementation. That means you cannot directly instantiate a CharSequence
. Rather you instantiate one of the classes that implements that interface.
For example, here we have x
that looks like a CharSequence
but underneath is actually a StringBuilder
object.
CharSequence x = new StringBuilder( "dog" ); // Looks like a `CharSequence` but is actually a `StringBuilder` instance.
This becomes less obvious when using a String literal. Keep in mind that when you see source code with just quote marks around characters, the compiler is translating that into a String object.
CharSequence y = "cat"; // Looks like a `CharSequence` but is actually a `String` instance.
There are some subtle differences between "cat"
and new String("cat")
as discussed in this other Question, but are irrelevant here.
This class diagram may help to guide you. I noted the version of Java in which they appeared to demonstrate how much change has churned through these classes and interfaces.
Other than adding more Unicode characters including a multitude of emoji, in recent years not much has changed in Java for working with text. Until text blocks.
Text blocks are a new way of better handling the tedium of string literals with multiple lines or character-escaping. This would make writing embedded code strings such as HTML, XML, SQL, or JSON much more convenient.
To quote JEP 378:
A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.
The text blocks feature does not introduce a new data type. Text blocks are merely a new syntax for writing a String
literal. A text block produces a String
object, just like the conventional literal syntax. A text block produces a String
object, which is also a CharSequence
object, as discussed above.
To quote JSR 378 again…
Using "one-dimensional" string literals.
String query = "SELECT \"EMP_ID\", \"LAST_NAME\" FROM \"EMPLOYEE_TB\"\n" +
"WHERE \"CITY\" = 'INDIANAPOLIS'\n" +
"ORDER BY \"EMP_ID\", \"LAST_NAME\";\n";
Using a "two-dimensional" block of text
String query = """
SELECT "EMP_ID", "LAST_NAME" FROM "EMPLOYEE_TB"
WHERE "CITY" = 'INDIANAPOLIS'
ORDER BY "EMP_ID", "LAST_NAME";
""";
Text blocks are found in Java 15 and later, per JEP 378: Text Blocks.
First previewed in Java 13, under JEP 355: Text Blocks (Preview). Then previewed again in Java 14 under JEP 368: Text Blocks (Second Preview).
This effort was preceded by JEP 326: Raw String Literals (Preview). The concepts were reworked to produce the Text Blocks feature instead.
In case this happens to someone. I built my own library to use with a third party code. While I was building it to deliver, I accidentally left my iPhone 4S plugged in, and so Xcode built my library only for the plugged architecture instead of following the project settings. Remove any plugged in devices and rebuilt the library, link it, and you should be all right.
Hope it helps.
You can use Exif-JS , to check the "Orientation" property of the image. Then apply a css transform as needed.
EXIF.getData(imageElement, function() {
var orientation = EXIF.getTag(this, "Orientation");
if(orientation == 6)
$(imageElement).css('transform', 'rotate(90deg)')
});
The best solution for me is:
// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
With angular5
the above answer no longer works!
The following code:
app.module.ts
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
//otherProviders...
]
})
Leads to following error:
Error: Missing locale data for the locale "de-at".
With angular5
you have to load and register the used locale file on your own.
app.module.ts
import { NgModule, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeDeAt from '@angular/common/locales/de-at';
registerLocaleData(localeDeAt);
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "de-at" }, //replace "de-at" with your locale
//otherProviders...
]
})
This answer is for users of SourceTree with limited terminal git experience.
Open the problematic submodule from within the Git project (super-project).
Fetch and ensure 'Fetch all tags' is checked.
Rebase pull your Git project.
This will solve the 'reference is not a tree' problem 9 out of ten times. That 1 time it won't, is a terminal fix as described by the top answer.
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
Very easy, just use the SQLCMD-syntax.
Remember to enable SQLCMD-mode in the SSMS, look under Query -> SQLCMD Mode
Try execute:
!!DIR
!!:GO
or maybe:
!!DIR "c:/temp"
!!:GO
I fixed this by updating the Request
class that my Controller receives.
I removed the following class level annotation from my Request
class on my server side. After that my client didn't get 415 error.
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
You could use something like this:
(function($) {
$.fn.parentNth = function(n) {
var el = $(this);
for(var i = 0; i < n; i++)
el = el.parent();
return el;
};
})(jQuery);
alert($("#foo").parentNth(2).attr("id"));
You shouldn't have to set height: 100%
at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hidden
to the container.
#container { overflow: hidden; }
Should be enough to solve whatever height problem you're having.
Please note: The first part of this answer is or version 1.x of pendulum. See below for a version 2.x answer.
I hope I'm not too late!
The pendulum library excels at this and other date-time calculations.
>>> import pendulum
>>> some_time_zones = ['Europe/Paris', 'Europe/Moscow', 'America/Toronto', 'UTC', 'Canada/Pacific', 'Asia/Macao']
>>> heres_a_time = '1996-03-25 12:03 -0400'
>>> pendulum_time = pendulum.datetime.strptime(heres_a_time, '%Y-%m-%d %H:%M %z')
>>> for tz in some_time_zones:
... tz, pendulum_time.astimezone(tz)
...
('Europe/Paris', <Pendulum [1996-03-25T17:03:00+01:00]>)
('Europe/Moscow', <Pendulum [1996-03-25T19:03:00+03:00]>)
('America/Toronto', <Pendulum [1996-03-25T11:03:00-05:00]>)
('UTC', <Pendulum [1996-03-25T16:03:00+00:00]>)
('Canada/Pacific', <Pendulum [1996-03-25T08:03:00-08:00]>)
('Asia/Macao', <Pendulum [1996-03-26T00:03:00+08:00]>)
Answer lists the names of the time zones that may be used with pendulum. (They're the same as for pytz.)
For version 2:
some_time_zones
is a list of the names of the time zones that might be used in a programheres_a_time
is a sample time, complete with a time zone in the form '-0400'show_time_zones
...
>>> import pendulum
>>> some_time_zones = ['Europe/Paris', 'Europe/Moscow', 'America/Toronto', 'UTC', 'Canada/Pacific', 'Asia/Macao']
>>> heres_a_time = '1996-03-25 12:03 -0400'
>>> pendulum_time = pendulum.from_format('1996-03-25 12:03 -0400', 'YYYY-MM-DD hh:mm ZZ')
>>> for tz in some_time_zones:
... tz, pendulum_time.in_tz(tz)
...
('Europe/Paris', DateTime(1996, 3, 25, 17, 3, 0, tzinfo=Timezone('Europe/Paris')))
('Europe/Moscow', DateTime(1996, 3, 25, 19, 3, 0, tzinfo=Timezone('Europe/Moscow')))
('America/Toronto', DateTime(1996, 3, 25, 11, 3, 0, tzinfo=Timezone('America/Toronto')))
('UTC', DateTime(1996, 3, 25, 16, 3, 0, tzinfo=Timezone('UTC')))
('Canada/Pacific', DateTime(1996, 3, 25, 8, 3, 0, tzinfo=Timezone('Canada/Pacific')))
('Asia/Macao', DateTime(1996, 3, 26, 0, 3, 0, tzinfo=Timezone('Asia/Macao')))
You can do like this:
Sub Get_Environmental_Variable()
Dim sHostName As String
Dim sUserName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
' Get Current User Name
sUserName = Environ$("username")
End Sub
For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post (TL;DR for most folks) which led me to this concise example.
The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.
That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:
var table = $('#example').DataTable();
table.rows.add( $(
'<tr>'+
' <td>Tiger Nixon</td>'+
' <td>System Architect</td>'+
' <td>Edinburgh</td>'+
' <td>61</td>'+
' <td>2011/04/25</td>'+
' <td>$3,120</td>'+
'</tr>'
) ).draw();
The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.
Here's a pl/pgsql function that locates records where any column contains a specific value. It takes as arguments the value to search in text format, an array of table names to search into (defaults to all tables) and an array of schema names (defaults all schema names).
It returns a table structure with schema, name of table, name of column and pseudo-column ctid
(non-durable physical location of the row in the table, see System Columns)
CREATE OR REPLACE FUNCTION search_columns(
needle text,
haystack_tables name[] default '{}',
haystack_schema name[] default '{}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
FOR schemaname,tablename,columnname IN
SELECT c.table_schema,c.table_name,c.column_name
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
JOIN information_schema.table_privileges p ON
(t.table_name=p.table_name AND t.table_schema=p.table_schema
AND p.privilege_type='SELECT')
JOIN information_schema.schemata s ON
(s.schema_name=t.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND (c.table_schema=ANY(haystack_schema) OR haystack_schema='{}')
AND t.table_type='BASE TABLE'
LOOP
FOR rowctid IN
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
schemaname,
tablename,
columnname,
needle
)
LOOP
-- uncomment next line to get some progress report
-- RAISE NOTICE 'hit in %.%', schemaname, tablename;
RETURN NEXT;
END LOOP;
END LOOP;
END;
$$ language plpgsql;
See also the version on github based on the same principle but adding some speed and reporting improvements.
Examples of use in a test database:
select * from search_columns('foobar'); schemaname | tablename | columnname | rowctid ------------+-----------+------------+--------- public | s3 | usename | (0,11) public | s2 | relname | (7,29) public | w | body | (0,2) (3 rows)
select * from search_columns('foobar','{w}'); schemaname | tablename | columnname | rowctid ------------+-----------+------------+--------- public | w | body | (0,2) (1 row)
select * from search_columns('foobar', array(select table_name::name from information_schema.tables where table_name like 's%'), array['public']); schemaname | tablename | columnname | rowctid ------------+-----------+------------+--------- public | s2 | relname | (7,29) public | s3 | usename | (0,11) (2 rows)
select * from public.w where ctid='(0,2)'; title | body | tsv -------+--------+--------------------- toto | foobar | 'foobar':2 'toto':1
To test against a regular expression instead of strict equality, like grep, this part of the query:
SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L
may be changed to:
SELECT ctid FROM %I.%I WHERE cast(%I as text) ~ %L
For case insensitive comparisons, you could write:
SELECT ctid FROM %I.%I WHERE lower(cast(%I as text)) = lower(%L)
Format
A U Thor <[email protected]>
simply mean that you should specify
FirstName MiddleName LastName <[email protected]>
Looks like middle and last names are optional (maybe the part before email doesn't have a strict format at all). Try, for example, this:
git commit --author="John <[email protected]>" -m "some fix"
As the docs say:
--author=<author>
Override the commit author. Specify an explicit author using the standard
A U Thor <[email protected]> format. Otherwise <author> is assumed to
be a pattern and is used to search for an existing commit by that author
(i.e. rev-list --all -i --author=<author>); the commit author is then copied
from the first such commit found.
if you don't use this format, git treats provided string as a pattern and tries to find matching name among the authors of other commits.
Here's some reusable css that will preserve the height of each element without using position: absolute
:
.stack {
display: grid;
}
.stack > * {
grid-row: 1;
grid-column: 1;
}
The first element in your stack
is the background, and the second is the foreground.
Try:
-webkit-transition: all .2s linear, background-position 0;
This worked for me on something similar..
You can get other constructors with getConstructor(...).
function msort(arr){
for(var i =0;i<arr.length;i++){
for(var j= i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
var swap = arr[i];
arr[i] = arr[j];
arr[j] = swap;
}
}
}
return arr;
}
# index dictionary by list of key names
def fn1():
print "One"
def fn2():
print "Two"
def fn3():
print "Three"
fndict = {"A": fn1, "B": fn2, "C": fn3}
keynames = ["A", "B", "C"]
fndict[keynames[1]]()
# keynames[1] = "B", so output of this code is
# Two
This is very simple and easily manage.
jQuery(document).ready(function(){
jQuery("#search").click(function(){
jQuery("#loader").show("slow");
jQuery("#response_result").hide("slow");
jQuery.post(siteurl+"/ajax.php?q="passyourdata, function(response){
setTimeout("finishAjax('response_result', '"+escape(response)+"')", 850);
});
});
})
function finishAjax(id,response){
jQuery("#loader").hide("slow");
jQuery('#response_result').html(unescape(response));
jQuery("#"+id).show("slow");
return true;
}
A primitive type cannot be null. So the solution is replace primitive type with primitive wrapper class in your tableName.java file. Such as:
@Column(nullable=true, name="client_os_id")
private Integer client_os_id;
public int getClient_os_id() {
return client_os_id;
}
public void setClient_os_id(int clientOsId) {
client_os_id = clientOsId;
}
reference http://en.wikipedia.org/wiki/Primitive_wrapper_class to find wrapper class of a primivite type.
If you are using Spring you can use StringUtils.join()
method which also allows you to specify prefix and suffix.
String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
"\n", "<value>", "</value>");
But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces.
Since an executable could, during execution of a process running it, rename(2) its file path to a different directory (of the same file system). See also syscalls(2) and inode(7).
On Linux, an executable could even (in principle) remove(3) itself by calling unlink(2). The Linux kernel should then keep the file allocated till no process references it anymore. With proc(5) you could do weird things (e.g. rename(2) that /proc/self/exe
file, etc...)
In other words, on Linux, the notion of a "current application's directory" does not make any sense.
Read also Advanced Linux Programming and Operating Systems: Three Easy Pieces for more.
Look also on OSDEV for several open source operating systems (including FreeBSD or GNU Hurd). Several of them provide an interface (API) close to POSIX ones.
Consider using (with permission) cross-platform C++ frameworks like Qt or POCO, perhaps contributing to them by porting them to your favorite OS.
Brighams answer uses literal regexp
.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
I run into this exact message often because I create a local branches via git checkout -b <feature-branch-name>
without first creating the remote branch.
After all the work was finished and committed locally the fix was git push -u
which created the remote branch, pushed all my work, and then the merge-request URL.
The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only
$("a").click(function(event) {
event.preventDefault();
});
If this method is called, the default action of the event will not be triggered.
PHP can use something like pointers:
$y=array(&$x);
Now $y acts like a pointer to $x and $y[0] dereferences a pointer.
The value array(&$x) is just a value, so it can be passed to functions, stored in other arrays, copied to other variables, etc. You can even create a pointer to this pointer variable. (Serializing it will break the pointer, however.)
According to Apple's session on "Implementing Dark Mode on iOS" (https://developer.apple.com/videos/play/wwdc2019/214/ starting at 31:13) it is possible to set overrideUserInterfaceStyle
to UIUserInterfaceStyleLight
or UIUserInterfaceStyleDark
on any view controller or view, which will the be used in the traitCollection
for any subview or view controller.
As already mentioned by SeanR, you can set UIUserInterfaceStyle
to Light
or Dark
in your app's plist file to change this for your whole app.
SELECT *
FROM TableName
WHERE julianday(substr(date,7)||'-'||substr(date,4,2)||'-'||substr(date,1,2)) BETWEEN julianday('2011-01-11') AND julianday('2011-08-11')
Note that I use the format : dd/mm/yyyy
If you use d/m/yyyy, Change in substr()
Hope this will help you.
I use helper class. Not sure it's good or bad
public class ListHelper<T> {
private final T[] t;
public ListHelper(T[] t) {
this.t = t;
}
public List<T> unique(List<T> list) {
Set<T> set = new HashSet<>(list);
return Arrays.asList(set.toArray(t));
}
}
Usage and test:
import static org.assertj.core.api.Assertions.assertThat;
public class ListHelperTest {
@Test
public void unique() {
List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
List<String> unique = new ListHelper<>(new String[0]).unique(s);
assertThat(unique).hasSize(3);
}
}
Or Java8 version:
public class ListHelper<T> {
public Function<List<T>, List<T>> unique() {
return l -> l.stream().distinct().collect(Collectors.toList());
}
}
public class ListHelperTest {
@Test
public void unique() {
List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
assertThat(new ListHelper<String>().unique().apply(s)).hasSize(3);
}
}
When you use just "localhost" the MySQL client library tries to use a Unix domain socket for the connection instead of a TCP/IP connection. The error is telling you that the socket, called MySQL
, cannot be used to make the connection, probably because it does not exist (error number 2).
From the MySQL Documentation:
On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option.
There are a few ways to solve this problem.
127.0.0.1
instead of localhost
when you connect. The Unix socket might by faster and safer to use, though.php.ini
: open the MySQL configuration file my.cnf
to find where MySQL creates the socket, and set PHP's mysqli.default_socket
to that path. On my system it's /var/run/mysqld/mysqld.sock
.Configure the socket directly in the PHP script when opening the connection. For example:
$db = new MySQLi('localhost', 'kamil', '***', '', 0,
'/var/run/mysqld/mysqld.sock')
Not sure if it's what you mean, but you can do this:
plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])
which then gives you the graph:
I ran into this issue around the time MVC1 was first released. See Generating PDF, error with IE and HTTPS regarding the Cache-Control header.
Declare a notification name
extension Notification.Name {
static let purchaseDidFinish = Notification.Name("purchaseDidFinish")
}
You can add observer in two ways:
Using Selector
NotificationCenter.default.addObserver(self, selector: #selector(myFunction), name: .purchaseDidFinish, object: nil)
@objc func myFunction(notification: Notification) {
print(notification.object ?? "") //myObject
print(notification.userInfo ?? "") //[AnyHashable("key"): "Value"]
}
or using block
NotificationCenter.default.addObserver(forName: .purchaseDidFinish, object: nil, queue: nil) { [weak self] (notification) in
guard let strongSelf = self else {
return
}
strongSelf.myFunction(notification: notification)
}
func myFunction(notification: Notification) {
print(notification.object ?? "") //myObject
print(notification.userInfo ?? "") //[AnyHashable("key"): "Value"]
}
Post your notification
NotificationCenter.default.post(name: .purchaseDidFinish, object: "myObject", userInfo: ["key": "Value"])
from iOS 9 and OS X 10.11. It is no longer necessary for an NSNotificationCenter observer to un-register itself when being deallocated. more info
For a block
based implementation you need to do a weak-strong dance if you want to use self
inside the block. more info
Block based observers need to be removed more info
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self.localeChangeObserver)
To Achieve ellipses for the text use the Text property numberofLines={1} which will automatically truncate the text with an ellipsis you can specify the ellipsizeMode as "head", "middle", "tail" or "clip" By default it is tail
I liked the solution provided by @madhead
However the problem I had is that it wouldn't work for a sorted list so instead of passing the index to the delete function I passed the item and then got the index via indexof
e.g.:
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
An updated version of madheads example is below: link to example
HTML
<!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div data-ng-controller="DemoController">
<ul>
<li data-ng-repeat="item in items|orderBy:'toString()'">
{{item}}
<button data-ng-click="removeItem(item)">Remove</button>
</li>
</ul>
<input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
</div>
</body>
</html>
JavaScript
"use strict";
var demo = angular.module("demo", []);
function DemoController($scope){
$scope.items = [
"potatoes",
"tomatoes",
"flour",
"sugar",
"salt"
];
$scope.addItem = function(item){
$scope.items.push(item);
$scope.newItem = null;
}
$scope.removeItem = function(item){
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
}
}
Not sure about your specific scenario, but you have three options:
1.) use Dictionary<..,..>
2.) create a wrapper class around your values and then you can use List
3.) use Tuple
your form is missing the method...
<form name="registrationform" action="register.php" method="post"> //here
anywyas to check the posted data u can use isset()..
Determine if a variable is set and is not NULL
if(!isset($firstname) || trim($firstname) == '')
{
echo "You did not fill out the required fields.";
}
'Create a class to hold the pair...
Public Class ColumnValue
Public ColumnName As String
Public ColumnValue As New Object
End Class
'Build the pair...
For Each row In [YourDataTable].Rows
For Each item As DataColumn In row.Table.Columns
Dim rowValue As New ColumnValue
rowValue.ColumnName = item.Caption
rowValue.ColumnValue = row.item(item.Ordinal)
RowValues.Add(rowValue)
rowValue = Nothing
Next
' Now you can grab the value by the column name...
Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select p.ColumnValue).FirstOrDefault
Next
Previous answers are good enough, but they might update original data. In case if you don't want the original data to be affected, you can try my code.
newhash=hash.reject{|k| k=='_id'}.merge({id:hash['_id']})
First it will ignore the key '_id' then merge with the updated one.
You can use file prefix to load the external application context file some thing like this
<context:property-placeholder location="file:///C:/Applications/external/external.properties"/>
You can use JavaScript like... Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
In my opinion it is worth to say that with the newly released EntityGraphOperations for Entity Framework Code First you can save yourself from writing some repetitive codes for defining the states of all entities in the graph. I am the author of this product. And I have published it in the github, code-project (includes a step-by-step demonstration and a sample project is ready for downloading) and nuget.
It will automatically set the state of the entities to Added
or Modified
. And you will manually choose which entities must be deleted if it is not exist anymore.
The example:
Let’s say I have get a Person
object. Person
could has many phones, a Document and could has a spouse.
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public int Age { get; set; }
public int DocumentId {get; set;}
public virtual ICollection<Phone> Phones { get; set; }
public virtual Document Document { get; set; }
public virtual PersonSpouse PersonSpouse { get; set; }
}
I want to determine the state of all entities which is included in the graph.
context.InsertOrUpdateGraph(person)
.After(entity =>
{
// Delete missing phones.
entity.HasCollection(p => p.Phones)
.DeleteMissingEntities();
// Delete if spouse is not exist anymore.
entity.HasNavigationalProperty(m => m.PersonSpouse)
.DeleteIfNull();
});
Also as you know unique key properties could play role while defining the state of Phone entity. For such special purposes we have ExtendedEntityTypeConfiguration<>
class, which inherits from EntityTypeConfiguration<>
. If we want to use such special configurations then we must inherit our mapping classes from ExtendedEntityTypeConfiguration<>
, rather than EntityTypeConfiguration<>
. For example:
public class PhoneMap: ExtendedEntityTypeConfiguration<Phone>
{
public PhoneMap()
{
// Primary Key
this.HasKey(m => m.Id);
…
// Unique keys
this.HasUniqueKey(m => new { m.Prefix, m.Digits });
}
}
That’s all.
Calling addView
is the correct answer, but you need to do a little more than that to get it to work.
If you create a View via a constructor (e.g., Button myButton = new Button();
), you'll need to call setLayoutParams
on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.
For example, you might have the following code in your onCreate()
function assuming your LinearLayout has id R.id.main
:
LinearLayout myLayout = findViewById(R.id.main);
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
myLayout.addView(myButton);
Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.
I made this function for my needs.
Feel free to use it. Works great on mobile devices.
function detectswipe(el,func) {
swipe_det = new Object();
swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
var min_x = 30; //min x swipe for horizontal swipe
var max_x = 30; //max x difference for vertical swipe
var min_y = 50; //min y swipe for vertical swipe
var max_y = 60; //max y difference for horizontal swipe
var direc = "";
ele = document.getElementById(el);
ele.addEventListener('touchstart',function(e){
var t = e.touches[0];
swipe_det.sX = t.screenX;
swipe_det.sY = t.screenY;
},false);
ele.addEventListener('touchmove',function(e){
e.preventDefault();
var t = e.touches[0];
swipe_det.eX = t.screenX;
swipe_det.eY = t.screenY;
},false);
ele.addEventListener('touchend',function(e){
//horizontal detection
if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y) && (swipe_det.eX > 0)))) {
if(swipe_det.eX > swipe_det.sX) direc = "r";
else direc = "l";
}
//vertical detection
else if ((((swipe_det.eY - min_y > swipe_det.sY) || (swipe_det.eY + min_y < swipe_det.sY)) && ((swipe_det.eX < swipe_det.sX + max_x) && (swipe_det.sX > swipe_det.eX - max_x) && (swipe_det.eY > 0)))) {
if(swipe_det.eY > swipe_det.sY) direc = "d";
else direc = "u";
}
if (direc != "") {
if(typeof func == 'function') func(el,direc);
}
direc = "";
swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
},false);
}
function myfunction(el,d) {
alert("you swiped on element with id '"+el+"' to "+d+" direction");
}
To use the function just use it like
detectswipe('an_element_id',myfunction);
detectswipe('an_other_element_id',my_other_function);
If a swipe is detected the function "myfunction" is called with parameter element-id and "l,r,u,d" (left,right,up,down).
Example: http://jsfiddle.net/rvuayqeo/1/
I (UlysseBN) made a new version of this script based on this one which use more modern JavaScript, it looks like it behaves better on some cases. If you think it should rather be an edit of this answer let me know, if you are the original author and you end up editing, I'll delete my answer.
If you have a newer distro with a newer systemd
(systemd
version 236 or newer), you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
.
Long story:
In newer versions of systemd
there is a relatively new option (the github request is from 2016 ish and the enhancement is merged/closed 2017 ish) where you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
. The file:path
option is documented in the most recent systemd.exec
man page.
This new feature is relatively new and so is not available for older distros like centos-7 (or any centos before that).
Consider it as an array of arrays and this will work for sure.
int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
}
}
Please use json.Decoder
instead of json.Unmarshal
.
func test(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t test_struct
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
log.Println(t.Test)
}
import datetime
monthinteger = 4
month = datetime.date(1900, monthinteger, 1).strftime('%B')
print month
April
static variable stored in data segment or code segment as mentioned before.
You can be sure that it will not be allocated on stack or heap.
There is no risk for collision since static
keyword define the scope of the variable to be a file or function, in case of collision there is a compiler/linker to warn you about.
A nice example
This should work. You need to put in two slashes
str = str.replaceAll("(\\r\\n|\\n)", "<br />");
In this Reference, there is an example which shows
private final String REGEX = "\\d"; // a single digit
I have used two slashes in many of my projects and it seems to work fine!
After nearly a decade of work — with proposals, proofs-of-concept, discussions and other contributions by the broader web developer community — the CSS Working Group has finally laid some of the groundwork needed for container queries to be written into a future edition of the CSS Containment spec! For more details on how such a feature might work and be used, check out Miriam Suzanne's extensive explainer.
Hopefully it won't be much longer before we see a robust cross-browser implementation of such a system. It's been a grueling wait, but I'm glad that it's no longer something we simply have to accept as an insurmountable limitation of CSS due to cyclic dependencies or infinite loops or what have you (these are still a potential issue in some aspects of the proposed design, but I have faith that the CSSWG will find a way).
Media queries aren't designed to work based on elements in a page. They are designed to work based on devices or media types (hence why they are called media queries). width
, height
, and other dimension-based media features all refer to the dimensions of either the viewport or the device's screen in screen-based media. They cannot be used to refer to a certain element on a page.
If you need to apply styles depending on the size of a certain div
element on your page, you'll have to use JavaScript to observe changes in the size of that div
element instead of media queries.
Alternatively, with more modern layout techniques introduced since the original publication of this answer such as flexbox and standards such as custom properties, you may not need media or element queries after all. Djave provides an example.
My issue was resolved by replacing the'SID' in URL with 'service name' and correct host.
In Django 3.x
, the accepted answer won't work because render_to_response
has been removed completely as well as some more changes have been made since the version the accepted answer worked for.
Some other answers are also there but I'm presenting a little cleaner answer:
In your main urls.py
file:
handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'
In yourapp/views.py
file:
def handler404(request, exception):
context = {}
response = render(request, "pages/errors/404.html", context=context)
response.status_code = 404
return response
def handler500(request):
context = {}
response = render(request, "pages/errors/500.html", context=context)
response.status_code = 500
return response
Ensure that you have imported render()
in yourapp/views.py
file:
from django.shortcuts import render
Side note: render_to_response()
was deprecated in Django 2.x
and it has been completely removed in verision 3.x
.
I would like to update the answers above to 2018 and say to use both VisualVM and Eclipse MAT.
VisualVM is used for live monitoring and dump heap. You can also analyze the heap dumps there with great power, however MAT have more capabilities (such as automatic analysis to find leaks) and therefore, I read the VisualVM dump output (.hprof file) into MAT.
Download VisualVM here: https://visualvm.github.io/
You also need to download the plugin for Intellij:
Then you'll see in intellij another 2 new orange icons:
Once you run your app with an orange one, in VisualVM you'll see your process on the left, and data on the right. Sit some time and learn this tool, it is very powerful:
Download here: https://www.eclipse.org/mat/downloads.php
Hope it helps!
From the Twitter FAQ:
Most integrations with the API will require you to identify your application to Twitter by way of an API key. On the Twitter platform, the term "API key" usually refers to what's called an OAuth consumer key. This string identifies your application when making requests to the API. In OAuth 1.0a, your "API keys" probably refer to the combination of this consumer key and the "consumer secret," a string that is used to securely "sign" your requests to Twitter.
For result in base64, before convert to canvas:
var getBase64ImageUrl = function(url, callback, mine) {
var img = new Image();
url = url.replace("http://","//");
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL(mine || "image/jpeg");
callback(dataURL);
};
img.src = url;
img.onerror = function(){
console.log('on error')
callback('');
}
}
getBase64ImageUrl('Koala.jpeg', function(img){
//img is a base64encode result
//return img;
console.log(img);
var doc = new jsPDF();
doc.setFontSize(40);
doc.text(30, 20, 'Hello world!');
doc.output('datauri');
doc.addImage(img, 'JPEG', 15, 40, 180, 160);
});
There's lots of FTP sites you can get into with the 'anonymous' account and download, but a 'public' site that allows anonymous uploads would be utterly swamped with pr0n and warez in short order.
It's easy enough to set up your own FTP server for testing uploads. There's plenty of them for most any desktop OS. There's one built into IIS, for instance.
This is a great solution! With a few additional CSS rules you can format it just like an MS Word outline list with a hanging first line indent:
OL {
counter-reset: item;
}
LI {
display: block;
}
LI:before {
content: counters(item, ".") ".";
counter-increment: item;
padding-right:10px;
margin-left:-20px;
}
you should try with jquery validate plugin :
$('form').validate({
rules:{
email:{
required:true,
email:true
}
},
messages:{
email:{
required:"Email is required",
email:"Please type a valid email"
}
}
})
Also, to "increment" string, when update, use CONCAT
update dbo.test set foo=CONCAT(foo, 'bar') where 1=1
You want this:
function validate() {
var acc = document.getElementsByName('acc')[0].value;
var pass = document.getElementsByName('pass')[0].value;
alert (acc);
}
May this also can help using configuration file like java class way.
@Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfig {
@Autowired
JdbcConfigProperties jdbc;
@Bean(name = "hikariDataSource")
public DataSource hikariDataSource() {
HikariConfig config = new HikariConfig();
HikariDataSource dataSource;
config.setJdbcUrl(jdbc.getUrl());
config.setUsername(jdbc.getUser());
config.setPassword(jdbc.getPassword());
// optional: Property setting depends on database vendor
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
dataSource = new HikariDataSource(config);
return dataSource;
}
}
How to use it:
@Component
public class Car implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(AptSommering.class);
@Autowired
@Qualifier("hikariDataSource")
private DataSource hikariDataSource;
}
You can specify a new column. You also need to compute the mean along the rows, so use axis=1
.
df['mean'] = df.mean(axis=1)
>>> df
Y1961 Y1962 Y1963 Y1964 Y1965 Region mean
0 82.567307 83.104757 83.183700 83.030338 82.831958 US 82.943612
1 2.699372 2.610110 2.587919 2.696451 2.846247 US 2.688020
2 14.131355 13.690028 13.599516 13.649176 13.649046 US 13.743824
3 0.048589 0.046982 0.046583 0.046225 0.051750 US 0.048026
4 0.553377 0.548123 0.582282 0.577811 0.620999 US 0.576518
Make sure that the sorting is not to complicated for the end user. I always thought sorting on group and sub group is a little bit complicated to understand. If its a technical end user it might be OK.
.NET and Mono are great environments, with many tools and and excellent skills base of people who know how to use them.
I think Mono has the opportunity to be the mobile cross-platform development environment of choice, seeing as they are the only alternative to Objective-C on the iPhone and should be portable to Android, and .NET is already on Windows Mobile.
I'm really hoping to see a solid implementation of Mono on Android, with wrappers for the Android API as with Monotouch, and would be prepared to pay for it since I'm not in a position to do it myself.
Does that work in IE6?
No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.
You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.
EDIT
If you are to ignore IE6, you could do (CSS2.1):
input[type=submit][disabled=disabled],
button[disabled=disabled] {
...
}
CSS3 (IE9+):
input[type=submit]:disabled,
button:disabled {
...
}
You can substitute [disabled=disabled]
(attribute value) with [disabled]
(attribute presence).
I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
work with you apply runat="server" in your div section...
<div runat="server" id="hideid">
On your button click event:
protected void btnSubmit_Click(object sender, EventArgs e)
{
hideid.Visible = false;
}
Use DATE_FORMAT
select DATE_FORMAT(date,'%d') from tablename =>Date only
example:
select DATE_FORMAT(`date_column`,'%d') from `database_name`.`table_name`;
I needed this same solution, but if you use the native ListObject.Add()
method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:
Sub AddDataRow(tableName As String, values() As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = ActiveWorkbook.Worksheets("Sheet1")
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
table.ListRows.Add
Exit For
End If
Next col
Else
table.ListRows.Add
End If
'Iterate through the last row and populate it with the entries from values()
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
Next col
End Sub
To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design
tab of the ribbon, in Excel 2013 at least:
Example code for a table with three columns:
Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x
Try putting the following in the environment variables
for the scheme under run(debug)
OS_ACTIVITY_MODE = disable
Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');
Dec 4, 2020 4:58 PM
moment.locale(); // en
moment().format('LT'); // 4:59 PM
moment().format('LTS'); // 4:59:47 PM
moment().format('L'); // 12/08/2020
moment().format('l'); // 12/8/2020
moment().format('LL'); // December 8, 2020
moment().format('ll'); // Dec 8, 2020
moment().format('LLL'); // December 8, 2020 4:59 PM
moment().format('lll'); // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM
Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>
Somehow "classpath:xxx" is not picking the file.
Typescript is (a superset of) javascript, so you just use JSON.parse
as you would in javascript:
let obj = JSON.parse(jsonString);
Only that in typescript you can have a type to the resulting object:
interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);
Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
recurse-submodules=<check|on-demand>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
So you could push everything in one go with (from the parent repo) a:
git push --recurse-submodules=on-demand
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.
See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe
).
(Merged by Junio C Hamano -- gitster
-- in commit 5d35d72, 21 Dec 2015)
push
: addrecurseSubmodules
config optionThe
--recurse-submodules
command line parameter has existed for some time but it has no config file equivalent.Following the style of the corresponding parameter for
git fetch
, let's inventpush.recurseSubmodules
to provide a default for this parameter.
This also requires the addition of--recurse-submodules=no
to allow the configuration to be overridden on the command line when required.The most straightforward way to implement this appears to be to make
push
use code insubmodule-config
in a similar way tofetch
.
The git config
doc now include:
push.recurseSubmodules
:Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.
- If the value is '
check
', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.- If the value is '
on-demand
' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -- If the value is '
no
' then default behavior of ignoring submodules when pushing is retained.You may override this configuration at time of push by specifying '
--recurse-submodules=check|on-demand|no
'.
So:
git config push.recurseSubmodules on-demand
git push
Git 2.12 (Q1 2017)
git push --dry-run --recurse-submodules=on-demand
will actually work.
See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 12cf113, 16 Dec 2016)
push run with --dry-run
doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.Teach
push
to respect the--dry-run
option when configured to recursively push submodules 'on-demand'.
This is done by passing the--dry-run
flag to the child process which performs a push for a submodules when performing a dry-run.
And still in Git 2.12, you now havea "--recurse-submodules=only
" option to push submodules out without pushing the top-level superproject.
See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw
).
(Merged by Junio C Hamano -- gitster
-- in commit 792e22e, 31 Jan 2017)
When you say "copy the contents of a variable", does that variable contain a file name, or does it contain a name of a file?
I'm assuming by your question that $var
contains the contents you want to copy into the file:
$ echo "$var" > "$destdir"
This will echo the value of $var into a file called $destdir. Note the quotes. Very important to have "$var" enclosed in quotes. Also for "$destdir" if there's a space in the name. To append it:
$ echo "$var" >> "$destdir"
Observation : When you call static method within a static entity, you need to change the class in @PrepareForTest.
For e.g. :
securityAlgo = MessageDigest.getInstance(SECURITY_ALGORITHM);
For the above code if you need to mock MessageDigest class, use
@PrepareForTest(MessageDigest.class)
While if you have something like below :
public class CustomObjectRule {
object = DatatypeConverter.printHexBinary(MessageDigest.getInstance(SECURITY_ALGORITHM)
.digest(message.getBytes(ENCODING)));
}
then, you'd need to prepare the class this code resides in.
@PrepareForTest(CustomObjectRule.class)
And then mock the method :
PowerMockito.mockStatic(MessageDigest.class);
PowerMockito.when(MessageDigest.getInstance(Mockito.anyString()))
.thenThrow(new RuntimeException());
Fast:
SELECT TOP (1) CASE
WHEN **NOT_NULL_COLUMN** IS NULL
THEN 'empty table'
ELSE 'not empty table'
END AS info
FROM **TABLE_NAME**
I have referred this post, it worked like charm , except it did not hide the arrow in IE browser.
However adding following hides the arrow in IE:
&::-ms-expand {_x000D_
display: none;_x000D_
}
_x000D_
Complete solution ( sass )
$select-border-color: #ccc;_x000D_
$select-focus-color: green;_x000D_
_x000D_
select {_x000D_
_x000D_
cursor: pointer;_x000D_
/* styling */_x000D_
background-color: white;_x000D_
border: 1px solid $select-border-color;_x000D_
border-radius: 4px;_x000D_
display: inline-block;_x000D_
font: inherit;_x000D_
line-height: 1.5em;_x000D_
padding: 0.5em 3.5em 0.5em 1em;_x000D_
_x000D_
/* reset */_x000D_
margin: 0;_x000D_
-webkit-box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
box-sizing: border-box;_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
_x000D_
background-image: linear-gradient(45deg, transparent 50%, $select-border-color 50%),_x000D_
linear-gradient(135deg, $select-border-color 50%, transparent 50%),_x000D_
linear-gradient(to right, $select-border-color, $select-border-color);_x000D_
background-position: calc(100% - 20px) calc(1em + 2px),_x000D_
calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 0.5em;_x000D_
background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
background-repeat: no-repeat;_x000D_
_x000D_
/* Very imp: hide arrow in IE */_x000D_
&::-ms-expand {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
&:-moz-focusring {_x000D_
color: transparent;_x000D_
text-shadow: none;_x000D_
}_x000D_
_x000D_
&:focus {_x000D_
background-image: linear-gradient(45deg, $select-focus-color 50%, transparent 50%),_x000D_
linear-gradient(135deg, transparent 50%, $select-focus-color 50%), linear-gradient(to right, $select-focus-color, $select-focus-color);_x000D_
background-position: calc(100% - 15px) 1em, calc(100% - 20px) 1em, calc(100% - 2.5em) 0.5em;_x000D_
background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
background-repeat: no-repeat;_x000D_
border-color: $select-focus-color;_x000D_
outline: 0;_x000D_
}_x000D_
}
_x000D_
Anybody interested in a DOS CMD tail using batch commands (see below).
It's not prefect, and lines sometime repeat.
Usage: tail.bat -d tail.bat -f -f
@echo off
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
rem tail.bat -d <lines> <file>
rem tail.bat -f <file>
rem ****** MAIN ******
IF "%1"=="-d" GOTO displayfile
IF "%1"=="-f" GOTO followfile
GOTO end
rem ************
rem Show Last n lines of file
rem ************
:displayfile
SET skiplines=%2
SET sourcefile=%3
rem *** Get the current line count of file ***
FOR /F "usebackq tokens=3,3 delims= " %%l IN (`find /c /v "" %sourcefile%`) DO (call SET find_lc=%%l)
rem *** Calculate the lines to skip
SET /A skiplines=%find_lc%-!skiplines!
rem *** Display to screen line needed
more +%skiplines% %sourcefile%
GOTO end
rem ************
rem Show Last n lines of file & follow output
rem ************
:followfile
SET skiplines=0
SET findend_lc=0
SET sourcefile=%2
:followloop
rem *** Get the current line count of file ***
FOR /F "usebackq tokens=3,3 delims= " %%l IN (`find /c /v "" %sourcefile%`) DO (call SET find_lc=%%l)
FOR /F "usebackq tokens=3,3 delims= " %%l IN (`find /c /v "" %sourcefile%`) DO (call SET findend_lc=%%l)
rem *** Calculate the lines to skip
SET /A skiplines=%findend_lc%-%find_lc%
SET /A skiplines=%find_lc%-%skiplines%
rem *** Display to screen line when file updated
more +%skiplines% %sourcefile%
goto followloop
:end
I came here and looking how to get the number of elements inside a JSONArray
. From your question i used length()
like that:
JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());
and it worked as expected. On the other hand jar.size();
(as proposed in the other answer) is not working for me.
So for future users searching (like me) how to get the size of a JSONArray
, length()
works just fine.
From quirksmode.org:
Event capturing
When you use event capturing
| | ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 \ / | | | ------------------------- | | Event CAPTURING | -----------------------------------the event handler of element1 fires first, the event handler of element2 fires last.
Event bubbling
When you use event bubbling
/ \ ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 | | | | | ------------------------- | | Event BUBBLING | -----------------------------------the event handler of element2 fires first, the event handler of element1 fires last.
Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.
| | / \ -----------------| |--| |----------------- | element1 | | | | | | -------------| |--| |----------- | | |element2 \ / | | | | | -------------------------------- | | W3C event model | ------------------------------------------
From w3.org, for event capture:
If the capturing
EventListener
wishes to prevent further processing of the event from occurring it may call thestopPropagation
method of theEvent
interface. This will prevent further dispatch of the event, although additionalEventListeners
registered at the same hierarchy level will still receive the event. Once an event'sstopPropagation
method has been called, further calls to that method have no additional effect. If no additional capturers exist andstopPropagation
has not been called, the event triggers the appropriateEventListeners
on the target itself.
For event bubbling:
Any event handler may choose to prevent further event propagation by calling the
stopPropagation
method of theEvent
interface. If anyEventListener
calls this method, all additionalEventListeners
on the currentEventTarget
will be triggered but bubbling will cease at that level. Only one call tostopPropagation
is required to prevent further bubbling.
For event cancelation:
Cancelation is accomplished by calling the
Event
'spreventDefault
method. If one or moreEventListeners
callpreventDefault
during any phase of event flow the default action will be canceled.
In the following examples, a click on the hyperlink in the web browser triggers the event's flow (the event listeners are executed) and the event target's default action (a new tab is opened).
HTML:
<div id="a">
<a id="b" href="http://www.google.com/" target="_blank">Google</a>
</div>
<p id="c"></p>
JavaScript:
var el = document.getElementById("c");
function capturingOnClick1(ev) {
el.innerHTML += "DIV event capture<br>";
}
function capturingOnClick2(ev) {
el.innerHTML += "A event capture<br>";
}
function bubblingOnClick1(ev) {
el.innerHTML += "DIV event bubbling<br>";
}
function bubblingOnClick2(ev) {
el.innerHTML += "A event bubbling<br>";
}
// The 3rd parameter useCapture makes the event listener capturing (false by default)
document.getElementById("a").addEventListener("click", capturingOnClick1, true);
document.getElementById("b").addEventListener("click", capturingOnClick2, true);
document.getElementById("a").addEventListener("click", bubblingOnClick1, false);
document.getElementById("b").addEventListener("click", bubblingOnClick2, false);
Example 1: it results in the output
DIV event capture
A event capture
A event bubbling
DIV event bubbling
Example 2: adding stopPropagation()
to the function
function capturingOnClick1(ev) {
el.innerHTML += "DIV event capture<br>";
ev.stopPropagation();
}
results in the output
DIV event capture
The event listener prevented further downward and upward propagation of the event. However it did not prevent the default action (a new tab opening).
Example 3: adding stopPropagation()
to the function
function capturingOnClick2(ev) {
el.innerHTML += "A event capture<br>";
ev.stopPropagation();
}
or the function
function bubblingOnClick2(ev) {
el.innerHTML += "A event bubbling<br>";
ev.stopPropagation();
}
results in the output
DIV event capture
A event capture
A event bubbling
This is because both event listeners are registered on the same event target. The event listeners prevented further upward propagation of the event. However they did not prevent the default action (a new tab opening).
Example 4: adding preventDefault()
to any function, for instance
function capturingOnClick1(ev) {
el.innerHTML += "DIV event capture<br>";
ev.preventDefault();
}
prevents a new tab from opening.
swift 3.0
self.uiTextView.layer.borderWidth = 0.5
self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor
eval
is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval
should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:
If you need to build up your commands over time, use arrays:
tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"
Alternately, if this is just about defining your commands in one central place, use functions:
tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd
In a comment on @paxdiablo's answer, you asked:
"So basically, is it better to use Double than Float?"
That is a complicated question. I will deal with it in two parts
double
versus float
On the one hand, a double
occupies 8 bytes versus 4 bytes for a float
. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double
values is typically slower than with float
values ... though once again this is hardware dependent.
On the other hand, a double
can represent larger (and smaller) numbers than a float
and can represent them with more than twice the precision. For the details, refer to Wikipedia.
The tricky question is knowing whether you actually need the extra range and precision of a double
. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double
is going to give you enough precision. (And beware of the trap of expecting float
and double
to give you an exact representation. They won't and they can't!)
There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.
Double
versus Float
For the Double
versus Float
case, the issues of precision and range are the same as for double
versus float
, but the relative performance measures will be slightly different.
A Double
(on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float
. Compare this to 8 bytes versus 4 bytes for the double
versus float
case. So the ratio is 5 to 4 versus 2 to 1.
Arithmetic involving Double
and Float
typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double
case.
Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double
in preference to float
, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float
will make a difference with respect to that requirement.
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
You cannot "convert" an existing column into an IDENTITY
column - you will have to create a new column as INT IDENTITY
:
ALTER TABLE ProductInProduct
ADD NewId INT IDENTITY (1, 1);
Update:
OK, so there is a way of converting an existing column to IDENTITY
. If you absolutely need this - check out this response by Martin Smith with all the gory details.
Simply add these to your ggplot:
+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge'
could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.
You should use this code
this.setVisible(false); //this will close frame i.e. NewJFrame
new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed
For urllib
you can use:
from urllib import FancyURLopener
class MyOpener(FancyURLopener, object):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
myopener = MyOpener()
myopener.retrieve('https://www.google.com/search?q=test', 'useragent.html')
I had the same question but about rather short vector<bool>
(afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):
-O0 -O3
-------- --------
memset 0.666 1.045
fill 19.357 1.066
iterator 67.368 1.043
assign 17.975 0.530
for i 22.610 1.004
So apparently for these sizes, vector<bool>::assign()
is faster. The code used for tests:
#include <vector>
#include <cstring>
#include <cstdlib>
#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;
using namespace std;
int main(int argc, char** argv) {
std::vector<int> v(TEST_ARRAY_SIZE, 0);
for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
std::fill(v.begin(), v.end(), false);
#elif TEST_METHOD == 3
for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
*it = 0;
}
#elif TEST_METHOD == 4
v.assign(v.size(),false);
#elif TEST_METHOD == 5
for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
v[i] = false;
}
#endif
}
return EXIT_SUCCESS;
}
I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:
g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp
I encountered this error, and the fix appears to be turning off SNI, which Python 2.7 does not support:
As far as I know, renaming a file will not append its contents to that of an existing file with the target name.
About renaming a file in Java, see the documentation for the renameTo()
method in class File
.
As of Git 2.23 you can use git blame --ignore-rev
For the example given in the question this would be:
git blame -L10,+1 src/options.cpp --ignore-rev fe25b6d
(however it's a trick question because fe25b6d is the file's first revision!)
You can't hit breakpoints while attached to IIS process if you haven't logged into your Microsoft account in VS2017.
This is a code sample for grid system with equal height.
#outer{
width: 100%;
margin-top: 1rem;
display: flex;
height:auto;
}
Above is the CSS for outer div
#inner{
width: 20%;
float: left;
border: 1px solid;
}
Above is the inner div
Hope this help you
This is the industry standard:
int is_negative(float num)
{
char *p = (char*) malloc(20);
sprintf(p, "%f", num);
return p[0] == '-';
}
Have you tried setting the scroll direction of your UICollectionViewFlowLayout to horizontal?
[yourFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
And if you want it to page like springboard does, you'll need to enable paging on your collection view like so:
[yourCollectionView setPagingEnabled:YES];
The HTTP POST payload is just a flat bunch of bytes. Django (like most frameworks) decodes it into a dictionary from either URL encoded parameters, or MIME-multipart encoding. If you just dump the JSON data in the POST content, Django won't decode it. Either do the JSON decoding from the full POST content (not the dictionary); or put the JSON data into a MIME-multipart wrapper.
In short, show the JavaScript code. The problem seems to be there.
HTTP VS HTTPS PERFORMANCE COMPARISON
I have always associated HTTPS with slower page load times when compared to plain old HTTP. As a web developer, web page performance is important to me and anything that will slow down the performance of my web pages is a no-no.
In order to understand the performance implications involved, the diagram below gives you a basic idea of what happens under the hood when you make a request for a resource using HTTPS.
As you can see from the diagram above, there are a few extra steps that need to take place when using HTTPS compared to using plain HTTP. When you make a request using HTTPS, a handshake needs to occur in order to verify the authenticity of the request. This handshake is an extra step when compared to an HTTP request and does unfortunately incur some overhead.
In order to understand the performance implications and see for myself whether or not the performance impact would be significant, I used this site as a testing platform. I headed over to webpagetest.org and used the visual comparison tool to compare this site loading using HTTPS vs HTTP.
As you can see from Here is Test video Result using HTTPS did have an impact on my page load times, however the difference is negligible and I only noticed a 300 millisecond difference. It's important to note that these times depend on many factors, such as computer performance, connection speed, server load, and distance from server.
Your site may be different, and it is important to test your site thoroughly and check the performance impact involved in switching to HTTPS.
As far as I read manual pages, scanf says that 'l' length modifier indicates (in case of floating points) that the argument is of type double rather than of type float, so you can have 'lf, le, lg'.
As for printing, officially, the manual says that 'l' applies only to integer types. So it might be not supported on some systems or by some standards. For instance, I get the following error message when compiling with gcc -Wall -Wextra -pedantic
a.c:6:1: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]
So you may want to doublecheck if your standard supports the syntax.
To conclude, I would say that you read with '%lf' and you print with '%f'.
I should change a little thing of what Reigel said:
(function($) {
$.fn.hasScrollBar = function() {
return this[0] ? this[0].scrollHeight > this.innerHeight() : false;
}
})(jQuery);
innerHeight counts control's height and its top and bottom paddings
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
serves two purposes.
IE=edge
: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.chrome=1
: specifies that Google Chrome frame should start if the user has it installedThe IE=edge
flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.
As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1
will do nothing more than consume a few bytes of bandwidth.
I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.
Note, the W3C validator will flag chrome=1
as an error:
Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.
ALTER TABLE <table name>
ADD <new column name> <data type> NOT NULL
GO
ALTER TABLE <table name>
ADD CONSTRAINT <constraint name> DEFAULT <default value> FOR <new column name>
GO
If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL
for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual
from the backend.
Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...
I found a shortcut: File - Project Structure - Tab:Dependencies Click on the green + sign, select support-v4 (or any other you need), click OK.
now go to your gradle file and see that is been added
// 24-hour time to 12-hour time
$time_in_12_hour_format = date("g:i a", strtotime("13:30"));
// 12-hour time to 24-hour time
$time_in_24_hour_format = date("H:i", strtotime("1:30 PM"));
Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects
.
See their examples:
string myJsonString = @"{
"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}";
// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
Below is what I use to literally block the keystrokes. This only allows numbers 0-9 and a decimal point. Easy to implement, not a lot of code, and works like a charm:
<script>
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
} else {
return true;
}
}
</script>
<input value="" onkeypress="return isNumberKey(event)">
This answer may appear at the surface to be unrelated, but there is an indirect cause of this error message.
First, the "Uses VFP register..." error message is directly caused from mixing mfloat-abi=soft and mfloat-abi=hard options within your build. This setting must be consistent for all objects that are to be linked. This fact is well covered in the other answers to this question.
The indirect cause of this error may be due to the Eclipse editor getting confused by a self-inflicted error in the project's ".cproject" file. The Eclipse editor frequently reswizzles file links and sometimes it breaks itself when you make changes to your directory structures or file locations. This can also affect the path settings to your gcc compiler - and only for a subset of your project's files. While I'm not yet sure of exactly what causes this failure, replacing the .cproject file with a backup copy corrected this problem for me. In my case I noticed .java.null.pointer errors after adding an include directory path and started receiving the "VFP register error" messages out of the blue. In the build log I noticed that a different path to the gcc compiler was being used for some of my sources that were local to the workspace, but not all of them!? The two gcc compilers were using different float settings for unknown reasons - hence the VFP register error.
I compared the .cproject settings with a older copy and observed differences in entries for the sources causing the trouble - even though the overriding of project settings was disabled. By replacing the .cproject file with the old version the problem went away, and I'm leaving this answer as a reminder of what happened.
For anybody who is getting an error like : '2*' string cannot be converted to Length.
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" /><!--This will make any control in this column of grid take 2/5 of total width-->
<ColumnDefinition Width="3*" /><!--This will make any control in this column of grid take 3/5 of total width-->
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition MinHeight="30" />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0">Your text block a:</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="0">Your text block b:</TextBlock>
</Grid>
The following command will create a copy in a new window. So you can continue see both original file and the new file.
:w {newfilename} | sp #
In addition to the answer by Scott Barta above, you may still have import problems if there are references to Eclipse workspace library files, with e.g.
/workspace/android-support-v7-appcompat
being a common one.
In this case the import will halt until you provide a reference (and if you've cloned from a git repo, it probably won't be there) and even pointing to your own install (e.g. something like /android-sdk-macosx/extras/android/m2repository/com/android/support/appcompat-v7) won't be recognised and will halt the import, leaving you in no-man's land.
To get around this, look for refs in the project.properties or .classpath files that came in from the Eclipse project and remove/comment them out, e.g.
<classpathentry combineaccessrules="false" kind="src" path="/android-support-v7-appcompat"/>
That will get you past the import stage and you can then add these refs in your build.gradle (Module:app) as indicated in the Android tutorial, like below:
dependencies {
compile 'com.android.support:appcompat-v7:22.2.0'
}
The search
function will return all objects which contain a value which has contains the search query
function search(arr, s){_x000D_
var matches = [], i, key;_x000D_
_x000D_
for( i = arr.length; i--; )_x000D_
for( key in arr[i] )_x000D_
if( arr[i].hasOwnProperty(key) && arr[i][key].indexOf(s) > -1 )_x000D_
matches.push( arr[i] ); // <-- This can be changed to anything_x000D_
_x000D_
return matches;_x000D_
};_x000D_
_x000D_
// dummy data_x000D_
var items = [_x000D_
{_x000D_
"foo" : "bar",_x000D_
"bar" : "sit"_x000D_
},_x000D_
{_x000D_
"foo" : "lorem",_x000D_
"bar" : "ipsum"_x000D_
},_x000D_
{_x000D_
"foo" : "dolor",_x000D_
"bar" : "amet"_x000D_
}_x000D_
];_x000D_
_x000D_
var result = search(items, 'lo'); // search "items" for a query value_x000D_
console.log(result); // print the result
_x000D_
.NET Core 2.0 has Path.GetRelativePath
, else, use this.
/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static String MakeRelativePath(String fromPath, String toPath)
{
if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
if (String.IsNullOrEmpty(toPath)) throw new ArgumentNullException("toPath");
Uri fromUri = new Uri(fromPath);
Uri toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
String relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
This worked for me (I am on Ubuntu):
import os
os.path.dirname(os.getcwd())
#mybox:hover { display: none; }
#mybox:hover { visibility: hidden; }
#mybox:hover { background: none; }
#mybox:hover { color: green; }
though it should be noted that IE6 and below wont listen to the hover when it's not on an A tag. For that you have to incorporate JavaScript to add a class to the div during the hover.
Here is a generic Bash function you can use in your scripts.
# @see https://stackoverflow.com/a/11307382/430062
function countFiles {
shopt -s nullglob
logfiles=($1)
echo ${#logfiles[@]}
}
FILES_COUNT=$(countFiles "$file-*")
Any element with 'primay' tag has the color @brand-primary. One of the options to change it is adding a customized css file like below:
.my-primary{_x000D_
color: lightYellow ;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.my-primary:focus, .my-primary:hover{_x000D_
color: yellow ;_x000D_
background-color: darkRed;_x000D_
}_x000D_
_x000D_
a.navbar-brand {_x000D_
color: lightYellow ;_x000D_
}_x000D_
_x000D_
.navbar-brand:hover{_x000D_
color: yellow;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
<br>_x000D_
<nav class="navbar navbar-dark bg-primary mb-3">_x000D_
<div class="container">_x000D_
<a class="navbar-brand" href="/">Default (navbar-dark bg-primary)</a>_x000D_
</div>_x000D_
</nav>_x000D_
<button type="button" class="btn btn-primary">Default (btn btn-primary)</button>_x000D_
</div>_x000D_
_x000D_
_x000D_
<br>_x000D_
_x000D_
<div class="container">_x000D_
<nav class="navbar my-primary mb-3">_x000D_
<div class="container">_x000D_
<a class="navbar-brand" href="/">Customized (my-primary)</a>_x000D_
</div>_x000D_
</nav>_x000D_
<button type="button" class="btn my-primary">Customized (btn my-primary)</button>_x000D_
</div>
_x000D_
For more about customized css files with bootstrap, here is a helpful link: https://bootstrapbay.com/blog/bootstrap-button-styles/ .
Have a look at the strcat function.
In particular, you could try this:
const char* name = "hello";
const char* extension = ".txt";
char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */
This will return the matching word or an error if no match is found. For this example I used the following.
List of words to search for: G1:G7
Cell to search in: A1
=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))
Enter as an array formula by pressing Ctrl+Shift+Enter.
This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX()
function, throwing an error.
To return the row number of a matching word, you can use the following:
=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))
This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1
if no match is found.
WhatsApp has chosen Erlang a language built for writing scalable applications that are designed to withstand errors. Erlang uses an abstraction called the Actor model for it's concurrency - http://en.wikipedia.org/wiki/Actor_(programming_language) Instead of the more traditional shared memory approach, actors communicate by sending each other messages. Actors unlike threads are designed to be lightweight. Actors could be on the same machine or on different machines and the message passing abstractions works for both. A simple implementation of WhatsApp could be: Each user/device is represented as an actor. This actor is responsible for handling the inbox of the user, how it gets serialized to disk, the messages that the user sends and the messages that the user receives. Let's assume that Alice and Bob are friends on WhatsApp. So there is an an Alice actor and a Bob actor.
Let's trace a series of messages flowing back and forth:
Alice decides to message Bob. Alice's phone establishes a connection to the WhatsApp server and it is established that this connection is definitely from Alice's phone. Alice now sends via TCP the following message: "For Bob: A giant monster is attacking the Golden Gate Bridge". One of the WhatsApp front end server deserializes this message and delivers this message to the actor called Alice.
Alice the actor decides to serialize this and store it in a file called "Alice's Sent Messages", stored on a replicated file system to prevent data loss due to unpredictable monster rampage. Alice the actor then decides to forward this message to Bob the actor by passing it a message "Msg1 from Alice: A giant monster is attacking the Golden Gate Bridge". Alice the actor can retry with exponential back-off till Bob the actor acknowledges receiving the message.
Bob the actor eventually receives the message from (2) and decides to store this message in a file called "Bob's Inbox". Once it has stored this message durably Bob the actor will acknowledge receiving the message by sending Alice the actor a message of it's own saying "I received Msg1". Alice the actor can now stop it's retry efforts. Bob the actor then checks to see if Bob's phone has an active connection to the server. It does and so Bob the actor streams this message to the device via TCP.
Bob sees this message and replies with "For Alice: Let's create giant robots to fight them". This is now received by Bob the actor as outlined in Step 1. Bob the actor then repeats Step 2 and 3 to make sure Alice eventually receives the idea that will save mankind.
WhatsApp actually uses the XMPP protocol instead of the vastly superior protocol that I outlined above, but you get the point.
So you are doing this a bit backwards. Typically you'd do something like this:
?<div class='article'>
Article 1
</div>
<div class='article'>
Article 2
</div>
<div class='article'>
Article 3
</div>?
And then in your jQuery:
$('.article').click(function(){
article = $(this).text(); //$(this) is what you clicked!
});?
When I see things like #search-item .search-article
, #search-item .search-article
, and #search-item .search-article
I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.
<iframe src="https://www.youtube.com/embed/7cjVj1ZyzyE?autoplay=1&loop=1&playlist=7cjVj1ZyzyE&mute=1" frameborder="0" allowfullscreen></iframe>
_x000D_
mute=1
This is the solution that I came up with trying to solve this problem for myself in order to systematically produce \n's as separators. It writes using a list of strings where each string is one line of the file, however it seems that it may work for you as well. (Python 3.+)
#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
line = 0
lines = []
while line < len(strList):
lines.append(cheekyNew(line) + strList[line])
line += 1
file = open(file, "w")
file.writelines(lines)
file.close()
#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
if line != 0:
return "\n"
return ""
My solution is a bit different:
$( 'input[name="your_radio_input_name"]:radio:first' ).click();
Using OVER()
and LIMIT 1
:
SELECT COUNT(1) OVER()
FROM posts
INNER JOIN votes ON votes.post_id = posts.id
GROUP BY posts.id
LIMIT 1;
I have used the following lines to display the soft keyboard manually inside the onclick event.
public void showKeyboard(final EmojiconEditText ettext){
ettext.requestFocus();
ettext.postDelayed(new Runnable(){
@Override public void run(){
InputMethodManager keyboard=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(ettext,0);
}
}
,200);
}
To include the direction along with the orderBy function:
ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"
where
defaultSortDirection = 0; // 0 = Ascending, 1 = Descending
var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.
For that reason I am posting the answer listed in the comments to give it the exposure it deserves.
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
Copy the files to the default directory for your other database files. To find out what that is, you can use the sp_helpfile procedure in SSMS. On my machine it is: C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA
. By copying the files to this directory, they automatically get permissions applied that will allow the attach to succeed.
Here is a very good explanation :
See this list of php image libraries. Basically it's GD or Imagemagick.
A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).
Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
Advantages:
Disadvantages:
So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl
) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).
As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.
Using useState with useEffect as described above is absolutely correct way. But if getSearchResults function returns subscription then useEffect should return a function which will be responsible for unsubscribing the subscription . Returned function from useEffect will run before each change to dependency(name in above case) and on component destroy
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum
in C# is an int
, you can just cast it.
You have to add repositories
to your build file. For maven repositories you have to prefix repository name with maven{}
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
Open the port where your system is running (sample 8080). Open the port everywhere... Modem, firewalls, etc etc etc.
THen, send your ip + port to the person who will use it.
Abstraction is a means of hiding details in order to simplify an interface.
So, using a car as an example, all of the controls in a car are abstractions. This allows you to operate a vehicle without understanding the underlying details of the steering, acceleration, or deceleration systems.
A good abstraction is one that standardizes an interface broadly, across multiple instances of a similar problem. A great abstraction can change an industry.
The modern steering wheel, brake pedal, and gas pedal are all examples of great abstractions. Car steering initially looked more like bicycle steering. And both brakes and throttles were operated by hand. But the abstractions we use today were so powerful, they swept the industry.
--
Encapsulation is a means of hiding details in order to protect them from outside manipulation.
Encapsulation is what prevents the driver from manipulating the way the car drives — from the stiffness of the steering, suspension, and braking, to the characteristics of the throttle, and transmission. Most cars do not provide interfaces for changing any of these things. This encapsulation ensures that the vehicle will operate as the manufacturer intended.
Some cars offer a small number of driving modes — like luxury, sport, and economy — which allow the driver to change several of these attributes together at once. By providing driving modes, the manufacturer is allowing the driver some control over the experience while preventing them from selecting a combination of attributes that would render the vehicle less enjoyable or unsafe. In this way, the manufacturer is hiding the details to prevent unsafe manipulations. This is encapsulation.
you can use this.
<span [attr.checked]="val? true : false"> </span>
For the kinds of large files I tend to get, I generally wouldn't even do this in R. I would use the cut
command in Linux to process data before it gets to R. This isn't a critique of R, just a preference for using some very basic Linux tools like grep, tr, cut, sort, uniq, and occasionally sed & awk (or Perl) when there's something to be done about regular expressions.
Another reason to use standard GNU commands is that I can pass them back to the source of the data and ask that they prefilter the data so that I don't get extraneous data. Most of my colleagues are competent with Linux, fewer know R.
(Updated) A method that I would like to use before long is to pair mmap
with a text file and examine the data in situ, rather than read it at all into RAM. I have done this with C, and it can be blisteringly fast.
Ah, that would be because RegExp is not jQuery. :)
Try this page. jQuery.attr
doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text()
to return the String representation.
Something like:
$("li").val("title").search(/sometext/i));
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
Assuming you are on Linux, check if php-fpm is running by searching through the process list:
ps aux | grep php-fpm
If running over IP (as opposed to over Unix socket) then you can also check for the port:
netstat -an | grep :9000
Or using nmap:
nmap localhost -p 9000
Lastly, I've read that you can request the status, but in my experience this has proven unreliable:
/etc/init.d/php5-fpm status
May be helpful for late comers.
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
if (argc != 2) {
cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
return -1;
}else{
Mat image;
Mat grayImage;
image = imread(argv[1], IMREAD_COLOR);
if (!image.data) {
cout << "Could not open the image file" << endl;
return -1;
}
else {
int height = image.rows;
int width = image.cols;
cvtColor(image, grayImage, CV_BGR2GRAY);
namedWindow("Display window", WINDOW_AUTOSIZE);
imshow("Display window", image);
namedWindow("Gray Image", WINDOW_AUTOSIZE);
imshow("Gray Image", grayImage);
cvWaitKey(0);
image.release();
grayImage.release();
return 0;
}
}
}
I created the following function to generate an html table from an arbitrary JSON object:
function toTable(json, colKeyClassMap, rowKeyClassMap){
let tab;
if(typeof colKeyClassMap === 'undefined'){
colKeyClassMap = {};
}
if(typeof rowKeyClassMap === 'undefined'){
rowKeyClassMap = {};
}
const newTable = '<table class="table table-bordered table-condensed table-striped" />';
if($.isArray(json)){
if(json.length === 0){
return '[]'
} else {
const first = json[0];
if($.isPlainObject(first)){
tab = $(newTable);
const row = $('<tr />');
tab.append(row);
$.each( first, function( key, value ) {
row.append($('<th />').addClass(colKeyClassMap[key]).text(key))
});
$.each( json, function( key, value ) {
const row = $('<tr />');
$.each( value, function( key, value ) {
row.append($('<td />').addClass(colKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap)))
});
tab.append(row);
});
return tab;
} else if ($.isArray(first)) {
tab = $(newTable);
$.each( json, function( key, value ) {
const tr = $('<tr />');
const td = $('<td />');
tr.append(td);
$.each( value, function( key, value ) {
td.append(toTable(value, colKeyClassMap, rowKeyClassMap));
});
tab.append(tr);
});
return tab;
} else {
return json.join(", ");
}
}
} else if($.isPlainObject(json)){
tab = $(newTable);
$.each( json, function( key, value ) {
tab.append(
$('<tr />')
.append($('<th style="width: 20%;"/>').addClass(rowKeyClassMap[key]).text(key))
.append($('<td />').addClass(rowKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap))));
});
return tab;
} else if (typeof json === 'string') {
if(json.slice(0, 4) === 'http'){
return '<a target="_blank" href="'+json+'">'+json+'</a>';
}
return json;
} else {
return ''+json;
}
};
So you can simply call:
$('#mydiv').html(toTable([{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]));
Sure you can. Something like:
HTML
<div ng-controller="fessCntrl">
<label ng-repeat="(key,val) in list">
<input type="radio" name="localityTypeRadio" ng-model="$parent.localityTypeRadio" ng-value="key" />{{key}}
<div ng-if="key == 'City' || key == 'County'">
<pre>City or County !!! {{$parent.localityTypeRadio}}</pre>
</div>
<div ng-if="key == 'Town'">
<pre>Town!!! {{$parent.localityTypeRadio}}</pre>
</div>
</label>
</div>
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.list = {
City: [{name: "cityA"}, {name: "cityB"}],
County: [{ name: "countyA"}, {name: "countyB"}],
Town: [{ name: "townA"}, {name: "townB"}]
};
$scope.localityTypeRadio = 'City';
});
fessmodule.$inject = ['$scope'];
Demo Fiddle
Swift 4/5, iOS 9+
Rebuilding the whole CoreData
SQLite file will make sure all data is erased, therefore all entities are deleted. Just call deleteAndRebuild()
.
class CoreDataStack {
// Change this
static let datamodelName = "ProjectName"
static let storeType = "sqlite"
static let persistentContainer = NSPersistentContainer(name: datamodelName)
private static let url: URL = {
let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("\(datamodelName).\(storeType)")
assert(FileManager.default.fileExists(atPath: url.path))
return url
}()
static func loadStores() {
persistentContainer.loadPersistentStores(completionHandler: { (nsPersistentStoreDescription, error) in
if let error = error {
fatalError(error.localizedDescription)
}
})
}
static func deleteAndRebuild() {
try! persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: url, ofType: storeType, options: nil)
loadStores()
}
}
This suits the requirement:
select username, account_status, EXPIRY_DATE from dba_users where
username='<username>';
Output:
USERNAME ACCOUNT_STATUS EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM EXPIRED 13-NOV-17
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
Powerful tool for "Bulletproof Email Background Images" (VML for Outlook 2007/2010/2013, and HTML/CSS for Outlook 2000/2003, Gmail, Hotmail...)
as an exemple :
<div style="background-color:#f6f6f6;">
<!--[if gte mso 9]>
<v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
<v:fill type="tile" src="http://i.imgur.com/n8Q6f.png" color="#f6f6f6"/>
</v:background>
<![endif]-->
<table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td valign="top" align="left" background="http://i.imgur.com/n8Q6f.png">
</td>
</tr>
</table>
</div>
in order to have the specified background image to Full email body.
This link help to use the Vector Markup Language (VML)
window.scrollBarWidth = function() {
document.body.style.overflow = 'hidden';
var width = document.body.clientWidth;
document.body.style.overflow = 'scroll';
width -= document.body.clientWidth;
if(!width) width = document.body.offsetWidth - document.body.clientWidth;
document.body.style.overflow = '';
return width;
}
I know you are specifically asking about the PHP timeout, but what no one else seems to have mentioned is that there can also be a timeout on the webserver and it can look very similar to the PHP timeout.
So if you have tried:
And you have checked with the phpinfo() function that max_execution_time has indeed be increased, then you might want to try adding this to .htaccess which will make sure Apache itself does not time out:
RewriteRule .* - [E=noabort:1]
RewriteRule .* - [E=noconntimeout:1]
More info here: https://www.antropy.co.uk/blog/php-script-keeps-timing-out-despite-ini-set/
While it's not a batch process, Visual Studio can also add/edit file resources.
Just use File->Open->File on the .EXE or .DLL. This is handy for fixing version information post-build, or adding it to files that don't have these resources to begin with.
How do I obtain a function pointer for a class member function, and later call that member function with a specific object?
It's easiest to start with a typedef
. For a member function, you add the classname in the type declaration:
typedef void(Dog::*BarkFunction)(void);
Then to invoke the method, you use the ->*
operator:
(pDog->*pBark)();
Also, if possible, I’d like to invoke the constructor via a pointer as well. Is this possible, and if so, what is the preferred way to do this?
I don't believe you can work with constructors like this - ctors and dtors are special. The normal way to achieve that sort of thing would be using a factory method, which is basically just a static function that calls the constructor for you. See the code below for an example.
I have modified your code to do basically what you describe. There's some caveats below.
#include <iostream>
class Animal
{
public:
typedef Animal*(*NewAnimalFunction)(void);
virtual void makeNoise()
{
std::cout << "M00f!" << std::endl;
}
};
class Dog : public Animal
{
public:
typedef void(Dog::*BarkFunction)(void);
typedef Dog*(*NewDogFunction)(void);
Dog () {}
static Dog* newDog()
{
return new Dog;
}
virtual void makeNoise ()
{
std::cout << "Woof!" << std::endl;
}
};
int main(int argc, char* argv[])
{
// Call member function via method pointer
Dog* pDog = new Dog ();
Dog::BarkFunction pBark = &Dog::makeNoise;
(pDog->*pBark)();
// Construct instance via factory method
Dog::NewDogFunction pNew = &Dog::newDog;
Animal* pAnimal = (*pNew)();
pAnimal->makeNoise();
return 0;
}
Now although you can normally use a Dog*
in the place of an Animal*
thanks to the magic of polymorphism, the type of a function pointer does not follow the lookup rules of class hierarchy. So an Animal method pointer is not compatible with a Dog method pointer, in other words you can't assign a Dog* (*)()
to a variable of type Animal* (*)()
.
The static newDog
method is a simple example of a factory, which simply creates and returns new instances. Being a static function, it has a regular typedef
(with no class qualifier).
Having answered the above, I do wonder if there's not a better way of achieving what you need. There's a few specific scenarios where you would do this sort of thing, but you might find there's other patterns that work better for your problem. If you describe in more general terms what you are trying to achieve, the hive-mind may prove even more useful!
Related to the above, you will no doubt find the Boost bind library and other related modules very useful.
def jsonFile = new File('File Path');
JsonSlurper jsonSlurper = new JsonSlurper();
def parseJson = jsonSlurper.parse(jsonFile)
String json = JsonOutput.toJson(parseJson)
def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)
simply if you want to create any HTML tag you can try this for example
var selectBody = $('body');
var div = $('<div>');
var h1 = $('<h1>');
var p = $('<p>');
if you want to add any element on the flay you can try this
selectBody.append(div);
Try doing this :
recipients="[email protected],[email protected],[email protected]"
And another approach, using shell here-doc :
/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from
Example Message
EOF
Be sure to separate the headers from the body with a blank line as per RFC 822.
Problem: The accepted answer does not actually fix the indentation in the current document.
Solution: Run Format Document
to re-process the document according to current (new) settings.
Problem: The HTML docs in my projects are of type "Django HTML" not "HTML" and there is no formatter available.
Solution: Switch them to syntax "HTML", format them, then switch back to "Django HTML."
Problem: The HTML formatter doesn't know how to handle Django template tags and undoes much of my carefully applied nesting.
Solution: Install the Indent 4-2 extension, which performs indentation strictly, without regard to the current language syntax (which is what I want in this case).
An old tip...
var daddy = window.self;
daddy.opener = window.self;
daddy.close();