You can use an Explain Plan to get an objective answer.
For your problem, an Exists filter would probably perform the fastest.
You can do the following to learn/test the concept:
Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module
In newly added Module1 add the declaration; Public Global1 As String
in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:
Sub setMe() Global1 = "Hello" End Sub
Sub showMe() Debug.Print (Global1) End Sub
setMe()
and then Sub showMe()
to test the global visibility/accessibility of the var Global1
Hope this will help.
By creating the increment table you should be aware not to delete inserted rows. reason for this is to avoid storing large dumb data in db with ID-s in it. Otherwise in case of mysql restart it would get max existing row and continue increment from that point as mention in documentation http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html
//HashSet allows only the unique values to the list
HashSet<int> uniqueList = new HashSet<int>();
var a = uniqueList.Add(1);
var b = uniqueList.Add(2);
var c = uniqueList.Add(3);
var d = uniqueList.Add(2); // should not be added to the list but will not crash the app
//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"Happy");
dict.Add(2, "Smile");
dict.Add(3, "Happy");
dict.Add(2, "Sad"); // should be failed // Run time error "An item with the same key has already been added." App will crash
//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<string, int> dictRev = new Dictionary<string, int>();
dictRev.Add("Happy", 1);
dictRev.Add("Smile", 2);
dictRev.Add("Happy", 3); // should be failed // Run time error "An item with the same key has already been added." App will crash
dictRev.Add("Sad", 2);
For people who are using CentOS7, In order to allow access to port 8000, you need to modify firewall rules in a new SSH connection:
sudo firewall-cmd --zone=public --permanent --add-port=8000/tcp
sudo firewall-cmd --reload
You can use cut with a delimiter like this:
with space delim:
cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv
with tab delim:
cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv
I gave you the version of cut in which you can extract a list of intervals...
Hope it helps!
If you changed the location, using option 'Use custom location (does not modify Tomcat installation)' and the deployed directory is "wtpwebapps" then you'll have to:
<role rolename="manager-gui"/> <role rolename="manager-status"/> <role rolename="manager-jmx"/> <role rolename="manager-script"/> <role rolename="admin-gui"/> <role rolename="admin"/> <user username="admin" password="yourpassword" roles="admin, admin-gui, manager-gui"/>
readonly="true"into the <Resource/> key of the <GlobalNamingResources/> group.
NOTE: if you change the server configuration, say if you like to compare the default configuration (use tomcat installation directory) and the 'new directory', when switching back to the 'new directory' this 'tomcat-users.xml' will be overwritten by the default file, so SAVE THE CONTENT OF THIS FILE somewhere before doing that, then copy it back. If you only give the the username "admin" role, you will be prompted of help messages. It says: you should not grant the admin-gui, or manager-gui role the 'manager-jmx' and 'manager-script' roles.
My pure CSS implementation based on above with 100% width. Hope it helps!
#wave-container {_x000D_
width: 100%;_x000D_
height: 100px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#wave {_x000D_
display: block;_x000D_
position: relative;_x000D_
height: 40px;_x000D_
background: black;_x000D_
}_x000D_
_x000D_
#wave:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
border-radius: 100%;_x000D_
width: 100%;_x000D_
height: 300px;_x000D_
background-color: white;_x000D_
right: -25%;_x000D_
top: 20px_x000D_
}_x000D_
_x000D_
#wave:after {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
border-radius: 100%;_x000D_
width: 100%;_x000D_
height: 300px;_x000D_
background-color: black;_x000D_
left: -25%;_x000D_
top: -240px;_x000D_
}
_x000D_
<div id="wave-container">_x000D_
<div id="wave">_x000D_
</div>_x000D_
</div>
_x000D_
Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.
$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. .. .den .hi .hidden a b c
$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c
$ shopt -s dotglob
$ ls *
.den .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c
It defaults to "off".
$ shopt dotglob
dotglob off
It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.
I confirmed this works in SQL Developer 3.0.04. Our passwords are required to have a special character, so the double-quoted string is needed in our case. Of course, this only works if the password has not already expired and you are currently logged in.
ALTER USER MYUSERID
IDENTIFIED BY "new#password"
REPLACE "old#password"
Useful extension based of @Jeremy Thompson's solution
public static class RandomExtensions
{
public static DateTime Next(this Random random, DateTime start, DateTime? end = null)
{
end ??= new DateTime();
int range = (end.Value - start).Days;
return start.AddDays(random.Next(range));
}
}
The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.
Spreadsheetgear is the best commercial library we have found and are using. Our company does a lot of advanced excel import and export and Spreadsheetgear supports lots of advanced excel features far beyond anything you can do with simple CSV, and it's fast. It isn't free or very cheap though but worth it because the support is excellent. The developers will actually respond to you if you run into an issue.
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
public DataSet GetDataSet(string ConnectionString, string SQL)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
I think if theme should be generated some problem but its dynamically set black arrow.So i Suggested try this one.
Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
backArrow.setColorFilter(getResources().getColor(R.color.md_grey_900), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(backArrow);
This is worked for me using JAVA script for chrome extension.
document.body.innerHTML = myFunction();
function myFunction()
{
var phonedef = new RegExp("(?:(?:\\+|0{0,2})91(\\s*[\\- ]\\s*)?|[0 ]?)?[789]\\d{9}|(\\d[ -]?){10}\\d", "g");
var str = document.body.innerHTML;
var res = str.replace(phonedef, function myFunction(x){return "<a href='tel:"+x.replace( /(\s|-)/g, "")+"'>"+x+"</a>";});
return res;
}
This covers following numbers pattern
9883443344
8888564723
7856128945
09883443344
0 9883443344
0-9883443344
919883443344
91 8834433441
91-9883443344
91 -9883443344
91- 9883443344
91 - 9883443344
91 -9883443344
+917878525200
+91 8834433441
+91-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
+91 -9883443344
0919883443344
0091-7779015989
0091 - 8834433440
022-24130000
080 25478965
0416-2565478
08172-268032
04512-895612
02162-240000
022-24141414
079-22892350
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
I just wanted to echo @Luann's comment as I use this approach always.
Just right click on the table > Script table as > Select to > New Query window.
You will see the select query. Just take out the column you want to exclude and you have your preferred select query.
For checking Strings for letters you can use regular expressions for example:
someString.matches("[A-F]");
For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here
public int readInt(String prompt, int min, int max)
{
Scanner scan = new Scanner(System.in);
int number = 0;
//Run once and loop until the input is within the specified range.
do
{
//Print users message.
System.out.printf("\n%s > ", prompt);
//Prevent string input crashing the program.
while (!scan.hasNextInt())
{
System.out.printf("Input doesn't match specifications. Try again.");
System.out.printf("\n%s > ", prompt);
scan.next();
}
//Set the number.
number = scan.nextInt();
//If the number is outside range print an error message.
if (number < min || number > max)
System.out.printf("Input doesn't match specifications. Try again.");
} while (number < min || number > max);
return number;
}
I had similar problem with integer column as input when I needed fixed sized varchar (or string) output. For instance, 1 to '01', 12 to '12'. This code works:
SELECT RIGHT(CONCAT('00',field::text),2)
If the input is also a column of varchar, you can avoid the casting part.
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
You can use rsplit
string.rsplit('delimeter',1)[1]
To get the string from reverse.
timer.scheduleAtFixedRate( new Task(), 1000,3000);
The hash "#" currently works for jump links in conjunction with the base element, but only in the latest versions of Google Chrome and Firefox, NOT IE9.
IE9 appears to cause the page to be reloaded, without jumping anywhere. If you are using jump links on the outside of an iframe, while directing the frame to load the jump links on a separate page within the frame, you will instead get a second copy of the jump link page loaded inside the frame.
I don't think there is any kind of bug in the PagerAdapter
. The problem is that understanding how it works is a little complex. Looking at the solutions explained here, there is a misunderstanding and therefore a poor usage of instantiated views from my point of view.
The last few days I have been working with PagerAdapter
and ViewPager
, and I found the following:
The notifyDataSetChanged()
method on the PagerAdapter
will only notify the ViewPager
that the underlying pages have changed. For example, if you have created/deleted pages dynamically (adding or removing items from your list) the ViewPager
should take care of that. In this case I think that the ViewPager
determines if a new view should be deleted or instantiated using the getItemPosition()
and getCount()
methods.
I think that ViewPager
, after a notifyDataSetChanged()
call takes it's child views and checks their position with the getItemPosition()
. If for a child view this method returns POSITION_NONE
, the ViewPager
understands that the view has been deleted, calling the destroyItem()
, and removing this view.
In this way, overriding getItemPosition()
to always return POSITION_NONE
is completely wrong if you only want to update the content of the pages, because the previously created views will be destroyed and new ones will be created every time you call notifyDatasetChanged()
. It may seem to be not so wrong just for a few TextView
s, but when you have complex views, like ListViews populated from a database, this can be a real problem and a waste of resources.
So there are several approaches to efficiently change the content of a view without having to remove and instantiate the view again. It depends on the problem you want to solve. My approach is to use the setTag()
method for any instantiated view in the instantiateItem()
method. So when you want to change the data or invalidate the view that you need, you can call the findViewWithTag()
method on the ViewPager
to retrieve the previously instantiated view and modify/use it as you want without having to delete/create a new view each time you want to update some value.
Imagine for example that you have 100 pages with 100 TextView
s and you only want to update one value periodically. With the approaches explained before, this means you are removing and instantiating 100 TextView
s on each update. It does not make sense...
Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.
The code below requires the Json.NET package.
public static string GetUserCountryByIp(string ip)
{
IpInfo ipInfo = new IpInfo();
try
{
string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
ipInfo.Country = myRI1.EnglishName;
}
catch (Exception)
{
ipInfo.Country = null;
}
return ipInfo.Country;
}
And the IpInfo
Class I used:
public class IpInfo
{
[JsonProperty("ip")]
public string Ip { get; set; }
[JsonProperty("hostname")]
public string Hostname { get; set; }
[JsonProperty("city")]
public string City { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("loc")]
public string Loc { get; set; }
[JsonProperty("org")]
public string Org { get; set; }
[JsonProperty("postal")]
public string Postal { get; set; }
}
Since OS X Lion, the scrollbar on websites are hidden by default and only visible once you start scrolling. Personally, I prefer the hidden scrollbar, but in case you really need it, you can overwrite the default and force the scrollbar in WebKit browsers back like this:
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
_x000D_
You can use AddHandler to add a handler for any event.
For example, this might be:
AddHandler theButton.Click, AddressOf Me.theButton_Click
I have figured it out a bit of a strange way of doing it compared to the old WF forms:
ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();
For anyone using entity framework core ending up here. This is how you do it.
# Powershell / Package manager console
Script-Migration
# Cli
dotnet ef migrations script
You can use the -From
and -To
parameter to generate an update script to update a database to a specific version.
Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2
https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts
There are several options to this command.
The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify
0
(this is the default).The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.
An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.
The ready
event occurs after the HTML document has been loaded, while the onload
event occurs later, when all content (e.g. images) also has been loaded.
The onload
event is a standard event in the DOM, while the ready
event is specific to jQuery. The purpose of the ready
event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
what you need exactly is
def fun():
raise Exception()
f = lambda x:print x if x==2 else fun()
now call the function the way you need
f(2)
f(3)
Weird error.
Can you test this?
const char* const S = "ABCD";
char t[] = { S[0], S[1], S[2], S[3] };
char u[] = { S[3], S[2], S[1], S[0] };
A generic method, whose result you can iterate over may be of interest:
public static Object[][] chunk(Object[] src, int chunkSize) {
int overflow = src.length%chunkSize;
int numChunks = (src.length/chunkSize) + (overflow>0?1:0);
Object[][] dest = new Object[numChunks][];
for (int i=0; i<numChunks; i++) {
dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];
System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length);
}
return dest;
}
Flask includes the redirect
function for redirecting to any url. Futhermore, you can abort a request early with an error code with abort
:
from flask import abort, Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def hello():
return redirect(url_for('hello'))
@app.route('/hello'):
def world:
abort(401)
By default a black and white error page is shown for each error code.
The redirect
method takes by default the code 302. A list for http status codes here.
Try CSS Generator.
You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:
text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);
Permanent:
UPDATE
MyTable
SET
MyColumn = UPPER(MyColumn)
Temporary:
SELECT
UPPER(MyColumn) AS MyColumn
FROM
MyTable
Choosing to Project -> Clean should resolve this
It could also mean something like "Lexical Environment Type or Tied".. It bothers me that it would simply be "let this be that". And let rec wouldn't make sense in lambda calculus.
Well, I am using this:
stripUrl(urlToStrip){
let stripped = urlToStrip.split('?')[0];
stripped = stripped.split('&')[0];
stripped = stripped.split('#')[0];
return stripped;
}
or:
stripUrl(urlToStrip){
return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
}
If you want to allow the user to browse for a file, you need to have an input type="file"
The closest you could get to your requirement would be to place the input type="file"
on the page and hide it. Then, trigger the click event of the input when the button is clicked:
#myFileInput {
display:none;
}
<input type="file" id="myFileInput" />
<input type="button"
onclick="document.getElementById('myFileInput').click()"
value="Select a File" />
Here's a working fiddle.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
npm start
in Node.js Command Prompt.c:\users\MyUser\npm-debug.log
C:\\Program Files\\nodejs\\\\node.exe
Call node.exe + <full path to your server file.js>
Server is listening on port 1337 !
In 99.9% of all cases it is bad program design to share non-constant, global variables between files. There are very few cases when you actually need to do this: they are so rare that I cannot come up with any valid cases. Declarations of hardware registers perhaps.
In most of the cases, you should either use (possibly inlined) setter/getter functions ("public"), static variables at file scope ("private"), or incomplete type implementations ("private") instead.
In those few rare cases when you need to share a variable between files, do like this:
// file.h
extern int my_var;
// file.c
#include "file.h"
int my_var = something;
// main.c
#include "file.h"
use(my_var);
Never put any form of variable definition in a h-file.
The android documents have been edited to correct the errors.
The view inside the AlertDialog is called android.R.id.custom
http://developer.android.com/reference/android/app/AlertDialog.html
From site PostgreSQL, of date 02/04/2016 (https://jdbc.postgresql.org/download.html):
"This is the current version of the driver. Unless you have unusual requirements (running old applications or JVMs), this is the driver you should be using. It supports Postgresql 7.2 or newer and requires a 1.6 or newer JVM. It contains support for SSL and the javax.sql package. If you are using the 1.6 then you should use the JDBC4 version. If you are using 1.7 then you should use the JDBC41 version. If you are using 1.8 then you should use the JDBC42 versionIf you are using a java version older than 1.6 then you will need to use a JDBC3 version of the driver, which will by necessity not be current"
The default value table only applies to initializing a variable.
Per the linked page, the following two methods of initialization are equivalent...
int x = 0;
int x = new int();
In your code, you merely defined the variable, but never initialized the object.
To do this easily, the use of Stack
is better. Create a Stack
Then inside Stack add Align
or Positioned
and set position according to your needed, You can add multiple Container
.
Container
child: Stack(
children: <Widget>[
Align(
alignment: FractionalOffset.center,
child: Text(
"? 1000",
)
),
Positioned(
bottom: 0,
child: Container(
width: double.infinity,
height: 30,
child: Text(
"Balance", ,
)
),
)
],
)
)
Stack
a widget that positions its children relative to the edges of its box.
Stack
class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.
Download the C++17 International Standard final draft here.
Aggregates
C++17 expands and enhances aggregates and aggregate initialization. The standard library also now includes an std::is_aggregate
type trait class. Here is the formal definition from section 11.6.1.1 and 11.6.1.2 (internal references elided):
An aggregate is an array or a class with
— no user-provided, explicit, or inherited constructors,
— no private or protected non-static data members,
— no virtual functions, and
— no virtual, private, or protected base classes.
[ Note: Aggregate initialization does not allow accessing protected and private base class’ members or constructors. —end note ]
The elements of an aggregate are:
— for an array, the array elements in increasing subscript order, or
— for a class, the direct base classes in declaration order, followed by the direct non-static data members that are not members of an anonymous union, in declaration order.
What changed?
struct B1 // not a aggregate
{
int i1;
B1(int a) : i1(a) { }
};
struct B2
{
int i2;
B2() = default;
};
struct M // not an aggregate
{
int m;
M(int a) : m(a) { }
};
struct C : B1, B2
{
int j;
M m;
C() = default;
};
C c { { 1 }, { 2 }, 3, { 4 } };
cout
<< "is C aggregate?: " << (std::is_aggregate<C>::value ? 'Y' : 'N')
<< " i1: " << c.i1 << " i2: " << c.i2
<< " j: " << c.j << " m.m: " << c.m.m << endl;
//stdout: is C aggregate?: Y, i1=1 i2=2 j=3 m.m=4
struct D // not an aggregate
{
int i = 0;
D() = default;
explicit D(D const&) = default;
};
struct B1
{
int i1;
B1() : i1(0) { }
};
struct C : B1 // not an aggregate
{
using B1::B1;
};
Trivial Classes
The definition of trivial class was reworked in C++17 to address several defects that were not addressed in C++14. The changes were technical in nature. Here is the new definition at 12.0.6 (internal references elided):
A trivially copyable class is a class:
— where each copy constructor, move constructor, copy assignment operator, and move assignment operator is either deleted or trivial,
— that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and
— that has a trivial, non-deleted destructor.
A trivial class is a class that is trivially copyable and has one or more default constructors, all of which are either trivial or deleted and at least one of which is not deleted. [ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]
Changes:
std::memcpy
. This was a semantic contradiction, because, by defining as deleted all constructor/assignment operators, the creator of the class clearly intended that the class could not be copied/moved, yet the class still met the definition of a trivially copyable class. Hence in C++17 we have a new clause stating that trivially copyable class must have at least one trivial, non-deleted (though not necessarily publicly accessible) copy/move constructor/assignment operator. See N4148, DR1734Standard-layout Classes
The definition of standard-layout was also reworked to address defect reports. Again the changes were technical in nature. Here is the text from the standard (12.0.7). As before, internal references are elided:
A class S is a standard-layout class if it:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions and no virtual base classes,
— has the same access control for all non-static data members,
— has no non-standard-layout base classes,
— has at most one base class subobject of any given type,
— has all non-static data members and bit-fields in the class and its base classes first declared in the same class, and
— has no element of the set M(S) of types (defined below) as a base class.108
M(X) is defined as follows:
— If X is a non-union class type with no (possibly inherited) non-static data members, the set M(X) is empty.
— If X is a non-union class type whose first non-static data member has type X0 (where said member may be an anonymous union), the set M(X) consists of X0 and the elements of M(X0).
— If X is a union type, the set M(X) is the union of all M(Ui) and the set containing all Ui, where each Ui is the type of the ith non-static data member of X.
— If X is an array type with element type Xe, the set M(X) consists of Xe and the elements of M(Xe).
— If X is a non-class, non-array type, the set M(X) is empty.
[ Note: M(X) is the set of the types of all non-base-class subobjects that are guaranteed in a standard-layout class to be at a zero offset in X. —end note ]
[ Example:
—end example ]struct B { int i; }; // standard-layout class struct C : B { }; // standard-layout class struct D : C { }; // standard-layout class struct E : D { char : 4; }; // not a standard-layout class struct Q {}; struct S : Q { }; struct T : Q { }; struct U : S, T { }; // not a standard-layout class
108) This ensures that two subobjects that have the same class type and that belong to the same most derived object are not allocated at the same address.
Changes:
Note: The C++ standards committee intended the above changes based on defect reports to apply to C++14, though the new language is not in the published C++14 standard. It is in the C++17 standard.
Many suggestions here, most along the lines of git checkout $revision -- $file
. A couple of obscure alternatives:
git show $revision:$file > $file
And also, I use this a lot just to see a particular version temporarily:
git show $revision:$file
or
git show $revision:$file | vim -R -
(OBS: $file
needs to be prefixed with ./
if it is a relative path for git show $revision:$file
to work)
And the even more weird:
git archive $revision $file | tar -x0 > $file
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
You just need to add a jquery selector after the url.
See: http://api.jquery.com/load/
Example straight from the API:
$('#result').load('ajax/test.html #container');
So what that does is it loads the #container element from the specified url.
You could do it like this:
HTML
<table>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
<td><a href="#" id="show_1">Show Extra</a></td>
</tr>
<tr>
<td colspan="5">
<div id="extra_1" style="display: none;">
<br>hidden row
<br>hidden row
<br>hidden row
</div>
</td>
</tr>
</table>
jQuery
$("a[id^=show_]").click(function(event) {
$("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
event.preventDefault();
});
See a demo on JSFiddle
In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.
Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.
I wanted to use the top rated answer above
Object.prototype.keys = function () ...
However when using in conjunction with the google maps API v3, google maps is non-functional.
for (var key in h) ...
works well.
make sure to include __init__.py
, which makes Python know that those directories containpackages
I know this is a old question but i think i must provide my answer to it because my problem was not solved by others.
first of all : i was dynamically adding fragments using fragmentTransactions. Second: my fragments were modified using AsyncTasks (DB queries on a server). Third: my fragment was not instantiated at activity start Fourth: i used a custom fragment instantiation "create or load it" in order to get the fragment variable. Fourth: activity was recreated because of orientation change
The problem was that i wanted to "remove" the fragment because of the query answer, but the fragment was incorrectly created just before. I don't know why, probably because of the "commit" be done later, the fragment was not added yet when it was time to remove it. Therefore getActivity() was returning null.
Solution : 1)I had to check that i was correctly trying to find the first instance of the fragment before creating a new one 2)I had to put serRetainInstance(true) on that fragment in order to keep it through orientation change (no backstack needed therefore no problem) 3)Instead of "recreating or getting old fragment" just before "remove it", I directly put the fragment at activity start. Instantiating it at activity start instead of "loading" (or instantiating) the fragment variable before removing it prevented getActivity problems.
Note the output while doing the merge - it is saying Fast Forward
In such situations, you want to do:
git merge v1.0 --no-commit --no-ff
With the two previous steps stated above, you're still missing the foreign key constraint. This should work:
class AddUserReferenceToTester < ActiveRecord::Migration
def change
add_column :testers, :user_id, :integer, references: :users
end
end
Just use DROP TABLE IF EXISTS
:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
I used exe4j to package all java jars into one final .exe file, which user can use it as normal windows application.
Referencing Qwerty's answer, if the destRow isnot null, sheet.shiftRows() will change the destRow's reference to the next row; so we should always create a new row:
if (destRow != null) {
sheet.shiftRows(destination, sheet.getLastRowNum(), 1);
}
destRow = sheet.createRow(destination);
From the man page for time:
/usr/bin/time
You can provide a format string and one of the format options is elapsed time - e.g. %E
/usr/bin/time -f'%E' $CMD
Example:
$ /usr/bin/time -f'%E' ls /tmp/mako/
res.py res.pyc
0:00.01
If you're using windows, create this POLL.CMD file
@echo off
:top
xcopy /m /y %1 %2 | find /v "File(s) copied"
timeout /T 1 > nul
goto :top
then you can type "poll dir1 dir2" and it will copy all the files from dir1 to dir2 and check for updates once per second.
The "find" is optional, just to make the console less noisy.
This is not recursive. Maybe you could make it recursive using /e on the xcopy.
In Data Source
(on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard
. A new window will appear, expand the Connection string, you can find the connection string in there
Simply check if the query returned a column_name.
If not, execute something like this:
ALTER TABLE x ADD COLUMN y int;
Where you put something useful for 'x' and 'y' and of course a suitable datatype where I used int.
Look at jQuery Toggle
HTML:
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
For versions of jQuery 1.7 and newer use
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
For reference, kindly check this demo
Application.Current results in an appdomain http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx
Also this should give you the location of the assembly
AppDomain.CurrentDomain.BaseDirectory
I seem to recall there being multiple ways of getting the location of the application. but this one worked for me in the past atleast (it's been a while since i've done winforms programming :/)
After I removed
\usepackage{fontspec}% font selecting commands
\usepackage{xunicode}% unicode character macros
\usepackage{xltxtra} % some fixes/extras
it seems to have worked "correctly".
It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.
FYI: MikTeX 2.7 under Vista
Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.
$("#button_1, #button_2").on("click", function(e) {
e.preventDefault();
$.ajax({type: "POST",
url: "/pages/test/",
data: { id: $(this).val(), access_token: $("#access_token").val() },
success:function(result) {
alert('ok');
},
error:function(result) {
alert('error');
}
});
});
You shouldn't need a $watch. Just bind to resize event on window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E',
template: '<div>window size: {{width}}px</div>'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
angular.element($window).bind('resize', function(){
scope.width = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
}]);
Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.
With the signature you have given, T
must be associated to a single type (e.g. String
or Integer
) at the call-site. You can, however, declare method signatures which take multiple type parameters
public <S, T> void func(Set<S> s, Set<T> t)
Note in the above signature that I have declared the types S
and T
in the signature itself. These are therefore different to and independent of any generic types associated with the class or interface which contains the function.
public class MyClass<S, T> {
public void foo(Set<S> s, Set<T> t); //same type params as on class
public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
}
You might like to take a look at some of the method signatures of the collection classes in the java.util
package. Generics is really rather a complicated subject, especially when wildcards (? extends
and ? super
) are considered. For example, it's often the case that a method which might take a Set<Number>
as a parameter should also accept a Set<Integer>
. In which case you'd see a signature like this:
public void baz(Set<? extends T> s);
There are plenty of questions already on SO for you to look at on the subject!
Not sure what the point of returning an int
from the function is, although you could do that if you want!
a bit example
var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')_x000D_
_x000D_
if (audio.paused) {_x000D_
audio.play()_x000D_
} else {_x000D_
audio.pause()_x000D_
}
_x000D_
You can also use ngIf
if the situation permits:
<div ng-repeat="p in [
{ name: 'Justin' },
{ name: 'Jimi' },
{ name: 'Bob' }
]" ng-if="['Jimi', 'Bob'].indexOf(e.name) > -1">
{{ p.name }} is cool
</div>
Here is an extension of @Trasp's answer that has additional logic for handling the corner case of a file that has only one line. It may be useful to handle this case if you repeatedly want to read the last line of a file that is continuously being updated. Without this, if you try to grab the last line of a file that has just been created and has only one line, IOError: [Errno 22] Invalid argument
will be raised.
def tail(filepath):
with open(filepath, "rb") as f:
first = f.readline() # Read the first line.
f.seek(-2, 2) # Jump to the second last byte.
while f.read(1) != b"\n": # Until EOL is found...
try:
f.seek(-2, 1) # ...jump back the read byte plus one more.
except IOError:
f.seek(-1, 1)
if f.tell() == 0:
break
last = f.readline() # Read last line.
return last
You could use "Test Mail Server Tool" to test email sending on your machine or localhost. Google and Download "Test Mail Server Tool" and set it up.
Then in your settings.py:
EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
From shell:
from django.core.mail import send_mail
send_mail('subject','message','sender email',['receipient email'], fail_silently=False)
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
A double quote character ("
) can be escaped as "
, but here's the rest of the story...
In XML attributes delimited by double quotes:
<EscapeNeeded name="Pete "Maverick" Mitchell"/>
In XML textual content:
<NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
In XML attributes delimited by single quotes ('
):
<NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
Similarly, ('
) require no escaping if ("
) are used for the attribute value delimiters:
<NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
=IF(CR<=10, "RED", if(CR<50, "YELLOW", if(CR<101, "GREEN")))
CR = ColRow (Cell)
This is an example. In this example when value in Cell is less then or equal to 10 then RED word will appear on that cell. In the same manner other if conditions are true if first if is false.
Executing ng new --skip-install PROJECT_NAME and then manually going into the created folder and typing npm install. https://github.com/angular/angular-cli/issues/3906
Use the method .rdd
like this:
rdd = df.rdd
try sorting list , char have the ascii code, the same can be used for sorting the list of char.
aw=[1,2,2,1,1,3,5,342,345,56,2,35,436,6,576,54,76,47,658,8758,87,878]
for i in range(aw.__len__()):
for j in range(aw.__len__()):
if aw[i] < aw[j] :aw[i],aw[j]=aw[j],aw[i]
Based on my experience, by creating a delimited expression from the employeeIDs, there is a tricky and nice solution for this problem. You should only create an string expression like ';123;434;365;'
in-which 123
, 434
and 365
are some employeeIDs. By calling the below procedure and passing this expression to it, you can fetch your desired records. Easily you can join the "another table" into this query. This solution is suitable in all versions of SQL server. Also, in comparison with using table variable or temp table, it is very faster and optimized solution.
CREATE PROCEDURE dbo.DoSomethingOnSomeEmployees @List AS varchar(max)
AS
BEGIN
SELECT EmployeeID
FROM EmployeesTable
-- inner join AnotherTable on ...
where @List like '%;'+cast(employeeID as varchar(20))+';%'
END
GO
bit late but nevermind easy one is
import autopy
import time
time.sleep(2)
b = autopy.bitmap.capture_screen()
b.save("C:/Users/mak/Desktop/m.png")
One other work-around is to use jupyter notebooks and use the markdown mode in cells to render equations.
Basic stuff seems to work perfectly, like centered equations
\begin{equation}
...
\end{equation}
or inline equations
$ \sum_{\forall i}{x_i^{2}} $
Although, one of the functions that I really wanted did not render at all in github was \mbox{}
, which was a bummer. But, all in all this has been the most successful way of rendering equations on github.
If you don't want to use numpy
nor zip
, you can use the following solution:
>>> t = [1, 3, 6]
>>> v = [t[i+1]-t[i] for i in range(len(t)-1)]
>>> v
[2, 3]
This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.
wp_users
, add a key, like abc123 to the
user_activation
column. Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
DateUtils from Apache Commons-Lang. Watch out for time zone!
Use javascript array push()
method,
it adds the given object in the end of the array.
JS Arrays are pretty flexible,you can push as many objects as you wish in an array without specifying its length beforehand. Also,different types of objects can be pushed to the same Array.
Below is a simple way to convert dataframe column into numpy array.
df = pd.DataFrame(somedict)
ytrain = df['label']
ytrain_numpy = np.array([x for x in ytrain['label']])
ytrain_numpy is a numpy array.
I tried with to.numpy()
but it gave me the below error:
TypeError: no supported conversion for types: (dtype('O'),) while doing Binary Relevance classfication using Linear SVC.
to.numpy() was converting the dataFrame into numpy array but the inner element's data type was list because of which the above error was observed.
Use Column or Row in a Button child, Row for horizontal button, Column for vertical, and dont forget to contain it with the size you need:
Container(
width: 120.0,
height: 30.0,
child: RaisedButton(
color: Color(0XFFFF0000),
child: Row(
children: <Widget>[
Text('Play this song', style: TextStyle(color: Colors.white),),
Icon(Icons.play_arrow, color: Colors.white,),
],
),
),
),
I have a simple script I use for this:
me@mycomputer:~$ cat /usr/local/bin/c
#!/bin/sh
echo "$*" | sed 's/x/\*/g' | bc -l
It changes x
to *
since *
is a special character in the shell. Use it as follows:
c 5x5
c 5-4.2 + 1
c '(5 + 5) * 30'
(you still have to use quotes if the expression contains any parentheses).In a git bash session, you can add a script to ~/.profile
or ~/.bashrc
(with ~
being usually set to %USERPROFILE%
), in order for said session to launch automatically the ssh-agent
. If the file doesn't exist, just create it.
This is what GitHub describes in "Working with SSH key passphrases".
The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not. Below is just a snippet, see the GitHub article for the full solution.
# This is just a snippet. See the article above.
if ! agent_is_running; then
agent_start
ssh-add
elif ! agent_has_keys; then
ssh-add
fi
Other Resources:
"Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.
The best and the coolest way to add new data to the present data is
ArrayList<String> newItems = new ArrayList<String>();
newItems = getList();
int oldListItemscount = alcontainerDetails.size();
alcontainerDetails.addAll(newItems);
recyclerview.getAdapter().notifyItemChanged(oldListItemscount+1, al_containerDetails);
If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows
git rebase --onto <sha of 1> <sha of 2> <blue branch>
And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.
In the Edge browser as of build 20.10240.16384.0 you can hide the address bar by setting location=no in the window.open features.
check this one:
import java.io.*;
public class UserInputInteger
{
public static void main(String args[])throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int number;
System.out.println("Enter the number");
number = Integer.parseInt(in.readLine());
}
}
The Boost::serialization
library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here.
The only native way to do it is to use streams. That's essentially all the Boost::serialization
library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format.
For built-in types, or your own types with operator<<
and operator>>
properly defined, that's fairly simple; see the C++ FAQ for more information.
An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?
memcpy(arrayOfByte, &x, sizeof x);
A simple elegant one liner that will also work with any other data type.
If you need the bytes reversed you can use std::reverse
memcpy(arrayOfByte, &x, sizeof x);
std::reverse(arrayOfByte, arrayOfByte + sizeof x);
or better yet, just copy the bytes in reverse to begin with
BYTE* p = (BYTE*) &x;
std::reverse_copy(p, p + sizeof x, arrayOfByte);
If you don't want to make a copy of the data at all, and just have its byte representation
BYTE* bytes = (BYTE*) &x;
Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
I have this function in my .bash_profile
or .profile
or .zprofile
or whatever gets sourced in login shells:
function gac () {
# Usage: gac [files] [message]
# gac (git add commit) stages files specified by the first argument
# and commits the changes with a message specified by the second argument.
# Using quotes one can add multiple files at once: gac "file1 file2" "Message".
git add $1 && git commit -m "$2"
}
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
You need to add the line-height
attribute and that attribute must match the height of the div
. In your case:
.center {_x000D_
height: 309px;_x000D_
line-height: 309px; /* same as height! */_x000D_
}
_x000D_
<div class="center">_x000D_
A single line._x000D_
</div>
_x000D_
In fact, you could probably remove the height
attribute altogether.
This only works for one line of text though, so be careful.
If you don't have any error messages and don't know what the problem is - why PowerShell scripts don't want to start from a Scheduled Task do the following steps to get the answer:
You should be able to see all error notifications.
In case of one of my script it was:
"Unable to find type [System.ServiceProcess.ServiceController]. Make sure that the assembly that contains this type is loaded."
And in this case I have to add additional line at the begining of the script to load the missing assembly:
Add-Type -AssemblyName "System.ServiceProcess"
And next errors:
Exception calling "GetServices" with "1" argument(s): "Cannot open Service Control Manager on computer ''. This operation might require other privileges."
select : The property cannot be processed because the property "Database Name" already exists
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
If you want to revert the changes only in current working directory, use
git checkout -- .
And before that, you can list the files that will be reverted without actually making any action, just to check what will happen, with:
git checkout --
You just add an accessor who define what you change
class Post < AR::Base
attr_reader :what_changed
before_filter :what_changed?
def what_changed?
@what_changed = changes || []
end
after_filter :action_on_changes
def action_on_changes
@what_changed.each do |change|
p change
end
end
end
You can generalize @Nithin's answer to work directly with DRF's existing serializer system by generating a parser class to parse specific fields which are then fed directly into the standard DRF serializers:
from django.http import QueryDict
import json
from rest_framework import parsers
def gen_MultipartJsonParser(json_fields):
class MultipartJsonParser(parsers.MultiPartParser):
def parse(self, stream, media_type=None, parser_context=None):
result = super().parse(
stream,
media_type=media_type,
parser_context=parser_context
)
data = {}
# find the data field and parse it
qdict = QueryDict('', mutable=True)
for json_field in json_fields:
json_data = result.data.get(json_field, None)
if not json_data:
continue
data = json.loads(json_data)
if type(data) == list:
for d in data:
qdict.update({json_field: d})
else:
qdict.update({json_field: data})
return parsers.DataAndFiles(qdict, result.files)
return MultipartJsonParser
This is used like:
class MyFileViewSet(ModelViewSet):
parser_classes = [gen_MultipartJsonParser(['tags', 'permissions'])]
# ^^^^^^^^^^^^^^^^^^^
# Fields that need to be further JSON parsed
....
I got this working.
log4j.appender.file.File=${LogFilePath}
-DLogFilePath=C:\work\MyLogFile.log
A quick note for the answer from @subin sahayam
import random
file=open("datafile.txt","r")
data=list()
for line in file:
data.append(line.split(#your preferred delimiter))
file.close()
random.shuffle(data)
train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
test_data = data[int(len(data)*.80+1):] #Splits 20% data to test set
If your list size is a even number, you should not add the 1 in the code below. Instead, you need to check the size of the list first and then determine if you need to add the 1.
test_data = data[int(len(data)*.80+1):]
Old question but I have a much better way of doing this. Rather than using rect()
use polygon
. This allows you to keep everything in plot
without using points
. Also you don't have to mess with par
at all. If you want to keep things automated make the coordinates of polygon
a function of your data.
plot.new()
polygon(c(-min(df[,1])^2,-min(df[,1])^2,max(df[,1])^2,max(df[,1])^2),c(-min(df[,2])^2,max(df[,2])^2,max(df[,2])^2,-min(df[,2])^2), col="grey")
par(new=T)
plot(df)
Here's another version of XMLillies w/ domi's LI change that uses a search string instead of a path level. I think this is a little more obvious what's happening for my use case.
statsApp.directive('activeTab', function ($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) {
if (attrs.href!=undefined) { // this directive is called twice for some reason
// The activeTab attribute should contain a path search string to match on.
// I.e. <li><a href="#/nested/section1/partial" activeTab="/section1">First Partial</a></li>
if ($location.path().indexOf(attrs.activeTab) >= 0) {
element.parent().addClass("active");//parent to get the <li>
} else {
element.parent().removeClass("active");
}
}
});
}
};
});
HTML now looks like:
<ul class="nav nav-tabs">
<li><a href="#/news" active-tab="/news">News</a></li>
<li><a href="#/some/nested/photos/rawr" active-tab="/photos">Photos</a></li>
<li><a href="#/contact" active-tab="/contact">Contact</a></li>
</ul>
You can use implode to return your array with a string separator.
$withComma = implode(",", $array);
echo $withComma;
// Will display apple,banana,orange
It is actually a 3 step process to connect to a PostgreSQL server remotely through pgAdmin3.
Note: I use Ubuntu 11.04 and PostgreSQL 8.4.
You have to make PostgreSQL listening for remote incoming TCP connections because the default settings allow to listen only for connections on the loopback interface. To be able to reach the server remotely you have to add the following line into the file /etc/postgresql/8.4/main/postgresql.conf:
listen_addresses = '*'
PostgreSQL by default refuses all connections it receives from any remote address, you have to relax these rules by adding this line to /etc/postgresql/8.4/main/pg_hba.conf:
host all all 0.0.0.0/0 md5
This is an access control rule that let anybody login in from any address if he can provide a valid password (the md5 keyword). You can use needed network/mask instead of 0.0.0.0/0 .
When you have applied these modifications to your configuration files you need to restart PostgreSQL server. Now it is possible to login to your server remotely, using the username and password.
Sometimes I have repositories with folders that will only ever contain files considered to be "content"—that is, they are not files that I care about being versioned, and therefore should never be committed. With Git's .gitignore file, you can ignore entire directories. But there are times when having the folder in the repo would be beneficial. Here's a excellent solution for accomplishing this need.
What I've done in the past is put a .gitignore file at the root of my repo, and then exclude the folder, like so:
/app/some-folder-to-exclude
/another-folder-to-exclude/*
However, these folders then don't become part of the repo. You could add something like a README file in there. But then you have to tell your application not to worry about processing any README files.
If your app depends on the folders being there (though empty), you can simply add a .gitignore file to the folder in question, and use it to accomplish two goals:
Tell Git there's a file in the folder, which makes Git add it to the repo. Tell Git to ignore the contents of this folder, minus this file itself. Here is the .gitignore file to put inside your empty directories:
*
!.gitignore
The first line (*) tells Git to ignore everything in this directory. The second line tells Git not to ignore the .gitignore file. You can stuff this file into every empty folder you want added to the repository.
I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency.
The conversion was probably not successful. The only thing that was successful was the running of VCUpgrade. The actual conversion itself failed but you don't know until you experience the errors you are seeing. For some of the details, see Visual Studio on the Crypto++ wiki.
Any ideas how to fix this?
To resolve your issues, you should download vs2010.zip
if you want static C/C++ runtime linking (/MT
or /MTd
), or vs2010-dynamic.zip
if you want dynamic C/C++ runtime linking (/MT
or /MTd
). Both fix the latent, silent failures produced by VCUpgrade.
vs2010.zip
, vs2010-dynamic.zip
and vs2005-dynamic.zip
are built from the latest GitHub sources. As of this writing (JUN 1 2016), that's effectively pre-Crypto++ 5.6.4. If you are using the ZIP files with a down level Crypto++, like 5.6.2 or 5.6.3, then you will run into minor problems.
There are two minor problems I am aware. First is a rename of bench.cpp
to bench1.cpp
. Its error is either:
C1083: Cannot open source file: 'bench1.cpp': No such file or directory
LNK2001: unresolved external symbol "void __cdecl OutputResultOperations(char const *,char const *,bool,unsigned long,double)" (?OutputResultOperations@@YAXPBD0_NKN@Z)
The fix is to either (1) open cryptest.vcxproj
in notepad, find bench1.cpp
, and then rename it to bench.cpp
. Or (2) rename bench.cpp
to bench1.cpp
on the filesystem. Please don't delete this file.
The second problem is a little trickier because its a moving target. Down level releases, like 5.6.2 or 5.6.3, are missing the latest classes available in GitHub. The missing class files include HKDF (5.6.3), RDRAND (5.6.3), RDSEED (5.6.3), ChaCha (5.6.4), BLAKE2 (5.6.4), Poly1305 (5.6.4), etc.
The fix is to remove the missing source files from the Visual Studio project files since they don't exist for the down level releases.
Another option is to add the missing class files from the latest sources, but there could be complications. For example, many of the sources subtly depend upon the latest config.h
, cpu.h
and cpu.cpp
. The "subtlety" is you won't realize you are getting an under-performing class.
An example of under-performing class is BLAKE2. config.h
adds compile time ARM-32 and ARM-64 detection. cpu.h
and cpu.cpp
adds runtime ARM instruction detection, which depends upon compile time detection. If you add BLAKE2 without the other files, then none of the detection occurs and you get a straight C/C++ implementation. You probably won't realize you are missing the NEON opportunity, which runs around 9 to 12 cycles-per-byte versus 40 cycles-per-byte or so for vanilla C/C++.
Try this query:
SELECT sysdate FROM schema_name.table_name;
This should display the timestamp that you might need.
You could do something like this:
\documentclass{article}
\begin{document}
Normal:
\begin{itemize}
\item foo
\item bar
\item baz
\end{itemize}
Less space:
\begin{itemize}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
Also you need to disable below line in configuration file: bind-address = 127.0.0.1
Again for completeness I'll add my most useful use-case for with
statements.
I do a lot of scientific computing and for some activities I need the Decimal
library for arbitrary precision calculations. Some part of my code I need high precision and for most other parts I need less precision.
I set my default precision to a low number and then use with
to get a more precise answer for some sections:
from decimal import localcontext
with localcontext() as ctx:
ctx.prec = 42 # Perform a high precision calculation
s = calculate_something()
s = +s # Round the final result back to the default precision
I use this a lot with the Hypergeometric Test which requires the division of large numbers resulting form factorials. When you do genomic scale calculations you have to be careful of round-off and overflow errors.
The simple version is 0x is a prefix denoting a hexadecimal number, source.
So the value you're computing is after the prefix, in this case 10.
But that is not the number 10. The most significant bit 1
denotes the hex value while 0
denotes the units.
So the simple math you would do is
0x10
1 * 16 + 0 = 16
Note - you use 16 because hex is base 16.
Another example:
0xF7
15 * 16 + 7 = 247
You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.
Broadcasting is really good for this:
row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]
row_sums[:, numpy.newaxis]
reshapes row_sums from being (3,)
to being (3, 1)
. When you do a / b
, a
and b
are broadcast against each other.
You can learn more about broadcasting here or even better here.
This is what worked for me when I had this error:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
</dict>
</dict>
</dict>
Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.
Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.
And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.
I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :
su root
Reconfigure your local settings :
dpkg-reconfigure locales
Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)
Uninstall and clean properly postgresql :
apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres
Re-install postgresql :
aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1
Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).
A fresh look at this(possibly)
in your php:
else{
$hidemydiv = "hide";
}
And then later in your html code:
<div class='<?php echo $hidemydiv ?>' > maybe show or hide this</div>
in this way your php remains quite clean
I found this thread looking for information about dealing with parameters; this easy guide was so cool:
import argparse
parser = argparse.ArgumentParser(description='Script so useful.')
parser.add_argument("--opt1", type=int, default=1)
parser.add_argument("--opt2")
args = parser.parse_args()
opt1_value = args.opt1
opt2_value = args.opt2
run like:
python myScript.py --opt2 = 'hi'
I would use the scheduler (control panel) rather than a cmd line or other application.
Control Panel -> Scheduled tasks
I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.
In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id()
instead of get_the_ID()
.
$postID = get_queried_object_id();
I got
No 'Access-Control-Allow-Origin' header is present
and the problem was with the URL I was providing. I was providing the URL without a route, e.g., https://misty-valley-1234.herokuapp.com/
.
When I added a path it worked, e.g.,
https://misty-valley-1234.herokuapp.com/messages
. With GET requests it worked either way but with POST responses it only worked with the added path.
Try using .pull-left to left align image along with text.
Ex:
<p>At the time all text elements goes here.At the time all text elements goes here. At the time all text elements goes here.<img src="images/hello-missing.jpg" class="pull-left img-responsive" style="padding:15px;" /> to uncovering the truth .</p>
I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.
The code will work like this:
int a=5,i;
i=++a + ++a + a++; /*a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8); i=20;*/
i=a++ + ++a + ++a; /*a = 5;
i=a++ + ++a + ++a; =>
i=8 + 10 + 11; (a=11); i=29;*/
a=++a + ++a + a++; /*a=5;
a=++a + ++a + a++; =>
a=12 + 13 + 13; a=38;*/
System.out.println(a); //output: 38
System.out.println(i); //output: 29
You can use two approaches for this...
To make text align center horizontally, apply this Property (textAlign:"center")
.
Now to make the text align vertically, first check direction of flex. If flexDirection is column apply property (justifyContent:"center"
) and if flexDirection is row is row apply property (alignItems : "center"
) .
To Make text align center apply same property (textAlign:"center"
). Now to make it align vertically make the hieght of the <Text> </Text>
equal to view and then apply property
(textAlignVertical: "center"
)...
Most Probably it will Work...
Citing the official javadoc of List.addAll
:
Appends all of the elements in the specified collection to the end of
this list, in the order that they are returned by the specified
collection's iterator (optional operation). The behavior of this
operation is undefined if the specified collection is modified while
the operation is in progress. (Note that this will occur if the
specified collection is this list, and it's nonempty.)
So you will copy the references of the objects in list
to anotherList
. Any method that does not operate on the referenced objects of anotherList
(such as removal, addition, sorting) is local to it, and therefore will not influence list
.
What you are trying to achieve is equivalent to
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.
Solutions above didn't work. It simply displayed the last key/value pairs, but this did:
http://localhost/?key[]=1&key[]=2
Returns:
Array
(
[key] => Array
(
[0] => 1
[1] => 2
)
To continue off of bobince's answer
In es6 you can now actually create a class
So now you can do:
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Shape at ${this.x}, ${this.y}`;
}
}
So extend to a circle (as in the other answer) you can do:
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
toString() {
let shapeString = super.toString();
return `Circular ${shapeString} with radius ${this.r}`;
}
}
Ends up a bit cleaner in es6 and a little easier to read.
Here is a good example of it in action:
class Shape {_x000D_
constructor(x, y) {_x000D_
this.x = x;_x000D_
this.y = y;_x000D_
}_x000D_
_x000D_
toString() {_x000D_
return `Shape at ${this.x}, ${this.y}`;_x000D_
}_x000D_
}_x000D_
_x000D_
class Circle extends Shape {_x000D_
constructor(x, y, r) {_x000D_
super(x, y);_x000D_
this.r = r;_x000D_
}_x000D_
_x000D_
toString() {_x000D_
let shapeString = super.toString();_x000D_
return `Circular ${shapeString} with radius ${this.r}`;_x000D_
}_x000D_
}_x000D_
_x000D_
let c = new Circle(1, 2, 4);_x000D_
_x000D_
console.log('' + c, c);
_x000D_
returning true or false indicates that whether execution should continue or stop right there. So just an example
<input type="button" onclick="return func();" />
Now if func() is defined like this
function func()
{
// do something
return false;
}
the click event will never get executed. On the contrary if return true is written then the click event will always be executed.
Also you are tying up a threadpool thread for the lifetime of the background worker, which may be of concern as there are only a finite number of them. I would say that if you are only ever creating the thread once for your app (and not using any of the features of background worker) then use a thread, rather than a backgroundworker/threadpool thread.
Use str.join
:
In [27]: mylist = ['10', '12', '14']
In [28]: print '\n'.join(mylist)
10
12
14
You can drop the database
and then recreate it with the below:-
mysql> drop database [database name];
mysql> create database [database name];
Download and extract .zip file having all .dll plugin files under the path
C:\ProgramData\Notepad++\plugins\
Make sure to create a separated folder for each plugin
with the newest version react 0.11 you can also just return null to have no content rendered.
For me, it was having my code folder in Dropbox on windows 10. During the build process Dropbox would flip out over having more than 500,000 files. I moved my folder out and now it builds fine!
In my case this happened with React and postal.js when I didn't unsubscribe from a channel in the componentWillUnmount
callback of my React component.
Java does not allow extending multiple classes.
Let's assume C class is extending A and B classes. Then if suppose A and B classes have method with same name(Ex: method1()). Consider the code:
C obj1 = new C();
obj1.method1();
- here JVM will not understand to which method it need to access. Because both A and B classes have this method. So we are putting JVM in dilemma, so that is the reason why multiple inheritance is removed from Java. And as said implementing multiple classes will resolve this issue.
Hope this has helped.
I would re-write the original target test, taking care the needed variable is defined IN THE SAME SUB-PROCESS as the application to launch:
test:
( NODE_ENV=test mocha --harmony --reporter spec test )
glBegin(GL_POLYGON); // Middle circle
double radius = 0.2;
double ori_x = 0.0; // the origin or center of circle
double ori_y = 0.0;
for (int i = 0; i <= 300; i++) {
double angle = 2 * PI * i / 300;
double x = cos(angle) * radius;
double y = sin(angle) * radius;
glVertex2d(ori_x + x, ori_y + y);
}
glEnd();
They've now deprecated click(), so best to go with on('click')
Having a similar case and I couldn't use StackAttacks solution as he's referring to SDL2 which is for the legacy code I'm using too new.
Fortunately our friends from askUbuntu had something similar:
tar xvf SDL-1.2.tar.gz
cd SDL-1.2
./configure
make
sudo make install
I solve this trouble with config APACHE ! All methods (in this topic) is incorrect for me... Then I try chanche apache config:
Timeout 3600
Then my script worked!
PROBLEM SOLVED !!!!!!!
Turns out the storage
function DID NOT run even once.
because i had to include app.use(upload)
as upload = multer({storage}).single('file');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './storage')
},
filename: function (req, file, cb) {
console.log(file) // this didn't print anything out so i assumed it was never excuted
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({storage}).single('file');
If you're using ReSharper, go into the ReSharper menu → Code → Generate...
(Or hit Alt + Ins inside the surrounding class), and you'll get all the options for generating getters and/or setters you can think of :-)
try this
bool flag = dg1.CurrentRow.Selected;
if(flag)
{
/// datagridview row is selected in datagridview rowselect selection mode
}
else
{
/// no row is selected or last empty row is selected
}
From High Performance Android Apps book (page 157):
The year()
function just retrieves the year component of the underlying Date
object, so it returns a number.
Calling format('YYYY')
will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY
, then the result will be a string containing the year.
If all you need is the year, then use the year()
function. It will be faster, as there is less work to do.
Do note that while years are the same in this regard, months are not! Calling format('M')
will return months in the range 1-12. Calling month()
will return months in the range 0-11. This is due to the same behavior of the underlying Date
object.
or you can use another approach:
$( "#serverMsg", window.opener.document )
In addition to Nick Holt's observations, I ran a few cases for Array
data type:
//primitive Array
int demo[] = new int[5];
Class<? extends int[]> clzz = demo.getClass();
System.out.println(clzz.getName());
System.out.println(clzz.getCanonicalName());
System.out.println(clzz.getSimpleName());
System.out.println();
//Object Array
Integer demo[] = new Integer[5];
Class<? extends Integer[]> clzz = demo.getClass();
System.out.println(clzz.getName());
System.out.println(clzz.getCanonicalName());
System.out.println(clzz.getSimpleName());
Above code snippet prints:
[I
int[]
int[]
[Ljava.lang.Integer;
java.lang.Integer[]
Integer[]
This should be working. Please have a look at this fiddle.
$(function() {
$( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code
Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.
Your conversion data is response[25] and follow the below steps.
var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34
For those that might be curious about the ConcreteListTypeConverter that was referenced by Oliver, here is my attempt:
public class ConcreteListTypeConverter<TInterface, TImplementation> : JsonConverter where TImplementation : TInterface
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var res = serializer.Deserialize<List<TImplementation>>(reader);
return res.ConvertAll(x => (TInterface) x);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
Dude... exit()
function is defined under stdlib.h
So you need to add a preprocessor.
Put include stdlib.h
in the header section
Then use exit();
wherever you like but remember to put an interger number in the parenthesis of exit.
for example:
exit(0);
You can use this text-underline-position: under
See here for more detail: https://css-tricks.com/almanac/properties/t/text-underline-position/
See also browser compatibility.
If you're open to using jQuery:
<script type="text/javascript">
function fncsave()
{
$('#<%= savebtn.ClientID %>').click();
}
</script>
Also, if you are using .NET 4 or better you can make the ClientIDMode == static
and simplify the code:
<script type="text/javascript">
function fncsave()
{
$("#savebtn").click();
}
</script>
Reference: MSDN Article for Control.ClientIDMode
You can use a combination of other LINQ methods to handle not matching condition:
var res = dictionary.Where(x => x.Value.ID == someID)
.Select(x => x.Value.DisplayName)
.DefaultIfEmpty("Unknown")
.First();
The most concise way to remove duplicates from an array using native javascript functions is to use a sequence like below:
vals.sort().reduce(function(a, b){ if (b != a[0]) a.unshift(b); return a }, [])
there's no need for slice
nor indexOf
within the reduce function, like i've seen in other examples! it makes sense to use it along with a filter function though:
vals.filter(function(v, i, a){ return i == a.indexOf(v) })
Yet another ES6(2015) way of doing this that already works on a few browsers is:
Array.from(new Set(vals))
or even using the spread operator:
[...new Set(vals)]
cheers!
You can try this logic because it is worked for me.
frag_profile profile_fragment = new frag_profile();
boolean flag = false;
@SuppressLint("ResourceType")
public void profile_Frag(){
if (flag == false) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
manager.getBackStackEntryCount();
transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
transaction.commit();
flag = true;
}
}
@Override
public void onBackPressed() {
if (flag == true) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
manager.getBackStackEntryCount();
transaction.remove(profile_fragment);
transaction.commit();
flag = false;
}
else super.onBackPressed();
}
In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.
For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:
Function cleanString(text As String) As String
Dim output As String
Dim c 'since char type does not exist in vba, we have to use variant type.
For i = 1 To Len(text)
c = Mid(text, i, 1) 'Select the character at the i position
If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
output = output & c 'add the character to your output.
Else
output = output & " " 'add the replacement character (space) to your output
End If
Next
cleanString = output
End Function
The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.
This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.
You could just use:
<div id="GridDiv">
// gridview inside...
</div>
<a href="#GridDiv">Scroll to top</a>
The const
keyword is in the ECMAScript 6 draft but it thus far only enjoys a smattering of browser support: http://kangax.github.io/compat-table/es6/. The syntax is:
const CONSTANT_NAME = 0;
What you need is strstr()
(or stristr()
, like LucaB pointed out). Use it like this:
if(strstr($text, "world")) {/* do stuff */}
None
, Python's null?There's no null
in Python; instead there's None
. As stated already, the most accurate way to test that something has been given None
as a value is to use the is
identity operator, which tests that two variables refer to the same object.
>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False
None
None
is the sole instance of the class NoneType
and any further attempts at instantiating that class will return the same object, which makes None
a singleton. Newcomers to Python often see error messages that mention NoneType
and wonder what it is. It's my personal opinion that these messages could simply just mention None
by name because, as we'll see shortly, None
leaves little room to ambiguity. So if you see some TypeError
message that mentions that NoneType
can't do this or can't do that, just know that it's simply the one None
that was being used in a way that it can't.
Also, None
is a built-in constant. As soon as you start Python, it's available to use from everywhere, whether in module, class, or function. NoneType
by contrast is not, you'd need to get a reference to it first by querying None
for its class.
>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType
You can check None
's uniqueness with Python's identity function id()
. It returns the unique number assigned to an object, each object has one. If the id of two variables is the same, then they point in fact to the same object.
>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000
None
cannot be overwrittenIn much older versions of Python (before 2.4) it was possible to reassign None
, but not any more. Not even as a class attribute or in the confines of a function.
# In Python 2.7
>>> class SomeClass(object):
... def my_fnc(self):
... self.None = 'foo'
SyntaxError: cannot assign to None
>>> def my_fnc():
None = 'foo'
SyntaxError: cannot assign to None
# In Python 3.5
>>> class SomeClass:
... def my_fnc(self):
... self.None = 'foo'
SyntaxError: invalid syntax
>>> def my_fnc():
None = 'foo'
SyntaxError: cannot assign to keyword
It's therefore safe to assume that all None
references are the same. There isn't any "custom" None
.
None
use the is
operatorWhen writing code you might be tempted to test for Noneness like this:
if value==None:
pass
Or to test for falsehood like this
if not value:
pass
You need to understand the implications and why it's often a good idea to be explicit.
None
Why do
value is None
rather than
value==None
?
The first is equivalent to:
id(value)==id(None)
Whereas the expression value==None
is in fact applied like this
value.__eq__(None)
If the value really is None
then you'll get what you expected.
>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True
In most common cases the outcome will be the same, but the __eq__()
method opens a door that voids any guarantee of accuracy, since it can be overridden in a class to provide special behavior.
Consider this class.
>>> class Empty(object):
... def __eq__(self, other):
... return not other
So you try it on None
and it works
>>> empty = Empty()
>>> empty==None
True
But then it also works on the empty string
>>> empty==''
True
And yet
>>> ''==None
False
>>> empty is None
False
None
as a booleanThe following two tests
if value:
# Do something
if not value:
# Do something
are in fact evaluated as
if bool(value):
# Do something
if not bool(value):
# Do something
None
is a "falsey", meaning that if cast to a boolean it will return False
and if applied the not
operator it will return True
. Note however that it's not a property unique to None
. In addition to False
itself, the property is shared by empty lists, tuples, sets, dicts, strings, as well as 0, and all objects from classes that implement the __bool__()
magic method to return False
.
>>> bool(None)
False
>>> not None
True
>>> bool([])
False
>>> not []
True
>>> class MyFalsey(object):
... def __bool__(self):
... return False
>>> f = MyFalsey()
>>> bool(f)
False
>>> not f
True
So when testing for variables in the following way, be extra aware of what you're including or excluding from the test:
def some_function(value=None):
if not value:
value = init_value()
In the above, did you mean to call init_value()
when the value is set specifically to None
, or did you mean that a value set to 0
, or the empty string, or an empty list should also trigger the initialization? Like I said, be mindful. As it's often the case, in Python explicit is better than implicit.
None
in practiceNone
used as a signal valueNone
has a special status in Python. It's a favorite baseline value because many algorithms treat it as an exceptional value. In such scenarios it can be used as a flag to signal that a condition requires some special handling (such as the setting of a default value).
You can assign None
to the keyword arguments of a function and then explicitly test for it.
def my_function(value, param=None):
if param is None:
# Do something outrageous!
You can return it as the default when trying to get to an object's attribute and then explicitly test for it before doing something special.
value = getattr(some_obj, 'some_attribute', None)
if value is None:
# do something spectacular!
By default a dictionary's get()
method returns None
when trying to access a non-existing key:
>>> some_dict = {}
>>> value = some_dict.get('foo')
>>> value is None
True
If you were to try to access it by using the subscript notation a KeyError
would be raised
>>> value = some_dict['foo']
KeyError: 'foo'
Likewise if you attempt to pop a non-existing item
>>> value = some_dict.pop('foo')
KeyError: 'foo'
which you can suppress with a default value that is usually set to None
value = some_dict.pop('foo', None)
if value is None:
# Booom!
None
used as both a flag and valid valueThe above described uses of None
apply when it is not considered a valid value, but more like a signal to do something special. There are situations however where it sometimes matters to know where None
came from because even though it's used as a signal it could also be part of the data.
When you query an object for its attribute with getattr(some_obj, 'attribute_name', None)
getting back None
doesn't tell you if the attribute you were trying to access was set to None
or if it was altogether absent from the object. The same situation when accessing a key from a dictionary, like some_dict.get('some_key')
, you don't know if some_dict['some_key']
is missing or if it's just set to None
. If you need that information, the usual way to handle this is to directly attempt accessing the attribute or key from within a try/except
construct:
try:
# Equivalent to getattr() without specifying a default
# value = getattr(some_obj, 'some_attribute')
value = some_obj.some_attribute
# Now you handle `None` the data here
if value is None:
# Do something here because the attribute was set to None
except AttributeError:
# We're now handling the exceptional situation from here.
# We could assign None as a default value if required.
value = None
# In addition, since we now know that some_obj doesn't have the
# attribute 'some_attribute' we could do something about that.
log_something(some_obj)
Similarly with dict:
try:
value = some_dict['some_key']
if value is None:
# Do something here because 'some_key' is set to None
except KeyError:
# Set a default
value = None
# And do something because 'some_key' was missing
# from the dict.
log_something(some_dict)
The above two examples show how to handle object and dictionary cases. What about functions? The same thing, but we use the double asterisks keyword argument to that end:
def my_function(**kwargs):
try:
value = kwargs['some_key']
if value is None:
# Do something because 'some_key' is explicitly
# set to None
except KeyError:
# We assign the default
value = None
# And since it's not coming from the caller.
log_something('did not receive "some_key"')
None
used only as a valid valueIf you find that your code is littered with the above try/except
pattern simply to differentiate between None
flags and None
data, then just use another test value. There's a pattern where a value that falls outside the set of valid values is inserted as part of the data in a data structure and is used to control and test special conditions (e.g. boundaries, state, etc.). Such a value is called a sentinel and it can be used the way None
is used as a signal. It's trivial to create a sentinel in Python.
undefined = object()
The undefined
object above is unique and doesn't do much of anything that might be of interest to a program, it's thus an excellent replacement for None
as a flag. Some caveats apply, more about that after the code.
With function
def my_function(value, param1=undefined, param2=undefined):
if param1 is undefined:
# We know nothing was passed to it, not even None
log_something('param1 was missing')
param1 = None
if param2 is undefined:
# We got nothing here either
log_something('param2 was missing')
param2 = None
With dict
value = some_dict.get('some_key', undefined)
if value is None:
log_something("'some_key' was set to None")
if value is undefined:
# We know that the dict didn't have 'some_key'
log_something("'some_key' was not set at all")
value = None
With an object
value = getattr(obj, 'some_attribute', undefined)
if value is None:
log_something("'obj.some_attribute' was set to None")
if value is undefined:
# We know that there's no obj.some_attribute
log_something("no 'some_attribute' set on obj")
value = None
As I mentioned earlier, custom sentinels come with some caveats. First, they're not keywords like None
, so Python doesn't protect them. You can overwrite your undefined
above at any time, anywhere in the module it's defined, so be careful how you expose and use them. Next, the instance returned by object()
is not a singleton. If you make that call 10 times you get 10 different objects. Finally, usage of a sentinel is highly idiosyncratic. A sentinel is specific to the library it's used in and as such its scope should generally be limited to the library's internals. It shouldn't "leak" out. External code should only become aware of it, if their purpose is to extend or supplement the library's API.
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
The following will produce, in the output directory,
But it does not contain all .NET Core runtime assemblies.
<PropertyGroup>
<Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>
<ItemGroup>
<BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>
<Target Name="GenerateNetcoreExe"
AfterTargets="Build"
Condition="'$(IsNestedBuild)' != 'true'">
<RemoveDir Directories="$(Temp)" />
<Exec
ConsoleToMSBuild="true"
Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
<Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
</Exec>
<Copy
SourceFiles="@(BootStrapFiles)"
DestinationFolder="$(OutputPath)"
/>
</Target>
I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
$("#target")[0].selectedIndex = 0;
Do you want to look for strings that include an escape character? For instance you want this:
select * from table where myfield like '%10%%'.
Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.
select * from table where myfield like '%10!%%' ESCAPE '!'
Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS
variant or a LEFT JOIN
), but your query is perfectly legit.
Be aware of pitfalls with NOT IN
, though, when involving any NULL
values:
Variant with LEFT JOIN:
SELECT *
FROM friend f
LEFT JOIN likes l USING (id1, id2)
WHERE l.id1 IS NULL;
See @Michal's answer for the NOT EXISTS
variant.
A more detailed assessment of four basic variants:
I am very familiar with Mercurial's locking code (as of 1.9.1). The above advice is good, but I'd add that:
(For the curious: I haven't yet been able to catch the cause of this problem, but suspect it's either an older version of Mercurial accessing the repository or a problem in Python's socket.gethostname() call on certain versions of Windows.)
I copied over .svn folder from my peer worker's directory and that fixed the issue.
I would simply do this, which literally follows what your desired logic was:
df.groupby(['org']).mean().groupby(['cluster']).mean()
Simply, @Id: This annotation specifies the primary key of the entity.
@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used.
GenerationType enum defines four strategies:
1. Generation Type . TABLE,
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY
4. Generation Type. AUTO
GenerationType.SEQUENCE
With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities.
GenerationType.TABLE
With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities.
GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.
Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM. i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
<a href="#">link</a>
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.
It´s because a list is a mutable object. You´re not setting x to the value of [0,1,2,3], you´re defining a label to the object [0,1,2,3].
You should declare your function f() like this:
def f(n, x=None):
if x is None:
x = []
...
Options -MultiViews -Indexes
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
#cambiamos el valor para subir archivos
php_value memory_limit 400M
php_value post_max_size 400M
php_value upload_max_filesize 400M
php_value max_execution_time 300 #esta es la linea que necesitas agregar.
I finally realized now that instead of
git fetch --all && git reset --hard origin/master
it should be
git fetch --all && git reset --hard origin/<branch_name>
instead (if one works on a different branch)
Just give any name to the DataTable Like:
DataTable dt = new DataTable();
dt = SecondDataTable.Copy();
dt .TableName = "New Name";
DataSet.Tables.Add(dt );
One of the most used tool in the scientific community to that purpose is DummyNet. Once you have installed the ipfw
kernel module, in order to introduce 50ms propagation delay between 2 machines simply run these commands:
./ipfw pipe 1 config delay 50ms
./ipfw add 1000 pipe 1 ip from $IP_MACHINE_1 to $IP_MACHINE_2
In order to also introduce 50% of packet losses you have to run:
./ipfw pipe 1 config plr 0.5
Here more details.
Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.
If you want force stop your thread:
thread._Thread_stop()
For me works very good.
You can also use order_by method with fluent and eloquent like as:
Posts::where_status(1)->order_by(DB::raw(''),DB::raw('RAND()'));
This is a little bit weird usage, but works.
Edit: As @Alex said, this usage is cleaner and also works:
Posts::where_status(1)->order_by(DB::raw('RAND()'));
You can also use awk
for these purposes, since it allows you to perform more complex checks in a clearer way:
Lines not containing foo
:
awk '!/foo/'
Lines containing neither foo
nor bar
:
awk '!/foo/ && !/bar/'
Lines containing neither foo
nor bar
which contain either foo2
or bar2
:
awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'
And so on.
$.getJSON()
is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).
'generic' would be something like:
$.ajaxSetup({
"error":function() { alert("error"); }
});
And the 'specific' way:
$.getJSON("example.json", function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
Add the following dependency to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
Is this what you are trying to do?
# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
# Split into individual elements by the '.' character
# Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )
# We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )
# Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
# V1 V2 V3 V4
#1 F US CLE V13
#2 F US CA6 U13
#3 F US CA6 U13
#4 F US CA6 U13
#5 F US CA6 U13
#6 F US CA6 U13