This is very simple and works just as well as any of the others:
function parseNumber(val, decimalPlaces) {
if (decimalPlaces == null) decimalPlaces = 0
var ret = Number(val).toFixed(decimalPlaces)
return Number(ret)
}
Since toFixed() can only be called on numbers, and unfortunately returns a string, this does all the parsing for you in both directions. You can pass a string or a number, and you get a number back every time! Calling parseNumber(1.49) will give you 1, and parseNumber(1.49,2) will give you 1.50. Just like the best of 'em!
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
You can change the separator either by setting a locale or using the DecimalFormatSymbols.
If you want the grouping separator to be a point, you can use an european locale:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);
currentLocale can be obtained from Locale.getDefault() i.e.:
Locale currentLocale = Locale.getDefault();
Integer.valueOf()
returns an Integer object, while Integer.parseInt()
returns an int
primitive.
OK - str to float.
package test;
import java.text.DecimalFormat;
public class TestPtz {
public static void main(String[] args) {
String preset0 = "0.09,0.20,0.09,0.07";
String[] thisto = preset0.split(",");
float a = (Float.valueOf(thisto[0])).floatValue();
System.out.println("[Original]: " + a);
a = (float) (a + 0.01);
// Part 1 - for display / debug
System.out.printf("[Local]: %.2f \n", a);
// Part 2 - when value requires to be send as it is
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
System.out.println("[Remote]: " + df.format(a));
}
}
Output:
run:
[Original]: 0.09
[Local]: 0.10
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)
Following Code Currency Mask for EditText ($ 123,125.155)
Xml Layout
<EditText
android:inputType="numberDecimal"
android:layout_height="wrap_content"
android:layout_width="200dp"
android:digits="0123456789.,$" />
Code
EditText testFilter=...
testFilter.addTextChangedListener( new TextWatcher() {
boolean isEdiging;
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override public void afterTextChanged(Editable s) {
if(isEdiging) return;
isEdiging = true;
String str = s.toString().replaceAll( "[^\\d]", "" );
double s1 = Double.parseDouble(str);
NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
((DecimalFormat)nf2).applyPattern("$ ###,###.###");
s.replace(0, s.length(), nf2.format(s1));
isEdiging = false;
}
});
The code below can be used to add your own version of Math.round to your own namespace which takes a precision parameter. Unlike Decimal rounding in the example above, this performs no conversion to and from strings, and the precision parameter works same way as PHP and Excel whereby a positive 1 would round to 1 decimal place and -1 would round to the tens.
var myNamespace = {};
myNamespace.round = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230
Simple solution:
double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));
//output: 123.45
Declare it as a decimal
which uses the int
variable and divide this by 100
int number = 700
decimal correctNumber = (decimal)number / 100;
Edit: Bala was faster with his reaction
Try this light weight solution:
function round(x, digits){
return parseFloat(x.toFixed(digits))
}
round(1.222, 2) ;
// 1.22
round(1.222, 10) ;
// 1.222
Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html
Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.
There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices
.
You can call view.setVisibility(View.GONE)
if you want to remove it from the layout.
Or view.setVisibility(View.INVISIBLE)
if you just want to hide it.
From Android Docs:
INVISIBLE
This view is invisible, but it still takes up space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.GONE
This view is invisible, and it doesn't take any space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.
maybe this is what you want
import pandas as pd
idx = pd.MultiIndex.from_product([['state1','state2'], ['county1','county2','county3','county4']])
df = pd.DataFrame({'pop': [12,15,65,42,78,67,55,31]}, index=idx)
pop state1 county1 12 county2 15 county3 65 county4 42 state2 county1 78 county2 67 county3 55 county4 31
df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('pop', ascending=False)).groupby(level=0).head(3)
> Out[29]:
pop
state1 county3 65
county4 42
county2 15
state2 county1 78
county2 67
county3 55
This is a very simple solution for windows forms if all is needed is the final value as a (string). The items' names will be displayed on the Combo Box and the selected value can be easily compared.
List<string> items = new List<string>();
// populate list with test strings
for (int i = 0; i < 100; i++)
items.Add(i.ToString());
// set data source
testComboBox.DataSource = items;
and on the event handler get the value (string) of the selected value
string test = testComboBox.SelectedValue.ToString();
I am facing the same problem with you. Based on the hint of @thuliha, the following codes has solved my issues.
In the html
file, modify as the following sample:
<img class="img-responsive center-block" src=".....png" alt="Third slide">
In the carousel.css
, modify the class:
.carousel .item {
text-align: center;
height: 470px;
background-color: #777;
}
DateTime.Now.Tostring();
. You can supply parameters to To string function in a lot of ways like given in this link http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
This will be a lot useful. If you reside somewhere else than the regular format (MM/dd/yyyy)
use always MM not mm, mm gives minutes and MM gives month.
Both SOAP webservices and REST webservices can use the HTTP protocol and other protocols as well (just to mention SOAP can be the underlying protocol of REST). I will talk only about the HTTP protocol related SOAP and REST, because this is the most frequent usage of them.
SOAP ("simple" object access protocol) is a protocol (and a W3C standard). It defines how to create, send and process SOAP messages.
SOAP messages are XML documents with a specific structure: they contain an envelope which contains the header and the body section. The body contains the actual data - we want to send - in an XML format. There are two encoding styles, but we usually choose literal, which means that our application or its SOAP driver does the XML serialization and unserialization of the data.
SOAP messages travel as HTTP messages with SOAP+XML MIME subtype. These HTTP messages can be multipart, so optionally we can attach files to SOAP messages.
Obviously we use a client-server architecture, so the SOAP clients send requests to the SOAP webserices and the services send back responses to the clients. Most of the webservices use a WSDL file to describe the service. The WSDL file contains the XML Schema (XSD hereafter) of the data we want to send and the WSDL binding which defines how the webservice is bound to the HTTP protocol. There are two binding styles: RPC and document. By the RPC style binding the SOAP body contains the representation of an operation call with the parameters (HTTP requests) or the return values (HTTP response). The parameters and return values are validated against the XSD. By the document style binding the SOAP body contains an XML document which is validated against the XSD. I think the document binding style is better suited to event based systems, but I never used that binding style. The RPC binding style is more prevalent, so most people use SOAP for XML/RPC purposes by distributed applications. The webservices usually find each other by asking an UDDI server. UDDI servers are registries which store the location of the webservices.
So the - in my opinion - most prevalent SOAP webservice uses RPC binding style and literal encoding style and it has the following properties:
REST (representational state transfer) is an architecture style which is described in the dissertation of Roy Fielding. It does not concern about protocols like SOAP does. It starts with a null architecture style having no constraints and defines the constraints of the REST architecture one by one. People use the term RESTful for webservices which fulfill all of the REST constraints, but according to Roy Fielding, there are no such things as REST levels. When a webservice does not meet with every single REST constraint, then it is not a REST webservice.
Uniform interface
https://example.com/api/v1/users?offset=50&count=25
. URLs have some specifications, for example URLs with the same pathes but different queries are not identical, or the path part should contain the hierarhical data of the URL and the query part should contain the non-hierarchical data. These are the basics of how to create URLs by REST. Btw. the URL structure does matter only for the service developers, a real REST client does not concern with it. Another frequently asked question is API versioning, which is an easy one, because according to Fielding the only constant thing by resource is semantics. If the semantics change, then you can add a new version number. You can use classical 3 number versioning and add only the major number to the URLs (https://example.com/api/v1/
). So by backward compatible changes nothing happens, by non-backward compatible changes you will have a non-backward compatible semantics with a new API root https://example.com/api/v2/
. So the old clients won't break, because they can use the https://example.com/api/v1/
with the old semantics.PATCH https://example.com/api/v1/users/1 {name: "Mrs Smith"}
request where the {name: "Mrs Smith"}
is a JSON representation of the intended resource state, in other words: the new name. This happens vica-versa, the service sends representations of resources to the clients in order to change their states. For example if we want to read the new name, we can send a GET https://example.com/api/v1/users/1?fields="name"
retrieval request, which results in a 200 ok, {name: "Mrs Smith"}
response. So we can use this representation to change the client state, for example we can display a "Welcome to our page Mrs Smith!" message. A resource can have many representations depending on the resource identifier (URL) or the accept
header we sent with the request. For example we can send an image of Mrs Smith (probably not nude) if image/jpeg
is requested. Hypermedia as the engine of application state (HATEOAS hereafter) - Hypermedia is a media type which can contain hyperlinks. By the web we follow links - described by a hypermedia format (usually HTML) - to achieve a goal, instead of typing the URLs into the addres bar. REST follows the same concept, the representations sent by the service can contain hyperlinks. We use these hyperlinks to send requests to the service. With the response we get data (and probably more links) which we can use to build the new client state, and so on... So that's why hypermedia is the engine of application state (client state). You probably wonder how do clients recognize and follow the hyperlinks? By humans it is pretty simple, we read the title of the link, maybe fill input fields, and after that just a single click. By machines we have to add semantics to the links with RDF (by JSON-LD with Hydra) or with hypermedia specific solutions (for example IANA link relations and vendor specific MIME types by HAL+JSON). There are many machine readable XML and JSON hypermedia formats, just a short list of them:
Sometimes it is hard to choose...
So a REST webservice is very different from a SOAP webservice (with RPC binding style and literal encoding style)
and so on...
A SOAP RPC webservice does not meet all of the REST constraints:
It's a reasonable idea to want to script an FTP session the way the original poster imagined, and that is the kind of thing Expect would help with. Batch files on Windows cannot do this.
But rather than doing cURL or Expect, you may find it easier to script the FTP interaction with Powershell. It's a different model, in that you are not directly scripting the text to send to the FTP server. Instead you will use Powershell to manipulate objects that generate the FTP dialogue for you.
Upload:
$File = "D:\Dev\somefilename.zip"
$ftp = "ftp://username:[email protected]/pub/incoming/somefilename.zip"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $File..."
$webclient.UploadFile($uri, $File)
Download:
$File = "c:\store\somefilename.zip"
$ftp = "ftp://username:[email protected]/pub/outbound/somefilename.zip"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Downloading $File..."
$webclient.DownloadFile($uri, $File)
You need Powershell to do this. If you are not aware, Powershell is a shell like cmd.exe which runs your .bat files. But Powershell runs .ps1 files, and is quite a bit more powerful. Powershell is a free add-on to Windows and will be built-in to future versions of Windows. Get it here.
Source: http://poshcode.org/1134
This isn't on the code parter it's on the server side Contact your Server Manager or fix it from server if you own it If you use CPANEL/WHM GO TO WHM/SMTP RESTRICTIONS AND DISABLE IT
Your problem is that you are naming your component class Date
. When you call new Date()
within your class, it won't create an instance of the Date
you expect it to create (which is likely this Date
)- it will try to create an instance of your component class. Then the constructor will try to create another instance, and another instance, and another instance... Until you run out of stack space and get the error you're seeing.
If you want to use Date
within your class, try naming your class something different such as Calendar
or DateComponent
.
The reason for this is how JavaScript deals with name scope: Whenever you create a new named entity, if there is already an entity with that name in scope, that name will stop referring to the previous entity and start referring to your new entity. So if you use the name Date
within a class named Date
, the name Date
will refer to that class and not to any object named Date
which existed before the class definition started.
If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.
You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)
If you pass $element
into a controller, like you would $scope
, you can use its find()
function. Note that, in the jQueryLite included in Angular, find()
will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find()
can be used, including finding by attribute.
So, for this HTML:
<div ng-controller='MyCtrl'>
<div>
<div name='foo' class='myElementClass'>this one</div>
</div>
</div>
This AngularJS code should work:
angular.module('MyClient').controller('MyCtrl', [
'$scope',
'$element',
'$log',
function ($scope, $element, $log) {
// Find the element by its class attribute, within your controller's scope
var myElements = $element.find('.myElementClass');
// myElements is now an array of jQuery DOM elements
if (myElements.length == 0) {
// Not found. Are you sure you've included the full jQuery?
} else {
// There should only be one, and it will be element 0
$log.debug(myElements[0].name); // "foo"
}
}
]);
To add to squarecandy's google calendar contribution, here the brand new
OUTLOOK CALENDAR format (Without a need to create .ics) !!
<a href="https://bay02.calendar.live.com/calendar/calendar.aspx?rru=addevent&dtstart=20151119T140000Z&dtend=20151119T160000Z&summary=Summary+of+the+event&location=Location+of+the+event&description=example+text.&allday=false&uid=">add to Outlook calendar</a>
Best would be to url_encode the summary, location and description variable's values.
For the sake of knowledge,
YAHOO CALENDAR format
<a href="https://calendar.yahoo.com/?v=60&view=d&type=20&title=Summary+of+the+event&st=20151119T090000&et=20151119T110000&desc=example+text.%0A%0AThis+is+the+text+entered+in+the+event+description+field.&in_loc=Location+of+the+event&uid=">add to Yahoo calendar</a>
Doing it without a third party holds a lot of advantages for example using it in emails.
Sounds like you want to do something like this:
{{> person {another: 'attribute'} }}
Yehuda already gave you a way of doing that:
{{> person this}}
But to clarify:
To give your partial its own data, just give it its own model inside the existing model, like so:
{{> person this.childContext}}
In other words, if this is the model you're giving to your template:
var model = {
some : 'attribute'
}
Then add a new object to be given to the partial:
var model = {
some : 'attribute',
childContext : {
'another' : 'attribute' // this goes to the child partial
}
}
childContext
becomes the context of the partial like Yehuda said -- in that, it only sees the field another
, but it doesn't see (or care about the field some
). If you had id
in the top level model, and repeat id
again in the childContext, that'll work just fine as the partial only sees what's inside childContext
.
Single line, and only calculating logs once. First convert to log-space, then take the 1-period diff.
np.diff(np.log(df.price))
In earlier versions of numpy:
np.log(df.price)).diff()
Using CrudRepository and JPA query works for me:
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface TokenCrudRepository extends CrudRepository<Token, Integer> {
/**
* Finds a token by using the user as a search criteria.
* @param user
* @return A token element matching with the given user.
*/
@Query("SELECT t FROM Token t WHERE LOWER(t.user) = LOWER(:user)")
public Token find(@Param("user") String user);
}
and you invoke the find custom method like this:
public void destroyCurrentToken(String user){
AbstractApplicationContext context = getContext();
repository = context.getBean(TokenCrudRepository.class);
Token token = ((TokenCrudRepository) repository).find(user);
int idToken = token.getId();
repository.delete(idToken);
context.close();
}
You could try to use anchorScroll.
So the controller would be:
app.controller('MainCtrl', function($scope, $location, $anchorScroll, $routeParams) {
$scope.scrollTo = function(id) {
$location.hash(id);
$anchorScroll();
}
});
And the view:
<a href="" ng-click="scrollTo('foo')">Scroll to #foo</a>
...and no secret for the anchor id:
<div id="foo">
This is #foo
</div>
Assuming you are reading from a data row, what you want is:
if ( !rdrSelect.IsNull(23) )
{
//handle parsing
}
Here is the corresponding presentViewController version that I used if it helps other newbies like myself:
if ([self respondsToSelector:@selector(presentModalViewController:animated:)]) {
[self performSelector:@selector(presentModalViewController:animated:) withObject:testView afterDelay:0];
} else {
[self presentViewController:configView animated:YES completion:nil];
}
[testView.testFrame setImage:info]; //this doesn't work for performSelector
[testView.testText setHidden:YES];
I had used a ViewController 'generically' and was able to get the modal View to appear differently depending what it was called to do (using setHidden and setImage). and things were working nicely before, but performSelector ignores 'set' stuff, so in the end it seems to be a poor solution if you try to be efficient like I tried to be...
Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,
In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,
@Autowired
private RestTemplate restTemplate;
Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.
ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<POJO>>() {
});
List<POJO> pojoObjList = responseEntity.getBody();
Happy Coding :)
Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
// Your Extended Properties
public long? OrganizationId { get; set; }
}
Then what you need is to create an extension method like so (I create mine in an new Extensions folder):
namespace App.Extensions
{
public static class IdentityExtensions
{
public static string GetOrganizationId(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
}
When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here => this.OrganizationId is a value stored in database against the user
userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId.ToString()));
return userIdentity;
}
Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:
in my case: using App.Extensions;
within a Controller and @using. App.Extensions
withing a .cshtml View file.
EDIT:
What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there.
Now look for the <namespaces>
tag and add your extension namespace there like so:
<add namespace="App.Extensions" />
Save your file and you're done. Now every View will know of your extensions.
You can access the Extension Method:
var orgId = User.Identity.GetOrganizationId();
You can get from Dateformatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)
For PySpark, you can also set the log level in your scripts with sc.setLogLevel("FATAL")
. From the docs:
Control our logLevel. This overrides any user-defined log settings. Valid log levels include: ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN
Other configurable Spark option relating to jars and classpath, in case of yarn
as deploy mode are as follows
From the spark documentation,
spark.yarn.jars
List of libraries containing Spark code to distribute to YARN containers. By default, Spark on YARN will use Spark jars installed locally, but the Spark jars can also be in a world-readable location on HDFS. This allows YARN to cache it on nodes so that it doesn't need to be distributed each time an application runs. To point to jars on HDFS, for example, set this configuration to hdfs:///some/path. Globs are allowed.
spark.yarn.archive
An archive containing needed Spark jars for distribution to the YARN cache. If set, this configuration replaces spark.yarn.jars and the archive is used in all the application's containers. The archive should contain jar files in its root directory. Like with the previous option, the archive can also be hosted on HDFS to speed up file distribution.
Users can configure this parameter to specify their jars, which inturn gets included in Spark driver's classpath.
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
This blog entry has a way to emulate border-color: transparent
in IE6. The below example includes the "hasLayout" fix that is brought up in the blog entry comments:
/* transparent border */
.testDiv {
width: 200px;
height: 200px;
border: solid 10px transparent;
}
/* IE6 fix */
*html .testDiv {
zoom: 1;
border-color: #FEFEFE;
filter: chroma(color=#FEFEFE);
}
Make sure that the border-color
used in the IE6 fix is not used anywhere in the .testDiv
element. I changed the example from pink
to #FEFEFE
because that seems even less likely to be used.
If you need a progmatic solution this should work in jQuery:
$(".abc.xyz").css("width", 200);
Try this script to get your browser language
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
Cheers
Prefork and worker are two type of MPM apache provides. Both have their merits and demerits.
By default mpm is prefork which is thread safe.
Prefork MPM uses multiple child processes with one thread each and each process handles one connection at a time.
Worker MPM uses multiple child processes with many threads each. Each thread handles one connection at a time.
For more details you can visit https://httpd.apache.org/docs/2.4/mpm.html and https://httpd.apache.org/docs/2.4/mod/prefork.html
I have started using IntelliJ IDEA Community Edition version 12.1.3 and I found the setting in the following place: -
File > Other Settings > Default Settings > {choose from Code Style dropdown}
You can use a BinaryWriter
object.
protected bool SaveData(string FileName, byte[] Data)
{
BinaryWriter Writer = null;
string Name = @"C:\temp\yourfile.name";
try
{
// Create a new stream to write to the file
Writer = new BinaryWriter(File.OpenWrite(Name));
// Writer raw data
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
//...
return false;
}
return true;
}
Edit: Oops, forgot the finally
part... lets say it is left as an exercise for the reader ;-)
create function [Sistema].[fParseDecimal]
(
@Valor nvarchar(4000)
)
returns decimal(18, 4) as begin
declare @Valores table (Valor varchar(50));
insert into @Valores values (@Valor);
declare @Resultado decimal(18, 4) = (select top 1
cast('' as xml).value('sql:column("Valor") cast as xs:decimal ?', 'decimal(18, 4)')
from @Valores);
return @Resultado;
END
Just execute
sudo npm i --save
That's all
Some years back Javaworld had an article on determining the size of composite and potentially nested Java objects, they basically walk through creating a sizeof() implementation in Java. The approach basically builds on other work where people experimentally identified the size of primitives and typical Java objects and then apply that knowledge to a method that recursively walks an object graph to tally the total size.
It is always going to be somewhat less accurate than a native C implementation simply because of the things going on behind the scenes of a class but it should be a good indicator.
Alternatively a SourceForge project appropriately called sizeof that offers a Java5 library with a sizeof() implementation.
P.S. Do not use the serialization approach, there is no correlation between the size of a serialized object and the amount of memory it consumes when live.
Batch file for setting a new dns server
@echo off
rem usage: setdns <dnsserver> <interface>
rem default dsnserver is dhcp
rem default interface is Wi-Fi
set dnsserver="%1"
if %dnsserver%=="" set dnsserver="dhcp"
set interface="%2"
if %interface%=="" set interface="Wi-Fi"
echo Showing current DNS setting for interface a%interface%
netsh interface ipv4 show dnsserver %interface%
echo Changing dnsserver on interface %interface% to %dnsserver%
if %dnsserver% == "dhcp" netsh interface ipv4 set dnsserver %interface% %dnsserver%
if NOT %dnsserver% == "dhcp" netsh interface ipv4 add dnsserver %interface% address=%dnsserver% index=1
echo Showing new DNS setting for interface %interface%
netsh interface ipv4 show dnsserver %interface%
When I'm teaching someone programming (just about any language) I introduce for
loops with terminology similar to this code example:
for eachItem in someList:
doSomething(eachItem)
... which, conveniently enough, is syntactically valid Python code.
The Python range()
function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).
So range(5)
returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).
A call to range(2,10)
would return: 2, 3, 4, 5, 6, 7, 8, 9
A call to range(2,12,3)
would return: 2, 5, 8, 11
Notice that I said, a couple times, that Python's range()
function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range()
built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break
" out of the loop early (after finding some particular item in which you were interested, for example).
Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.
The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."
Other constructs in the language (such as those underlying the for
loop) can then work with that object (iterate through it) as though it were a list.
For most cases you don't have to know whether your version of Python is using the old implementation of range()
or the newer one based on generators. You can just use it and be happy.
If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range()
on an old version of Python. In such cases you could re-think your design and use while
loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange()
version of range()
if your version of Python includes it, or the range()
function from a version of Python that uses the generators implicitly.
Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).
[Update: for Python3 (the currently maintained versions of Python) the range()
function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].
I'd wrap the dictionary in another class:
public class MyListDictionary
{
private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();
public void Add(string key, string value)
{
if (this.internalDictionary.ContainsKey(key))
{
List<string> list = this.internalDictionary[key];
if (list.Contains(value) == false)
{
list.Add(value);
}
}
else
{
List<string> list = new List<string>();
list.Add(value);
this.internalDictionary.Add(key, list);
}
}
}
You can use the with_fileglob
loop for this:
- copy:
src: "{{ item }}"
dest: /etc/fooapp/
owner: root
mode: 600
with_fileglob:
- /playbooks/files/fooapp/*
For your last question, why ? I'll try to explain with what I know
A brief explanation of those three status codes in layman's terms.
If caching is enabled in the server
For some files browser is deciding to request from server and for some it's deciding to read from stored (cached) files. Why is this ? Every files has an expiry date, so
If a file is not expired then the browser will use from cache (200 cache).
If file is expired, browser requests server for a file. Server check file in both places (browser and server). If same file found, server refuses the request. As per protocol browser uses existing file.
look at this nginx configuration
location / {
add_header Cache-Control must-revalidate;
expires 60;
etag on;
...
}
Here the expiry is set to 60 seconds, so all static files are cached for 60 seconds. So if u request a file again within 60 seconds browser will read from memory (200 memory). If u request after 60 seconds browser will request server (304).
I assumed that the file is not changed after 60 seconds, in that case you would get 200 (ie, updated file will be fetched from server).
So, if the servers are configured with different expiring and caching headers (policies), the status may differ.
In your case you are using cdn, the main purpose of cdn is high availability and fast delivery. Therefore they use multiple servers. Even though it seems like files are in same directory, cdn might use multiple servers to provide u content, if those servers have different configurations. Then these status can change. Hope it helps.
I just wanted to point out my answer since I know for
loop is faster then $.each
loop
here it is:
just add class="required"
to inputs you want to be required and then in jquery do:
$('#signup_form').submit(function(){
var fields = $('input.required');
for(var i=0;i<fields.length;i++){
if($(fields[i]).val() != ''){
//whatever
}
}
});
When you run the official entrypoint (A.K.A. when you launch the container), it runs initdb
in $PGDATA
(/var/lib/postgresql/data
by default), and then it stores in that directory these 2 files:
postgresql.conf
with default manual settings.postgresql.auto.conf
with settings overriden automatically with ALTER SYSTEM
commands.The entrypoint also executes any /docker-entrypoint-initdb.d/*.{sh,sql}
files.
All this means you can supply a shell/SQL script in that folder that configures the server for the next boot (which will be immediately after the DB initialization, or the next times you boot the container).
Example:
conf.sql
file:
ALTER SYSTEM SET max_connections = 6;
ALTER SYSTEM RESET shared_buffers;
Dockerfile
file:
FROM posgres:9.6-alpine
COPY *.sql /docker-entrypoint-initdb.d/
RUN chmod a+r /docker-entrypoint-initdb.d/*
And then you will have to execute conf.sql
manually in already-existing databases. Since configuration is stored in the volume, it will survive rebuilds.
Another alternative is to pass -c
flag as many times as you wish:
docker container run -d postgres -c max_connections=6 -c log_lock_waits=on
This way you don't need to build a new image, and you don't need to care about already-existing or not databases; all will be affected.
The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.
You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.
I've actually implemented one before. Here's a link.
This problem can be easily solved by installing the following Individual components:
We can get a list of files inside a folder on the file system using various golang standard library functions.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
func main() {
var (
root string
files []string
err error
)
root := "/home/manigandan/golang/samples"
// filepath.Walk
files, err = FilePathWalkDir(root)
if err != nil {
panic(err)
}
// ioutil.ReadDir
files, err = IOReadDir(root)
if err != nil {
panic(err)
}
//os.File.Readdir
files, err = OSReadDir(root)
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
The
path/filepath
package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.
func FilePathWalkDir(root string) ([]string, error) {
var files []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, path)
}
return nil
})
return files, err
}
ioutil.ReadDir
reads the directory named by dirname and returns a list of directory entries sorted by filename.
func IOReadDir(root string) ([]string, error) {
var files []string
fileInfo, err := ioutil.ReadDir(root)
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.
func OSReadDir(root string) ([]string, error) {
var files []string
f, err := os.Open(root)
if err != nil {
return files, err
}
fileInfo, err := f.Readdir(-1)
f.Close()
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Benchmark results.
Get more details on this Blog Post
I solved the problem like that: go to Run
and Select Clean and Rerun
.
While you have your answer from Daniel, here are some customizations possible using OpenCSVSerde
:
CREATE EXTERNAL TABLE `mydb`.`mytable`(
`product_name` string,
`brand_id` string,
`brand` string,
`color` string,
`description` string,
`sale_price` string)
PARTITIONED BY (
`seller_id` string)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
'separatorChar' = '\t',
'quoteChar' = '"',
'escapeChar' = '\\')
STORED AS INPUTFORMAT
'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
'hdfs://namenode.com:port/data/mydb/mytable'
TBLPROPERTIES (
'serialization.null.format' = '',
'skip.header.line.count' = '1')
With this, you have total control over the separator, quote character, escape character, null handling and header handling.
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.
Here are the some of the reasons I am aware of:
I had to do the following:
brew update
brew uninstall node
VARCHAR with probably 15-20 length would be sufficient and would be the best option for the database. Since you would probably require various hyphens and plus signs along with your phone numbers.
Change your css as below
#element1 {float:left;margin-right:10px;}
#element2 {float:left;}
Here is the JSFiddle http://jsfiddle.net/a4aME/
You can get that error if you have an object with the same name as the schema. For example:
create sequence s2;
begin
s2.a;
end;
/
ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored
When you refer to S2.MY_FUNC2
the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2
there is no confusion, so it works.
The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.
It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.
select owner, object_type, object_name
from all_objects
where object_name = 'S2';
for color in ['r', 'b', 'g', 'k', 'm']:
plot(x, y, color=color)
I know this is an old Question
But in case you want to do it programmatically or the java way
For Image Backgrounds; you can use BackgroundImage class
BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));
For Paint or Fill Backgrounds; you can use BackgroundFill class
BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));
Keeps your java alive && your css dead..
I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.
function secure_password($user_pwd, $multi) {
/*
secure_password ( string $user_pwd, boolean/string $multi )
*** Description:
This function verifies a password against a (database-) stored password's hash or
returns $hash for a given password if $multi is set to either true or false
*** Examples:
// To check a password against its hash
if(secure_password($user_password, $row['user_password'])) {
login_function();
}
// To create a password-hash
$my_password = 'uber_sEcUrE_pass';
$hash = secure_password($my_password, true);
echo $hash;
*/
// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);
// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
if (password_verify($user_pwd, $table_pwd = $multi)) {
return true; // valid password
} else {
return false; // invalid password
}
// If $multi is boolean return $hash
} else return $hash;
}
None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:
<repository>
<id>1_maven.apache.org</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>true</enabled> </snapshots>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
</repository>
<repository>
<id>2_maven.oracle.com</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>false</enabled> </snapshots>
<url>https://maven.oracle.com</url>
<layout>default</layout>
</repository>
As a rephrasing of Andrey's answer:
The Boost TypeIndex library can be used to print names of types.
Inside a template, this might read as follows
#include <boost/type_index.hpp>
#include <iostream>
template<typename T>
void printNameOfType() {
std::cout << "Type of T: "
<< boost::typeindex::type_id<T>().pretty_name()
<< std::endl;
}
I had same problem. I wanted to edit ENUM values in table structure. Problem was because of rows that was saved before and new ENUM values doesn't contain saved values.
Solution was updating old saved rows in MySql table.
Since 0.14.1, you can now do nlargest
and nsmallest
on a groupby
object:
In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]:
id
1 2 3
1 2
2 6 4
5 3
3 7 1
4 8 1
dtype: int64
There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.
If you're not interested in it, you can do .reset_index(level=1, drop=True)
to get rid of it altogether.
(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series
and SeriesGroupBy
.)
select the index then select the ones needed then select sql and click action then click rebuild
From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
This is a one line solution involving LINQ.
var elements = new String[] { "1", "2", "3" };
Foo(elements.Cast<object>().ToArray())
You could also use viewport percentages if you don't care about old school IE.
height: 100vh;
they are similar but not same
set.seed(0)
x<-matrix(rnorm(10),1)
# one can compute from the other
rank(x) == col(x)%*%diag(length(x))[order(x),]
order(x) == col(x)%*%diag(length(x))[rank(x),]
# rank can be used to sort
sort(x) == x%*%diag(length(x))[rank(x),]
I do it like this, to launch the SendFreeTextActivity from a (custom) menu fragment that appears in multiple activities:
In the MenuFragment class:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "sendFreeTextButton clicked");
Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
MenuFragment.this.startActivity(intent);
}
});
...
Alternatively, you can create a button on your webpage and in the Page_Load type;
Trace.IsEnabled = True
And in the button click event type;
Response.Write(Trace)
This will bring up all the trace information and you will find your ASP.NET version in the "Response Headers Collection" under "X-ASPNet-Version".
You can use this JDBC URL directly in your data source configuration:
jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull
If you are using a non default MySQL port number then do the following:
33747
then paste the following
$cfg['Servers'][$i]['port'] = 33747;
under the
/* Authentication type and info */
section.I guess that the most correct answer is: Use :nth-child
(or, in this specific case, its counterpart :nth-last-child
). Most only know this selector by its first argument to grab a range of items based on a calculation with n, but it can also take a second argument "of [any CSS selector]".
Your scenario could be solved with this selector: .commentList .comment:nth-last-child(1 of .comment)
But being technically correct doesn't mean you can use it, though, because this selector is as of now only implemented in Safari.
For further reading:
I had this error for two weeks, and the majority of the solutions stated 'chmod -R' as the the answer, unfortunately for me my git repos (local / remote / shared - with team) were all on Windows OS, and even though chmod -Rv showed all the files changed to 'rwxrwxrwx', a subsequent 'ls -l' still showed all files as 'rwxr-xr-x' and the error repeated itself. I eventually saw this solution by Ariejan de Vroom. It worked and we were all able to pull and push again.
On both local (the local that is having trouble pushing) and remote repos, run the following commands:
$ git fsck
$ git prune
$ git repack
$ git fsck
On a side note, I tried using Windows' native file permissions / ACL and even resorted to elevating the problem user to Administrator, but none of that seemed to help. Not sure if the environment is important, but it may help someone with a similar setup - problem team member and remote (Windows Server 2008 R2 Standard), my local (Windows 7 VM).
Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.
There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .
After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.
In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.
Considering you've four scripts named script1.js, script2.js, script3.js, script4.js
then you can do it with applying async = false:
[
'script1.js',
'script2.js',
'script3.js',
'script4.js'
].forEach(function(src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.head.appendChild(script);
});
Now, Spec says: Download together, execute in order as soon as all download.
Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.
Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.
IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.
Everything else says: I’m your friend, we’re going to do this by the book.
Now, the full code with IE < 10 workaround:
var scripts = [
'script1.js',
'script2.js',
'script3.js',
'script4.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];
// Watch scripts load in IE
function stateChange() {
// Execute as many scripts in order as we can
var pendingScript;
while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
pendingScript = pendingScripts.shift();
// avoid future loading events from this script (eg, if src changes)
pendingScript.onreadystatechange = null;
// can't just appendChild, old IE bug if element isn't closed
firstScript.parentNode.insertBefore(pendingScript, firstScript);
}
}
// loop through our script urls
while (src = scripts.shift()) {
if ('async' in firstScript) { // modern browsers
script = document.createElement('script');
script.async = false;
script.src = src;
document.head.appendChild(script);
}
else if (firstScript.readyState) { // IE<10
// create a script and add it to our todo pile
script = document.createElement('script');
pendingScripts.push(script);
// listen for state changes
script.onreadystatechange = stateChange;
// must set src AFTER adding onreadystatechange listener
// else we’ll miss the loaded event for cached scripts
script.src = src;
}
else { // fall back to defer
document.write('<script src="' + src + '" defer></'+'script>');
}
}
You can use opendir()
and check if ENOENT == errno
on failure:
#include <dirent.h>
#include <errno.h>
DIR* dir = opendir("mydir");
if (dir) {
/* Directory exists. */
closedir(dir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
} else {
/* opendir() failed for some other reason. */
}
Using top: 40px
and bottom: 40px
(assuming your footer is also 40px) with no defined height, you can get this to work.
.header {
width: 100%;
height: 40px;
position: absolute;
top: 0;
background-color:red;
}
.mainBody {
width: 100%;
top: 40px;
bottom: 40px;
position: absolute;
background-color: gray;
}
.footer {
width: 100%;
height: 40px;
position: absolute;
bottom: 0;
background-color: blue;
}
This is simple, and works with Django 1.4:
class ClientAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ClientAdminForm, self).__init__(*args, **kwargs)
# access object through self.instance...
self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)
class ClientAdmin(admin.ModelAdmin):
form = ClientAdminForm
....
You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):
ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to
override the default formfield for a foreign keys field. For example,
to return a subset of objects for this foreign key field based on the
user:'''
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.
I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site.
The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration).
The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset.
In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above.
class FrontEndAdmin(models.ModelAdmin):
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(FrontEndAdmin, self).__init__(model, admin_site)
remove 'delete' buttons:
def get_actions(self, request):
actions = super(FrontEndAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
prevents delete permission
def has_delete_permission(self, request, obj=None):
return False
filters objects that can be viewed on the admin site:
def get_queryset(self, request):
if request.user.is_superuser:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
return qs
else:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
if hasattr(self.model, ‘user’):
return qs.filter(user=request.user)
if hasattr(self.model, ‘porcupine’):
return qs.filter(porcupine=request.user.porcupine)
else:
return qs
filters choices for all foreignkey fields on the admin site:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.employee.is_superuser:
return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
else:
if hasattr(db_field.rel.to, 'user'):
kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
if hasattr(db_field.rel.to, 'porcupine'):
kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)
You could use the add
method and pass it a negative number. However, you could also write a simpler method that doesn't use the Calendar
class such as the following
public static void addDays(Date d, int days)
{
d.setTime( d.getTime() + (long)days*1000*60*60*24 );
}
This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the "proper" calendar solution:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime( c.getTime().getTime() );
}
Note that both of these solutions change the Date
object passed as a parameter rather than returning a completely new Date
. Either function could be easily changed to do it the other way if desired.
Use this to convert String to Blob. Where connection is the connection to db object.
String strContent = s;
byte[] byteConent = strContent.getBytes();
Blob blob = connection.createBlob();//Where connection is the connection to db object.
blob.setBytes(1, byteContent);
Some HTML elements have predefined margins (namely: body
, h1
to h6
, p
, fieldset
, form
, ul
, ol
, dl
, dir
, menu
, blockquote
and dd
).
In your case it's the h1
causing your problem. It has { margin: .67em }
by default. If you set it to 0 it will remove the space.
To solve problems like these generally, I recommend using your browser's dev tools. For most browsers: right-click on the element you want to know more about and select "Inspect Element". In the "Styles" tab, at the very bottom, you have a CSS box-model. This is a great tool for visualising borders, padding and margins and what elements are the root of your styling headaches.
There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.
To have a cookie sent by the browser to another site during a request the following criteria must be met:
Set-Cookie
header from the target site must contain the SameSite=None
and Secure
labels. If Secure
is not used the SameSite
header will be ignored.https
endpoint, a requirement of the Secure
flag.XHRRequest
must be made with withCredentials=true
. If using $.ajax()
this is accomplished with the xhrFields
parameter (requiring jQuery=1.5.1+
)Access-Control-Allow-Origin
header that matches the request Origin
header. (*
will not be respected in this case)A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.
Open the Servers view -> double click tomcat -> drop down the Timeouts section you can increase the startup time for each particular server. like 45 to 450
importing col, when from pyspark.sql.functions and updating fifth column to integer(0,1,2) based on the string(string a, string b, string c) into a new DataFrame.
from pyspark.sql.functions import col, when
data_frame_temp = data_frame.withColumn("col_5",when(col("col_5") == "string a", 0).when(col("col_5") == "string b", 1).otherwise(2))
@andruboy's suggestion of https://gist.github.com/chrisbanes/11247418 is probably your best bet.
https://github.com/thebnich/FloatingHintEditText kind of works with appcompat-v7 v21.0.0, but since v21.0.0 does not support accent colors with subclasses of EditText
, the underline of the FloatingHintEditText
will be the default solid black or white. Also the padding is not optimized for the Material style EditText
, so you may need to adjust it.
I had a similar problem.
Issue was there was a trigger on the table that would write changes to an audit log table. Columns were missing in audit log table.
if you want to run app in debug mode
1) Look at Left Side bottom, above Favorites there is Build Variants
2) Click on Build Variants. Click on release and choose debug
it works perfect !!!
Add a log4j.properties(log4j.xml) file with at least one appender in root of your classpath.
The contents of the file(log4j.properties) can be as simple as
log4j.rootLogger=WARN,A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c %x - %m%n
This will enable log4j logging with default log level as WARN
and use the java console to log the messages.
@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
WebClient client = new WebClient();
using (Stream data = client.OpenRead(Text))
{
using (StreamReader reader = new StreamReader(data))
{
string content = reader.ReadToEnd();
string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
MatchCollection matches = Regex.Matches(content,pattern);
List<string> urls = new List<string>();
foreach (Match match in matches)
{
urls.Add(match.Value);
}
}
How about:
private List<String> Parse(String str) {
List<String> output = new ArrayList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
I would recommend you to make use of the $.post
or $.get
syntax of jQuery for simple cases:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
});
If you need to catch the fail cases, just do this:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}, 'json');
Here is your solution for the problem,
$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
if(ord($i) % 2 != 0)
$letter[] .= $i;
}
print_r($letter);
You need to get the ASCII value for that character which will solve your problem.
Here is ord doc and working code.
For your requirement, you can do like this,
for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
$letter[] .= $i;
}
print_r($letter);
Here set $x as per your requirement.
There are a couple of things to check:
proceedToSecond
" into the FireBug console to see if the function gets definedscript
tag: it should be <script type="text/javascript">
instead of <script type = "text/javascript">
If you truly wish to use PHP, you could use
include "file.php";
or
require "file.php";
and then in file.php, use a heredoc & echo it in.
file.php contents:
$some_js_code <<<_code
function myFunction()
{
Alert("Some JS code would go here.");
}
_code;
At the top of your PHP file, bring in the file using either include or require then in head (or body section) echo it in
<?php
require "file.php";
?>
<html>
<head>
<?php
echo $some_js_code;
?>
</script>
</head>
<body>
</body>
</html>
Different way but it works. Just my $.02...
There are various APIs available to read/write XML files through Java. I would refer using StaX
Also This can be useful - Java XML APIs
Here has an easy way to solve this.
<?php
$date = "2015-11-17";
echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>
Output will be:
2015-11-22
Solution has found from here - How to Add Days to Date in PHP
Platform-independent way (starting from c++11) is:
#include <thread>
std::this_thread::get_id();
The most reliable way I've found is to wrap it in a self-elevating .bat file:
@echo off
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
CD %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
EXIT
:ADMINTASKS
powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"
EXIT
The .bat checks if you're already admin and relaunches the script as Administrator if needed. It also prevents extraneous "cmd" windows from opening with the 4th parameter of ShellExecute()
set to 0
.
Unfortunately SQL Server interprets the quoted comma as a delimiter. This applies to both BCP and bulk insert .
From http://msdn.microsoft.com/en-us/library/ms191485%28v=sql.100%29.aspx
If a terminator character occurs within the data, it is interpreted as a terminator, not as data, and the data after that character is interpreted as belonging to the next field or record. Therefore, choose your terminators carefully to make sure that they never appear in your data.
See findSourceTraceback()
of the R.utils package, which
Finds all 'srcfile' objects generated by source() in all call frames. This makes it possible to find out which files are currently scripted by source().
An alternative shorter method could be:
$r = explode(',', $s);
foreach ($r as &$i) $i = (int) $i;
It has the same performance as Method 3.
In Bootstrap 3 (3.0.3) adding the "text-center"
class to a td
element works out of the box.
I.e., the following centers some text
in a table cell:
<td class="text-center">some text</td>
Look at this:
<script>
function f(a){
alert(typeof(a));
if (a==null) alert('null');
a?alert(true):alert(false);
}
</script>
//return:
<button onclick="f()">nothing</button> //undefined null false
<button onclick="f(null)">null</button> //object null false
<button onclick="f('')">empty</button> //string false
<button onclick="f(0)">zero</button> //number false
<button onclick="f(1)">int</button> //number true
<button onclick="f('x')">str</button> //string true
Either add this to your Activity B
and Activity C
android:noHistory="true"
or Override
onBackPressed
function to avoid back pressing with a return
.
@Override
public void onBackPressed() {
return;
}
garbage collector implies that objects that are no longer needed by the program are "garbage" and can be thrown away.
Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core”
Based on one of your previous questions you're using Tomcat 7. In that case you need JSTL 1.2. However, you've there a jstl.jar
file while JSTL 1.2 has clearly the version number included like so jstl-1.2.jar
. The sole filename jstl.jar
is typical for JSTL 1.0 and 1.1. This version requires a standard.jar
along in /WEB-INF/lib
which contains the necessary TLD files. However, in your particular case the standard.jar
is clearly missing in /WEB-INF/lib
and that's exactly the reason why the taglib URI couldn't be resolved.
To solve this you must remove the wrong JAR file, download jstl-1.2.jar and drop it in its entirety in /WEB-INF/lib
. That's all. You do not need to extract it nor to fiddle in project's Build Path.
Don't forget to remove that loose c.tld
file too. It absolutely doesn't belong there. This is indeed instructed in some poor tutorials or answers elsewhere in the Internet. This is a myth caused by a major misunderstanding and misconfiguration. There is never a need to have a loose JSTL TLD file in the classpath, also not in previous JSTL versions.
In case you're using Maven, use the below coordinate:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
You should also make sure that your web.xml
is declared conform at least Servlet 2.4 and thus not as Servlet 2.3 or older. Otherwise EL expressions inside JSTL tags would in turn fail to work. Pick the highest version matching your target container and make sure that you don't have a <!DOCTYPE>
anywhere in your web.xml
. Here's a Servlet 3.0 (Tomcat 7) compatible example:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Config here. -->
</web-app>
###See also:
new Date().toLocaleTimeString()
You can get data from post response Headers in this way (Angular 6):
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response' as 'response'
};
this.http.post(link,body,httpOptions).subscribe((res: HttpResponse<any>) => {
console.log(res.headers.get('token-key-name'));
})
CGRect
Can be simply created using an instance of a CGPoint
or CGSize
, thats given below.
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))
// Or
let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
Or if we want to specify each value in CGFloat
or Double
or Int
, we can use this method.
let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // CGFloat, Double, Int
CGPoint
Can be created like this.
let point = CGPoint(x: 0,y :0) // CGFloat, Double, Int
CGSize
Can be created like this.
let size = CGSize(width: 100, height: 100) // CGFloat, Double, Int
Also size and point with 0 as the values, it can be done like this.
let size = CGSize.zero // width = 0, height = 0
let point = CGPoint.zero // x = 0, y = 0, equal to CGPointZero
let rect = CGRect.zero // equal to CGRectZero
CGRectZero
& CGPointZero
replaced with CGRect.zero
& CGPoint.zero
in Swift 3.0
.
I have written the function to find distance between two coordinates. It will return distance in meter.
function findDistance() {
var R = 6371e3; // R is earth’s radius
var lat1 = 23.18489670753479; // starting point lat
var lat2 = 32.726601; // ending point lat
var lon1 = 72.62524545192719; // starting point lon
var lon2 = 74.857025; // ending point lon
var lat1radians = toRadians(lat1);
var lat2radians = toRadians(lat2);
var latRadians = toRadians(lat2-lat1);
var lonRadians = toRadians(lon2-lon1);
var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
Math.cos(lat1radians) * Math.cos(lat2radians) *
Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
console.log(d)
}
function toRadians(val){
var PI = 3.1415926535;
return val / 180.0 * PI;
}
Possibly close related code of Pascal
@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
public enum Right {
READ(100), WRITE(200), EDITOR(300);
private Integer value;
private Right(Integer value) {
this.value = value;
}
// Reverse lookup Right for getting a Key from it's values
private static final Map<Integer, Right> lookup = new HashMap<Integer, Right>();
static {
for (Right item : Right.values())
lookup.put(item.getValue(), item);
}
public Integer getValue() {
return value;
}
public static Right getKey(Integer value) {
return lookup.get(value);
}
};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
@Column(name = "RIGHT_ID")
private Integer rightId;
public Right getRight() {
return Right.getKey(this.rightId);
}
public void setRight(Right right) {
this.rightId = right.getValue();
}
}
Yeah. Just put the $ sign in front of your desired constant cell.
Like $A6 if you wish to just change the number 6 serially and keep a constant, or $A$6 if you do not want anything from that reference to change at all.
Example: Cell A5 contains my exchange rate. In B1 you put say ( = C1 * $A$1). when you fill B1 through B....... the value in A5 remains constant and the value in C1 increases serially.
I am by far not be good at teacher, but I hope this helps!!!! Wink wink
You have 2 choices as far as I know:
PHPExcel uses Spreadsheet_Excel_Reader for the Office 2003 format.
Update: I once had to read some Excel files but I used the Office 2003 XML format in order to read them and told the people that were using the application to save and upload only that type of Excel file.
if you want capitalize each word from string (in progress -> In Progress), you can use array like this.
.filter('capitalize', function() {
return function(input) {
return (!!input) ? input.split(' ').map(function(wrd){return wrd.charAt(0).toUpperCase() + wrd.substr(1).toLowerCase();}).join(' ') : '';
}
});
import static java.util.Comparator.naturalOrder;
...
list.stream()
.map(User::getDate)
.max(naturalOrder())
.orElse(null) // replace with .orElseThrow() is the list cannot be empty
It appears to be a bug in React native that shadowOpacity
is set to type CGFloat
instead of float
according to CALayer doc. use iPhone 5 simulator before it's fixed. (CGFloat
is float
in older devices. )
The React Native issue which is tracking this is:
Just put a pair of double quotes around your file name like this:
this.Response.AddHeader("Content-disposition", $"attachment; filename=\"{outputFileName}\"");
/**
This Program will display the given number in words from 0 to 999999999
@author Manoj Kumar Dunna
Mail Id : [email protected]
**/
import java.util.Scanner;
class NumberToString
{
public enum hundreds {OneHundred, TwoHundred, ThreeHundred, FourHundred, FiveHundred, SixHundred, SevenHundred, EightHundred, NineHundred}
public enum tens {Twenty, Thirty, Forty, Fifty, Sixty, Seventy, Eighty, Ninety}
public enum ones {One, Two, Three, Four, Five, Six, Seven, Eight, Nine}
public enum denom {Thousand, Lakhs, Crores}
public enum splNums { Ten, Eleven, Twelve, Thirteen, Fourteen, Fifteen, Sixteen, Seventeen, Eighteen, Nineteen}
public static String text = "";
public static void main(String[] args)
{
System.out.println("Enter Number to convert into words");
Scanner sc = new Scanner(System.in);
long num = sc.nextInt();
int rem = 0;
int i = 0;
while(num > 0)
{
if(i == 0){
rem = (int) (num % 1000);
printText(rem);
num = num / 1000;
i++;
}
else if(num > 0)
{
rem = (int) (num % 100);
if(rem > 0)
text = denom.values()[i - 1]+ " " + text;
printText(rem);
num = num / 100;
i++;
}
}
if(i > 0)
System.out.println(text);
else
System.out.println("Zero");
}
public static void printText(int num)
{
if(!(num > 9 && num < 19))
{
if(num % 10 > 0)
getOnes(num % 10);
num = num / 10;
if(num % 10 > 0)
getTens(num % 10);
num = num / 10;
if(num > 0)
getHundreds(num);
}
else
{
getSplNums(num % 10);
}
}
public static void getSplNums(int num)
{
text = splNums.values()[num]+ " " + text;
}
public static void getHundreds(int num)
{
text = hundreds.values()[num - 1]+ " " + text;
}
public static void getTens(int num)
{
text = tens.values()[num - 2]+ " " + text;
}
public static void getOnes(int num)
{
text = ones.values()[num - 1]+ " " + text;
}
}
Interestingly array is randomly accessible by the index. And removing randomly an element may impact the indexes of other elements as well.
int remove_element(int*from, int total, int index) {
if((total - index - 1) > 0) {
memmove(from+i, from+i+1, sizeof(int)*(total-index-1));
}
return total-1; // return the new array size
}
Note that memcpy
will not work in this case because of the overlapping memory.
One of the efficient way (better than memory move) to remove one random element is swapping with the last element.
int remove_element(int*from, int total, int index) {
if(index != (total-1))
from[index] = from[total-1];
return total; // **DO NOT DECREASE** the total here
}
But the order is changed after the removal.
Again if the removal is done in loop operation then the reordering may impact processing. Memory move is one expensive alternative to keep the order while removing an array element. Another of the way to keep the order while in a loop is to defer the removal. It can be done by validity array of the same size.
int remove_element(int*from, int total, int*is_valid, int index) {
is_valid[index] = 0;
return total-1; // return the number of elements
}
It will create a sparse array. Finally, the sparse array can be made compact(that contains no two valid elements that contain invalid element between them) by doing some reordering.
int sparse_to_compact(int*arr, int total, int*is_valid) {
int i = 0;
int last = total - 1;
// trim the last invalid elements
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements from last
// now we keep swapping the invalid with last valid element
for(i=0; i < last; i++) {
if(is_valid[i])
continue;
arr[i] = arr[last]; // swap invalid with the last valid
last--;
for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements
}
return last+1; // return the compact length of the array
}
Concurrent signal assignment:
library ieee;
use ieee.std_logic_1164.all;
entity foo is
end;
architecture behave of foo is
signal clk: std_logic := '0';
begin
CLOCK:
clk <= '1' after 0.5 ns when clk = '0' else
'0' after 0.5 ns when clk = '1';
end;
ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw
Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.
if you want to execute ENABLE TRIGGER Directly From Source :
we can't write like this:
Conn.Execute "ENABLE TRIGGER trigger_name ON table_name"
instead, we can write :
Conn.Execute "ALTER TABLE table_name DISABLE TRIGGER trigger_name"
In SQL Server 2008 or above I use the following query to find all the dependant stored procedures, user defined functions, triggers, etc. for a given table:
SELECT
coalesce(Referenced_server_name+'.','')+ --possible server name if cross-server
coalesce(referenced_database_name+'.','')+ --possible database name if cross-database
coalesce(referenced_schema_name+'.','')+ --likely schema name
coalesce(referenced_entity_name,'') + --very likely entity name
coalesce('.'+col_name(referenced_ID,referenced_minor_id),'')AS [referencing],
coalesce(object_schema_name(Referencing_ID)+'.','')+ --likely schema name
object_name(Referencing_ID)+ --definite entity name
coalesce('.'+col_name(referencing_ID,referencing_minor_id),'') AS [referenced]
FROM sys.sql_expression_dependencies
WHERE referenced_id =object_id('Table_name')
ORDER BY [referenced]
In Kotlin 1.2 simply call:
invalidateOptionsMenu()
and the onCreateOptionsMenu
function will be called again.
There are codes for other space characters, and the codes as such work well, but the characters themselves are legacy character. They have been included into character sets only due to their presence in existing character data, rather than for use in new documents. For some combinations of font and browser version, they may cause a generic glyph of unrepresentable character to be shown. For details, check my page about Unicode spaces.
So using CSS is safer and lets you specify any desired amount of spacing, not just the specific widths of fixed-width spaces. If you just want to have added spacing around your h2 elements, as it seems to me, then setting padding on those elements (changing the value of the padding: 0 settings that you already have) should work fine.
private List<DataValue> datavalue=new ArrayList<Datavalue>;
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
datavalue.remove(position);
notifyDataSetChanged();
}
});
}
}
Based on the other answers to this question, I've implemented a new approach using bcrypt.
If I understand correctly, the argument to use bcrypt
over SHA512
is that bcrypt
is designed to be slow. bcrypt
also has an option to adjust how slow you want it to be when generating the hashed password for the first time:
# The '12' is the number that dictates the 'slowness'
bcrypt.hashpw(password, bcrypt.gensalt( 12 ))
Slow is desirable because if a malicious party gets their hands on the table containing hashed passwords, then it is much more difficult to brute force them.
def get_hashed_password(plain_text_password):
# Hash a password for the first time
# (Using bcrypt, the salt is saved into the hash itself)
return bcrypt.hashpw(plain_text_password, bcrypt.gensalt())
def check_password(plain_text_password, hashed_password):
# Check hashed password. Using bcrypt, the salt is saved into the hash itself
return bcrypt.checkpw(plain_text_password, hashed_password)
I was able to install the library pretty easily in a linux system using:
pip install py-bcrypt
However, I had more trouble installing it on my windows systems. It appears to need a patch. See this Stack Overflow question: py-bcrypt installing on win 7 64bit python
You can use a HybridDictionary which automaticly detects the breaking point, and accepts null-values, making it essentialy the same as a HashSet.
public static void main(String[] args)
{
int [] [] ar=
{
{12,33,23},
{34,56,75},
{14,76,89},
{45,87,20}
};
I prefer using enhanced loop in Java
Since our ar
is an array of array [2D]. So, when you iterate over it, you will first get an array, and then you can iterate over that array
to get individual elements.
for(int[] num: ar)
{
for(int ele : num)
{
System.out.print(" " +ele);
}
System.out.println(" " );
}
}
I think the answers are below
List<string> aa = (from char c in source
select c.ToString() ).ToList();
List<string> aa2 = (from char c1 in source
from char c2 in source
select string.Concat(c1, ".", c2)).ToList();
A little shorter would be:
List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);
Third times the charm. My guess is that this is a bug and Zhenya's answer suggests it's fixed in the latest version. I have version 0.99.1.1 and I've created the following solution:
import matplotlib.pyplot as plt
import numpy as np
def forceAspect(ax,aspect=1):
im = ax.get_images()
extent = im[0].get_extent()
ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)
data = np.random.rand(10,20)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_xlabel('xlabel')
ax.set_aspect(2)
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')
forceAspect(ax,aspect=1)
fig.savefig('force.png')
This is 'force.png':
Below are my unsuccessful, yet hopefully informative attempts.
Second Answer:
My 'original answer' below is overkill, as it does something similar to axes.set_aspect()
. I think you want to use axes.set_aspect('auto')
. I don't understand why this is the case, but it produces a square image plot for me, for example this script:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10,20)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_aspect('equal')
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')
Produces an image plot with 'equal' aspect ratio: and one with 'auto' aspect ratio:
The code provided below in the 'original answer' provides a starting off point for an explicitly controlled aspect ratio, but it seems to be ignored once an imshow is called.
Original Answer:
Here's an example of a routine that will adjust the subplot parameters so that you get the desired aspect ratio:
import matplotlib.pyplot as plt
def adjustFigAspect(fig,aspect=1):
'''
Adjust the subplot parameters so that the figure has the correct
aspect ratio.
'''
xsize,ysize = fig.get_size_inches()
minsize = min(xsize,ysize)
xlim = .4*minsize/xsize
ylim = .4*minsize/ysize
if aspect < 1:
xlim *= aspect
else:
ylim /= aspect
fig.subplots_adjust(left=.5-xlim,
right=.5+xlim,
bottom=.5-ylim,
top=.5+ylim)
fig = plt.figure()
adjustFigAspect(fig,aspect=.5)
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))
fig.savefig('axAspect.png')
This produces a figure like so:
I can imagine if your having multiple subplots within the figure, you would want to include the number of y and x subplots as keyword parameters (defaulting to 1 each) to the routine provided. Then using those numbers and the hspace
and wspace
keywords, you can make all the subplots have the correct aspect ratio.
What is a
when you call Ancestors('A',a)
? If a['A']
is None, or if a['A'][0]
is None, you'd receive that exception.
If you have a lot of files and you don't want to use the elegant shopt -s nullglob
and bash array solution, you can use find and so on as long as you don't print out the file name (which might contain newlines).
find -maxdepth 1 -name "log*" -not -name ".*" -printf '%i\n' | wc -l
This will find all files that match log* and that don't start with .*
— The "not name .*" is redunant, but it's important to note that the default for "ls" is to not show dot-files, but the default for find is to include them.
This is a correct answer, and handles any type of file name you can throw at it, because the file name is never passed around between commands.
But, the shopt nullglob
answer is the best answer!
try
<select onchange="location=this.value">_x000D_
<option value="unit_01.htm">Unit 1</option>_x000D_
<option value="#5.2" selected >Bookmark 2</option>_x000D_
</select>
_x000D_
If the insertion point of the new object does not need to match the previous object's index then the simplest way to do this with lodash is by using _.reject
and then pushing new values in to the array:
var arr = [
{ id: 1, name: "Person 1" },
{ id: 2, name: "Person 2" }
];
arr = _.reject(arr, { id: 1 });
arr.push({ id: 1, name: "New Val" });
// result will be: [{ id: 2, name: "Person 2" }, { id: 1, name: "New Val" }]
If you have multiple values that you want to replace in one pass, you can do the following (written in non-ES6 format):
var arr = [
{ id: 1, name: "Person 1" },
{ id: 2, name: "Person 2" },
{ id: 3, name: "Person 3" }
];
idsToReplace = [2, 3];
arr = _.reject(arr, function(o) { return idsToReplace.indexOf(o.id) > -1; });
arr.push({ id: 3, name: "New Person 3" });
arr.push({ id: 2, name: "New Person 2" });
// result will be: [{ id: 1, name: "Person 1" }, { id: 3, name: "New Person 3" }, { id: 2, name: "New Person 2" }]
My answer is basically the same as @pi-k. In my case my program worked locally but failed to build on QA servers. (I suspect devops had older versions of the package blocked and my version must have been too out-of-date) I just decided to upgrade everything
$ pip install pip-review
$ pip-review --local --interactive
You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:
a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }
Also you can make some cool effects this way:
a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }
Hope it helps.
Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue
Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.
The OP always wants two decimal places displayed, so explicitly calling a formatting function, as all the other answers have done, is not good enough.
As others have already pointed out, Decimal
works well for currency. But Decimal
shows all the decimal places. So, override its display formatter:
class D(decimal.Decimal):
def __str__(self):
return f'{self:.2f}'
Usage:
>>> cash = D(300000.991)
>>> print(cash)
300000.99
Simple.
With just one column of data in each to compare a PivotTable may provide much more information. In the image below ColumnA is in Sheet1 (with a copy in Sheet2 for the sake of the image) and ColumnC in Sheet2. In each sheet a source flag has been added (Columns B and D in the image). The PT has been created with multiple consolidation ranges (Sheet1!$A$1:$B$15
and Sheet2!$C$1:$D$10
):
The left hand numeric column shows what is present in Sheet1 (including q
twice) and the right what in Sheet2 (again with duplicates – of c
and d
). d-l
are in Sheet1 but not Sheet2 and w
and z
are in Sheet2 (excluding those there just for the image) but not Sheet1. Add display Show grand totals for columns
and control totals would appear.
This may not be what you are looking for, but in the interest of coming at a problem from another angle....
Are these two Java processes that might want to access the same file in the same application? Perhaps you can just filter all access to the file through a single, synchronized method (or, even better, using JSR-166)? That way, you can control access to the file, and perhaps even queue access requests.
Here is some Perl code that tries to work around the limit by creating an inline view and then selecting from it. The statement text is compressed by using rows of twelve items each instead of selecting each item from DUAL individually, then uncompressed by unioning together all columns. UNION or UNION ALL in decompression should make no difference here as it all goes inside an IN which will impose uniqueness before joining against it anyway, but in the compression, UNION ALL is used to prevent a lot of unnecessary comparing. As the data I'm filtering on are all whole numbers, quoting is not an issue.
#
# generate the innards of an IN expression with more than a thousand items
#
use English '-no_match_vars';
sub big_IN_list{
@_ < 13 and return join ', ',@_;
my $padding_required = (12 - (@_ % 12)) % 12;
# get first dozen and make length of @_ an even multiple of 12
my ($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l) = splice @_,0,12, ( ('NULL') x $padding_required );
my @dozens;
local $LIST_SEPARATOR = ', '; # how to join elements within each dozen
while(@_){
push @dozens, "SELECT @{[ splice @_,0,12 ]} FROM DUAL"
};
$LIST_SEPARATOR = "\n union all\n "; # how to join @dozens
return <<"EXP";
WITH t AS (
select $a A, $b B, $c C, $d D, $e E, $f F, $g G, $h H, $i I, $j J, $k K, $l L FROM DUAL
union all
@dozens
)
select A from t union select B from t union select C from t union
select D from t union select E from t union select F from t union
select G from t union select H from t union select I from t union
select J from t union select K from t union select L from t
EXP
}
One would use that like so:
my $bases_list_expr = big_IN_list(list_your_bases());
$dbh->do(<<"UPDATE");
update bases_table set belong_to = 'us'
where id in ($bases_list_expr)
UPDATE
You can use recursion in lambdas and defaultdict, no need to define names:
a = defaultdict((lambda f: f(f))(lambda g: lambda:defaultdict(g(g))))
Here's an example:
>>> a['new jersey']['mercer county']['plumbers']=3
>>> a['new jersey']['middlesex county']['programmers']=81
>>> a['new jersey']['mercer county']['programmers']=81
>>> a['new jersey']['middlesex county']['salesmen']=62
>>> a
defaultdict(<function __main__.<lambda>>,
{'new jersey': defaultdict(<function __main__.<lambda>>,
{'mercer county': defaultdict(<function __main__.<lambda>>,
{'plumbers': 3, 'programmers': 81}),
'middlesex county': defaultdict(<function __main__.<lambda>>,
{'programmers': 81, 'salesmen': 62})})})
You can run your Python code using sl4a. sl4a supports Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell script.
You can learn sl4a Python Examples.
I faced the same issue while trying to build a jar file of my project application using mvn clean install
, though the application was working fine while running from Eclipse.
The issue was, indeed too naive, that I had not set the JAVA_HOME environment variable. All I had to do is set JAVA_HOME environment variable to JDK directory, make sure it is not till "\bin" and without semi-colon ";".
How I understood it is as:
The application worked fine in Eclipse as JRE System Library was referring to JRE inside the JDK folder instead of external JRE folder without JDK. [As explained very well in other answers]
This configuration does not apply to maven command that we run on command prompt. It will still look for JAVA_HOME variable to access the JRE System library and when it is not found it refers to external JRE folder without JDK.
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
I wish AngularJS had a built in confirmation dialog. Often, it is nicer to have a customized dialog than using the built in browser one.
I briefly used the twitter bootstrap until it was discontinued with version 6. I looked around for alternatives, but the ones I found were complicated. I decided to try the JQuery UI one.
Here is my sample that I call when I am about to remove something from ng-grid;
// Define the Dialog and its properties.
$("<div>Are you sure?</div>").dialog({
resizable: false,
modal: true,
title: "Modal",
height: 150,
width: 400,
buttons: {
"Yes": function () {
$(this).dialog('close');
//proceed with delete...
/*commented out but left in to show how I am using it in angular
var index = $scope.myData.indexOf(row.entity);
$http['delete']('/EPContacts.svc/json/' + $scope.myData[row.rowIndex].RecordID).success(function () { console.log("groovy baby"); });
$scope.gridOptions.selectItem(index, false);
$scope.myData.splice(index, 1);
*/
},
"No": function () {
$(this).dialog('close');
return;
}
}
});
I hope this helps someone. I was pulling my hair out when I needed to upgrade ui-bootstrap-tpls.js but it broke my existing dialog. I came into work this morning, tried a few things and then realized I was over complicating.
Try:
printf("%04x",a);
0
- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4
(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x
- Specifier for hexadecimal
integer.More here
As mentioned in comments, this is a scoping issue. Specifically, $con
is not in scope within your getPosts
function.
You should pass your connection object in as a dependency, eg
function getPosts(mysqli $con) {
// etc
I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
getPosts($con);
Simple method:
public static boolean isBlank(String value) {
return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
Here is example to draw stroke circle canvas
val paint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = 10f
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(200f, 100f, 100f, paint)
}
Result
Example to draw solid circle canvas
val paint = Paint().apply {
color = Color.RED
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(200f, 100f, 100f, paint)
}
Result
Hope it help
You should not use "width" and "height" attributes directly, use the style attribute like style="some css here"
if you want to use inline styling:
<div class="button" style="width:60px;height:30px;">This is a button</div>
Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:
.button {_x000D_
background-color: #000000;_x000D_
color: #FFFFFF;_x000D_
padding: 10px;_x000D_
border-radius: 10px;_x000D_
-moz-border-radius: 10px;_x000D_
-webkit-border-radius: 10px;_x000D_
margin:10px_x000D_
}_x000D_
_x000D_
.small-btn {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
}_x000D_
_x000D_
.medium-btn {_x000D_
width: 70px;_x000D_
height: 30px;_x000D_
}_x000D_
_x000D_
.big-btn {_x000D_
width: 90px;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="button big-btn">This is a big button</div>_x000D_
<div class="button medium-btn">This is a medium button</div>_x000D_
<div class="button small-btn">This is a small button</div>_x000D_
_x000D_
Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.
If you want to call functions on components from outside React, you can call them on the return value of renderComponent:
var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();
The only way to get a handle to a React Component instance outside of React is by storing the return value of React.renderComponent. Source.
Node.js Tools for Visual Studio 2012 or 2013 includes a debugger. The overview here states "Node.js Tools for Visual Studio includes complete support for debugging node apps.". Being new to Node.js, but having a background in .NET, I've found this add in to be a great way to debug Node.js applications.
I've resolved this issue by inferring the produced return type into the first GET requestMethod. The important part here is the
produces="application/json;charset=UTF-8
So every one how use /account/**, Spring will return application/json;charset=UTF-8 content type.
@Controller
@Scope("session")
@RequestMapping(value={"/account"}, method = RequestMethod.GET,produces="application/json;charset=UTF-8")
public class AccountController {
protected final Log logger = LogFactory.getLog(getClass());
....//More parameters and method here...
@RequestMapping(value={"/getLast"}, method = RequestMethod.GET)
public @ResponseBody String getUltimo(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{
ObjectWriter writer = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
Account account = accountDao.getLast();
return writer.writeValueAsString(account);
}
catch (Exception e) {
return errorHandler(e, response, writer);
}
}
So, you do not have to set up for each method in your Controller, you can do it for the entire class. If you need more control over a specific method, you just only have to infer the produces return content type.
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
This overloaded version of the save function works for me:
yourDF.save(outputPath, org.apache.spark.sql.SaveMode.valueOf("Overwrite"))
The example above would overwrite an existing folder. The savemode can take these parameters as well (https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/SaveMode.html):
Append: Append mode means that when saving a DataFrame to a data source, if data/table already exists, contents of the DataFrame are expected to be appended to existing data.
ErrorIfExists: ErrorIfExists mode means that when saving a DataFrame to a data source, if data already exists, an exception is expected to be thrown.
Ignore: Ignore mode means that when saving a DataFrame to a data source, if data already exists, the save operation is expected to not save the contents of the DataFrame and to not change the existing data.
With Javascript/Jquery:
img
div
and set width, height and backgroundremove the original img
$(document).ready(function() {
var image = $("<img>");
var div = $("<div>")
image.load(function() {
div.css({
"width": this.width,
"height": this.height,
"background-image": "url(" + this.src + ")"
});
$("#container").append(div);
});
image.attr("src", "test0.png");
});
private static Date truncateTime(Calendar cal) {
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new Date(cal.getTime().getTime());
}
public static void main(String[] args) throws Exception{
Date d2 = new Date();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d2);
Date d1 = truncateTime( cal );
System.out.println(d1.toString());
System.out.println(d2.toString());
}
Many devices with different screen sizes/ratios/resolutions have come out even in the last five years, including new types of iPhones and iPads. It would be very difficult to customize a website for each device.
Meanwhile, media queries for device-width
, device-height
, and device-aspect-ratio
have been deprecated, so they may not work in future browser versions. (Source: MDN)
TLDR: Design based on browser widths, not devices. Here's a good introduction to this topic.
Actually, For the first build, please do it with Xcode and then do the following way:
brew install ios-deploy
npx react-native run-ios --device
The second command will run the app on the first connected device.
Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):
AttributeError: 'URLError' object has no attribute 'code'
Fast, but maybe not the best solution would be code using nested try/except block:
import urllib2
try:
urllib2.urlopen("some url")
except urllib2.HTTPError, err:
try:
if err.code == 404:
# Handle the error
else:
raise
except:
...
More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?
Is it possible that this is an error avoidance technique (advisable or not..)? Since "" is still a string, you would be able to call string functions on it that would result in an exception if it was NULL?
Add to your activity manifest information with attribute
android:launchMode="singleTask"
is working well for me
If you use WinForms:
Use the AppendText(myTxt)
method on the TextBox
instead (.net 3.5+):
private void button1_Click(object sender, EventArgs e)
{
string sent = chatBox.Text;
displayBox.AppendText(sent);
displayBox.AppendText(Environment.NewLine);
}
Text in itself has typically a low memory footprint (you can say a lot within f.ex. 10kb which is "nothing"). The TextBox does not render all text that is in the buffer, only the visible part so you don't need to worry too much about lag. The slower operations are inserting text. Appending text is relatively fast.
If you need a more complex handling of the content you can use StringBuilder
combined with the textbox. This will give you a very efficient way of handling text.
Take a look at the .classpath file in your project, which probably contains most of the information that you want. The easiest option may be to roll your own "build.xml export", i.e. process .classpath into a new build.xml during the build itself, and then call it with an ant subtask.
Parsing a little XML sounds much easier to me than to hook into Eclipse JDT.
I tried solutions from other threads. Adding M2 and M2_HOME at System variables, and even at User variables. Running cmd as admin. None of the methods worked.
But today I added entire path to maven bin to my System variables "PATH" (C:\Program Files (x86)\Apache Software Foundation\apache-maven-3.1.0\bin) besides other paths, and so far it's working good. Hopefully it'll stay that way.
I had a similar use case, except I wanted to checkout only the commit for a tag and prune the directories. Using --depth 1
makes it really sparse and can really speed things up.
mkdir myrepo
cd myrepo
git init
git config core.sparseCheckout true
git remote add origin <url> # Note: no -f option
echo "path/within_repo/to/subdir/" > .git/info/sparse-checkout
git fetch --depth 1 origin tag <tagname>
git checkout <tagname>
open Developer command prompt as Admin and navigate to
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Now use path where is your .exe
there
InstallUtil "D:\backup\WindowsService\WindowsService1\WindowsService1\obj\Debug\TestService.exe"
Install the extension "Code Runner". Check if you can compile your program with csc
(ex.: csc hello.cs
). The command csc
is shipped with Mono. Then add this to your VS Code user settings:
"code-runner.executorMap": {
"csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
// "csharp": "echo '# calling dotnet run\n' && dotnet run"
}
Open your C# file and use the execution key of Code Runner.
Edit: also added dotnet run
, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console
, dotnet restore
).
lookup only works on localhost. If you want to retrieve variables from a variables file you made remotely use include_vars: {{ varfile }}
. Contents of {{ varfile }}
should be a dictionary of the form {"key":"value"}
, you will find ansible gives you trouble if you include a space after the colon.
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
Given the specific title of this post, here's my suggestion:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'
The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo
The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.
I'd suggest the following to see the difference "in commits". For symmetric difference, repeat the command with inverted args:
git cherry -v master [your branch, or HEAD as default]
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.
If you're using Intellij on Mac, this setup finally worked for me.
Installations: Intellij
Settings:
Enable Annotation processor
Check if Lombok plugin is enabled
Add Lombok jar in Global Libraries and project dependencies.
File --> Project Structure --> Project Settings --> Modules --> Dependencies Tab = check lombok
Restart Intellij
Try this if your code lies in a form:
Graphics g = this.CreateGraphics();
points = pixels * 72 / g.DpiX;
g.Dispose();
The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?
link_to
can also produce links with anchors or query strings:
link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>
link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
This fixed the issue:
~/.Genymobile/Genymotion/ova
(Either you are on Mac OSX
or Windows, you can find this path by looking for Virtualbox path at
the Genymotion Settings, there is a path to Genymotion/deployed
folder, you should go to Genymotion/ova folder)Guest OS
type set to Other Linux 64
, you should double click and change it to your OS type (e.g Mac OSX El Captain (64-bit)) and Import:
I hope it helps future visitors to this page.
From the WordPress Codex:
<?php
$the_slug = 'my_slug';
$args = array(
'name' => $the_slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if( $my_posts ) :
echo 'ID on the first post found ' . $my_posts[0]->ID;
endif;
?>
Another option is to use Descendant selectors
HTML:
<div class="social">
<p class="first">burrito</p>
<p class="last">chimichanga</p>
</div>
Reference first one in CSS: .social .first { color: blue; }
Reference last one in CSS: .social .last { color: green; }
Jsfiddle: https://jsfiddle.net/covbtpaq/153/
Here's a more Windows-ish solution: Right click on the Windows shortcut that you use to launch git bash, and click Properties. Change the value of "Start In" to your desired workspace path.
Edit: Also check that the Target value does not include the --cd-to-home option as noted in the comments below.
from jinja2 import Template
def custom_function(a):
return a.replace('o', 'ay')
template = Template('Hey, my name is {{ custom_function(first_name) }} {{ func2(last_name) }}')
template.globals['custom_function'] = custom_function
You can also give the function in the fields as per Matroskin's answer
fields = {'first_name': 'Jo', 'last_name': 'Ko', 'func2': custom_function}
print template.render(**fields)
Will output:
Hey, my name is Jay Kay
Works with Jinja2 version 2.7.3
And if you want a decorator to ease defining functions on template.globals
check out Bruno Bronosky's answer
Very good answer, I have created a Golang implementation of the bjf:
package bjf
import (
"math"
"strings"
"strconv"
)
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func Encode(num string) string {
n, _ := strconv.ParseUint(num, 10, 64)
t := make([]byte, 0)
/* Special case */
if n == 0 {
return string(alphabet[0])
}
/* Map */
for n > 0 {
r := n % uint64(len(alphabet))
t = append(t, alphabet[r])
n = n / uint64(len(alphabet))
}
/* Reverse */
for i, j := 0, len(t) - 1; i < j; i, j = i + 1, j - 1 {
t[i], t[j] = t[j], t[i]
}
return string(t)
}
func Decode(token string) int {
r := int(0)
p := float64(len(token)) - 1
for i := 0; i < len(token); i++ {
r += strings.Index(alphabet, string(token[i])) * int(math.Pow(float64(len(alphabet)), p))
p--
}
return r
}
Hosted at github: https://github.com/xor-gate/go-bjf
This works for valid IP addresses:
regex = '^([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])[.]([0-9]|[1-9][0-9]|[1][0-9][0-9]|[2][0-5][0-5])$'
If you declare your callback as mentioned by @lex82 like
callback = "callback(item.id, arg2)"
You can call the callback method in the directive scope with object map and it would do the binding correctly. Like
scope.callback({arg2:"some value"});
without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/
Update: There is a small example of this in the documentation:
& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).
$user = User::where('email', request('email')->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
Look for the official 2.7 setuptools installer (which contains easy_install). You only need to install from sources for windows 64 bits.
I had the same problem when and I solved it by using the following annotation :
@EnableAutoConfiguration(exclude = {
SecurityAutoConfiguration.class
})
public class Application {...}
I think the behavior is the same as what Abhishek explained
To make Python not return to me "Attempted relative import in non-package". package/
init.py subpackage1/ init.py moduleX.py moduleY.py subpackage2/ init.py moduleZ.py moduleA.py
This error occurs only if you are applying relative import to the parent file. For example parent file already returns main after you code "print(name)" in moduleA.py .so THIS file is already main it cannot return any parent package further on. relative imports are required in files of packages subpackage1 and subpackage2 you can use ".." to refer to the parent directory or module .But parent is if already top level package it cannot go further above that parent directory(package). Such files where you are applying relative importing to parents can only work with the application of absolute import. If you will use ABSOLUTE IMPORT IN PARENT PACKAGE NO ERROR will come as python knows who is at the top level of package even if your file is in subpackages because of the concept of PYTHON PATH which defines the top level of the project
select * into newtable from oldtable
Or.... Call your main .bat file from another .bat file and output the result to a result file i.e.
runner.bat > mainresults.txt
Where runner.bat calls the main .bat file
You should see all the actions performed in the main .bat file now
Small change to sam yi's answer (for better readability):
select top 1000 TableID
into #ControlTable
from dbo.table
where StatusID = 7
declare @TableID int
while exists (select * from #ControlTable)
begin
select @TableID = (select top 1 TableID
from #ControlTable
order by TableID asc)
-- Do something with your TableID
delete #ControlTable
where TableID = @TableID
end
drop table #ControlTable
Doesn't the Directory.GetFiles(String, String)
overload already do that? You would just do Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)
If you want to put them in a list, then just replace the "*.jpg"
with a variable that iterates over a list and aggregate the results into an overall result set. Much clearer than individually specifying them. =)
Something like...
foreach(String fileExtension in extensionList){
foreach(String file in Directory.GetFiles(dir, fileExtension, SearchOption.AllDirectories)){
allFiles.Add(file);
}
}
(If your directories are large, using EnumerateFiles
instead of GetFiles
can potentially be more efficient)
Something like this might help:
SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=
The important part is the first line. It takes the output of the internal DATE
value and parses it into an environmental variable named Today
, in the format CCYYMMDD
, as in '20110407`.
The %Date:~10,4%
says to extract a *substring of the Date
environmental variable 'Thu 04/07/2011' (built in - type echo %Date%
at a command prompt) starting at position 10 for 4 characters (2011
). It then concatenates another substring of Date:
starting at position 4 for 2 chars (04
), and then concats two additional characters starting at position 7 (07
).
*The substring value starting points are 0-based.
You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.
Use strncpy
e.g.
strncpy(dest, src + beginIndex, endIndex - beginIndex);
This assumes you've
dest
is large enough.endIndex
is greater than beginIndex
beginIndex
is less than strlen(src)
endIndex
is less than strlen(src)
As discussed somewhat in the question comments, this is one way you could do it:
<input ... ng-model="$parent.storeDefault" value="{{location.id}}">
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
I think writing PHP into an .html file is confusing and anti-natural. Why would you do that??
Anyway, if what you want is to execute PHP files and show them as .html in the address bar, an easiest solution would be using .php as normal, and write a rule in your .htaccess like this:
RewriteRule ^([^.]+)\.html$ $1.php [L]
delete them using git-rm
, and then add .DS_Store to .gitignore
to stop them getting added again. You can also use blueharvest to stop them getting created all together
The trick is to