(Posted on behalf of the OP).
I believe I figured it out.
In my case, I added [class*="col-"] {padding: 0 7.5px;};
.
Then added .row {margin: 0 -7.5px;}
.
This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;}
to .row {margin: 0 -8.5px;}
, then it works perfectly.
I have no idea why there is a 1px margin. Maybe someone can explain it?
See the sample I created:
From the description of material design specs:
Grid Lists are an alternative to standard list views. Grid lists are distinct from grids used for layouts and other visual presentations.
If you are looking for a much lightweight Grid component library, I'm using React-Flexbox-Grid, the implementation of flexboxgrid.css
in React.
On top of that, React-Flexbox-Grid played nicely with both material-ui, and react-toolbox (the alternative material design implementation).
As always, read Bootstrap's great documentation:
3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting
Make sure the parent level row is inside of a .container
element. Whenever you'd like to nest rows, just open up a new .row
inside of your column.
Here's a simple layout to work from:
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting
Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature
<div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
Which will look like this (with a little bit of added styling):
Propably this would do it for you.
$('input').val('').removeAttr('checked').removeAttr('selected');
uint32_t
is defined in the standard, in
<cstdint>
synopsis [cstdint.syn]namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}
uint32
is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32
) for ease of use.
Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:
private static void dateDiff() {
System.out.println("Calculate difference between two dates");
System.out.println("=================================================================");
DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
DateTime endDate = new DateTime();
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(" Difference between " + endDate);
System.out.println(" and " + startDate + " is " + days + " days.");
}
This solution doesn't need web.config file changes or catch-all routes.
First, create a controller like this;
public class ErrorController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Regular Error";
return View();
}
public ActionResult NotFound404()
{
ViewBag.Title = "Error 404 - File not Found";
return View("Index");
}
}
Then create the view under "Views/Error/Index.cshtml" as;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>We're sorry, page you're looking for is, sadly, not here.</p>
Then add the following in the Global asax file as below:
protected void Application_Error(object sender, EventArgs e)
{
// Do whatever you want to do with the error
//Show the custom error page...
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
{
routeData.Values["action"] = "Index";
}
else
{
// Handle 404 error and response code
Response.StatusCode = 404;
routeData.Values["action"] = "NotFound404";
}
Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
errorsController.Execute(rc);
Response.End();
}
If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors>
</httpErrors>
</system.webServer>
Download the bootbox typings
Then add a reference to it inside your .ts file.
I am not able to run my own build on the other suggestions here. I even tried different versions of maven-compiler-plugin: 3.1, 3.7.0, etc.
I made it work adding this:
<testSourceDirectory>/src/test/java</testSourceDirectory>
I tried this approach because it seems like the /src/test/java directory is considered a java class that is why it is compiled the same time as /src/test/java. So my hunch were right in my case.
Maybe it is to others too, so just try this one.
There could be a potential problem that leads to the StaleElementReferenceException that no one mentioned so far (in regard to actions).
I explain it in Javascript, but it's the same in Java.
This won't work:
let actions = driver.actions({ bridge: true })
let a = await driver.findElement(By.css('#a'))
await actions.click(a).perform() // this leads to a DOM change, #b will be removed and added again to the DOM.
let b = await driver.findElement(By.css('#b'))
await actions.click(b).perform()
But instantiating the actions again will solve it:
let actions = driver.actions({ bridge: true })
let a = await driver.findElement(By.css('#a'))
await actions.click(a).perform() // this leads to a DOM change, #b will be removed and added again to the DOM.
actions = driver.actions({ bridge: true }) // new
let b = await driver.findElement(By.css('#b'))
await actions.click(b).perform()
More information needed for a definitive answer, but this code
myNodeList = (ArrayList<MyNode>)this.getVertices();
will only work if this.getVertices()
returns a (subtype of) List<MyNode>
. If it is a different collection (like your Exception seems to indicate), you want to use
new ArrayList<MyNode>(this.getVertices())
This will work as long as a Collection type is returned by getVertices.
An interface is a contract that says “this object is able to do this thing”, whereas a trait is giving the object the ability to do the thing.
A trait is essentially a way to “copy and paste” code between classes.
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
Assuming that your script is named x.php, try this
<?php
function display($s) {
echo $s;
}
?>
<html>
<body>
<form method="post" action="x.php">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
display();
}
?>
</body>
</html>
You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result
#place this in /system/.htaccess as you had before
deny from all
If anyone is getting this error after a Phpmyadmin export, using the custom options and adding the "drop tables" statements cleared this right up.
Create Schema :
IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe'))
BEGIN
EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
END
ALTER Schema :
ALTER SCHEMA exe
TRANSFER dbo.Employees
I faced the same issue, and apparently Eclipse somehow left the version.xml
file in /res/values from the original google-play-services_lib
project while making a copy. I pulled the file from original project and pasted it in my copy of the project and the problem is fixed.
Exactly, you nearly got it:
GLfloat coordinates[8] = {1.0f, ..., 0.0f};
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
This is my implementation - it passes the tests and does the trick - you may want to change the replacement token if you're using three tildes in your statements:
private Regex LikeExpressionToRegexPattern(String likePattern)
{
var replacementToken = "~~~";
String result = likePattern.Replace("_", replacementToken)
.Replace("%", ".*");
result = Regex.Replace(result, @"\[.*" + replacementToken + @".*\]", "_");
result = result.Replace(replacementToken, ".");
return new Regex("^" + result + "$", RegexOptions.IgnoreCase);
}
Example:
// Define a test string.
string text = "Hello stackoverflow world";
string like = "%flow%";
// Define a regular expression and Find matches.
MatchCollection matches = LikeExpressionToRegexPattern(like).Matches(text);
//Result.
if (matches.Count > 0) {
//Yes
} else {
//No
}
What about this?
function replaceLast(x, y, z){
var a = x.split("");
a[x.lastIndexOf(y)] = z;
return a.join("");
}
replaceLast("Hello world!", "l", "x"); // Hello worxd!
It should be possible to do by first inlining the external svg images. The code below comes from replace all SVG images with inline SVG by Jess Frazelle.
$('img.svg').each(function(){
var $img = $(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
$.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = $(data).find('svg');
// Add replaced image's ID to the new SVG
if (typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if (typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http:validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
});
});
After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below
sudo mysql -u root
Then run the commands below to use the mysql database.
use mysql;
Finally, run the commands below to reset the root password.
update user set password=PASSWORD("new_password_here") where User='root';
Replace new_password _here with the new password you want to create for the root account, then press Enter.
After that, run the commands below to update the permissions and save your changes to disk.
flush privileges;
Exit (CTRL + D) and you’re done.
Next start MariaDB normally and test the new password you just created.
sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service
Logon to the database by running the commands below.
sudo mysql -u root -p
source: https://websiteforstudents.com/reset-mariadb-root-password-ubuntu-17-04-17-10/
for me the local copy was the source of the problem. this solved it
var local = context.Set<Contact>().Local.FirstOrDefault(c => c.ContactId == contact.ContactId);
if (local != null)
{
context.Entry(local).State = EntityState.Detached;
}
Since in many cases an empty map is used for null-safe design, you can utilize the nullToEmpty
utility method:
class MapUtils {
static <K,V> Map<K,V> nullToEmpty(Map<K,V> map) {
if (map != null) {
return map;
} else {
return Collections.<K,V>emptyMap(); // or guava ImmutableMap.of()
}
}
}
Similarly for sets:
class SetUtils {
static <T> Set<T> nullToEmpty(Set<T> set) {
if (set != null) {
return set;
} else {
return Collections.<T>emptySet();
}
}
}
and lists:
class ListUtils {
static <T> List<T> nullToEmpty(List<T> list) {
if (list != null) {
return list;
} else {
return Collections.<T>emptyList();
}
}
}
Use System.DateTime.DaysInMonth, from code sample:
const int July = 7;
const int Feb = 2;
// daysInJuly gets 31.
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
Although you ask about numpy
arrays, you can get the same behavior for regular Python lists by using operator.itemgetter
.
>>> from operator import itemgetter
>>> a = [0,88,26,3,48,85,65,16,97,83,91]
>>> ind_pos = [1, 5, 7]
>>> print itemgetter(*ind_pos)(a)
(88, 85, 16)
Advantages of this solution
Disadvantages - Mutation. Being internal only I don't care, maybe some others will not either.
Examples and Code
times(5, 3) // 15 (3+3+3+3+3)
times(5, (i) => Math.pow(2,i) ) // 31 (1+2+4+8+16)
times(5, '<br/>') // <br/><br/><br/><br/><br/>
times(3, (i, count) => { // name[0], name[1], name[2]
let n = 'name[' + i + ']'
if (i < count-1)
n += ', '
return n
})
function times(count, callbackOrScalar) {
let type = typeof callbackOrScalar
let sum
if (type === 'number') sum = 0
else if (type === 'string') sum = ''
for (let j = 0; j < count; j++) {
if (type === 'function') {
const callback = callbackOrScalar
const result = callback(j, count)
if (typeof result === 'number' || typeof result === 'string')
sum = sum === undefined ? result : sum + result
}
else if (type === 'number' || type === 'string') {
const scalar = callbackOrScalar
sum = sum === undefined ? scalar : sum + scalar
}
}
return sum
}
TypeScipt version
https://codepen.io/whitneyland/pen/aVjaaE?editors=0011
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
You are trying to execute an asynchronous function
in a synchronous way, which is unfortunately not possible in Javascript
.
As you guessed correctly, the roomId=results
.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.
Look at this article, it talks about .insert and not .find
, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html
Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;
SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;
my solution:
create a file card_view_border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white_background"/>
<stroke android:width="2dp"
android:color="@color/red" />
<corners android:radius="20dip"/>
</shape>
and set programmatically
cardView.setBackgroundResource(R.drawable.card_view_border);
In the meantime (since version 3.2, in the year 2013, thanks to SEC-2298) the authentication can be injected into MVC methods using the annotation @AuthenticationPrincipal:
@Controller
class Controller {
@RequestMapping("/somewhere")
public void doStuff(@AuthenticationPrincipal UserDetails myUser) {
}
}
In your unit test you can obviously call this Method directly. In integration tests using org.springframework.test.web.servlet.MockMvc
you can use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user()
to inject the user like this:
mockMvc.perform(get("/somewhere").with(user(myUserDetails)));
This will however just directly fill the SecurityContext. If you want to make sure that the user is loaded from a session in your test, you can use this:
mockMvc.perform(get("/somewhere").with(sessionUser(myUserDetails)));
/* ... */
private static RequestPostProcessor sessionUser(final UserDetails userDetails) {
return new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(final MockHttpServletRequest request) {
final SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())
);
request.getSession().setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext
);
return request;
}
};
}
private readonly UserManager<AppUser> _userManager;
public AccountsController(UserManager<AppUser> userManager)
{
_userManager = userManager;
}
[Authorize(Policy = "ApiUser")]
[HttpGet("api/accounts/GetProfile", Name = "GetProfile")]
public async Task<IActionResult> GetProfile()
{
var userId = ((ClaimsIdentity)User.Identity).FindFirst("Id").Value;
var user = await _userManager.FindByIdAsync(userId);
ProfileUpdateModel model = new ProfileUpdateModel();
model.Email = user.Email;
model.FirstName = user.FirstName;
model.LastName = user.LastName;
model.PhoneNumber = user.PhoneNumber;
return new OkObjectResult(model);
}
The best way to handle styling is by using classes with set of css properties.
example:
<Component className={this.getColor()} />
getColor() {
let class = "badge m2";
class += this.state.count===0 ? "warning" : danger;
return class;
}
Go File -> New Project.
Select Web under Visual C#.
Select ASP.NET Web Application
Click OK.
Select MVC.
Click OK.
HTTP status codes say something about the HTTP protocol. HTTP 200
means transmission is OK on the HTTP level (i.e request was technically OK and server was able to respond properly). See this wiki page for a list of all codes and their meaning.
HTTP 200 has nothing to do with success or failure of your "business code". In your example the HTTP 200
is an acceptable status to indicate that your "business code error message" was successfully transferred, provided that no technical issues prevented the business logic to run properly.
Alternatively you could let your server respond with HTTP 5xx
if technical or unrecoverable problems happened on the server. Or HTTP 4xx
if the incoming request had issues (e.g. wrong parameters, unexpected HTTP method...) Again, these all indicate technical errors, whereas HTTP 200
indicates NO technical errors, but makes no guarantee about business logic errors.
To summarize: YES it is valid to send error messages (for non-technical issues) in your http response together with HTTP status 200. Whether this applies to your case is up to you. If for instance the client is asking for a file that isn't there, that would be more like a 404
. If there is a misconfiguration on the server that might be a 500
. If client asks for a seat on a plane that is booked full, that would be 200
and your "implementation" will dictate how to recognise/handle this (e.g. JSON block with a { "booking","failed" }
)
You most likely did not create your own view engine.
The default view engine looks for the views in ~/Views/[Controller]/
and ~/Views/Shared/
.
You need to create your own view engine to make sure the views are searched in area views folder.
Take a look this post by Phil Haack.
You can try
$("your_div_id").remove();
or
$("your_div_id").html("");
You need to re-add that certificate to your machine or chose another certificate.
To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either
Once either of these is done, you should be able to build it again.
You can also use LocalDate.parse()
or LocalDateTime.parse()
on a String
without providing it with a pattern, if the String
is in ISO-8601 format.
for example,
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
System.out.println("Date: " + aLD);
String strDatewithTime = "2015-08-04T10:11:30";
LocalDateTime aLDT = LocalDateTime.parse(strDatewithTime);
System.out.println("Date with Time: " + aLDT);
Output,
Date: 2015-08-04
Date with Time: 2015-08-04T10:11:30
and use DateTimeFormatter
only if you have to deal with other date patterns.
For instance, in the following example, dd MMM uuuu represents the day of the month (two digits), three letters of the name of the month (Jan, Feb, Mar,...), and a four-digit year:
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
String anotherDate = "04 Aug 2015";
LocalDate lds = LocalDate.parse(anotherDate, dTF);
System.out.println(anotherDate + " parses to " + lds);
Output
04 Aug 2015 parses to 2015-08-04
also remember that the DateTimeFormatter
object is bidirectional; it can both parse input and format output.
String strDate = "2015-08-04";
LocalDate aLD = LocalDate.parse(strDate);
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd MMM uuuu");
System.out.println(aLD + " formats as " + dTF.format(aLD));
Output
2015-08-04 formats as 04 Aug 2015
(see complete list of Patterns for Formatting and Parsing DateFormatter)
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
p pad next pad modifier 1
' escape for text delimiter
'' single quote literal '
[ optional section start
] optional section end
# reserved for future use
{ reserved for future use
} reserved for future use
If you have downloaded the latest Version 4.3.4 then just follow these steps.
Load the mentioned js file
<script type="text/javascript" src="/ckeditor/ckeditor.js"></script> <textarea class="ckeditor" name="editor"></textarea>
Simplest Definition of Looper & Handler:
Looper is a class that turns a thread into a Pipeline Thread and Handler gives you a mechanism to push tasks into it from any other threads.
Details in general wording:
So a PipeLine Thread is a thread which can accept more tasks from other threads through a Handler.
The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because it is used to handle or accept that next task each time from any other thread and pass to Looper (Thread or PipeLine Thread).
Example:
A Looper and Handler or PipeLine Thread's very perfect example is to download more than one images or upload them to a server (Http) one by one in a single thread instead of starting a new Thread for each network call in the background.
Read more here about Looper and Handler and the definition of Pipeline Thread:
Your browser may be configured to accept only session cookies; if this is your case, any expiry time is transformed into session by your browser, you can change this setting of your browser or try another browser without such a configuration
Change the headers in .htaccess
BrowserMatch MSIE ie
Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie
Found the solution to this problem here: https://github.com/h5bp/html5-boilerplate/issues/378
Angular CLI: 8.3.1
when you have multiple module.ts
files inside a module, you need to specify for which module file you are generating component.
ng g c modulefolder/componentname --module=modulename.module
for e.g. i have shared module folder inside which i have shared.module.ts
and material.module.ts
like this
shared
> shared.module.ts
> material.module.ts
and i want to generate sidebar
component for shared.module.ts
then i will run following command
ng g c shared/sidebar --module=shared.module
if you want to export the component then run following command
ng g c shared/sidebar --module=shared.module --export
If you cannot change the class under test, then the only option I can suggest is using MS Fakes https://msdn.microsoft.com/en-us/library/hh549175.aspx. However, MS Fakes works only in a few editions of Visual Studio.
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
I built a formatting function based on stuff I stole off SO. I needed a way of "profiling" stuff in log messages, so I needed a fixed length duration message.
public static String GetElapsed(long aInitialTime, long aEndTime, boolean aIncludeMillis)
{
StringBuffer elapsed = new StringBuffer();
Map<String, Long> units = new HashMap<String, Long>();
long milliseconds = aEndTime - aInitialTime;
long seconds = milliseconds / 1000;
long minutes = milliseconds / (60 * 1000);
long hours = milliseconds / (60 * 60 * 1000);
long days = milliseconds / (24 * 60 * 60 * 1000);
units.put("milliseconds", milliseconds);
units.put("seconds", seconds);
units.put("minutes", minutes);
units.put("hours", hours);
units.put("days", days);
if (days > 0)
{
long leftoverHours = hours % 24;
units.put("hours", leftoverHours);
}
if (hours > 0)
{
long leftoeverMinutes = minutes % 60;
units.put("minutes", leftoeverMinutes);
}
if (minutes > 0)
{
long leftoverSeconds = seconds % 60;
units.put("seconds", leftoverSeconds);
}
if (seconds > 0)
{
long leftoverMilliseconds = milliseconds % 1000;
units.put("milliseconds", leftoverMilliseconds);
}
elapsed.append(PrependZeroIfNeeded(units.get("days")) + " days ")
.append(PrependZeroIfNeeded(units.get("hours")) + " hours ")
.append(PrependZeroIfNeeded(units.get("minutes")) + " minutes ")
.append(PrependZeroIfNeeded(units.get("seconds")) + " seconds ")
.append(PrependZeroIfNeeded(units.get("milliseconds")) + " ms");
return elapsed.toString();
}
private static String PrependZeroIfNeeded(long aValue)
{
return aValue < 10 ? "0" + aValue : Long.toString(aValue);
}
And a test class:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import junit.framework.TestCase;
public class TimeUtilsTest extends TestCase
{
public void testGetElapsed()
{
long start = System.currentTimeMillis();
GregorianCalendar calendar = (GregorianCalendar) Calendar.getInstance();
calendar.setTime(new Date(start));
calendar.add(Calendar.MILLISECOND, 610);
calendar.add(Calendar.SECOND, 35);
calendar.add(Calendar.MINUTE, 5);
calendar.add(Calendar.DAY_OF_YEAR, 5);
long end = calendar.getTimeInMillis();
assertEquals("05 days 00 hours 05 minutes 35 seconds 610 ms", TimeUtils.GetElapsed(start, end, true));
}
}
Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:
<html>_x000D_
<head>_x000D_
<script type="text/javascript">_x000D_
function displayFile(whatOption, whatColor) {_x000D_
var Test01 = {_x000D_
rectangle: {_x000D_
red: "RectangleRedFile",_x000D_
blue: "RectangleBlueFile"_x000D_
},_x000D_
square: {_x000D_
red: "SquareRedFile",_x000D_
blue: "SquareBlueFile"_x000D_
}_x000D_
};_x000D_
var filename = Test01[whatOption][whatColor];_x000D_
alert(filename);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
<br/>_x000D_
<p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
Use DateTime.TryParseExact()
if you want to match against a specific date format
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
else
{
Console.WriteLine("Not a date");
}
Similar Issue
I have an interface that looked roughly like:
Task DoSomething(int arg);
Symptoms
My unit test failed when my service under test awaited
the call to DoSomething
.
Fix
Unlike the accepted answer, you are unable to call .ReturnsAsync()
on your Setup()
of this method in this scenario, because the method returns the non-generic Task
, rather than Task<T>
.
However, you are still able to use .Returns(Task.FromResult(default(object)))
on the setup, allowing the test to pass.
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
Or use the sys.columns
--SQL 2005
SELECT *
FROM sys.columns
WHERE OBJECT_NAME(object_id) = 'spt_values'
-- returns 6 rows = 6 columns
--SQL 2000
SELECT *
FROM syscolumns
WHERE OBJECT_NAME(id) = 'spt_values'
-- returns 6 rows = 6 columns
SELECT *
FROM dbo.spt_values
-- 6 columns indeed
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
In the answers here, up to now, we find two ways of changing the JRE locale setting:
Programatically, using Locale.setDefault() (which, in my case, was the solution, since I didn't want to require any action of the user):
Locale.setDefault(new Locale("pt", "BR"));
Via arguments to the JVM:
java -jar anApp.jar -Duser.language=pt-BR
But, just as reference, I want to note that, on Windows, there is one more way of changing the locale used by the JRE, as documented here: changing the system-wide language.
Note: You must be logged in with an account that has Administrative Privileges.
Click Start > Control Panel.
Windows 7 and Vista: Click Clock, Language and Region > Region and Language.
Windows XP: Double click the Regional and Language Options icon.
The Regional and Language Options dialog box appears.
Windows 7: Click the Administrative tab.
Windows XP and Vista: Click the Advanced tab.
(If there is no Advanced tab, then you are not logged in with administrative privileges.)
Under the Language for non-Unicode programs section, select the desired language from the drop down menu.
Click OK.
The system displays a dialog box asking whether to use existing files or to install from the operating system CD. Ensure that you have the CD ready.
Follow the guided instructions to install the files.
Restart the computer after the installation is complete.
Certainly on Linux the JRE also uses the system settings to determine which locale to use, but the instructions to set the system-wide language change from distro to distro.
Try this code :
import numpy as np
a1 = np.array([])
n = int(input(""))
for i in range(0,n):
a = int(input(""))
a1 = np.append(a, a1)
a = 0
print(a1)
Also you can use array instead of "a"
For a given iterable, more_itertools.locate
yields positions of items that satisfy a predicate.
import more_itertools as mit
iterable = [
{"id": "1234", "name": "Jason"},
{"id": "2345", "name": "Tom"},
{"id": "3456", "name": "Art"}
]
list(mit.locate(iterable, pred=lambda d: d["name"] == "Tom"))
# [1]
more_itertools
is a third-party library that implements itertools recipes among other useful tools.
You can use Environment Replacement in your Dockerfile
as follows:
ENV PATH="/opt/gtk/bin:${PATH}"
You can use the following command. The SET
will set the input from the user console to the variable comment and then you can use that variable using %comment%
SET /P comment=Comment:
echo %comment%
pause
I think it is going to be possible soon in AMD FirePro GPU's, see press release here but support is coming 2016 Q1 for the developing tools:
An early access program for the "Boltzmann Initiative" tools is planned for Q1 2016.
su -sm ./*
You can see every file and folder size (-sm=Mb ; -sk=Kb) in the current directory like a list. This way runs in all Unix/Linux environment.
You can do do it. The input type submit should be inside of a form. Then all you have to do is write the link you want to redirect to inside the action attribute that is inside the form tag.
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
Late GraveDig ... Just constrain your byte array to the file size.
FileInputStream fis = new FileInputStream( file );
byte[] byteArray= new byte[(int) file.length()];
I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.
Here are a few links that might help:
Disable back button in android
MyActivity.java =>
@Override
public void onBackPressed() {
return;
}
How can I disable 'go back' to some activity?
AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>
Use the PS command in a little different way to ignore child process as well:
ps -eaf | grep -v grep | grep $PROCESS | grep -v $$
I was just going through this myself. I had ensured that my MSSQLSERVER login user had full access
but it was still causing issues. It only worked once I moved the destination to the root of C. More importantly out of a user folder (even though I had a share with full permissions - even tried "Everyone" as a test).
I don't know if i consider my issue "fixed", however it is "working".
Just a FYI for any other users that come across this thread.
jQuery("#input").live('change', function() {
// since we check more than once against the value, place it in a var.
var inputvalue = $("#input").attr("value");
// if it's value **IS NOT** ""
if(inputvalue !== "") {
jQuery(this).css('outline', 'solid 1px red');
}
// else if it's value **IS** ""
else if(inputvalue === "") {
alert('empty');
}
});
As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:
On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):
$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start
Two things are happening here.
Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.
What you want to do is the following:
<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
<div class="row">
<div class="col-md-4 myClassName"> <!-- myClassName is defined in my CSS as you defined your container -->
<img src="#.jpg" height="200px" width="300px">
</div>
</div>
</div>
Here you can find more info on the Bootstrap grid system.
That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
max-width: 900px;
overflow:hidden;
min-height:0px !important;
}
But I have always found that the "!important" clause just makes for messy CSS.
I couldn't figure out how to do this in pure MS LINQ, so I wrote my own extension method to do it:
public static bool In<T>(this T objToCheck, params T[] values)
{
if (values == null || values.Length == 0)
{
return false; //early out
}
else
{
foreach (T t in values)
{
if (t.Equals(objToCheck))
return true; //RETURN found!
}
return false; //nothing found
}
}
If you're running with 64-bit references:
sizeof(string) =
8 + // object header used by the VM
8 + // 64-bit reference to char array (value)
8 + string.length() * 2 + // character array itself (object header + 16-bit chars)
4 + // offset integer
4 + // count integer
4 + // cached hash code
In other words:
sizeof(string) = 36 + string.length() * 2
On a 32-bit VM or a 64-bit VM with compressed OOPs (-XX:+UseCompressedOops), the references are 4 bytes. So the total would be:
sizeof(string) = 32 + string.length() * 2
This does not take into account the references to the string object.
Try redirecting the output like this:
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1
You can set this value in a layout xml file using android:divider="#FF0000"
. If you are changing the colour/drawable, you have to set/reset the height of the divider too.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="@+id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="#FFCC00"
android:dividerHeight="4px"/>
</LinearLayout>
To put it simply, if in linear regression model more test cases arrive which are far away from the threshold(say =0.5)for a prediction of y=1 and y=0. Then in that case the hypothesis will change and become worse.Therefore linear regression model is not used for classification problem.
Another Problem is that if the classification is y=0 and y=1, h(x) can be > 1 or < 0.So we use Logistic regression were 0<=h(x)<=1.
Demo here
Try this one
$('html').on('click', 'a.Link', function(event){
event.preventDefault();
});
There is a command available for this on the SQLite command line:
.tables ?PATTERN? List names of tables matching a LIKE pattern
Which converts to the following SQL:
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1
It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None
differently from is None
.
In particular the output of a == None
does not even have to be boolean !! - a frequent cause of bugs.
For a specific example take a numpy array where the ==
comparison is implemented elementwise:
import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False
Update
As of 2019 this can be easily achieved using ProgressIndicator
, in Material Components library, used with the Widget.MaterialComponents.ProgressIndicator.Circular.Indeterminate
style.
For more details please check Gabriele Mariotti's answer below.
Old implementation
Here is an awesome implementation of the material design circular intermediate progress bar https://gist.github.com/castorflex/4e46a9dc2c3a4245a28e. The implementation only lacks the ability add various colors like in inbox by android app but this does a pretty great job.
The easiest way to do is so...
You set the name and value.
<input type="checkbox" name="selectedProducts" value="@item.ProductId" />@item.Name
Then on submitting grab the values of checkboxes and save in an int array. then the appropriate LinQ Function. That's it..
[HttpPost]
public ActionResult Checkbox(int[] selectedObjects)
{
var selected = from x in selectedObjects
from y in db
where y.ObjectId == x
select y;
return View(selected);
}
Using the Node.contains DOM API, you can check for the presence of any element in the page (currently in the DOM) quite easily:
document.body.contains(YOUR_ELEMENT_HERE);
CROSS-BROWSER NOTE: the document
object in Internet Explorer does not have a contains()
method - to ensure cross-browser compatibility, use document.body.contains()
instead.
This is for windows environment:
I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword
I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.
function myfunction() {_x000D_
var first = document.getElementById("textbox1").value;_x000D_
var second = document.getElementById("textbox2").value;_x000D_
var answer = parseFloat(first) + parseFloat(second);_x000D_
_x000D_
var textbox3 = document.getElementById('textbox3');_x000D_
textbox3.value = answer;_x000D_
}
_x000D_
<input type="text" name="textbox1" id="textbox1" /> + <input type="text" name="textbox2" id="textbox2" />_x000D_
<input type="submit" name="button" id="button1" onclick="myfunction()" value="=" />_x000D_
<br/> Your answer is:--_x000D_
<input type="text" name="textbox3" id="textbox3" readonly="true" />
_x000D_
I had the same problem (I'm running cygwin)
Starting a shell through cygwin.bat didn't help, but starting a shell through MingWShell did. Not quite sure why, but I think it had something to do with the extra layer that cygwin puts between the executing script and the underlying filesystem.
I was running pip install from within a virtual env's cygwin to install django sentry..
Try it:
if (Objects.equals(gender, "Male")) {
salutation ="Mr.";
} else if (Objects.equals(gender, "Female")) {
salutation ="Ms.";
}
A simple example that will clear both during executing script or inside script while calling a function.
#!/bin/bash
echo "parameterized function example"
function print_param_value(){
value1="${1}" # $1 represent first argument
value2="${2}" # $2 represent second argument
echo "param 1 is ${value1}" # As string
echo "param 2 is ${value2}"
sum=$(($value1+$value2)) # Process them as number
echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" # Space-separated value
# You can also pass parameters during executing the script
print_param_value "$1" "$2" # Parameter $1 and $2 during execution
# Suppose our script name is "param_example".
# Call it like this:
#
# ./param_example 5 5
#
# Now the parameters will be $1=5 and $2=5
As mentioned I think your return string data is very long. so the JSON format has been corrupted.
There's other way for this problem. You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
If you run the mount command with no command-line arguments, which displays the file systems mounted on your system, you’ll notice a line that looks something like this: none on /dev/pts type devpts (rw,gid=5,mode=620) This indicates that a special type of file system, devpts , is mounted at /dev/pts .This file system, which isn’t associated with any hardware device, is a “magic” file system that is created by the Linux kernel. It’s similar to the /proc file system
Like the /dev directory, /dev/pts contains entries corresponding to devices. But unlike /dev , which is an ordinary directory, /dev/pts is a special directory that is cre- ated dynamically by the Linux kernel.The contents of the directory vary with time and reflect the state of the running system. The entries in /dev/pts correspond to pseudo-terminals (or pseudo-TTYs, or PTYs).
Linux creates a PTY for every new terminal window you open and displays a corre- sponding entry in /dev/pts .The PTY device acts like a terminal device—it accepts input from the keyboard and displays text output from the programs that run in it. PTYs are numbered, and the PTY number is the name of the corresponding entry in /dev/pts .
For example, if the new terminal window’s PTY number is 7, invoke this command from another window: % echo ‘I am a virtual di ’ > /dev/pts/7 The output appears in the new terminal window.
You should now use the .on()
function to bind events.
You need to remove the brackets
ALTER TABLE Countries
ADD
HasPhotoInReadyStorage bit,
HasPhotoInWorkStorage bit,
HasPhotoInMaterialStorage bit,
HasText bit;
In fact, you need to use CSS.
document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");
It works on FireFox, Chrome and IE.
This is my simple barebone implementation:
let obj = {
"1": 5,
"2": 7,
"3": 0,
"4": 0,
"5": 0,
"6": 0,
"7": 0,
"8": 0,
"9": 0,
"10": 0,
"11": 0,
"12": 0
};
const objectToArray = obj => {
let sol = [];
for (key in obj) {
sol.push([key, obj[key]]);
}
return sol;
};
objectToArray(obj)
Visual Studio 2010 SP1 and 2012 added support for IIS Express eliminating the need to edit angle brackets.
I believe this solution is superior to the vikomall's options.
The UI-based solution above uses site-specific location elements in IIS Express's applicationHost.config leaving the app untouched.
More information here: http://msdn.microsoft.com/en-us/magazine/hh288080.aspx
I think that better way now is:
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
No! There is no 64-bit version of Visual Studio.
How to know it is not 64-bit: Once you download Visual Studio and click the install button, you will see that the initialization folder it selects automatically is C:\Program Files (x86)\Microsoft Visual Studio 14.0
As per my understanding, all 64-bit programs/applications goes to C:\Program Files and all 32-bit applications goes to C:\Program Files (x86) from Windows 7 onwards.
Found this simple work around which appears to prevent double click to zoom:
// Convert touchend events to click events to work around an IOS 10 feature which prevents
// developers from using disabling double click touch zoom (which we don't want).
document.addEventListener('touchend', function (event) {
event.preventDefault();
$(event.target).trigger('click');
}, false);
First
<table border="1">
<tr>
<td style='border:none;'>one</td>
<td style='border:none;'>two</td>
</tr>
<tr>
<td style='border:none;'>one</td>
<td style='border:none;'>two</td>
</tr>
</table>
Second example
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td style='border-left:none;border-top:none'>one</td>
<td style='border:none;'>two</td>
</tr>
<tr>
<td style='border-left:none;border-bottom:none;border-top:none'>one</td>
<td style='border:none;'>two</td>
</tr>
</table>
The choice of when to use a surrogate primary key as opposed to a natural key is tricky. Answers such as, always or never, are rarely useful. I find that it depends on the situation.
As an example, I have the following tables:
CREATE TABLE toll_booths (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
...
UNIQUE(name)
)
CREATE TABLE cars (
vin VARCHAR(17) NOT NULL PRIMARY KEY,
license_plate VARCHAR(10) NOT NULL,
...
UNIQUE(license_plate)
)
CREATE TABLE drive_through (
id INTEGER NOT NULL PRIMARY KEY,
toll_booth_id INTEGER NOT NULL REFERENCES toll_booths(id),
vin VARCHAR(17) NOT NULL REFERENCES cars(vin),
at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
amount NUMERIC(10,4) NOT NULL,
...
UNIQUE(toll_booth_id, vin)
)
We have two entity tables (toll_booths
and cars
) and a transaction table (drive_through
). The toll_booth
table uses a surrogate key because it has no natural attribute that is not guaranteed to change (the name can easily be changed). The cars
table uses a natural primary key because it has a non-changing unique identifier (vin
). The drive_through
transaction table uses a surrogate key for easy identification, but also has a unique constraint on the attributes that are guaranteed to be unique at the time the record is inserted.
http://database-programmer.blogspot.com has some great articles on this particular subject.
I took the answer posted by Osiloke (Which was the easiest and most complete imho) and I added a change event listener. Works great! Thanks Osiloke. See below if you are interested:
HTML:
<div file-button>
<button class='btn btn-success btn-large'>Select your awesome file</button>
</div>
Directive:
app.directive('fileButton', function() {
return {
link: function(scope, element, attributes) {
var el = angular.element(element)
var button = el.children()[0]
el.css({
position: 'relative',
overflow: 'hidden',
width: button.offsetWidth,
height: button.offsetHeight
})
var fileInput = angular.element('<input id='+scope.file_button_id+' type="file" multiple />')
fileInput.css({
position: 'absolute',
top: 0,
left: 0,
'z-index': '2',
width: '100%',
height: '100%',
opacity: '0',
cursor: 'pointer'
})
el.append(fileInput)
document.getElementById(scope.file_button_id).addEventListener('change', scope.file_button_open, false);
}
}
});
Controller:
$scope.file_button_id = "wo_files";
$scope.file_button_open = function()
{
alert("Files are ready!");
}
This post is a bit old so could be there was a bug andit was fixed, but I just did this:
git --work-tree=/X/Y --git-dir=/X/Y/.git pull origin branch
And it worked. Took me a minute to figure out that it wanted the dotfile and the parent directory (in a standard setup those are always parent/child but not in ALL setups, so they need to be specified explicitly.
you should return Scaffold widget and add your widget inside Scaffold
suck as this code :
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(child: new Text("Hello, World!"));
);
}
}
This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this
automatically gets set to the global scope. This can be confusing because you expect this
to have the same value as in the outer function.
var car = {};
car.starter = {};
car.start = function(){
var that = this;
// you can access car.starter inside this method with 'this'
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to the global scope
// 'this.starter' is undefined, so we use 'that' instead.
that.starter.active = true;
// you could also use car.starter, but using 'that' gives
// us more consistency and flexibility
};
activateStarter();
};
This is specifically a problem when you create a function as a method of an object (like car.start
in the example) then create a function inside that method (like activateStarter
). In the top level method this
points to the object it is a method of (in this case, car
) but in the inner function this
now points to the global scope. This is a pain.
Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that
is used. It's an easily recognizable convention for overcoming a shortcoming in the language.
Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.
Here is the simplest solution that worked for me.
The ActionBarDrawerToggle
has two types constructors. One of them take toolbar as a parameter. Use that (second one below) to get the animated hamburger.
ActionBarDrawerToggle(this, mDrawerLayout, R.string.content_desc_drawer_open,
R.string.content_desc_drawer_close);
ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.content_desc_drawer_open,
R.string.content_desc_drawer_close);` //use this constructor
While reading this thread, I often get the impression that people are using "UTF-8" as a synonym to "Unicode". Please make a distinction between Unicode's "Code-Points" which are an enlarged relative of the ASCII code and Unicode's various "encodings". And there are a few of them, of which UTF-8, UTF-16 and UTF-32 are the current ones and a few more are obsolete.
Please, UTF-8 (as well as all other encodings) exists and have meaning in input or in output only. Internally, since Perl 5.8.1, all strings are kept as Unicode "Code-points". True, you have to enable some features as admiringly covered previously.
There are three ways to enlarge the max_allowed_packet of mysql server:
max_allowed_packet=64M
in file /etc/mysql/my.cnf
on the mysql server machine and restart the serverset global max_allowed_packet=67108864;
connection.execute('set max_allowed_packet=67108864')
I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:
import java.util.*;
public class Customer {
private String name;
private String email;
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return name + " | " + email;
}
public static String toString(Collection<Customer> customers) {
String s = "";
for(Customer customer : customers) {
s += customer + "\n";
}
return s;
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Customer> customers = new ArrayList<>();
customers.add(new Customer("Bert", "[email protected]"));
customers.add(new Customer("Ernie", "[email protected]"));
System.out.println("customers before email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
customers.get(1).setEmail("[email protected]");
System.out.println("customers after email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
}
}
to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
change the version of spring boot parent
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :
</body>
<script>require('../script/viewLog.js')</script>
after :
<script>require('../script/viewLog.js')</script>
</body>
If you have both date and time information in the numeric value, then use as.POSIXct
. Data.table package IDateTime format is such a case. If you use fwrite
to save a file, the package automatically converts date-times to idatetime format which is unix time. To convert back to normal format following can be done.
Example: Let's say you have a unix time stamp with date and time info: 1442866615
> as.POSIXct(1442866615,origin="1970-01-01")
[1] "2015-09-21 16:16:54 EDT"
This works too and also demonstrates how to change the legend title:
ggplot(df, aes(x, y, colour=g)) +
geom_line(stat="identity") +
theme(legend.position="bottom") +
scale_color_discrete(name="")
WSDL (Web Services Description Language) describes your service and its operations - what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?
It's a description of the behavior of the service - it's functionality.
XSD (Xml Schema Definition) describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern) and so forth.
It's a description of datatypes and thus static properties of the service - it's about data.
You can use the below code to center pagination
.pagination-centered {_x000D_
text-align: center;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="pagination-centered">_x000D_
<ul class="pagination">_x000D_
<li class="active"><a href="#">1</a></li>_x000D_
<li><a href="#">2</a></li>_x000D_
<li><a href="#">3</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
My answer will differ on the exact question. If I want to access a certain element specifically, then will I use document.getElementById(). An example is computing the full name of a person, because it is building on multiple fields, but it is a repeatable formula.
If I want to access the element as part of a functional structure (a form), then will I use:
var frm = document.getElementById('frm_name');
for(var i = 0; i < frm.elements.length;i++){
..frm.elements[i]..
This is how it also works from the perspective of the business. Changes within the loop go along with functional changes in the application and are therefor meaningful. I apply it mostly for user friendly validation and preventing network calls for checking wrong data. I repeat the validation server side (and add there some more to it), but if I can help the user client side, then is that beneficial to all.
For aggregation of data (like building a pie chart based on data in the form) I use configuration documents and custom made Javascript objects. Then is the exact meaning of the field important in relation to its context and do I use document.getElementById().
I like to do it as an extension to Context so you can call it anywhere
fun Context.showKeyboard(editText: EditText) {
val inputMethodManager: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInputFromWindow(
editText.applicationWindowToken,
InputMethodManager.SHOW_IMPLICIT, 0
)
editText.requestFocus()
editText.setSelection(editText.text.length)
}
fun Context.hideKeyboard(editText: EditText) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
}
Convert the Special characters to apostrophe,
Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)
Below code it to remove extra ''' apostrophe
Data <- gsub("''","" , Data ,ignore.case = TRUE)
Use gsub(..)
function for replacing the special character with apostrophe
Here's a great discussion on GitHub which helped me a lot. Clearing the Cache of your React Native Project by Jarret Moses
There are solutions for 4 different instances.
RN <0.50 -
watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache
RN >=0.50 -
watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules/ && npm cache clean && npm install && npm start -- --reset-cache
watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache
del %appdata%\Temp\react-native-* & cd android & gradlew clean & cd .. & del node_modules/ & npm cache clean --force & npm install & npm start -- --reset-cache
The solution is similar to Vikram Biwal's Answer.
And there is a discussion below in the given link, so even if the above 4 cases don't work for you, you can scroll through and find a possible solution.
You can use either $().jquery;
or $.fn.jquery
which will return a string containing the version number, e.g. 1.6.2
.
I suspect the condition you are looking for is DUP_VAL_ON_INDEX
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
Bash job control involves multiple processes, not multiple threads.
You can execute a command in background with the &
suffix.
You can wait for completion of a background command with the wait
command.
You can execute multiple commands in parallel by separating them with |
. This provides also a synchronization mechanism, since stdout of a command at left of |
is connected to stdin of command at right.
I've tried with
let UUID = UIDevice.currentDevice().identifierForVendor?.UUIDString
instead
let UUID = NSUUID().UUIDString
and it works.
A simple command, git checkout remote_branch_name
will help you to create a local branch that has all the changes in the remote branch.
first install the library
pip install flask_sqlalchemy
after that
from flask_sqlalchemy import SQLAlchemy
put this in app.py file to get the access of database through SQLAlchemy
The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:
file sum___19.0, per Iteration___19.0 raf sum___16.0, per Iteration___16.0 channel sum__273.0, per Iteration__273.0
For 100 runs and 10000 iterations I get:
file sum__1767629.0, per Iteration__1.7676290000000001 raf sum___881284.0, per Iteration__0.8812840000000001 channel sum___414286.0, per Iteration__0.414286
I did run the following modified code giving as an argument the name of a 100MB file.
import java.io.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
public class FileSizeBench {
private static File file;
private static FileChannel channel;
private static RandomAccessFile raf;
public static void main(String[] args) throws Exception {
int runs = 1;
int iterations = 1;
file = new File(args[0]);
channel = new FileInputStream(args[0]).getChannel();
raf = new RandomAccessFile(args[0], "r");
HashMap<String, Double> times = new HashMap<String, Double>();
times.put("file", 0.0);
times.put("channel", 0.0);
times.put("raf", 0.0);
long start;
for (int i = 0; i < runs; ++i) {
long l = file.length();
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != file.length()) throw new Exception();
times.put("file", times.get("file") + System.nanoTime() - start);
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != channel.size()) throw new Exception();
times.put("channel", times.get("channel") + System.nanoTime() - start);
start = System.nanoTime();
for (int j = 0; j < iterations; ++j)
if (l != raf.length()) throw new Exception();
times.put("raf", times.get("raf") + System.nanoTime() - start);
}
for (Map.Entry<String, Double> entry : times.entrySet()) {
System.out.println(
entry.getKey() + " sum: " + 1e-3 * entry.getValue() +
", per Iteration: " + (1e-3 * entry.getValue() / runs / iterations));
}
}
}
The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.
See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.
But I still don't know why they wrote the spec so that the order matters.
The postscript()
device allows creation of EPS, but only if you change some of the default values. Read ?postscript
for the details.
Here is an example:
postscript("foo.eps", horizontal = FALSE, onefile = FALSE, paper = "special")
plot(1:10)
dev.off()
I needed the best x results of points per team.
Ranking does not solves this problem when there are results with equal points.
So I need a recordnumber
I made a VBA function in Access to create a recordnumber
that resets on ID change.
You have to query this query with where recordnumber <= x
to get the points per team.
NB Access changes the record-number
That is not what I thought that would happen.
Solved this by using a temporary table and saving the recordnumbers
and keys or an extra field in the table.
SELECT ID, Points, RecordNumberOffId([ID}) AS Recordnumber
FROM Team ORDER BY ID ASC, Points DESC;
It uses 3 module level variables to remember between calls
Dim PreviousID As Long
Dim PreviousRecordNumber As Long
Dim TimeLastID As Date
Public Function RecordNumberOffID(ID As Long) As Long
'ID is sortgroup identity
'Reset if last call longer dan nn seconds in the past
If Time() - TimeLastID > 0.0003 Then '0,000277778 = 1 second
PreviousID = 0
PreviousRecordNumber = 0
End If
If ID <> PreviousID Then
PreviousRecordNumber = 0
PreviousID = ID
End If
PreviousRecordNumber = PreviousRecordNumber + 1
RecordNumberOffID = PreviousRecordNumber
TimeLastID = Time()
End Function
My solution without JavaScript/images. Only CSS used. It works in all browsers.
HTML:
<a class="add_to_cart" href="https://www.redracingparts.com" title="Add to Cart!">
buy now<br />free shipping<br />no further costs
</a>
CSS:
.add_to_cart:hover {
background-color:#FF9933;
text-decoration:none;
color:#FFFFFF;
}
.add_to_cart {
cursor:pointer;
background-color:#EC5500;
display:block;
text-align:center;
margin-top:8px;
width:90px;
height:31px;
border-radius:5px;
border-width:1px;
border-style:solid;
border-color:#E70000;
}
There is an example on https://www.redracingparts.com/english/motorbikesmotorcycles/stackoverflow/examples/div/clickable.php
You can try the following:
theAnchorText = "I'm home";
OR
theAnchorText = 'I\'m home';
Another option:
=MID(A1,2,LEN(A1)-2)
Or this (for fun):
=RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)
I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.
See AES in ASP.NET with VB.NET for more information about encryption in .NET.
I want to leave this here because I struggled with this when compiling for Android in Windows with the Android SDK.
CMake distinguishes between TARGET and HOST platform.
My TARGET was Android so the variables like CMAKE_SYSTEM_NAME had the value "Android" and the variable WIN32 from the other answer here was not defined. But I wanted to know if my HOST system was Windows because I needed to do a few things differently when compiling on either Windows or Linux or IOs. To do that I used CMAKE_HOST_SYSTEM_NAME which I found is barely known or mentioned anywhere because for most people TARGEt and HOST are the same or they don't care.
Hope this helps someone somewhere...
At a guess, AppEngine is using a 64-bit implementation of Python (-5768830964305142685 won't fit in 32 bits) and your implementation of Python is 32 bits. You can't rely on object hashes being meaningfully comparable between different implementations.
Here all of the above outputs are giving a 10 digit number, but along with that the input field is accepting characters also, which is not the full solution. In order to set the 10 digit numbers only, we can use an input tag along with that type as number, and in that we can remove the up-down array by writing some small code in css which is shown below along with the input tag.
<input name="phone" maxlength="10" pattern="[1-9]{1}[0-9]{9}" class="form-control" id="mobile" placeholder="Enter your phone Number" type="number">
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin: 0;
}
There is an "onunload" parameter for the body tag you can call javascript functions from there. If it returns false it prevents navigating away.
This will do it:
#signin input {
background-color:#FFF;
min-height:200px;
}
Another possible solution specially if you want batch delete
deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3]))
session.execute(deleted_objects)
session.commit()
I'd just like to add a general note of caution.
If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are saving the date/time information for later reference or are computing date/times, beware!
Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.
1. There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.
2. If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.
3. Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.
A concrete example of overhead is the difference between a "local" procedure call and a "remote" procedure call.
For example, with classic RPC (and many other remote frameworks, like EJB), a function or method call looks the same to a coder whether its a local, in memory call, or a distributed, network call.
For example:
service.function(param1, param2);
Is that a normal method, or a remote method? From what you see here you can't tell.
But you can imagine that the difference in execution times between the two calls are dramatic.
So, while the core implementation will "cost the same", the "overhead" involved is quite different.
The following works:
@NonCPS
def printParams() {
env.getEnvironment().each { name, value -> println "Name: $name -> Value $value" }
}
printParams()
Note that it will most probably fail on first execution and require you approve various groovy methods to run in jenkins sandbox. This is done in "manage jenkins/in-process script approval"
The list I got included:
I do some quick tests and have the following findings:
1) if using SynchronousQueue:
After the threads reach the maximum size, any new work will be rejected with the exception like below.
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
2) if using LinkedBlockingQueue:
The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.
I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )
PostgreSQL also supports full POSIX regular expressions:
select * from table where value ~* 'foo|bar|baz';
The ~*
is for a case insensitive match, ~
is case sensitive.
Another option is to use ANY:
select * from table where value like any (array['%foo%', '%bar%', '%baz%']);
select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);
You can use ANY with any operator that yields a boolean. I suspect that the regex options would be quicker but ANY is a useful tool to have in your toolbox.
Here's something I was working on.
class Tree:
def __init__(self, value, *children):
'''Singly linked tree, children do not know who their parent is.
'''
self.value = value
self.children = tuple(children)
@property
def arguments(self):
return (self.value,) + self.children
def __eq__(self, tree):
return self.arguments == tree.arguments
def __repr__(self):
argumentStr = ', '.join(map(repr, self.arguments))
return '%s(%s)' % (self.__class__.__name__, argumentStr)
Use as such (numbers used as example values):
t = Tree(1, Tree(2, Tree(4)), Tree(3, Tree(5)))
Your method signature is:
- (void) myTest:(NSString *)
withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).
If you call the function in this manner:
[self performSelector:@selector(myTest:) withObject:myString];
It will work.
But, as the other posters have suggested, you may want to rename the method:
- (void)myTestWithAString:(NSString*)aString;
And call:
[self performSelector:@selector(myTestWithAString:) withObject:myString];
Go with STL. There's no performance penalty. The algorithms are very efficient and they do a good job of handling the kinds of details that most of us would not think about.
I don't use named parameters for all queries. For example it is unusual to use named parameters in JpaRepository.
To workaround I use JPQL CONCAT function (this code emulate start with):
@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
private static final String QUERY = "select b from Branch b"
+ " left join b.filial f"
+ " where f.id = ?1 and b.id like CONCAT(?2, '%')";
@Query(QUERY)
List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}
I found this technique in excellent docs: http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html
The way I've learned to implement this in a compact and readable manner for 1-D arrays, so far:
h = np.array([1,2,3,4,5])
v1 = np.vstack(h)
v2 = np.c_[h]
h1 = np.hstack(v1)
h2 = np.r_[v2[:,0]]
numpy.r_ and numpy.c_ translate slice objects to concatenation along the first and second axis, respectively. Therefore the slicing v2[:,0] in transposing back the vertical array v2 into the horizontal array h2
numpy.vstack is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.
The quick answer: switch off AutoSize.
The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.
Basically what you need to do in OnPaint is:
You will also need to set the ResizeRedraw style flag in the constructor.
One thing I don't see in examples is that when you cast BehaviorSubject to Observable via asObservable, it inherits behaviour of returning last value on subscription.
It's the tricky bit, as often libraries will expose fields as observable (i.e. params in ActivatedRoute in Angular2), but may use Subject or BehaviorSubject behind the scenes. What they use would affect behaviour of subscribing.
See here http://jsbin.com/ziquxapubo/edit?html,js,console
let A = new Rx.Subject();
let B = new Rx.BehaviorSubject(0);
A.next(1);
B.next(1);
A.asObservable().subscribe(n => console.log('A', n));
B.asObservable().subscribe(n => console.log('B', n));
A.next(2);
B.next(2);
I had the same issue! I was unable to change/set the ID attribute of elements. It worked in all other browsers but not IE. It probably isn't relevant to your problem but here is what I ended up doing:
Background
I was building an MVC site with jquery tabs. I wanted to create tabs dynamically and do an AJAX postback to the server saving the tab in the database. I wanted to use a unique identifier, in the form of an int, for the tabs so I wouldn't get in to trouble if a user created two tabs with the same name. I then used the unique ID to identify the tabs like:
<ul>
<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove List</span></li>
<ul>
When I then implemented the remove functions on the tabs the callback uses the index, witch is 0 based. Then I had no way to sending back the unique ID to the server to trash the DB entry. The callback for the tabremove event gives the jquery event and ui parameters. With one line of code I could get the ID of the span:
var dbIndex = event.currentTarget.id;
The problem was that the span tag didn't have any ID. So in the create callback I tried to set the ID buy extracting the ID from the a href like this:
ui.tab.parentNode.id = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);
That worked fine in FireFox but not in IE. So I tried a few other:
//ui.tab.parentNode.setAttribute('id', ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6));
//$(ui.tab.parentNode).attr({'id':ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6)});
//ui.tab.parentNode.id.value = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);
None of them worked! So after a few hours of test and Googeling I gave up and draw the conclusion that IE cant set the ID attribute of an element dynamically.
As I sad this is probably not relevant to your issue but I thought I would share.
Solution
And for all of you who found this by Googleing on the tabs issue I had here is what I ended up doing in the tabsremove callback to solve the issue:
var dbIndex = event.currentTarget.offsetParent.childNodes[0].href.substring(event.currentTarget.offsetParent.childNodes[0].href.indexOf('#list-') + 6);
Probably not the sexiest solution but hey it solved the issue. If anyone have any input please share...
The .net library System.Data.SQLite also provides for encryption.
I got the same Exception: Java gateway process exited before sending the driver its port number
in Cloudera VM when trying to start IPython with CSV support with a syntax error:
PYSPARK_DRIVER_PYTHON=ipython pyspark --packages com.databricks:spark-csv_2.10.1.4.0
will throw the error, while:
PYSPARK_DRIVER_PYTHON=ipython pyspark --packages com.databricks:spark-csv_2.10:1.4.0
will not.
The difference is in that last colon in the last (working) example, seperating the Scala version number from the package version number.
Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).
SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).
SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.
Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.
require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"
A project can be referenced by multiple solutions.
Put your library or core code into one project, then reference that project in both solutions.
datetime.datetime.now
is not timezone aware.
Django comes with a helper for this, which requires pytz
from django.utils import timezone
now = timezone.now()
You should be able to compare now
to challenge.datetime_start
Based on the excellent answer of @Federico A. Ramponi.
Just imagine you have this hierarchy:
public interface IAnimal
{
void DoSound();
}
public class Dog : IAnimal
{
public void DoSound()
{
Console.WriteLine("Woof");
}
}
public class Cat : IAnimal
{
public void DoSound(IOperation o)
{
Console.WriteLine("Meaw");
}
}
What happen if you need to add a "Walk" method here? That will be painful to the whole design.
At the same time, adding the "Walk" method generate new questions. What about "Eat" or "Sleep"? Must we really add a new method to the Animal hierarchy for every new action or operation that we want to add? That's ugly and most important, we will never be able to close the Animal interface. So, with the visitor pattern, we can add new method to the hierarchy without modifying the hierarchy!
So, just check and run this C# example:
using System;
using System.Collections.Generic;
namespace VisitorPattern
{
class Program
{
static void Main(string[] args)
{
var animals = new List<IAnimal>
{
new Cat(), new Cat(), new Dog(), new Cat(),
new Dog(), new Dog(), new Cat(), new Dog()
};
foreach (var animal in animals)
{
animal.DoOperation(new Walk());
animal.DoOperation(new Sound());
}
Console.ReadLine();
}
}
public interface IOperation
{
void PerformOperation(Dog dog);
void PerformOperation(Cat cat);
}
public class Walk : IOperation
{
public void PerformOperation(Dog dog)
{
Console.WriteLine("Dog walking");
}
public void PerformOperation(Cat cat)
{
Console.WriteLine("Cat Walking");
}
}
public class Sound : IOperation
{
public void PerformOperation(Dog dog)
{
Console.WriteLine("Woof");
}
public void PerformOperation(Cat cat)
{
Console.WriteLine("Meaw");
}
}
public interface IAnimal
{
void DoOperation(IOperation o);
}
public class Dog : IAnimal
{
public void DoOperation(IOperation o)
{
o.PerformOperation(this);
}
}
public class Cat : IAnimal
{
public void DoOperation(IOperation o)
{
o.PerformOperation(this);
}
}
}
To forget directory recursively add /*/*
to the path:
git update-index --assume-unchanged wordpress/wp-content/uploads/*/*
Using git rm --cached
is not good for collaboration. More details here: How to stop tracking and ignore changes to a file in Git?
I hope the below example will provide more clarity.
package main
type EmployeeManager struct{
category string
city string
calculateSalary func() int64
}
func NewEmployeeManager() (*EmployeeManager,error){
return &EmployeeManager{
category : "MANAGEMENT",
city : "NY",
calculateSalary: func() int64 {
var calculatedSalary int64
// some formula
return calculatedSalary
},
},nil
}
func (self *EmployeeManager) emWithSalaryCalculation(){
self.calculateSalary = func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}
}
func updateEmployeeInfo(em EmployeeManager){
// Some code
}
func processEmployee(){
updateEmployeeInfo(struct {
category string
city string
calculateSalary func() int64
}{category: "", city: "", calculateSalary: func() int64 {
var calculatedSalary int64
// some new formula
return calculatedSalary
}})
}
Add an annotation to the method using the keyword Obsolete
. Message argument is optional but a good idea to communicate why the item is now obsolete and/or what to use instead.
Example:
[System.Obsolete("use myMethodB instead")]
void myMethodA()
not need to run queries to sidable FKs on sql. If you have a FK from table A to B, you should:
You can also tell the destination not to check constraints
Wikipedia points out that the syntax of an IPv6 address includes colons and has a short form preventing fixed-length parsing, and therefore you have to delimit the address portion with []. This completely avoids the odd parsing errors.
(Taken from an edit Peter Wone made to the original question.)
a="abc"
b="def"
# Equality Comparison
if [ "$a" == "$b" ]; then
echo "Strings match"
else
echo "Strings don't match"
fi
# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
echo "$b is lexicographically smaller than $a"
else
echo "Strings are equal"
fi
Notes:
if
and [
and ]
are important>
and <
are redirection operators so escape it with \>
and \<
respectively for strings.There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.
Not sure why Matthew's solution didn't work for me (could be that I'm using OSX10.8 or perhaps something to do with macports). But I added the following to the end of the file at ~/.profile
export PYTHONPATH=/path/to/dir:$PYTHONPATH
my directory is now on the pythonpath -
my-macbook:~ aidan$ python
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/path/to/dir', ...
and I can import modules from that directory.
I was able to get Font Awesome to work by using the all.min.css file.
I found this error occurred when I was using the wrong version of Java. When I changed my environment from Java 7 down to Java 6 the error no longer appeared.
(The MSVCR71.DLL file is in the JDK 6 bin
directory, where JDK 7 has MSVCR100.DLL.)
Just for other's reference, I just received this and found it was due to AngularJS. It's for backwards compatibility:
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
This plugin is documented rather good in https://polylang.wordpress.com/documentation.
The developers documentation states the following logic as a means to generate URL's for different translations of the same post
<?php while ( have_posts() ) : the_post(); ?>
<ul class='translations'><?php pll_the_languages(array('post_id' =>; $post->ID)); ?></ul>
<?php the_content(); ?>
<?php endwhile; ?>
If you want more influence on what is rendered, inspet pll_the_languages
function and copy it's behaviour to your own output implementation
As you want buttons to switch language, this page: https://polylang.wordpress.com/documentation/frequently-asked-questions/the-language-switcher/ will give you the required info.
An implementation example:
<ul><?php pll_the_languages();?></ul>
Then style with CSS to create buttons, flags or whatever you want. It is also possible to use a widget for this, provided by te plugin
All plugins functions are explained here: https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/
In this case use:
pll_current_language();
Read the file line by line and then add it on a list in reverse order.
Here is an example of code :
reverse = []
with open("file.txt", "r") as file:
for line in file:
line = line.strip()
reverse[0:0] = line
if you in psql just type
set schema 'temp';
and after that \d shows all relations in "temp
The two functions you need are documented here:
In short:
// Load images in the C++ format
cv::Mat img = cv::imread("something.jpg");
cv::Mat src = cv::imread("src.jpg");
// Resize src so that is has the same size as img
cv::resize(src, src, img.size());
And please, please, stop using the old and completely deprecated IplImage* classes
You can overwrite your default activity animation. Here is the solution that I use:
Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
</style>
<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
<item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
<item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
<item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
<item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>
Create anim folder under res folder and then create this four animation files:
slide_in_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
This is my sample project in github.
That's all... Happy coding :)
I solved in this way:
I created the 'ObjectControls' module for ThreeJS that allows you to rotate a single OBJECT (or a Group), and not the SCENE.
Include the libary:
<script src="ObjectControls.js"></script>
Usage:
var controls = new ObjectControls(camera, renderer.domElement, yourMesh);
You can find here a live demo here: https://albertopiras.github.io/threeJS-object-controls/
Here is the repo: https://github.com/albertopiras/threeJS-object-controls.
An alternative way can be this: - recommended as using just one expression -
case when address.country <> '' then address.country
else 'United States'
end as country
Note: Result of checking
null
by<>
operator will returnfalse
.
And as documented:NULLIF
is equivalent to a searchedCASE
expression
andCOALESCE
expression is a syntactic shortcut for theCASE
expression.
So, combination of those are using two time ofcase
expression.
It's only possible when the server sends this header: Access-Control-Allow-Origin: *
If this is your code then you can setup it like this (PHP):
header('Access-Control-Allow-Origin: *');
Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.
Download zip file and extract it, with in that you will find mysql-connector-XXX.jar
file
If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java
Select the version you want to use and add the dependency in your pom.xml
file
Use the keyword and
, not &
because &
is a bit operator.
Be careful with this... just so you know, in Java and C++, the &
operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&
. Similarly |
is a bit operator, and ||
is a boolean operator. In Python and
and or
are used for boolean comparisons.
A subclass in java, is a class that inherits from another class.
Inheritance is a way for classes to add specialized behavior ontop of generalized behavior. This is often represented by the phrase "is a" relationship.
For example, a Triangle
is a Shape
, so it might make sense to implement a Shape class, and have the Triangle class inherit from it. In this example, Shape
is the superclass of Triangle
and Triangle
is the subclass of Shape
The hex values are on the mainpage of http://glyphicons.com/ in the tooltips of the specific icon.
onClick you should call function, thats called your function toggle.
onClick={() => this.toggle()}
For a time field, use:
import time
time.strftime('%Y-%m-%d %H:%M:%S')
I think strftime also applies to datetime.
Compare the password/confirm-password input values on their change
event and setCustomValidity accordingly:
function onChange() {_x000D_
const password = document.querySelector('input[name=password]');_x000D_
const confirm = document.querySelector('input[name=confirm]');_x000D_
if (confirm.value === password.value) {_x000D_
confirm.setCustomValidity('');_x000D_
} else {_x000D_
confirm.setCustomValidity('Passwords do not match');_x000D_
}_x000D_
}
_x000D_
<form>_x000D_
<label>Password: <input name="password" type="password" onChange="onChange()" /> </label><br />_x000D_
<label>Confirm : <input name="confirm" type="password" onChange="onChange()" /> </label><br />_x000D_
<input type="submit" />_x000D_
</form>
_x000D_
If you really need a "Backup" then you also need database schema, like table definitions, view definitions, store procedures and so on. A backup of a database isn't just the data.
The value of the mysqldump format for backup is specifically that it is very EASY to use it to restore mysql databases. A backup that isn't easily restored is far less useful. If you are looking for a method to reliably backup mysql data to so you can restore to a mysql server then I think you should stick with the mysqldump tool.
Mysql is free and runs on many different platforms. Setting up a new mysql server that I can restore to is simple. I am not at all worried about not being able to setup mysql so I can do a restore.
I would be far more worried about a custom backup/restore based on a fragile format like csv/tsv failing. Are you sure that all your quotes, commas, or tabs that are in your data would get escaped correctly and then parsed correctly by your restore tool?
If you are looking for a method to extract the data then see several in the other answers.
You could try using the -Clear
parameter
Example:-Clear Attribute1LDAPDisplayName, Attribute2LDAPDisplayName
Do a check (which fragment in the activity container) in the onStart method;
@Override
protected void onStart() {
super.onStart();
Fragment fragmentCurrent = getSupportFragmentManager.findFragmentById(R.id.constraintLayout___activity_main___container);
}
Some check:
if (fragmentCurrent instanceof MenuFragment)
I know this question is a little old but here is my solution.
// HTML
// <input type="checkbox" onClick="setcb1()"/>
// <input type="checkbox" onClick="setcb2()"/>
// cb1 = checkbox 1
// cb2 = checkbox 2
var cb1 = getId('cb1'),
cb2 = getId('cb2');
function getId(id) {
return document.getElementById(id);
}
function setcb1() {
if(cb1.checked === true) {
cb2.checked = false;
cb2.disabled = "disabled"; // You have to disable the unselected checkbox
} else if(cb1.checked === false) {
cb2.disabled = ""; // Then enable it if there isn't one selected.
}
}
function setcb2() {
if(cb2.checked === true) {
cb1.checked = false;
cb1.disabled = "disabled"
} else if(cb2.checked === false) {
cb1.disabled = ""
}
Hope this helps!
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
I had this issue recently and I resolved it by simply rolling IE8 back to IE7.
My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.
The problem is caused by your #grid
having a width:1140px
.
You need to set a min-width:1140px
on the body
.
This will stop the body
from getting smaller than the #grid
. Remove width:100%
as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/
html, body{
margin:0;
padding:0;
min-width: 1140px; /* this is the important part*/
}
#grid-container{
background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
width:1140px;
margin:0px auto;
}
I finally found the solution. As Rotemmiz said, you have to do it dynamically afterwards. This code stretches the buttons to fill the view horizontally, but the same can be done for vertically.
public void fillview(android.support.v7.widget.GridLayout gl)
{
Button buttontemp;
//Stretch buttons
int idealChildWidth = (int) ((gl.getWidth()-20*gl.getColumnCount())/gl.getColumnCount());
for( int i=0; i< gl.getChildCount();i++)
{
buttontemp = (Button) gl.getChildAt(i);
buttontemp.setWidth(idealChildWidth);
}
}
(The 20 is for the internal and external padding and margins. This could be done more universally, but this is far cleaner)
Then it can be called like this:
android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout)findViewById(R.id.buttongrid);
ViewTreeObserver vto = gl.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Override public void onGlobalLayout()
{
android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout) findViewById(R.id.buttongrid);
fillview(gl);
ViewTreeObserver obs = gl.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}});
It must be done with an observer because we need to wait for the view to be drawn before we call the views.
Nowadays, with ES6, I feel we could use an updated answer.
return (
<th value={column} onClick={()=>this.handleSort(column)} >{column}</th>
);
Basically, (for any that don't know) since onClick
is expecting a function passed to it, bind
works because it creates a copy of a function. Instead we can pass an arrow function expression that simply invokes the function we want, and preserves this
. You should never need to bind the render
method in React, but if for some reason you're losing this
in one of your component methods:
constructor(props) {
super(props);
this.myMethod = this.myMethod.bind(this);
}
Any of these three commands will print the character you want in a console, provided the console do accept UTF-8 characters (most current ones do):
echo -e "SKULL AND CROSSBONES (U+2620) \U02620"
echo $'SKULL AND CROSSBONES (U+2620) \U02620'
printf "%b" "SKULL AND CROSSBONES (U+2620) \U02620\n"
SKULL AND CROSSBONES (U+2620) ?
After, you could copy and paste the actual glyph (image, character) to any (UTF-8 enabled) text editor.
If you need to see how such Unicode Code Point is encoded in UTF-8, use xxd (much better hex viewer than od):
echo $'(U+2620) \U02620' | xxd
0000000: 2855 2b32 3632 3029 20e2 98a0 0a (U+2620) ....
That means that the UTF8 encoding is: e2 98 a0
Or, in HEX to avoid errors: 0xE2 0x98 0xA0. That is, the values between the space (HEX 20) and the Line-Feed (Hex 0A).
If you want a deep dive into converting numbers to chars: look here to see an article from Greg's wiki (BashFAQ) about ASCII encoding in Bash!
except:
accepts all exceptions, whereas
except Exception as e:
only accepts exceptions that you're meant to catch.
Here's an example of one that you're not meant to catch:
>>> try:
... input()
... except:
... pass
...
>>> try:
... input()
... except Exception as e:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
The first one silenced the KeyboardInterrupt
!
Here's a quick list:
issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False
issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False
issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False
If you want to catch any of those, it's best to do
except BaseException:
to point out that you know what you're doing.
All exceptions stem from BaseException
, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception
.
Instead of using <div>
, it would be better to use to provide the <tr>
(which you want to hide) an id and then hiding it using javascript.
Do as below using String#tr
:
"((String1))".tr('()', '')
# => "String1"
if(map.get(key) != null || (map.get(key) == null && map.containsKey(key)))