I've figured out what the issue is the namespace is ambigious in the loggerFactory.AddLog4Net(). Here is a brief summary of how I added log4Net to my Asp.Net Core project.
Add the log4net.config file in your root application folder
Open the Startup.cs file and change the Configure method to add log4net support with this line loggerFactory.AddLog4Net
First you have to import the package using Microsoft.Extensions.Logging; using the using statement
Here is the entire method, you have to prefix the ILoggerFactory interface with the namespace
public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { loggerFactory.AddLog4Net(); .... }
You can use the following maven dependency in your pom file. Otherwise, you can download the following two jars from net and add it to your build path.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
This is copied from my working project. First make sure it is working in your project. Then you can change the versions to use any other(versions) compatible jars.
For AggCat, you can refer the POM file of the sample java application.
Thanks
Have you tried adding a configsection
handler to your app.config? e.g.
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
I know this is an old thread but I got a nice solution to you (I think). It's copied from an class of mine, that handles all AJAX stuff.
When the script cannot be loaded, it set an error handler but when the error handler is not supported, it falls back to a timer that checks for errors for 15 seconds.
function jsLoader()
{
var o = this;
// simple unstopable repeat timer, when t=-1 means endless, when function f() returns true it can be stopped
o.timer = function(t, i, d, f, fend, b)
{
if( t == -1 || t > 0 )
{
setTimeout(function() {
b=(f()) ? 1 : 0;
o.timer((b) ? 0 : (t>0) ? --t : t, i+((d) ? d : 0), d, f, fend,b );
}, (b || i < 0) ? 0.1 : i);
}
else if(typeof fend == 'function')
{
setTimeout(fend, 1);
}
};
o.addEvent = function(el, eventName, eventFunc)
{
if(typeof el != 'object')
{
return false;
}
if(el.addEventListener)
{
el.addEventListener (eventName, eventFunc, false);
return true;
}
if(el.attachEvent)
{
el.attachEvent("on" + eventName, eventFunc);
return true;
}
return false;
};
// add script to dom
o.require = function(s, delay, baSync, fCallback, fErr)
{
var oo = document.createElement('script'),
oHead = document.getElementsByTagName('head')[0];
if(!oHead)
{
return false;
}
setTimeout( function() {
var f = (typeof fCallback == 'function') ? fCallback : function(){};
fErr = (typeof fErr == 'function') ? fErr : function(){
alert('require: Cannot load resource -'+s);
},
fe = function(){
if(!oo.__es)
{
oo.__es = true;
oo.id = 'failed';
fErr(oo);
}
};
oo.onload = function() {
oo.id = 'loaded';
f(oo);
};
oo.type = 'text/javascript';
oo.async = (typeof baSync == 'boolean') ? baSync : false;
oo.charset = 'utf-8';
o.__es = false;
o.addEvent( oo, 'error', fe ); // when supported
// when error event is not supported fall back to timer
o.timer(15, 1000, 0, function() {
return (oo.id == 'loaded');
}, function(){
if(oo.id != 'loaded'){
fe();
}
});
oo.src = s;
setTimeout(function() {
try{
oHead.appendChild(oo);
}catch(e){
fe();
}
},1);
}, (typeof delay == 'number') ? delay : 1);
return true;
};
}
$(document).ready( function()
{
var ol = new jsLoader();
ol.require('myscript.js', 800, true, function(){
alert('loaded');
}, function() {
alert('NOT loaded');
});
});
In Android 5.0 material design guidelines discourage the use of icon in actionBar
to enable it add the following code
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
credit goes to author of this article
You are asking a question about two different things:
Meta
inner class in Django models:
This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.
Short explanation is here: Django docs: Models: Meta options
List of available meta options is here: Django docs: Model Meta options
For latest version of Django: Django docs: Model Meta options
Metaclass in Python:
The best description is here: What are metaclasses in Python?
NSString * path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"jpg"];
UIImage * img = [[UIImage alloc]initWithContentsOfFile:path];
CGImageRef image = [img CGImage];
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(image));
const unsigned char * buffer = CFDataGetBytePtr(data);
All of todays browsers use at least version 1.5
:
http://en.wikipedia.org/wiki/ECMAScript#Dialect
Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide
You may still want to watch out for features which require version 1.6
or above, as this might give Internet Explorer some troubles.
Try this it works
<ul class="sub-menu" type="none">
<li class="sub-menu-list" ng-repeat="menu in list.components">
<a class="sub-menu-link">
{{ menu.component }}
</a>
</li>
</ul>
Came across this issue after I merged a pull request on Bitbucket.
Had to do
git fetch
and that was it.
myapp.h
{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;
myapp.m
@synthesize myButton;
-(IBAction)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}
The Ookii Dialogs for WPF library has a class that provides an implementation of a folder browser dialog for WPF.
There's also a version that works with Windows Forms.
I would do it this this way:
Stage all unstaged changes.
git add .
Stash the changes.
git stash save
Sync with remote.
git pull -r
Reapply the local changes.
git stash pop
or
git stash apply
I could never get $viewContentLoaded
to work for me, and ng-init
should really only be used in an ng-repeat
(according to the documentation), and also calling a function directly in a controller can cause errors if the code relies on an element that hasn't been defined yet.
This is what I do and it works for me:
$scope.$on('$routeChangeSuccess', function () {
// do something
});
Unless you're using ui-router
. Then it's:
$scope.$on('$stateChangeSuccess', function () {
// do something
});
I have found... margin: 0 auto; works for me. But I have also seen it NOT work due to the class being trumped by another specificity that had ... float:left; so watch for that you may need to add ... float:none; this worked in my case as I was coding a media query.
Just put the html tags with there content and add the xmlns attribute with quotes after the equals and in between the quotes is http://www.w3.org/1999/xhtml
Two steps works fine:
create table bu_x as (select a,b,c,d from x ) WITH no data;
insert into bu_x (a,b,c,d) select select a,b,c,d from x ;
I just found an elegant way:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/?????/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
Use either of the Map
implementations bundled with Java 6 and later that implement NavigableMap
(the successor to SortedMap
):
TreeMap
if running single-threaded, or if the map is to be read-only across threads after first being populated. ConcurrentSkipListMap
if manipulating the map across threads.NavigableMap
FYI, the SortedMap
interface was succeeded by the NavigableMap
interface.
You would only need to use SortedMap
if using 3rd-party implementations that have not yet declared their support of NavigableMap
. Of the maps bundled with Java, both of the implementations that implement SortedMap
also implement NavigableMap
.
s SortedMap the best answer? TreeMap?
As others mentioned, SortedMap
is an interface while TreeMap
is one of multiple implementations of that interface (and of the more recent NavigableMap
.
Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.
NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ;
currentAssignments.put( bob , setUpNewVendorsProject ) ;
This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:
NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;
…and the rest of your code using that map continues to work.
There are ten implementations of Map
bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.
Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap
keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap
remembers original insertion order.
I cross over the same problem
I put the following code in the folder ~/.gvimrc
and it works.
set guifont=Monaco:h20
I had the same problem while trying to consume net.tcp wcf service endpoint in a http asmx service.
As I saw no one wrote specific answer WHY is this problem occurring, but only how to be handled properly.
I've been struggling with it several days in a row and finally I found out where the problem comes from in my case.
Initially I thought that when you make a reference to a service the config file will be configured regarding security tag the same way as it's in the source, but that was not the case and I should take care of it manually. In my case I had only
<netTcpBinding>
<binding name="NetTcpBinding_IAuthenticationLoggerService"
</binding>
</netTcpBinding>`
Later I saw that the security part is missing and it should looks like this
<netTcpBinding>
<binding name="NetTcpBinding_IAuthenticationLoggerService" transferMode="Buffered">
<security mode="None">
<transport clientCredentialType="None"/>
</security>
</binding>
</netTcpBinding>
The second problem in my case was that I was using transferMode="Streamed"
on my source WCF service and in the client I had nothing specific about it, which was bad, because the default transferMode
is Buffered
and it's important on both places source and client to be configured in the same way.
To answer your question as I understand it: Why use C#? (You say you're already sold on F#.)
First off. It's not just "functional versus OO". It's "Functional+OO versus OO". C#'s functional features are pretty rudimentary. F#'s are not. Meanwhile, F# does almost all of C#'s OO features. For the most part, F# ends up as a superset of C#'s functionality.
However, there are a few cases where F# might not be the best choice:
Interop. There are plenty of libraries that just aren't going to be too comfortable from F#. Maybe they exploit certain C# OO things that F# doesn't do the same, or perhaps they rely on internals of the C# compiler. For example, Expression. While you can easily turn an F# quotation into an Expression, the result is not always exactly what C# would create. Certain libraries have a problem with this.
Yes, interop is a pretty big net and can result in a bit of friction with some libraries.
I consider interop to also include if you have a large existing codebase. It might not make sense to just start writing parts in F#.
Design tools. F# doesn't have any. Does not mean it couldn't have any, but just right now you can't whip up a WinForms app with F# codebehind. Even where it is supported, like in ASPX pages, you don't currently get IntelliSense. So, you need to carefully consider where your boundaries will be for generated code. On a really tiny project that almost exclusively uses the various designers, it might not be worth it to use F# for the "glue" or logic. On larger projects, this might become less of an issue.
This isn't an intrinsic problem. Unlike the Rex M's answer, I don't see anything intrinsic about C# or F# that make them better to do a UI with lots of mutable fields. Maybe he was referring to the extra overhead of having to write "mutable" and using <- instead of =.
Also depends on the library/designer used. We love using ASP.NET MVC with F# for all the controllers, then a C# web project to get the ASPX designers. We mix the actual ASPX "code inline" between C# and F#, depending on what we need on that page. (IntelliSense versus F# types.)
Other tools. They might just be expecting C# only and not know how to deal with F# projects or compiled code. Also, F#'s libraries don't ship as part of .NET, so you have a bit extra to ship around.
But the number one issue? People. If none of your developers want to learn F#, or worse, have severe difficulty comprehending certain aspects, then you're probably toast. (Although, I'd argue you're toast anyways in that case.) Oh, and if management says no, that might be an issue.
I wrote about this a while ago: Why NOT F#?
In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:
Install ThinBackup on both the source and the target Jenkins servers
Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)
On the source Jenkins, go to ThinBackup ? Backup Now
Copy from Jenkins source backup directory to the Jenkins target backup directory
On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.
If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.
If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity>
to false, and restart Jenkins.
Did you set the section header height in the viewDidLoad?
self.tableView.sectionHeaderHeight = 70
Plus you should replace
self.view.addSubview(view)
by
view.addSubview(label)
Finally you have to check your frames
let view = UIView(frame: CGRect.zeroRect)
and eventually the desired text color as it seems to be currently white on white.
You can use window.location
window.location="/newpage.php";
Or you can just make the form that the search button is in have a action of the page you want.
double *ptr = malloc(sizeof(double *) * TIME); /* ... */ for(tcount = 0; tcount <= TIME; tcount++) ^^
<=
to <
or alloc
SIZE + 1
elementsmalloc
is wrong, you'll want sizeof(double)
instead of
sizeof(double *)
ouah
comments, although not directly linked to your corruption problem, you're using *(ptr+tcount)
without initializing itptr[tcount]
instead of *(ptr + tcount)
malloc
+ free
since you already know SIZE
Other option using apache-commons:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
...
File file = new File( "path" );
byte[] bytes = Base64.decodeBase64( "base64" );
FileUtils.writeByteArrayToFile( file, bytes );
You can get the spark version by using the following command:
spark-submit --version
spark-shell --version
spark-sql --version
You can visit the below site to know the spark-version used in CDH 5.7.0
For Excel 2011 on Mac it's different. I did it as a three step process.
=B1
. For the next row to row N, the formula is =Concatenate(",",A2)
. You end up with: QA ,Sekuli ,Testing ,Applitools ,Visual Testing ,Test Automation ,Selenium
=B1
. For all other rows to N, the formula is =Concatenate(C1,B2)
. And you get:QA,Sekuli QA,Sekuli,Testing QA,Sekuli,Testing,Applitools QA,Sekuli,Testing,Applitools,Visual Testing QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation,Selenium
The last cell of the list will be what you want. This is compatible with Excel on Windows or Mac.
What about the Activity.finish()
method (quoting) :
Call this when your activity is done and should be closed.
I don't know MSSQL but would it not be:
alter table company drop **constraint** Company_CountryID_FK;
You might use Form
tag with action attribute to submit the mailto
.
Here is an example:
<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" />
</form>
What's the default superuser username/password for postgres after a new install?:
CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!
This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.
What you should do is follow Chris James's answer:
sudo -u postgres psql postgres # \password postgres Enter new password:
To explain it a little bit...
If anyone in the need for an answer,
I used this library: http://connect2id.com/products/nimbus-jose-jwt Maven here: http://mvnrepository.com/artifact/com.nimbusds/nimbus-jose-jwt/2.10.1
okay, here is my favorite xml way of doing it. I do this for the eclipse version so I can
and for some reason SO is not showing this all properly but most seems to be there...
<configuration scan="true" scanPeriod="30 seconds">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.GEventEvaluator">
<expression>
e.level.toInt() <= INFO.toInt()
</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<encoder>
<pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
</encoder>
</appender>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>warn</level>
</filter>
<encoder>
<pattern>%date{ISO8601} %X{sessionid}-%X{user} %caller{1} %-4level: %message%n</pattern>
</encoder>
<target>System.err</target>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="STDOUT"/>
<appender-ref ref="STDERR"/>
</root>
</configuration>
just set position: fixed
to the footer element (instead of relative)
Note that you may need to also set a margin-bottom
to the main
element at least equal to the height of the footer element (e.g. margin-bottom: 1.5em;
) otherwise, in some circustances, the bottom area of the main content could be partially overlapped by your footer
For a one time change you can do this:
export EMAIL='[email protected]'; mutt -s "Elvis is dead" [email protected]
I answered a similar question before on how to run a Docker container inside Docker.
To run docker inside docker is definitely possible. The main thing is that you
run
the outer container with extra privileges (starting with--privileged=true
) and then install docker in that container.Check this blog post for more info: Docker-in-Docker.
One potential use case for this is described in this entry. The blog describes how to build docker containers within a Jenkins docker container.
However, Docker inside Docker it is not the recommended approach to solve this type of problems. Instead, the recommended approach is to create "sibling" containers as described in this post
So, running Docker inside Docker was by many considered as a good type of solution for this type of problems. Now, the trend is to use "sibling" containers instead. See the answer by @predmijat on this page for more info.
Console.log implement process.sdout.write, process.sdout.write is a buffer/stream that will directly output in your console.
According to my puglin serverline : console = new Console(consoleOptions)
you can rewrite Console class with your own readline system.
You can see code source of console.log:
See more :
You can give it a property display block; so it will behave like a div and have its own line
CSS:
.feature_desc {
display: block;
....
}
Another solution is the following:
ISNULL(NULLIF(DATEPART(dw,DateField)-1,0),7)
//My Form
<form id="someform">
<div class="input-group">
<textarea placeholder="Post your Comment Here ..." name="post" class="form-control custom-control" rows="3" style="resize:none"></textarea>
<span class="input-group-addon">
<button type="submit" name="post_comment" class="btn btn-primary">
Post
</button>
</span>
</div>
</form>
//your text area get value to URL
<?php
if(isset($_POST['post_comment']))
{
echo htmlspecialchars($_POST['post']);
}
?>
//print the value using get
echo $_GET['post'];
//url must be like this
http://localhost/blog/home.php?post=asdasdsad&post_comment=
//post value has asdasdsad so it will print to your page
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
Even i faced the same in CentOS 6.8.
yum reinstall xorg*
End your current session and open another session in tool like mobiXterm. Make sure session has X11 forwarding enabled in the tool.
The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:
for item in myItemSet {
...
}
Or, to use the "sorted" method:
let itemsArray = myItemSet.sorted()
It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.
If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:
let itemsArray = myItemSet.map { $0 }
Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:
var itemsArray : [MyObjectType] = []
if let typedSet = myItemSet as? Set<MyObjectType> {
itemsArray = typedSet.map { $0 }
}
try with this code :
Controller:
-----------------------------
$fromdate=date('Y-m-d',strtotime(Input::get('fromdate')));
$todate=date('Y-m-d',strtotime(Input::get('todate')));
$datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To
return view('inventoryreport/inventoryreportview', compact('datas'));
View Page :
@foreach($datas as $student)
{{$student}}
@endforeach
[Link here]
Use jQuery
.In the HTML page -
<button type="button">Click Me</button>
<script>
$(document).ready(function() {
$("button").click(function(){
$.ajax({
url:"php_page.php", //the page containing php script
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
})
</script>
Php page -
echo "Hello";
Below code gives in hh:mm format.
select RIGHT(LEFT(job_end- job_start,17),5)
You can use a reusable sort function.
Array.prototype.order= function(prop, methods = {}) {
let swipe = 1;
if (prop?.constructor == Object) methods = prop;
swipe = methods.reverse ? -1 : 1;
function key(x) {
if (typeof prop == "string")
return methods.insensitive ? String(x[prop]).toLowerCase() : x[prop];
if (methods.insensitive) return String(x).toLowerCase();
return x;
}
this.sort((a, b) => {
if (key(a) < key(b)) return -1 * swipe;
if (key(b) < key(a)) return 1 * swipe;
return 0;
});
return this;
};
Its can be use to sort both Array and Object in array
.
let arr = [6, 2, 4, 1, 5, 3];
let arr2 = [
{ name: "Bar", age: 12 },
{ name: "Nur", age: 18 },
{ name: "foo", age: 30 },
{ name: "bazz", age: 15 }
];
arr.order({ reverse: true }); // [ 6, 5, 4, 3, 2, 1 ]
arr2.order("name", { reverse: 1, insensitive: 0});
let arr3 = [...arr2].order("age"); // new sorted array created from arr2 (But does not change original array)
1nd (optional) > to sort object contain in array.
2rd is method > { reverse: Boolean, insensitive: Boolean }
MVC is just a general design pattern that, in the context of lean web app development, makes it easy for the developer to keep the HTML markup in an app’s presentation layer (the view) separate from the methods that receive and handle client requests (the controllers) and the data representations that are returned within the view (the models). It’s all about separation of concerns, that is, keeping code that serves one functional purpose (e.g. handling client requests) sequestered from code that serves an entirely different functional purpose (e.g. representing data).
It’s the same principle for why anybody who’s spent more than 5 min trying to build a website can appreciate the need to keep your HTML markup, JavaScript, and CSS in separate files: If you just dump all of your code into a single file, you end up with spaghetti that’s virtually un-editable later on.
Since you asked for possible "cons": I’m no authority on software architecture design, but based on my experience developing in MVC, I think it’s also important to point out that following a strict, no-frills MVC design pattern is most useful for 1) lightweight web apps, or 2) as the UI layer of a larger enterprise app. I’m surprised this specification isn’t talked about more, because MVC contains no explicit definitions for your business logic, domain models, or really anything in the data access layer of your app. When I started developing in ASP.NET MVC (i.e. before I knew other software architectures even existed), I would end up with very bloated controllers or even view models chock full of business logic that, had I been working on enterprise applications, would have made it difficult for other devs who were unfamiliar with my code to modify (i.e. more spaghetti).
When nothing else works when it should work, restart ng serve. It's sad to find this kind of bugs.
Currently, i prefer using this methods:
String data = "Date from Register: ";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
// Verify that OS.Version is > API 26 (OREO)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Origin format
LocalDate localDate = LocalDate.parse(capitalModels.get(position).getDataServer(), formatter); // Parse String (from server) to LocalDate
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
//Output format
data = "Data de Registro: "+formatter1.format(localDate); // Output
Toast.makeText(holder.itemView.getContext(), data, Toast.LENGTH_LONG).show();
}else{
//Same resolutions, just use legacy methods to oldest android OS versions.
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd",Locale.getDefault());
try {
Date date = format.parse(capitalModels.get(position).getDataServer());
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
data = "Date from Register: "+formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:
public GoBoard(){
this.linien = 9;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
public GoBoard(int pLinien){
this.linien = pLinien;
}
If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:
// default constructor
public GoBoard(){
this(9); // calls other constructor
}
public GoBoard(int pLinien){
this.linien = pLinien;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,
class GoTest {
private static final int JB_WIDTH = 400;
private static final int JB_HEIGHT = JB_WIDTH;
private static void initGui() {
JFrame frame = new JFrame("GoBoard");
GoBoard jboard = new GoBoard();
jboard.setLayout(new BorderLayout(10, 10));
JPanel holdingPanel = new JPanel(new BorderLayout());
int eb = 20;
holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
holdingPanel.add(jboard, BorderLayout.CENTER);
frame.add(holdingPanel, BorderLayout.CENTER);
jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//!! frame.setSize(400, 400);
frame.pack();
frame.setVisible(true);
}
// .... etc....
You can use anycache to do the job for you. It considers all the details:
pickle
module to handle lambda
and all the nice
python features.Assuming you have a function myfunc
which creates the instance:
from anycache import anycache
class Company(object):
def __init__(self, name, value):
self.name = name
self.value = value
@anycache(cachedir='/path/to/your/cache')
def myfunc(name, value)
return Company(name, value)
Anycache calls myfunc
at the first time and pickles the result to a
file in cachedir
using an unique identifier (depending on the function name and its arguments) as filename.
On any consecutive run, the pickled object is loaded.
If the cachedir
is preserved between python runs, the pickled object is taken from the previous python run.
For any further details see the documentation
You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)
$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
//Process your response
$("#ajaxLoader").hide();
});
If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-
$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
Using blockUI is similar for example with mark up like:-
<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
<p id="result"></p>
</div>
<div id="ajaxLoader" style="display:none">
<h2>Please wait</h2>
<p>I'm getting my AJAX on!</p>
</div>
And using jQuery:-
$(function() {
$("#jsonLink").click(function(e) {
$.post(this.href, function(result) {
$("#resultContainer").fadeIn();
$("#result").text(result.Answer);
}, "json");
return false;
});
$("#ajaxLoader").ajaxStart(function() {
$.blockUI({ message: $("#ajaxLoader") });
})
.ajaxStop(function() {
$.unblockUI();
});
});
This will not give you the first one as javascript objects are unordered, however this is fine in some cases.
myObject[Object.keys(myObject)[0]]
you can use -clean parameter while starting eclipse like
C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean
Here's a one-liner to remove all remote-tracking branches matching a pattern:
git branch -rd $(git branch -a | grep '{pattern}' | cut -d'/' -f2-10 | xargs)
See below for working example with a collection of radio groups each associated with different sections. Your naming scheme is important, but ideally you should try and use a consistent naming scheme for inputs anyway (especially when they're in sections like here).
$('#submit').click(function(){_x000D_
var section = $('input:radio[name="sec_num"]:checked').val();_x000D_
var question = $('input:radio[name="qst_num"]:checked').val();_x000D_
_x000D_
var selectedVal = checkVal(section, question);_x000D_
$('#show_val_div').text(selectedVal);_x000D_
$('#show_val_div').show();_x000D_
});_x000D_
_x000D_
function checkVal(section, question) {_x000D_
var value = $('input:radio[name="sec'+section+'_r'+question+'"]:checked').val() || "Selection Not Made";_x000D_
return value;_x000D_
}
_x000D_
* { margin: 0; }_x000D_
div { margin-bottom: 20px; padding: 10px; }_x000D_
h5, label { display: inline-block; }_x000D_
.small { font-size: 12px; }_x000D_
.hide { display: none; }_x000D_
#formDiv { padding: 10px; border: 1px solid black; }_x000D_
.center { display:block; margin: 0 auto; text-align:center; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="center">_x000D_
<div>_x000D_
<h4>Section 1</h4>_x000D_
_x000D_
<h5>First question text</h5>_x000D_
<label class="small"><input type="radio" name="sec1_r1" value="(1:1) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec1_r1" value="(1:1) NO"> NO</label>_x000D_
<br/>_x000D_
<h5>Second question text</h5>_x000D_
<label class="small"><input type="radio" name="sec1_r2" value="(1:2) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec1_r2" value="(1:2) NO"> NO</label>_x000D_
<br/>_x000D_
<h5>Third Question</h5>_x000D_
<label class="small"><input type="radio" name="sec1_r3" value="(1:3) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec1_r3" value="(1:3) NO"> NO</label>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h4>Section 2</h4>_x000D_
<h5>First question text</h5>_x000D_
<label class="small"><input type="radio" name="sec2_r1" value="(2:1) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec2_r1" value="(2:1) NO"> NO</label>_x000D_
<br/>_x000D_
<h5>Second question text</h5>_x000D_
<label class="small"><input type="radio" name="sec2_r2" value="(2:2) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec2_r2" value="(2:2) NO"> NO</label>_x000D_
<br/>_x000D_
<h5>Third Question</h5>_x000D_
<label class="small"><input type="radio" name="sec2_r3" value="(2:3) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec2_r3" value="(2:3) NO"> NO</label>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h4>Section 3</h4>_x000D_
<h5>First question text</h5>_x000D_
<label class="small"><input type="radio" name="sec3_r1" value="(3:1) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec3_r1" value="(3:1) NO"> NO</label>_x000D_
<br/>_x000D_
<h5>Second question text</h5>_x000D_
<label class="small"><input type="radio" name="sec3_r2" value="(3:2) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec3_r2" value="(3:2) NO"> NO</label>_x000D_
<br/>_x000D_
<h5>Third Question</h5>_x000D_
<label class="small"><input type="radio" name="sec3_r3" value="(3:3) YES"> YES</label>_x000D_
<label class="small"><input type="radio" name="sec3_r3" value="(3:3) NO"> NO</label>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div id="formDiv" class="center">_x000D_
<form target="#show_val_div" method="post">_x000D_
<p>Choose Section Number</p>_x000D_
<label class="small">_x000D_
<input type="radio" name="sec_num" value="1"> 1</label>_x000D_
<label class="small">_x000D_
<input type="radio" name="sec_num" value="2"> 2</label>_x000D_
<label class="small">_x000D_
<input type="radio" name="sec_num" value="3"> 3</label>_x000D_
<br/><br/>_x000D_
_x000D_
<p>Choose Question Number</p>_x000D_
<label class="small">_x000D_
<input type="radio" name="qst_num" value="1"> 1</label>_x000D_
<label class="small">_x000D_
<input type="radio" name="qst_num" value="2"> 2</label>_x000D_
<label class="small">_x000D_
<input type="radio" name="qst_num" value="3"> 3</label>_x000D_
<br/><br/>_x000D_
_x000D_
<input id="submit" type="submit" value="Show Value">_x000D_
_x000D_
</form>_x000D_
<br/>_x000D_
<p id="show_val_div"></p>_x000D_
</div>_x000D_
<br/><br/><br/>
_x000D_
If you need just update your records in energydata
based on data in temp_energydata
, assuming that temp_enerydata
doesn't contain any new records, then try this:
UPDATE e SET e.kWh = t.kWh
FROM energydata e INNER JOIN
temp_energydata t ON e.webmeterID = t.webmeterID AND
e.DateTime = t.DateTime
Here is working sqlfiddle
But if temp_energydata
contains new records and you need to insert it to energydata
preferably with one statement then you should definitely go with the answer that Bacon Bits gave.
One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
// non-repetitive markup code here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
I made this function to print an array for debugging:
function print_a($arr) {
print '<code><pre style="text-align:left; margin:10px;">'.print_r($arr, TRUE).'</pre></code>';
}
Hope it helps, Tziuka S.
Application.StartupPath
and 7. System.IO.Path.GetDirectoryName(Application.ExecutablePath)
- Is only going to work for Windows Forms application
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location)
Is going to give you something like: "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\legal-services\\e84f415e\\96c98009\\assembly\\dl3\\42aaba80\\bcf9fd83_4b63d101"
which is where the page that you are running is.
AppDomain.CurrentDomain.BaseDirectory
for web application could be useful and will return something like "C:\\hg\\Services\\Services\\Services.Website\\"
which is base directory and is quite useful.
System.IO.Directory.GetCurrentDirectory()
and 5. Environment.CurrentDirectory
will get you location of where the process got fired from - so for web app running in debug mode from Visual Studio something like "C:\\Program Files (x86)\\IIS Express"
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
will get you location where .dll
that is running the code is, for web app that could be "file:\\C:\\hg\\Services\\Services\\Services.Website\\bin"
Now in case of for example console app points 2-6 will be directory where .exe
file is.
Hope this saves you some time.
Convert both dates to timestamps then do
pseudocode:
if date_from_user > start_date && date_from_user < end_date
return true
Good that you've managed to get it working with the html5 mode but it is also possible to make it work in the hashbang mode.
You could simply use:
$location.search().target
to get access to the 'target' search param.
For the reference, here is the working jsFiddle: http://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/
var myApp = angular.module('myApp', []);_x000D_
_x000D_
function MyCtrl($scope, $location) {_x000D_
_x000D_
$scope.location = $location;_x000D_
$scope.$watch('location.search()', function() {_x000D_
$scope.target = ($location.search()).target;_x000D_
}, true);_x000D_
_x000D_
$scope.changeTarget = function(name) {_x000D_
$location.search('target', name);_x000D_
}_x000D_
}
_x000D_
<div ng-controller="MyCtrl">_x000D_
_x000D_
<a href="#!/test/?target=Bob">Bob</a>_x000D_
<a href="#!/test/?target=Paul">Paul</a>_x000D_
_x000D_
<hr/> _x000D_
URL 'target' param getter: {{target}}<br>_x000D_
Full url: {{location.absUrl()}}_x000D_
<hr/>_x000D_
_x000D_
<button ng-click="changeTarget('Pawel')">target=Pawel</button>_x000D_
_x000D_
</div>
_x000D_
As others have already pointed out, using lodash or underscore is probably the best solution. But if you do not need those libraries for anything else, you can probably use something like this:
function deepClone(obj) {
// return value is input is not an Object or Array.
if (typeof(obj) !== 'object' || obj === null) {
return obj;
}
let clone;
if(Array.isArray(obj)) {
clone = obj.slice(); // unlink Array reference.
} else {
clone = Object.assign({}, obj); // Unlink Object reference.
}
let keys = Object.keys(clone);
for (let i=0; i<keys.length; i++) {
clone[keys[i]] = deepClone(clone[keys[i]]); // recursively unlink reference to nested objects.
}
return clone; // return unlinked clone.
}
That's what we decided to do.
A Natural Join is where 2 tables are joined on the basis of all common columns.
common column : is a column which has same name in both tables + has compatible datatypes in both the tables. You can use only = operator
A Inner Join is where 2 tables are joined on the basis of common columns mentioned in the ON clause.
common column : is a column which has compatible datatypes in both the tables but need not have the same name.
You can use only any comparision operator like =
, <=
, >=
, <
, >
, <>
Maybe it's better to use links
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
How to create a link to a directory
Hint: If you need not to see the link in your home you can start it with a dot . ; then it will be hidden by default then you can access it like
cd ~/.myHiddelLongDirLink
I don't really know what you mean by "local access". But for that solution you need to be able to access over ssh the server to copy the files where is database is stored.
I cannot use mysqldump, because my database is big (7Go, mysqldump fail) If the version of the 2 mysql database is too different it might not work, you can check your mysql version using mysql -V.
1) Copy the data from your remote server to your local computer (vps is the alias to your remote server, can be replaced by [email protected])
ssh vps:/etc/init.d/mysql stop
scp -rC vps:/var/lib/mysql/ /tmp/var_lib_mysql
ssh vps:/etc/init.d/apache2 start
2) Import the data copied on your local computer
/etc/init.d/mysql stop
sudo chown -R mysql:mysql /tmp/var_lib_mysql
sudo nano /etc/mysql/my.cnf
-> [mysqld]
-> datadir=/tmp/var_lib_mysql
/etc/init.d/mysql start
If you have a different version, you may need to run
/etc/init.d/mysql stop
mysql_upgrade -u root -pPASSWORD --force #that step took almost 1hrs
/etc/init.d/mysql start
Hive tables can be created as EXTERNAL or INTERNAL. This is a choice that affects how data is loaded, controlled, and managed.
Use EXTERNAL tables when:
Use INTERNAL tables when:
The data is temporary.
You want Hive to completely manage the lifecycle of the table and data.
I personally think the neatest way (not by any means the fastest) is with recursion.
function convert(num) {
if(num < 1){ return "";}
if(num >= 40){ return "XL" + convert(num - 40);}
if(num >= 10){ return "X" + convert(num - 10);}
if(num >= 9){ return "IX" + convert(num - 9);}
if(num >= 5){ return "V" + convert(num - 5);}
if(num >= 4){ return "IV" + convert(num - 4);}
if(num >= 1){ return "I" + convert(num - 1);}
}
console.log(convert(39));
//Output: XXXIX
This will only support numbers 1-40, but it can easily be extended by following the pattern.
Use Collections.emptyList()
if you want to make sure that the returned list is never modified.
This is what is returned on calling emptyList()
:
/**
* The empty list (immutable).
*/
public static final List EMPTY_LIST = new EmptyList();
// This code works for images on 2.2, not sure if any other media types
//Your file path - Example here is "/sdcard/cats.jpg"
final String filePathThis = imagePaths.get(position).toString();
MediaScannerConnectionClient mediaScannerClient = new
MediaScannerConnectionClient() {
private MediaScannerConnection msc = null;
{
msc = new MediaScannerConnection(getApplicationContext(), this);
msc.connect();
}
public void onMediaScannerConnected(){
msc.scanFile(filePathThis, null);
}
public void onScanCompleted(String path, Uri uri) {
//This is where you get your content uri
Log.d(TAG, uri.toString());
msc.disconnect();
}
};
Step 1 (same is in accepted answer written by KavinduWije):
netstat -ano | findstr :yourPortNumber
Change in Step 2 to:
tskill typeyourPIDhere
Note: taskkill
is not working in some git bash terminal
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate">
<%Html.RenderPartial("Modal");%>
</script>
...which lets me keep my templates in a partial view called Modal.ascx
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{Name}}</h3>
</div>
<div class="modal-body">
<table class="table table-striped table-condensed">
<tbody>
<tr><td>ID</td><td>{{Id}}</td></tr>
<tr><td>Name</td><td>{{Name}}</td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%>
<div data-id="<%=Html.Encode(item.Id)%>"
id="modelModal<%=Html.Encode(item.Id)%>"
class="modal hide fade">
</div>
<%}%>
...and make ajax calls with jQuery:
<script type="text/javascript">
var modalTemplate = $("#modalTemplate").html()
$(".modal[data-id]").each(function() {
var $this = $(this)
var id = $this.attr("data-id")
$this.on("show", function() {
if ($this.html()) return
$.ajax({
type: "POST",
url: "<%=Url.Action("SomeAction")%>",
data: { id: id },
success: function(data) {
$this.append(Mustache.to_html(modalTemplate, data))
}
})
})
})
</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%>
<a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
<%=Html.Encode(item.DutModel.Name)%>
</a>
<%}%>
First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.
Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.
Formatting doesn't fit general indentation rules, but I don't think it's a big deal.
//some code at it's proper level
$this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
$this->title = "Feedback";
//and so on
As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them
$sql = "SELECT * FROM $tablename
WHERE id in [$order_ids_list]
AND product_name = 'widgets'";
$x = 'The point of the "argument" was to illustrate the use of here documents';
Came here searching for best practices in abstracting code to submodules when working in Notebooks. I'm not sure that there is a best practice. I have been proposing this.
A project hierarchy as such:
+-- ipynb
¦ +-- 20170609-Examine_Database_Requirements.ipynb
¦ +-- 20170609-Initial_Database_Connection.ipynb
+-- lib
+-- __init__.py
+-- postgres.py
And from 20170609-Initial_Database_Connection.ipynb
:
In [1]: cd ..
In [2]: from lib.postgres import database_connection
This works because by default the Jupyter Notebook can parse the cd
command. Note that this does not make use of Python Notebook magic. It simply works without prepending %bash
.
Considering that 99 times out of a 100 I am working in Docker using one of the Project Jupyter Docker images, the following modification is idempotent
In [1]: cd /home/jovyan
In [2]: from lib.postgres import database_connection
I had a similar problem and the existing answers to this either weren't applicable, or worked but we couldn't use them for other reasons. So I had to figure out what Chrome disliked about our SVGs.
In our case in turned out to be that the id
attribute of the symbol
tag in the SVG file had a :
in it, which Chrome didn't like. Soon as I removed the :
it worked fine.
Bad:
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
<defs>
<symbol id="ThisIDHasAColon:AndChromeDoesNotLikeIt">
...
</symbol>
</defs>
<use
....
xlink:href="#ThisIDHasAColon:AndChromeDoesNotLikeIt"
/>
</svg>
Good:
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 72 72">
<defs>
<symbol id="NoMoreColon">
...
</symbol>
</defs>
<use
....
xlink:href="#NoMoreColon"
/>
</svg>
var trLength = jQuery('#tablebodyID >tr').length;
I'm able to make it in a native way @ jsfiddle. Hope it will help.
Post improved answer when it work, and help others.
$(function () {
$(".example").multiselect({
checkAllText : 'Select All',
uncheckAllText : 'Deselect All',
selectedText: function(numChecked, numTotal, checkedItems){
return numChecked + ' of ' + numTotal + ' checked';
},
minWidth: 325
});
$(".example").multiselect("checkAll");
});
Here is a simple solution:
import pandas as pd
# convert the timestamp column to datetime
df['timestamp'] = pd.to_datetime(df['timestamp'])
# extract hour from the timestamp column to create an time_hour column
df['time_hour'] = df['timestamp'].dt.hour
if( $("#field > div.field-item").text().indexOf('someText') >= 0)
Some browsers will include whitespace, others won't. >=
is appropriate here. Otherwise equality is double equals ==
I adapted a PHP script I found to do just this. You can use it to find the corners of a box around a point (say, 20 km out). My specific example is for Google Maps API:
For Rest API to upload images from host to host:
import urllib2
import requests
api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'
img_file = urllib2.urlopen(image_url)
response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)
You can use option verify set to False to omit SSL verification for HTTPS requests.
You can do it via router as well, similar to Francesco answer but with less clutter in router config
Route::get('/artisan/{cmd}', function($cmd) {
$cmd = trim(str_replace("-",":", $cmd));
$validCommands = ['cache:clear', 'optimize', 'route:cache', 'route:clear', 'view:clear', 'config:cache'];
if (in_array($cmd, $validCommands)) {
Artisan::call($cmd);
return "<h1>Ran Artisan command: {$cmd}</h1>";
} else {
return "<h1>Not valid Artisan command</h1>";
}
});
Then run them via visiting http://myapp.test/artisan/cache-clear etc If you need to add/edit valid Artisan commands just update the $validCommands array.
Try this: for the previous view use this:
navigationController?.popViewController(animated: true)
pop to root use this code:
navigationController?.popToRootViewController(animated: true)
You can use a CROSS JOIN
:
SELECT *
FROM ( SELECT SUM(Fdays) AS fDaysSum
FROM tblFieldDays
WHERE tblFieldDays.NameCode=35
AND tblFieldDays.WeekEnding=1) A -- use you real query here
CROSS JOIN (SELECT SUM(CHdays) AS hrsSum
FROM tblChargeHours
WHERE tblChargeHours.NameCode=35
AND tblChargeHours.WeekEnding=1) B -- use you real query here
well , you can create and also can subclass the UIStoryBoardSegue . subclassing is mostly used for giving custom transition animation.
you can see video of wwdc 2011 introducing StoryBoard. its available in youtube also.
I'll add that if you want to read the dimensions, you can do this:
int[][][] a = new int[4][3][2];
System.out.println(a.length); // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2
You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length
.
For installing mysql-shell
with homebrew, run
brew cask install mysql-shell
you can then launch the mysql shell with
mysqlsh
if you want to enter SQL mode directly, run
mysqlsh --sql
It is possible to convert a datetime object into a string by working directly with the components of the datetime object.
from datetime import date
myDate = date.today()
#print(myDate) would output 2017-05-23 because that is today
#reassign the myDate variable to myDate = myDate.month
#then you could print(myDate.month) and you would get 5 as an integer
dateStr = str(myDate.month)+ "/" + str(myDate.day) + "/" + str(myDate.year)
# myDate.month is equal to 5 as an integer, i use str() to change it to a
# string I add(+)the "/" so now I have "5/" then myDate.day is 23 as
# an integer i change it to a string with str() and it is added to the "5/"
# to get "5/23" and then I add another "/" now we have "5/23/" next is the
# year which is 2017 as an integer, I use the function str() to change it to
# a string and add it to the rest of the string. Now we have "5/23/2017" as
# a string. The final line prints the string.
print(dateStr)
Output --> 5/23/2017
Encode string as unicode.
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
\mbox
is the simplest answer. Regarding the update:
TeX prefers overlong lines to adding too much space between words on a line; I think the idea is that you will notice the lines that extend into the margin (and the black boxes it inserts after such lines), and will have a chance to revise the contents, whereas if there was too much space, you might not notice it.
Use \sloppy
or \begin{sloppypar}...\end{sloppypar}
to adjust this behavior, at least a little. Another possibility is \raggedright
(or \begin{raggedright}...\end{raggedright}
).
For some reason AngularJS allows to get me confused. Their documentation is pretty horrible on this. More good examples of variations would be welcome.
Anyway, I have a slight variation on Ben Lesh's answer.
My data collections looks like this:
items =
[
{ key:"AD",value:"Andorra" }
, { key:"AI",value:"Anguilla" }
, { key:"AO",value:"Angola" }
...etc..
]
Now
<select ng-model="countries" ng-options="item.key as item.value for item in items"></select>
still resulted in the options value to be the index (0, 1, 2, etc.).
Adding Track By fixed it for me:
<select ng-model="blah" ng-options="item.value for item in items track by item.key"></select>
I reckon it happens more often that you want to add an array of objects into an select list, so I am going to remember this one!
Be aware that from AngularJS 1.4 you can't use ng-options any more, but you need to use ng-repeat
on your option tag:
<select name="test">
<option ng-repeat="item in items" value="{{item.key}}">{{item.value}}</option>
</select>
you can solve this, taking the input
tag inside a div
,
then put the padding property on div
tag. This work's for me...
Like this:
<div class="paded">
<input type="text" />
</div>
and css:
.paded{
padding-right: 20px;
}
This should do it:
UPDATE TheTable
SET PhoneNumber = SUBSTRING(PhoneNumber, 1, 3) + '-' +
SUBSTRING(PhoneNumber, 4, 3) + '-' +
SUBSTRING(PhoneNumber, 7, 4)
Incorporated Kane's suggestion, you can compute the phone number's formatting at runtime. One possible approach would be to use scalar functions for this purpose (works in SQL Server):
CREATE FUNCTION FormatPhoneNumber(@phoneNumber VARCHAR(10))
RETURNS VARCHAR(12)
BEGIN
RETURN SUBSTRING(@phoneNumber, 1, 3) + '-' +
SUBSTRING(@phoneNumber, 4, 3) + '-' +
SUBSTRING(@phoneNumber, 7, 4)
END
Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.
tomcat/conf/server.xml
.<Connector port="8080" protocol="HTTP/1.1" address="127.0.0.1" connectionTimeout="20000" redirectPort="8443" />
Generally speaking, you'll hardly ever need to do type comparisons unless you're doing something with reflection or interfaces. Nonetheless:
If you know the type you want to compare it with, use the is
or as
operators:
if( unknownObject is TypeIKnow ) { // run code here
The as
operator performs a cast that returns null if it fails rather than an exception:
TypeIKnow typed = unknownObject as TypeIKnow;
If you don't know the type and just want runtime type information, use the .GetType() method:
Type typeInformation = unknownObject.GetType();
In newer versions of C#, you can use the is
operator to declare a variable without needing to use as
:
if( unknownObject is TypeIKnow knownObject ) {
knownObject.SomeMember();
}
Previously you would have to do this:
TypeIKnow knownObject;
if( (knownObject = unknownObject as TypeIKnow) != null ) {
knownObject.SomeMember();
}
I'm new to stack overflow and new to front end development. This is what worked for me. So I did not want list items to be displayed.
.hidden {_x000D_
display:none;_x000D_
} _x000D_
_x000D_
#loginButton{_x000D_
_x000D_
margin-right:2px;_x000D_
_x000D_
}
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">NavBar</a>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item active hidden">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item hidden">_x000D_
<a class="nav-link" href="#">Link</a>_x000D_
</li>_x000D_
<li class="nav-item hidden">_x000D_
<a class="nav-link disabled" href="#">Disabled</a>_x000D_
</li>_x000D_
</ul>_x000D_
<form class="form-inline my-2 my-lg-0">_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="loginButton"><a href="#">Log In</a></button>_x000D_
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"><a href="#">Register</a></button>_x000D_
</form>_x000D_
</div>_x000D_
</nav>
_x000D_
Based on the answer by Eduard Florinescu, but with newer code and the missing imports added:
$ cat work-auth.py
#!/usr/bin/python3
# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30) # Time to enter credentials
driver.quit()
$ cat work.py
#!/usr/bin/python3
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com') # Already authenticated
time.sleep(10)
driver.quit()
The easiest way is:
onClick= 'location.href="/controller/action/"+paramterValue'
echo -e "YOURPASSWORD\n" | sudo -S yourcommand
I could not get Alex's answer to work on Sql Server 2008 R2. So, I rewrote it using the same basic principles. It now allows for schemas and several fixes have been made for column-property mappings (including mapping nullable date types to nullable C# value types). Here is the Sql:
DECLARE @TableName VARCHAR(MAX) = 'NewsItem' -- Replace 'NewsItem' with your table name
DECLARE @TableSchema VARCHAR(MAX) = 'Markets' -- Replace 'Markets' with your schema name
DECLARE @result varchar(max) = ''
SET @result = @result + 'using System;' + CHAR(13) + CHAR(13)
IF (@TableSchema IS NOT NULL)
BEGIN
SET @result = @result + 'namespace ' + @TableSchema + CHAR(13) + '{' + CHAR(13)
END
SET @result = @result + 'public class ' + @TableName + CHAR(13) + '{' + CHAR(13)
SET @result = @result + '#region Instance Properties' + CHAR(13)
SELECT
@result = @result + CHAR(13)
+ ' public ' + ColumnType + ' ' + ColumnName + ' { get; set; } ' + CHAR(13)
FROM (SELECT
c.COLUMN_NAME AS ColumnName,
CASE c.DATA_TYPE
WHEN 'bigint' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int64?'
ELSE 'Int64'
END
WHEN 'binary' THEN 'Byte[]'
WHEN 'bit' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'bool?'
ELSE 'bool'
END
WHEN 'char' THEN 'string'
WHEN 'date' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?'
ELSE 'DateTime'
END
WHEN 'datetime' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?'
ELSE 'DateTime'
END
WHEN 'datetime2' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?'
ELSE 'DateTime'
END
WHEN 'datetimeoffset' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTimeOffset?'
ELSE 'DateTimeOffset'
END
WHEN 'decimal' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'decimal?'
ELSE 'decimal'
END
WHEN 'float' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Single?'
ELSE 'Single'
END
WHEN 'image' THEN 'Byte[]'
WHEN 'int' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'int?'
ELSE 'int'
END
WHEN 'money' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'decimal?'
ELSE 'decimal'
END
WHEN 'nchar' THEN 'string'
WHEN 'ntext' THEN 'string'
WHEN 'numeric' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'decimal?'
ELSE 'decimal'
END
WHEN 'nvarchar' THEN 'string'
WHEN 'real' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Double?'
ELSE 'Double'
END
WHEN 'smalldatetime' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?'
ELSE 'DateTime'
END
WHEN 'smallint' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int16?'
ELSE 'Int16'
END
WHEN 'smallmoney' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'decimal?'
ELSE 'decimal'
END
WHEN 'text' THEN 'string'
WHEN 'time' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'TimeSpan?'
ELSE 'TimeSpan'
END
WHEN 'timestamp' THEN 'Byte[]'
WHEN 'tinyint' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Byte?'
ELSE 'Byte'
END
WHEN 'uniqueidentifier' THEN CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Guid?'
ELSE 'Guid'
END
WHEN 'varbinary' THEN 'Byte[]'
WHEN 'varchar' THEN 'string'
ELSE 'Object'
END AS ColumnType,
c.ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = @TableName
AND ISNULL(@TableSchema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA) t
ORDER BY t.ORDINAL_POSITION
SET @result = @result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)
SET @result = @result + '}' + CHAR(13)
IF (@TableSchema IS NOT NULL)
BEGIN
SET @result = @result + CHAR(13) + '}'
END
PRINT @result
It produces C# like the following:
using System;
namespace Markets
{
public class NewsItem {
#region Instance Properties
public Int32 NewsItemID { get; set; }
public Int32? TextID { get; set; }
public String Description { get; set; }
#endregion Instance Properties
}
}
It may be an idea to use EF, Linq to Sql, or even Scaffolding; however, there are times when a piece of coding like this comes in handy. Frankly, I do not like using EF navigation properties where the code it generates made 19,200 separate database calls to populate a 1000 row grid. This could have been achieved in a single database call. Nonetheless, it could just be that your technical architect does not want you to use EF and the like. So, you have to revert to code like this... Incidentally, it may also be an idea to decorate each of the properties with attributes for DataAnnotations, etc., but I'm keeping this strictly POCO.
EDIT Fixed for TimeStamp and Guid?
As other answers have mentioned, NT (the kernel underlying modern versions of Windows) has an equivalent of Unix fork(). That's not the problem.
The problem is that cloning a process's entire state is not generally a sane thing to do. This is as true in the Unix world as it is in Windows, but in the Unix world, fork() is used all the time, and libraries are designed to deal with it. Windows libraries aren't.
For example, the system DLLs kernel32.dll and user32.dll maintain a private connection to the Win32 server process csrss.exe. After a fork, there are two processes on the client end of that connection, which is going to cause problems. The child process should inform csrss.exe of its existence and make a new connection – but there's no interface to do that, because these libraries weren't designed with fork() in mind.
So you have two choices. One is to forbid the use of kernel32 and user32 and other libraries that aren't designed to be forked – including any libraries that link directly or indirectly to kernel32 or user32, which is virtually all of them. This means that you can't interact with the Windows desktop at all, and are stuck in your own separate Unixy world. This is the approach taken by the various Unix subsystems for NT.
The other option is to resort to some sort of horrible hack to try to get unaware libraries to work with fork(). That's what Cygwin does. It creates a new process, lets it initialize (including registering itself with csrss.exe), then copies most of the dynamic state over from the old process and hopes for the best. It amazes me that this ever works. It certainly doesn't work reliably – even if it doesn't randomly fail due to an address space conflict, any library you're using may be silently left in a broken state. The claim of the current accepted answer that Cygwin has a "fully-featured fork()" is... dubious.
Summary: In an Interix-like environment, you can fork by calling fork(). Otherwise, please try to wean yourself from the desire to do it. Even if you're targeting Cygwin, don't use fork() unless you absolutely have to.
Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.
To follow up on the previous answer using mail :
Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:
{ echo -e "<pre>"
echo "Descriptive text here."
shell_command_1_here
another_shell_command
cat <<EOF
This is the ending text.
</pre><br>
</div>
EOF
} | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]
You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):
SELECT username, ip, time_stamp FROM (
SELECT username, ip, time_stamp,
ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
FROM Users
) tmp WHERE rn = 1;
They are they same because your doSomething function happens faster than the granularity of the timer. Try:
printf ("**MyProgram::before time= %ld\n", time(NULL));
for(i = 0; i < 1000; ++i) {
doSomthing();
doSomthingLong();
}
printf ("**MyProgram::after time= %ld\n", time(NULL));
.reduce
to build a map, and .filter
to find the intersection. delete
within the .filter
allows us to treat the second array as though it's a unique set.
function intersection (a, b) {
var seen = a.reduce(function (h, k) {
h[k] = true;
return h;
}, {});
return b.filter(function (k) {
var exists = seen[k];
delete seen[k];
return exists;
});
}
I find this approach pretty easy to reason about. It performs in constant time.
You could do
>>> import os
>>> os.path.basename('/folderA/folderB/folderC/folderD')
UPDATE1: This approach works in case you give it /folderA/folderB/folderC/folderD/xx.py. This gives xx.py as the basename. Which is not what you want I guess. So you could do this -
>>> import os
>>> path = "/folderA/folderB/folderC/folderD"
>>> if os.path.isdir(path):
dirname = os.path.basename(path)
UPDATE2: As lars pointed out, making changes so as to accomodate trailing '/'.
>>> from os.path import normpath, basename
>>> basename(normpath('/folderA/folderB/folderC/folderD/'))
'folderD'
This is very simple. Here is the code.
[yourLabel setFont:[UIFont boldSystemFontOfSize:15.0];
This will help you.
You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect
for this.
The following version works:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{ id: 0, value: " --- Select a State ---" }];
const allowedState = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const [stateOptions, setStateValues] = useState(initialValue);
// initialValue.push(...allowedState);
console.log(initialValue.length);
// ****** BEGINNING OF CHANGE ******
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setStateValues(allowedState);
}, []);
// ****** END OF CHANGE ******
return (<div>
<label>Select a State:</label>
<select>
{stateOptions.map((localState, index) => (
<option key={localState.id}>{localState.value}</option>
))}
</select>
</div>);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
and here it is in a code sandbox.
I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState
directly without using useState
at all). If so, that api call to load the list could also go inside the useEffect
block.
this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Initialize your now
variable.
time_t now = time(0); // Get the system time
The localtime
function is used to convert the time value in the passed time_t
to a struct tm
, it doesn't actually retrieve the system time.
On a fresh Debian image, cloning https://github.com/python/cpython and running:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get install build-essential python-dev python-setuptools python-pip python-smbus
sudo apt-get install libncursesw5-dev libgdbm-dev libc6-dev
sudo apt-get install zlib1g-dev libsqlite3-dev tk-dev
sudo apt-get install libssl-dev openssl
sudo apt-get install libffi-dev
Now execute the configure
file cloned above:
./configure
make # alternatively `make -j 4` will utilize 4 threads
sudo make altinstall
Got 3.7 installed and working for me.
Looks like I said I would update this answer with some more explanation and two years later I don't have much to add.
python-dev
might be necessary.altinstall
as opposed to install
argument in the make command.Aside from that I guess the choice would be to either read through the cpython codebase looking for #include
directives that need to be met, but what I usually do is keep trying to install the package and just keep reading through the output installing the required packages until it succeeds.
Reminds me of the story of the Engineer, the Manager and the Programmer whose car rolls down a hill.
For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:
[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{
var body = new StreamReader(Request.Body);
//The modelbinder has already read the stream and need to reset the stream index
body.BaseStream.Seek(0, SeekOrigin.Begin);
var requestBody = body.ReadToEnd();
//etc, we use this for an audit trail
}
Here is a short piece of code I use to capture the error as a string. Will retry till it succeeds. This catches all exceptions but you can change this as you wish.
start = 0
str_error = "Not executed yet."
while str_error:
try:
# replace line below with your logic , i.e. time out, max attempts
start = raw_input("enter a number, 0 for fail, last was {0}: ".format(start))
new_val = 5/int(start)
str_error=None
except Exception as str_error:
pass
WARNING: This code will be stuck in a forever loop until no exception occurs. This is just a simple example and MIGHT require you to break out of the loop sooner or sleep between retries.
in my case
my service has function to Upload Files
and this error just shown up on trying to upload Big Files
so I found this answer to Increase maxRequestLength
to needed value in web.config
and problem solved
if you don't make any upload or download operations maybe this answer will not help you
The easiest way would be to use use ProcessExplorer but it would still require some searching.
Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.
Note that it might be your binary simply has no command line switches.
For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:
You can avoid compilation errors if you remove the method definitions from the header files and let the classes contain only the method declarations and variable declarations/definitions. The method definitions should be placed in a .cpp file (just like a best practice guideline says).
The down side of the following solution is (assuming that you had placed the methods in the header file to inline them) that the methods are no longer inlined by the compiler and trying to use the inline keyword produces linker errors.
//A.h
#ifndef A_H
#define A_H
class B;
class A
{
int _val;
B* _b;
public:
A(int val);
void SetB(B *b);
void Print();
};
#endif
//B.h
#ifndef B_H
#define B_H
class A;
class B
{
double _val;
A* _a;
public:
B(double val);
void SetA(A *a);
void Print();
};
#endif
//A.cpp
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;
A::A(int val)
:_val(val)
{
}
void A::SetB(B *b)
{
_b = b;
cout<<"Inside SetB()"<<endl;
_b->Print();
}
void A::Print()
{
cout<<"Type:A val="<<_val<<endl;
}
//B.cpp
#include "B.h"
#include "A.h"
#include <iostream>
using namespace std;
B::B(double val)
:_val(val)
{
}
void B::SetA(A *a)
{
_a = a;
cout<<"Inside SetA()"<<endl;
_a->Print();
}
void B::Print()
{
cout<<"Type:B val="<<_val<<endl;
}
//main.cpp
#include "A.h"
#include "B.h"
int main(int argc, char* argv[])
{
A a(10);
B b(3.14);
a.Print();
a.SetB(&b);
b.Print();
b.SetA(&a);
return 0;
}
You can apply a theme to any activity by including android:theme
inside <activity>
inside manifest file.
For example:
<activity android:theme="@android:style/Theme.Dialog">
<activity android:theme="@style/CustomTheme">
And if you want to set theme programatically then use setTheme()
before calling setContentView()
and super.onCreate()
method inside onCreate()
method.
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
It is a textual file that includes a description of the library.
It allows libtool
to create platform-independent names.
For example, libfoo
goes to:
Under Linux:
/lib/libfoo.so # Symlink to shared object
/lib/libfoo.so.1 # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a # Static library
/lib/libfoo.la # 'libtool' library
Under Cygwin:
/lib/libfoo.dll.a # Import library
/lib/libfoo.a # Static library
/lib/libfoo.la # libtool library
/bin/cygfoo_1.dll # DLL
Under Windows MinGW:
/lib/libfoo.dll.a # Import library
/lib/libfoo.a # Static library
/lib/libfoo.la # 'libtool' library
/bin/foo_1.dll # DLL
So libfoo.la
is the only file that is preserved between platforms by libtool
allowing to understand what happens with:
Without depending on a specific platform implementation of libraries.
if you have Firebug installed on Firefox, just open the url. In the network panel, right-click and select Copy as cURL. You can see all curl parameters for this web call.
It can easily happen if you try to undo changes you've made by re-checking-out files and not quite getting the syntax right.
You can look at the output of git log
- you could paste the tail of the log here since the last successful commit, and we could all see what you did. Or you could paste-bin it and ask nicely in #git
on freenode IRC.
You can make the following sql query
IF ((SELECT COUNT(*) FROM table1 WHERE project = 1) > 0)
SELECT product, price FROM table1 WHERE project = 1
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 2) > 0)
SELECT product, price FROM table1 WHERE project = 2
ELSE IF ((SELECT COUNT(*) FROM table1 WHERE project = 3) > 0)
SELECT product, price FROM table1 WHERE project = 3
sth's solution didn't work for me
because in ...
Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension
It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case
You can bypass the format detection by setting the format yourself in a parameter
import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()
List<Integer> figureTypes = new ArrayList<Integer>(
Arrays.asList(
1,
2
));
List<Integer> figureTypes2 = new ArrayList<Integer>(
Arrays.asList(
1,
2));
assertTrue(figureTypes .equals(figureTypes2 ));
Java 8 new feature forEach
style
import java.util.HashMap;
public class PrintMap {
public static void main(String[] args) {
HashMap<String, Integer> example = new HashMap<>();
example.put("a", 1);
example.put("b", 2);
example.put("c", 3);
example.put("d", 5);
example.forEach((key, value) -> System.out.println(key + " : " + value));
// Output:
// a : 1
// b : 2
// c : 3
// d : 5
}
}
To get records from the last 24 hours:
SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)
Your MyComponentComponent
should be in MyComponentModule
.
And in MyComponentModule
, you should place the MyComponentComponent
inside the "exports".
Something like this, see code below.
@NgModule({
imports: [],
exports: [MyComponentComponent],
declarations: [MyComponentComponent],
providers: [],
})
export class MyComponentModule {
}
and place the MyComponentModule
in the imports
in app.module.ts
like this (see code below).
import { MyComponentModule } from 'your/file/path';
@NgModule({
imports: [MyComponentModule]
declarations: [AppComponent],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
After doing so, the selector of your component can now be recognized by the app.
You can learn more about it here: https://angular-2-training-book.rangle.io/handout/modules/feature-modules.html
Cheers!
You can do it in a less than a minute with Google Drive (and free, no hassles)
• Bulk Upload all your images on imgur.com
• Copy the Links of all the images together, appended with .jpg. Only imgur lets you do copy all the image links together, do that using the image tab top right.
• Use http://TextMechanic.co to prepend and append each line with this:
Prefix : =image("
AND
Suffix : ", 1)
So that it looks like this =image("URL", 1)
• Copy All
• Paste it in Google Spreadsheet
• Voila!
References :
http://www.labnol.org/internet/images-in-google-spreadsheet/18167/
https://support.google.com/drive/bin/answer.py?hl=en&answer=87037&from=1068225&rd=1
Following are the steps that will definitely work:
netstat -aon | find ":8080" | find "LISTENING"
Ctrl+Shift+Esc
)end process
NOTE : If you are running your program for the first time in Netbeans, it takes some time. So don't worry if it takes time.
I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.
Also, for posterity -- Clang (like GCC) accepts the -x
switch to set the language of the input files, for example,
$ clang -x c++ some_random_file.txt
This mailing list thread explains the difference between clang
and clang++
well: Difference between clang and clang++
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.
If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake
migrations.
./manage.py migrate <name> --ignore-ghost-migrations --merge --fake
For django version < 1.7 this will create entry in south_migrationhistory
table, you need to delete that entry.
Now you'll be able to revert back the migration easily.
PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.
Yes, you can use this query (Instead of 'Specialist'
and 'Developer'
, type any strings you want separated by comma and change employees
table with your table)
SELECT * FROM employees em
WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));
Why my query is better than the accepted answer: You don't need a CREATE TABLE
permission to run it. This can be executed with just SELECT
permissions.
The default value for InnoDB is actually pretty bad. InnoDB is very RAM dependent, you might find better result if you tweak the settings. Here's a guide that I used InnoDB optimization basic
You can create a Task with cancellation token, when you app goto background you can cancel this token.
You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle
var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
await Task.Delay(10000);
// call web API
}, cancelToken.Token);
//this stops the Task:
cancelToken.Cancel(false);
Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/
Git add .
Git status //Check file that being modified
// git reset HEAD --- replace to which file you want to ignore
git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!
git commit -m ''
git push
A minor update to this: a sender should never set the Return-Path:
header. There's no such thing as a Return-Path:
header for a message in transit. That header is set by the MTA that makes final delivery, and is generally set to the value of the 5321.From
unless the local system needs some kind of quirky routing.
It's a common misunderstanding because users rarely see an email without a Return-Path:
header in their mailboxes. This is because they always see delivered messages, but an MTA should never see a Return-Path:
header on a message in transit. See http://tools.ietf.org/html/rfc5321#section-4.4
function_that_needs_strings(*my_list) # works!
Select *, (Select SUM(SOMENUMT)
From @t S
Where S.id <= M.id)
From @t M
try this Dim Arraystr() as String ={}
After a while of research and disappointments....I was able to make this up
<?php $conn = new mysqli('hostname', 'username', 'password','dbname') or die ('Cannot connect to db') $result = $conn->query("select * from table");?>
//insert the below code in the body
<table id="myTable"> <tr class="header"> <th style="width:20%;">Name</th>
<th style="width:20%;">Email</th>
<th style="width:10%;">City/ Region</th>
<th style="width:30%;">Details</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['city']."</td>";
echo "<td>".$row['details']."</td>";
echo "</tr>";
}
?>
</table>
Trust me it works :)
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
Server-side functions are on the server-side, client-side functions reside on the client.
What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load
handler you can access value of variable and call the server method.
Try This:
CGSize scrollSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, scrollHeight);
[scrollView setContentSize: scrollSize];
Simply call window.frameElement
from your framed page.
If the page is not in a frame then frameElement
will be null
.
The other way (getting the window element inside a frame is less trivial) but for sake of completeness:
/**
* @param f, iframe or frame element
* @return Window object inside the given frame
* @effect will append f to document.body if f not yet part of the DOM
* @see Window.frameElement
* @usage myFrame.document = getFramedWindow(myFrame).document;
*/
function getFramedWindow(f)
{
if(f.parentNode == null)
f = document.body.appendChild(f);
var w = (f.contentWindow || f.contentDocument);
if(w && w.nodeType && w.nodeType==9)
w = (w.defaultView || w.parentWindow);
return w;
}
Null OR an empty string?
if (!empty($user)) {}
Use empty().
After realizing that $user ~= $_POST['user'] (thanks matt):
var uservariable='<?php
echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';
Use the string.substring(from, to)
API. In your case, use string.substring(0,8).
$a = 'This', 'Is', 'a', 'cat'
Using double quotes (and optionally use the separator $ofs
)
# This Is a cat
"$a"
# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"
Using operator join
# This-Is-a-cat
$a -join '-'
# ThisIsacat
-join $a
Using conversion to [string]
# This Is a cat
[string]$a
# This-Is-a-cat
$ofs = '-'
[string]$a
Kotlin Style way to do this more simple (example):
isVisible = false
Complete example:
if (some_data_array.details == null){
holder.view.some_data_array.isVisible = false}
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
matrix multiplication, see the following example:
> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 3 8 3
[3,] 4 9 3
>
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
>
> B
[,1] [,2] [,3]
[1,] 2 8 3
[2,] 4 9 4
[3,] 5 2 5
>
>
> A %*% B
[,1] [,2] [,3]
[1,] 27 55 28
[2,] 53 102 56
[3,] 59 119 63
> B %*% A
[,1] [,2] [,3]
[1,] 38 101 35
[2,] 47 128 43
[3,] 31 86 26
Also see:
http://en.wikipedia.org/wiki/Matrix_multiplication
If this does not follow the size of matrix rule you will get the error:
> A <- matrix(c(1,2,3,4,5,6), 3,2)
> A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)
> B
[,1] [,2] [,3]
[1,] 3 4 4
[2,] 1 4 4
[3,] 3 4 3
> A%*%B
Error in A %*% B : non-conformable arguments
Using annotations, as described in the question.
Annotation: @Monitor
Annotation on class, app/PagesController.java
:
package app;
@Controller
@Monitor
public class PagesController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody String home() {
return "w00t!";
}
}
Annotation on method, app/PagesController.java
:
package app;
@Controller
public class PagesController {
@Monitor
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody String home() {
return "w00t!";
}
}
Custom annotation, app/Monitor.java
:
package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}
Aspect for annotation, app/MonitorAspect.java
:
package app;
@Component
@Aspect
public class MonitorAspect {
@Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
public void before(JoinPoint joinPoint) throws Throwable {
LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
}
@After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
public void after(JoinPoint joinPoint) throws Throwable {
LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
}
}
Enable AspectJ, servlet-context.xml
:
<aop:aspectj-autoproxy />
Include AspectJ libraries, pom.xml
:
<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>
DEPRECATED - this part is outdated so please don't use it.
You can also try this code, if you have for example later added dynamic forms. For example you loaded a window async with ajax and want to submit this form.
$('#cpa-form').live('submit' ,function(e){
e.preventDefault();
// do something
});
UPDATE - you should use the jQuery on() method an try to listen to the document DOM if you want to handle dynamically added content.
Case 1, static version: If you have only a few listeners and your form to handle is hardcoded, then you can listen directly on "document level". I wouldn't use the listeners on document level but I would try to go deeper in the doom tree because it could lead to performance issues (depends on the size of your website and your content)
$('form#formToHandle').on('submit'...
OR
$('form#formToHandle').submit(function(e) {
e.preventDefault();
// do something
});
Case 2, dynamic version: If you already listen to the document in your code, then this way would be good for you. This will also work for code that was added later via DOM or dynamic with AJAX.
$(document).on('submit','form#formToHandle',function(){
// do something like e.preventDefault();
});
OR
$(document).ready(function() {
console.log( "Ready, Document loaded!" );
// all your other code listening to the document to load
$("#formToHandle").on("submit", function(){
// do something
})
});
OR
$(function() { // <- this is shorthand version
console.log( "Ready, Document loaded!" );
// all your other code listening to the document to load
$("#formToHandle").on("submit", function(){
// do something
})
});
A simple way is to tell IIS to send your custom error file for HTTP requests. The file can then contain a meta redirect, a JavaScript redirect and instructions with link, etc... Importantly, you can still check "Require SSL" for the site (or folder) and this will work.
</configuration>
</system.webServer>
<httpErrors>
<clear/>
<!--redirect if connected without SSL-->
<error statusCode="403" subStatusCode="4" path="errors\403.4_requiressl.html" responseMode="File"/>
</httpErrors>
</system.webServer>
</configuration>
Some other options:
<object type="application/pdf" data="filename.pdf" width="100%" height="100%">
</object>
<object type="application/pdf" data="#request.localhost#_includes/filename.pdf"
width="100%" height="100%">
<param name="src" value="#request.localhost#_includes/filename.pdf">
</object>
You want "rbind".
b$b <- NA
new <- rbind(a, b)
rbind requires the data frames to have the same columns.
The first line adds column b to data frame b.
Results
> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
a c
1 9 12
2 10 13
3 11 14
> b$b <- NA
> b
a c b
1 9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
a b c
1 0 3 6
2 1 4 7
3 2 5 8
4 9 NA 12
5 10 NA 13
6 11 NA 14
Get-Content
(alias: gc
) is your usual option for reading a text file. You can then filter further:
gc log.txt | select -first 10 # head
gc -TotalCount 10 log.txt # also head
gc log.txt | select -last 10 # tail
gc -Tail 10 log.txt # also tail (since PSv3), also much faster than above option
gc log.txt | more # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' } # sed
This works well enough for small files, larger ones (more than a few MiB) are probably a bit slow.
The PowerShell Community Extensions include some cmdlets for specialised file stuff (e.g. Get-FileTail).
The directive has changed to character-set-system=utf8
http://dev.mysql.com/doc/refman/5.6/en/charset-configuration.html
There are two ways you can do this. You can use the throw the values into a hash for a lookup table, as suggested by the other posts. ( I'll add just another idiom. )
my %bad_param_lookup;
@bad_param_lookup{ @bad_params } = ( 1 ) x @bad_params;
But if it's data of mostly word characters and not too many meta, you can dump it into a regex alternation:
use English qw<$LIST_SEPARATOR>;
my $regex_str = do {
local $LIST_SEPARATOR = '|';
"(?:@bad_params)";
};
# $front_delim and $back_delim being any characters that come before and after.
my $regex = qr/$front_delim$regex_str$back_delim/;
This solution would have to be tuned for the types of "bad values" you're looking for. And again, it might be totally inappropriate for certain types of strings, so caveat emptor.
For Laravel 5.2 >=
use the Eloquent method:
inRandomOrder()
The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:
$randomUser = DB::table('users')
->inRandomOrder()
->first();
from docs: https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset
Since you don't seem to like computer science or mathy examples, here is a different one: wire puzzles.
Many wire puzzles involve removing a long closed loop of wire by working it in and out of wire rings. These puzzles are recursive. One of them is called "arrow dynamics". I am sue you could find it if you google for "arrow dynamics wire puzzle"
These puzzles are a lot like the towers of Hanoi.
These days the location of the emulated SD card is at /storage/emulated/0
var yourstring = 'tasty food'; // the string to check against
var substrings = ['foo','bar'],
length = substrings.length;
while(length--) {
if (yourstring.indexOf(substrings[length])!=-1) {
// one of the substrings is in yourstring
}
}
let transactionId =${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getMilliseconds()}
let transactionId =`${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getMilliseconds()}`
console.log(transactionId)
_x000D_
Just use CR to go to beginning of the line.
import time
for x in range (0,5):
b = "Loading" + "." * x
print (b, end="\r")
time.sleep(1)
You can use a CharAdapter
and a CharBag
from Eclipse Collections and avoid boxing to Character
and Integer
.
CharBag bag = Strings.asChars("aasjjikkk").toBag();
Assert.assertEquals(2, bag.occurrencesOf('a'));
Assert.assertEquals(1, bag.occurrencesOf('s'));
Assert.assertEquals(2, bag.occurrencesOf('j'));
Assert.assertEquals(1, bag.occurrencesOf('i'));
Assert.assertEquals(3, bag.occurrencesOf('k'));
Note: I am a committer for Eclipse Collections.
In case you are getting property exception, add the following configuration:
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
jaxbMarshaller.setProperty("com.sun.xml.internal.bind.xmlDeclaration", Boolean.FALSE);
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
Going through the answers there are some details missing regarding `Cascade' and id generation. See question
Also, it is worth mentioning that you can have separate Cascade
annotations for merging and persisting: Cascade.MERGE
and Cascade.PERSIST
which will be treated according to the used method.
The spec is your friend ;)
Kotlin version of Raghav Sood's answer
Rater.kt
class Rater {
companion object {
private const val APP_TITLE = "App Name"
private const val APP_NAME = "com.example.name"
private const val RATER_KEY = "rater_key"
private const val LAUNCH_COUNTER_KEY = "launch_counter_key"
private const val DO_NOT_SHOW_AGAIN_KEY = "do_not_show_again_key"
private const val FIRST_LAUNCH_KEY = "first_launch_key"
private const val DAYS_UNTIL_PROMPT: Int = 3
private const val LAUNCHES_UNTIL_PROMPT: Int = 3
fun start(mContext: Context) {
val prefs: SharedPreferences = mContext.getSharedPreferences(RATER_KEY, 0)
if (prefs.getBoolean(DO_NOT_SHOW_AGAIN_KEY, false)) {
return
}
val editor: Editor = prefs.edit()
val launchesCounter: Long = prefs.getLong(LAUNCH_COUNTER_KEY, 0) + 1;
editor.putLong(LAUNCH_COUNTER_KEY, launchesCounter)
var firstLaunch: Long = prefs.getLong(FIRST_LAUNCH_KEY, 0)
if (firstLaunch == 0L) {
firstLaunch = System.currentTimeMillis()
editor.putLong(FIRST_LAUNCH_KEY, firstLaunch)
}
if (launchesCounter >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)
) {
showRateDialog(mContext, editor)
}
}
editor.apply()
}
fun showRateDialog(mContext: Context, editor: Editor) {
Dialog(mContext).apply {
setTitle("Rate $APP_TITLE")
val ll = LinearLayout(mContext)
ll.orientation = LinearLayout.VERTICAL
TextView(mContext).apply {
text =
"If you enjoy using $APP_TITLE, please take a moment to rate it. Thanks for your support!"
width = 240
setPadding(4, 0, 4, 10)
ll.addView(this)
}
Button(mContext).apply {
text = "Rate $APP_TITLE"
setOnClickListener {
mContext.startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=$APP_NAME")
)
);
dismiss()
}
ll.addView(this)
}
Button(mContext).apply {
text = "Remind me later"
setOnClickListener {
dismiss()
};
ll.addView(this)
}
Button(mContext).apply {
text = "No, thanks"
setOnClickListener {
editor.putBoolean(DO_NOT_SHOW_AGAIN_KEY, true);
editor.commit()
dismiss()
};
ll.addView(this)
}
setContentView(ll)
show()
}
}
}
}
Optimized answer
Rater.kt
class Rater {
companion object {
fun start(context: Context) {
val prefs: SharedPreferences = context.getSharedPreferences(RATER_KEY, 0)
if (prefs.getBoolean(DO_NOT_SHOW_AGAIN_KEY, false)) {
return
}
val editor: Editor = prefs.edit()
val launchesCounter: Long = prefs.getLong(LAUNCH_COUNTER_KEY, 0) + 1;
editor.putLong(LAUNCH_COUNTER_KEY, launchesCounter)
var firstLaunch: Long = prefs.getLong(FIRST_LAUNCH_KEY, 0)
if (firstLaunch == 0L) {
firstLaunch = System.currentTimeMillis()
editor.putLong(FIRST_LAUNCH_KEY, firstLaunch)
}
if (launchesCounter >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)
) {
showRateDialog(context, editor)
}
}
editor.apply()
}
fun showRateDialog(context: Context, editor: Editor) {
Dialog(context).apply {
setTitle("Rate $APP_TITLE")
LinearLayout(context).let { layout ->
layout.orientation = LinearLayout.VERTICAL
setDescription(context, layout)
setPositiveAnswer(context, layout)
setNeutralAnswer(context, layout)
setNegativeAnswer(context, editor, layout)
setContentView(layout)
show()
}
}
}
private fun setDescription(context: Context, layout: LinearLayout) {
TextView(context).apply {
text = context.getString(R.string.rate_description, APP_TITLE)
width = 240
setPadding(4, 0, 4, 10)
layout.addView(this)
}
}
private fun Dialog.setPositiveAnswer(
context: Context,
layout: LinearLayout
) {
Button(context).apply {
text = context.getString(R.string.rate_now)
setOnClickListener {
context.startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse(context.getString(R.string.market_uri, APP_NAME))
)
);
dismiss()
}
layout.addView(this)
}
}
private fun Dialog.setNeutralAnswer(
context: Context,
layout: LinearLayout
) {
Button(context).apply {
text = context.getString(R.string.remind_later)
setOnClickListener {
dismiss()
};
layout.addView(this)
}
}
private fun Dialog.setNegativeAnswer(
context: Context,
editor: Editor,
layout: LinearLayout
) {
Button(context).apply {
text = context.getString(R.string.no_thanks)
setOnClickListener {
editor.putBoolean(DO_NOT_SHOW_AGAIN_KEY, true);
editor.commit()
dismiss()
};
layout.addView(this)
}
}
}
}
Constants.kt
object Constants {
const val APP_TITLE = "App Name"
const val APP_NAME = "com.example.name"
const val RATER_KEY = "rater_key"
const val LAUNCH_COUNTER_KEY = "launch_counter_key"
const val DO_NOT_SHOW_AGAIN_KEY = "do_not_show_again_key"
const val FIRST_LAUNCH_KEY = "first_launch_key"
const val DAYS_UNTIL_PROMPT: Int = 3
const val LAUNCHES_UNTIL_PROMPT: Int = 3
}
strings.xml
<resources>
<string name="rate_description">If you enjoy using %1$s, please take a moment to rate it. Thanks for your support!</string>
<string name="rate_now">Rate now</string>
<string name="no_thanks">No, thanks</string>
<string name="remind_later">Remind me later</string>
<string name="market_uri">market://details?id=%1$s</string>
</resources>
I have never considered it to be a bad practice to throw an exception in the constructor. When the class is designed, you have a certain idea in mind of what the structure for that class should be. If someone else has a different idea and tries to execute that idea, then you should error accordingly, giving the user feedback on what the error is. In your case, you might consider something like
if (age < 0) throw new NegativeAgeException("The person you attempted " +
"to construct must be given a positive age.");
where NegativeAgeException
is an exception class that you constructed yourself, possibly extending another exception like IndexOutOfBoundsException
or something similar.
Assertions don't exactly seem to be the way to go, either, since you're not trying to discover bugs in your code. I would say terminating with an exception is absolutely the right thing to do here.
A better and optimised solution to display multiple validation messages for a single element would be like this.
<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
<span class="error" ng-message="required"> <your message> </span>
<span class="error" ng-message="size"> <your message> </span>
<span class="error" ng-message="filetype"> <your message> </span>
</div>
Controller Code should be the one suggested by @ Ben Lesh
While onclick
works in all browsers, addEventListener
does not work in older versions of Internet Explorer, which uses attachEvent
instead.
The downside of onclick
is that there can only be one event handler, while the other two will fire all registered callbacks.
What I did to solve was simply:
This is for solving when using docker compose
Select [insert your fields here]
from tablename
where signin = (select max(signin) from tablename where ID = 1)
I came here randomly and never had a reason to repeat a char in javascript before.
I was impressed by artistoex's way of doing it and disfated's results. I noticed that the last string concat was unnecessary, as Dennis also pointed out.
I noticed a few more things when playing with the sampling disfated put together.
The results varied a fair amount often favoring the last run and similar algorithms would often jockey for position. One of the things I changed was instead of using the JSLitmus generated count as the seed for the calls; as count was generated different for the various methods, I put in an index. This made the thing much more reliable. I then looked at ensuring that varying sized strings were passed to the functions. This prevented some of the variations I saw, where some algorithms did better at the single chars or smaller strings. However the top 3 methods all did well regardless of the string size.
Forked test set
http://jsfiddle.net/schmide/fCqp3/134/
// repeated string
var string = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789';
// count paremeter is changed on every test iteration, limit it's maximum value here
var maxCount = 200;
var n = 0;
$.each(tests, function (name) {
var fn = tests[name];
JSLitmus.test(++n + '. ' + name, function (count) {
var index = 0;
while (count--) {
fn.call(string.slice(0, index % string.length), index % maxCount);
index++;
}
});
if (fn.call('>', 10).length !== 10) $('body').prepend('<h1>Error in "' + name + '"</h1>');
});
JSLitmus.runAll();
I then included Dennis' fix and decided to see if I could find a way to eek out a bit more.
Since javascript can't really optimize things, the best way to improve performance is to manually avoid things. If I took the first 4 trivial results out of the loop, I could avoid 2-4 string stores and write the final store directly to the result.
// final: growing pattern + prototypejs check (count < 1)
'final avoid': function (count) {
if (!count) return '';
if (count == 1) return this.valueOf();
var pattern = this.valueOf();
if (count == 2) return pattern + pattern;
if (count == 3) return pattern + pattern + pattern;
var result;
if (count & 1) result = pattern;
else result = '';
count >>= 1;
do {
pattern += pattern;
if (count & 1) result += pattern;
count >>= 1;
} while (count > 1);
return result + pattern + pattern;
}
This resulted in a 1-2% improvement on average over Dennis' fix. However, different runs and different browsers would show a fair enough variance that this extra code probably isn't worth the effort over the 2 previous algorithms.
Edit: I did this mostly under chrome. Firefox and IE will often favor Dennis by a couple %.
xdocdiff plugin for SVN
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
I had this issue and realized I was using a different account from the one whose repo it was. Logging in as the original user resolved the issue.
You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (GetCurrentProcess ? OpenProcessToken ? GetTokenInformation ? LookupAccountSid).
I wrote a small module that can do this straight from Python, getuser.py. Usage:
import getuser
print(getuser.lookup_username())
It works on both Windows and *nix (the latter uses the pwd
module as described in the other answers).
Perhaps this example could explain.
CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2));
We have a table like this:
+-------+-------------+
| Field | Type |
+-------+-------------+
| fla | float |
| flb | float |
| dba | double(10,2)|
| dbb | double(10,2)|
+-------+-------------+
For first difference, we try to insert a record with '1.2' to each field:
INSERT INTO `test` values (1.2,1.2,1.2,1.2);
The table showing like this:
SELECT * FROM `test`;
+------+------+------+------+
| fla | flb | dba | dbb |
+------+------+------+------+
| 1.2 | 1.2 | 1.20 | 1.20 |
+------+------+------+------+
See the difference?
We try to next example:
SELECT fla+flb, dba+dbb FROM `test`;
Hola! We can find the difference like this:
+--------------------+---------+
| fla+flb | dba+dbb |
+--------------------+---------+
| 2.4000000953674316 | 2.40 |
+--------------------+---------+
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));
//Output : C
items.forEach(item->{
System.out.println(item);
System.out.println(item.toLowerCase());
}
});
If istream fails to insert, it will set the fail bit.
int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
std::cout << "I failed, try again ..." << std::endl
std::cin.clear(); // reset the failed state
}
You can set this up in a do-while loop to get the correct type (int
in this case) propertly inserted.
For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly
This is what I found to be useful
global $base_root;
$base_root . request_uri();
Returns query strings and it's what's used in core: page_set_cache()
This is an example without the new C++ interface (works for 90, 180 and 270 degrees, using param = 1, 2 and 3). Remember to call cvReleaseImage
on the returned image after using it.
IplImage *rotate_image(IplImage *image, int _90_degrees_steps_anti_clockwise)
{
IplImage *rotated;
if(_90_degrees_steps_anti_clockwise != 2)
rotated = cvCreateImage(cvSize(image->height, image->width), image->depth, image->nChannels);
else
rotated = cvCloneImage(image);
if(_90_degrees_steps_anti_clockwise != 2)
cvTranspose(image, rotated);
if(_90_degrees_steps_anti_clockwise == 3)
cvFlip(rotated, NULL, 1);
else if(_90_degrees_steps_anti_clockwise == 1)
cvFlip(rotated, NULL, 0);
else if(_90_degrees_steps_anti_clockwise == 2)
cvFlip(rotated, NULL, -1);
return rotated;
}
map
doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map
.
map
in Python 3 is equivalent to this:
def map(func, iterable):
for i in iterable:
yield func(i)
and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yield
ing.
Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map
, particularly if you're using a lambda expression as the first argument:
[func(i) for i in iterable]
As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -
>>> a = "hello, world"
>>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')
A use of map
here would be if you start with a list of strings instead of a single string - map
can listify all of them individually:
>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
Note that map(list, a)
is equivalent in Python 2, but in Python 3 you need the list
call if you want to do anything other than feed it into a for
loop (or a processing function such as sum
that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:
>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]
You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)
So to insert Employee / Department pairs that do not currently exist you might try something like the following.
CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e
on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
See Can't make hibernate stop showing SQL using Spring JPA Vendor Adapter
Note that cp A B; rm A
is exactly mv A B
. It'll be faster too, as you don't have to actually copy the bytes (assuming the destination is on the same filesystem), just rename the file. So you want cp A B; mv A C
Was looking for this: Shift-L
in JupyterLab 1.0.0
Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.
Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.
Implementing the necessary interfaces for using an object as a data source can be found here.
Try This...
Go to your notification area in the taskbar.
Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.
There are several options available..
a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.
b. Disabled - It will force the portrait apps to work in landscape mode.
c. Enabled - It will force the portrait apps to work in portrait mode only.
This May help you..
I suggest you to use provider
.
Provide is good when you want to configure it first before to use (against Service/Factory)
Something like:
.provider('Magazines', function() {
this.url = '/';
this.urlArray = '/';
this.organId = 'Default';
this.$get = function() {
var url = this.url;
var urlArray = this.urlArray;
var organId = this.organId;
return {
invoke: function() {
return ......
}
}
};
this.setUrl = function(url) {
this.url = url;
};
this.setUrlArray = function(urlArray) {
this.urlArray = urlArray;
};
this.setOrganId = function(organId) {
this.organId = organId;
};
});
.config(function(MagazinesProvider){
MagazinesProvider.setUrl('...');
MagazinesProvider.setUrlArray('...');
MagazinesProvider.setOrganId('...');
});
And now controller:
function MyCtrl($scope, Magazines) {
Magazines.invoke();
....
}
json
is a built-in module, you don't need to install it with pip
.
You can do this with the use of Ascii integers. Put this code in the Textbox's Keypress event. e.KeyChar
represents the key that's pressed. And the the built-in function Asc()
converts it into its Ascii integer.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
I just had this issue, and moving the JS references and code towards the bottom of the page before the </body>
tag fixed it for me.
Read /usr/src/linux/Documentation/sysctl/kernel.txt.
[/proc/sys/kernel/]core_pattern is used to specify a core dumpfile pattern name.
- If the first character of the pattern is a '|', the kernel will treat the rest of the pattern as a command to run. The core dump will be written to the standard input of that program instead of to a file.
Instead of writing the core dump to disk, your system is configured to send it to the abrt
program instead. Automated Bug Reporting Tool is possibly not as documented as it should be...
In any case, the quick answer is that you should be able to find your core file in /var/cache/abrt
, where abrt
stores it after being invoked. Similarly, other systems using Apport may squirrel away cores in /var/crash
, and so on.