Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Make sure you are injecting the repository into the service's constructor. That solved it for me. ::smacks forehead::
This error can also occur when you try to connect to http while the server is on https.
It was a bit confusing because my get-requests were OK, the problem was only present with post-requests.
I came across this error while attempting to pass an un-encrypted file path to the Decrypt method.The solution was to check if the passed file is encrypted first before attempting to decrypt
if (Sec.IsFileEncrypted(e.File.FullName))
{
var stream = Sec.Decrypt(e.File.FullName);
}
else
{
// non-encrypted scenario
}
Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.
class Point2D {
double X, Y;
public Point2D(double x, double y) {
init(x, y);
}
public Point2D(Point2D point) {
if (point == null)
throw new ArgumentNullException("point");
init(point.X, point.Y);
}
void init(double x, double y) {
// ... Contracts ...
X = x;
Y = y;
}
}
If I am reading your question right - the code that wants the synchronous call to an async method is executing on a suspended dispatcher thread. And you want to actually synchronously block that thread until the async method is completed.
Async methods in C# 5 are powered by effectively chopping the method into pieces under the hood, and returning a Task
that can track the overall completion of the whole shabang. However, how the chopped up methods execute can depend on the type of the expression passed to the await
operator.
Most of the time, you'll be using await
on an expression of type Task
. Task's implementation of the await
pattern is "smart" in that it defers to the SynchronizationContext
, which basically causes the following to happen:
await
is on a Dispatcher or WinForms message loop thread, it ensures that the chunks of the async method occurs as part of the processing of the message queue.await
is on a thread pool thread, then the remaining chunks of the async method occur anywhere on the thread pool.That's why you're probably running into problems - the async method implementation is trying to run the rest on the Dispatcher - even though it's suspended.
.... backing up! ....
I have to ask the question, why are you trying to synchronously block on an async method? Doing so would defeat the purpose on why the method wanted to be called asynchronously. In general, when you start using await
on a Dispatcher or UI method, you will want to turn your entire UI flow async. For example, if your callstack was something like the following:
WebRequest.GetResponse()
YourCode.HelperMethod()
YourCode.AnotherMethod()
YourCode.EventHandlerMethod()
[UI Code].Plumbing()
- WPF
or WinForms
CodeWPF
or WinForms
Message LoopThen once the code has been transformed to use async, you'll typically end up with
WebRequest.GetResponseAsync()
YourCode.HelperMethodAsync()
YourCode.AnotherMethodAsync()
YourCode.EventHandlerMethodAsync()
[UI Code].Plumbing()
- WPF
or WinForms
CodeWPF
or WinForms
Message LoopActually Answering
The AsyncHelpers class above actually works because it behaves like a nested message loop, but it installs its own parallel mechanic to the Dispatcher rather than trying to execute on the Dispatcher itself. That's one workaround for your problem.
Another workaround is to execute your async method on a threadpool thread, and then wait for it to complete. Doing so is easy - you can do it with the following snippet:
var customerList = TaskEx.RunEx(GetCustomers).Result;
The final API will be Task.Run(...), but with the CTP you'll need the Ex suffixes (explanation here).
why not simply eg
var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;
oh ... according to the documentation you can leave out the .Distinct()
This method excludes duplicates from the return set
One already exists. If you cannot get over the "Move" syntax of the System.IO
namespace. There is a static class FileSystem
within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory
and RenameFile
already within it.
As mentioned by SLaks, this is just a wrapper for Directory.Move
and File.Move
.
My code is amazing it just took 00:00:00.0007143 less than milisecond with 34 file in folder
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
bool IsEmptyDirectory = (Directory.GetFiles("d:\\pdf").Length == 0);
sw.Stop();
Console.WriteLine(sw.Elapsed);
I hope that I am understing your question correctly, but you can do this very quickly with Linq. I'm assuming that universally you will always have an Id property. Just create an interface to ensure this.
If how you identify an object to be the same changes from class to class, I would recommend passing in a delegate that returns true if the two objects have the same persistent id.
Here is how to do it in Linq:
List<Employee> listA = new List<Employee>();
List<Employee> listB = new List<Employee>();
listA.Add(new Employee() { Id = 1, Name = "Bill" });
listA.Add(new Employee() { Id = 2, Name = "Ted" });
listB.Add(new Employee() { Id = 1, Name = "Bill Sr." });
listB.Add(new Employee() { Id = 3, Name = "Jim" });
var identicalQuery = from employeeA in listA
join employeeB in listB on employeeA.Id equals employeeB.Id
select new { EmployeeA = employeeA, EmployeeB = employeeB };
foreach (var queryResult in identicalQuery)
{
Console.WriteLine(queryResult.EmployeeA.Name);
Console.WriteLine(queryResult.EmployeeB.Name);
}
I was playing around with the same thing and worked this up. It's not fully tested but seems to handle the issue with value types (the unaryexpression issue you ran into)
public static string GetName(Expression<Func<object>> exp)
{
MemberExpression body = exp.Body as MemberExpression;
if (body == null) {
UnaryExpression ubody = (UnaryExpression)exp.Body;
body = ubody.Operand as MemberExpression;
}
return body.Member.Name;
}
I forgot to comment out a line with a MsgBox before executing my macro. Meaning I'd have to click OK over a hundred thousand times. The ESC key was just escaping the message box but not stopping the execution of the macro. Holding the ESC key continuously for a few seconds helped me stop the execution of the code.
if you want same string output then try below else use without double quotes for proper output
$str = '20130814';
echo date('"F Y"', strtotime($str));
//output : "August 2013"
In simple words.
DDL(Data definition language): will work on structure of data. define the data structures.
DML (data manipulation language): will work on data. manipulates the data itself
You need to look at the return value of the call to showConfirmDialog
. I.E.:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
// Saving code here
}
You were testing against dialogButton
, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton
would never have been anything other than JOptionPane.YES_NO_OPTION
.
Per the Javadoc for showConfirmDialog
:
Returns: an integer indicating the option selected by the user
That's what worked for me:
1. The Remotes
$ git remote rm origin
$ git remote add origin [email protected]:<USER>/<REPO>.git
If your SSH key is already in use on another github rep, you can generate a new one.
2. Generating a new SSH key
$ ssh-keygen -t rsa -b 4096 -C "[email protected]"
3. Addition of the key at the SSH agent level
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa_github
4. Add the new key to the Github repo.
There are two ways to set this up. If you have an SID, use this (older) format:
jdbc:oracle:thin:@[HOST][:PORT]:SID
If you have an Oracle service name, use this (newer) format:
jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE
Source: this OraFAQ page
The call to getConnection()
is correct.
Also, as duffymo said, make sure the actual driver code is present by including ojdbc6.jar
in the classpath, where the number corresponds to the Java version you're using.
Update for mid 2016:
The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!
Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!
Google "npm as build tool" result: https://medium.com/@dabit3/introduction-to-using-npm-as-a-build-tool-b41076f488b0#.c33e74tsa
Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!
Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot
Your questions:
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
Everything belongs in package.json now
Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev
(--save-dev updates your package.json by adding an entry to devDependencies)
npm install lodash --save
(--save updates your package.json by adding an entry to dependencies)If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?
Always. Just because of comfort. When you add a flag (--save-dev
or --save
) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name
is npm i -D package-name
and shortcut for npm install --save package-name
is npm i -S package-name
class PassByReference:
def Change(self, var):
self.a = var
print(self.a)
s=PassByReference()
s.Change(5)
Use PacBot (Policy as Code Bot) - An Open Source project which is a platform for continuous compliance monitoring, compliance reporting and security automation for the cloud. All resources across all accounts and all regions are discovered by PacBot are evaluated against these policies to gauge policy conformance. Omni Search features are also available giving ability to search all discovered resources. Even you can terminated/deleted resource details through PacBot.
Omni Search
Search Results Page With Results filtering
Asset 360 / Asset Details Page
Following are the key PacBot capabilities
I got this error: "Type does not contain a definition for GetProperty" when tying the accepted answer.
This is what i ended up with:
using System.Reflection;
if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{
}
If you have an issue, you need to locate your pg_hba.conf
. The command is:
find / -name 'pg_hba.conf' 2>/dev/null
and after that change the configuration file:
Postgresql 9.3
Postgresql 9.4
The next step is: Restarting your db instance:
service postgresql-9.3 restart
If you have any problems, you need to set password again:
ALTER USER db_user with password 'db_password';
I'm using fileupload-jquery in haml. The original js is below:
<!-- The template to display files available for download -->_x000D_
<script id="template-download" type="text/x-tmpl">_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
<tr class="template-download fade">_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
<span>{%=locale.fileupload.destroy%}</span>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}_x000D_
</script>
_x000D_
At first I used the :cdata
to convert (from html2haml), it doesn't work properly (Delete button can't remove relevant component in callback).
<script id='template-download' type='text/x-tmpl'>_x000D_
<![CDATA[_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
<tr class="template-download fade">_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
<span>{%=locale.fileupload.destroy%}</span>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}_x000D_
]]>_x000D_
</script>
_x000D_
So I use :plain
filter:
%script#template-download{:type => "text/x-tmpl"}_x000D_
:plain_x000D_
{% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
<tr class="template-download fade">_x000D_
{% if (file.error) { %}_x000D_
<td></td>_x000D_
<td class="name"><span>{%=file.name%}</span></td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
{% } else { %}_x000D_
<td class="preview">{% if (file.thumbnail_url) { %}_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
{% } %}</td>_x000D_
<td class="name">_x000D_
<a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
</td>_x000D_
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
<td colspan="2"></td>_x000D_
{% } %}_x000D_
<td class="delete">_x000D_
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
<i class="icon-trash icon-white"></i>_x000D_
<span>{%=locale.fileupload.destroy%}</span>_x000D_
</button>_x000D_
<input type="checkbox" name="delete" value="1">_x000D_
</td>_x000D_
</tr>_x000D_
{% } %}
_x000D_
The converted result is exactly the same as the original.
So :plain
filter in this senario fits my need.
:plain Does not parse the filtered text. This is useful for large blocks of text without HTML tags, when you don’t want lines starting with . or - to be parsed.
For more detail, please refer to haml.info
Use the "geometry" package and write \newgeometry{left=3cm,bottom=0.1cm}
where you want to change your margins. When you want to reset your margins, you write \restoregeometry
.
Most of the other answers point to eager loading, but I found another solution.
In my case I had an EF object InventoryItem
with a collection of InvActivity
child objects.
class InventoryItem {
...
// EF code first declaration of a cross table relationship
public virtual List<InvActivity> ItemsActivity { get; set; }
public GetLatestActivity()
{
return ItemActivity?.OrderByDescending(x => x.DateEntered).SingleOrDefault();
}
...
}
And since I was pulling from the child object collection instead of a context query (with IQueryable
), the Include()
function was not available to implement eager loading. So instead my solution was to create a context from where I utilized GetLatestActivity()
and attach()
the returned object:
using (DBContext ctx = new DBContext())
{
var latestAct = _item.GetLatestActivity();
// attach the Entity object back to a usable database context
ctx.InventoryActivity.Attach(latestAct);
// your code that would make use of the latestAct's lazy loading
// ie latestAct.lazyLoadedChild.name = "foo";
}
Thus you aren't stuck with eager loading.
Check your code for errors in my case i had an error in Kernel.php. First solve errors if any Than run composer require ....(package you wish)
You have to put a g
at the end, it stands for "global":
echo dog dog dos | sed -r 's:dog:log:g'
^
There is nothing wrong with your code. The problem is not visible form here.
Check if after the submit, the script is called at all.
Have a look at what is submitted: var_dump($_REQUEST)
I’ve seen on different answers that we have to remove ib_logfile0
and ib_logfile1
in Applications/MAMP/db/mysql56/
If you use MAMP PRO 4, these files are in /Library/Application Support/appsolute/MAMP PRO/db/mysql56/
Removing theses fils works for me (the serveur doesn’t start after a system crash).
I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick
event handler for the radio buttons:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var ex1 = document.getElementById('example1');
var ex2 = document.getElementById('example2');
var ex3 = document.getElementById('example3');
ex1.onclick = handler;
ex2.onclick = handler;
ex3.onclick = handler;
}
function handler() {
alert('clicked');
}
</script>
</head>
<body>
<input type="radio" name="example1" id="example1" value="Example 1" />
<label for="example1">Example 1</label>
<input type="radio" name="example2" id="example2" value="Example 2" />
<label for="example1">Example 2</label>
<input type="radio" name="example3" id="example3" value="Example 3" />
<label for="example1">Example 3</label>
</body>
</html>
Since you mentioned it's always going to have a length of 4, I won't be doing any error checking to make this slick. ;)
function pad(input) {
var BASE = "0000";
return input ? BASE.substr(0, 4 - Math.ceil(input / 10)) + input : BASE;
}
Idea: Simply replace '0000' with number provided... Issue with that is, if input
is 0, I need to hard-code it to return '0000'. LOL.
This should be slick enough.
JSFiddler: http://jsfiddle.net/Up5Cr/
It is possible by managing a flag in SharedPreferences or in Application Activity.
On starting of app (on Splash Screen) set the flag = false; On Logout Click event just set the flag true and in OnResume() of every activity, check if flag is true then call finish().
It works like a charm :)
You can consider leveraging React's Context feature.
class NavigationContainer extends React.Component {
constructor(props) {
super(props);
this.goTo = this.goTo.bind(this);
}
goTo(location) {
...
}
getChildContext() {
// returns the context to pass to children
return {
goTo: this.goTo
}
}
...
}
// defines the context available to children
NavigationContainer.childContextTypes = {
goTo: PropTypes.func
}
class SomeViewContainer extends React.Component {
render() {
// grab the context provided by ancestors
const {goTo} = this.context;
return <button onClick={evt => goTo('somewhere')}>
Hello
</button>
}
}
// Define the context we want from ancestors
SomeViewContainer.contextTypes = {
goTo: PropTypes.func
}
With context
, you can pass data through the component tree without having to pass the props down manually at every level. There is a big warning on this being an experimental feature and may break in the future, but I would imagine this feature to be around given the majority of the popular frameworks like Redux use context
extensively.
The main advantage of using context
v.s. a global variable is context
is "scoped" to a subtree (this means you can define different scopes for different subtrees).
Do note that you should not pass your model data via context
, as changes in context
will not trigger React's component render cycle. However, I do find it useful in some use case, especially when implementing your own custom framework or workflow.
I made a little helper function to do this and catch all malformed data
function convertToPounds(str) {
var n = Number.parseFloat(str);
if(!str || isNaN(n) || n < 0) return 0;
return n.toFixed(2);
}
Demo is here
Once you have the intent and custom url scheme for your app set up, this javascript code at the top of a receiving page has worked for me on both iOS and Android:
<script type="text/javascript">
// if iPod / iPhone, display install app prompt
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i) ||
navigator.userAgent.match(/android/i)) {
var store_loc = "itms://itunes.com/apps/raditaz";
var href = "/iphone/";
var is_android = false;
if (navigator.userAgent.match(/android/i)) {
store_loc = "https://play.google.com/store/apps/details?id=com.raditaz";
href = "/android/";
is_android = true;
}
if (location.hash) {
var app_loc = "raditaz://" + location.hash.substring(2);
if (is_android) {
var w = null;
try {
w = window.open(app_loc, '_blank');
} catch (e) {
// no exception
}
if (w) { window.close(); }
else { window.location = store_loc; }
} else {
var loadDateTime = new Date();
window.setTimeout(function() {
var timeOutDateTime = new Date();
if (timeOutDateTime - loadDateTime < 5000) {
window.location = store_loc;
} else { window.close(); }
},
25);
window.location = app_loc;
}
} else {
location.href = href;
}
}
</script>
This has only been tested on the Android browser. I am not sure about Firefox or Opera. The key is even though the Android browser will not throw a nice exception for you on window.open(custom_url, '_blank')
, it will fail and return null
which you can test later.
Update: using store_loc = "https://play.google.com/store/apps/details?id=com.raditaz";
to link to Google Play on Android.
Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex
on the row container and at least making sure your middle container on the row has a flex-grow
value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow
properties applied, middle container only needs 1 for flex-grow
).
Here's a pic of what I was trying to do and sample code for how I solved it.
.row {
background: lightgray;
height: 30px;
width: 100%;
display: flex;
align-items:flex-end;
margin-top:5px;
}
.left {
background:lightblue;
}
.separator{
flex-grow:1;
border-bottom:dotted 2px black;
}
.right {
background:coral;
}
_x000D_
<div class="row">
<div class="left">Left</div>
<div class="separator"></div>
<div class="right">Right With Text</div>
</div>
<div class="row">
<div class="left">Left With More Text</div>
<div class="separator"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left With Text</div>
<div class="separator"></div>
<div class="right">Right With More Text</div>
</div>
_x000D_
Update: I wrote a solution that doesn't require reading the entire file in one go. It's too big for a stackoverflow answer, but can be found here jsonstream
.
You can use json.JSONDecoder.raw_decode
to decode arbitarily big strings of "stacked" JSON (so long as they can fit in memory). raw_decode
stops once it has a valid object and returns the last position where wasn't part of the parsed object. It's not documented, but you can pass this position back to raw_decode
and it start parsing again from that position. Unfortunately, the Python json
module doesn't accept strings that have prefixing whitespace. So we need to search to find the first none-whitespace part of your document.
from json import JSONDecoder, JSONDecodeError
import re
NOT_WHITESPACE = re.compile(r'[^\s]')
def decode_stacked(document, pos=0, decoder=JSONDecoder()):
while True:
match = NOT_WHITESPACE.search(document, pos)
if not match:
return
pos = match.start()
try:
obj, pos = decoder.raw_decode(document, pos)
except JSONDecodeError:
# do something sensible if there's some error
raise
yield obj
s = """
{"a": 1}
[
1
,
2
]
"""
for obj in decode_stacked(s):
print(obj)
prints:
{'a': 1}
[1, 2]
I had the same problem. The answers got me on the right track. So the problem is that functions marked with async don't return a task of the function itself as expected (but another continuation task of the function).
So its the "await"and "async" keywords that screws thing up. The simplest solution then is simply to remove them. Then it works as expected. As in:
static void Main(string[] args)
{
Console.WriteLine("Foo called");
var result = Foo(5);
while (result.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId, result.Status);
Task.Delay(100).Wait();
}
Console.WriteLine("Result: {0}", result.Result);
Console.WriteLine("Finished.");
Console.ReadKey(true);
}
private static Task<string> Foo(int seconds)
{
return Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
return "Foo Completed.";
});
}
Which outputs:
Foo called
Thread ID: 1, Status: WaitingToRun
Thread ID: 3, second 0.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 1.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 2.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 3.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 4.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Result: Foo Completed.
Finished.
try this
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()
$.each(json, function (key, data) {
console.log(key)
$.each(data, function (index, data) {
console.log('index', data)
})
})
Demo: Fiddle
As mentioned by Nacho.L PBKDF2WithHmacSHA1 derivation is used as it is more secured.
import android.util.Base64;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AESEncyption {
private static final int pswdIterations = 10;
private static final int keySize = 128;
private static final String cypherInstance = "AES/CBC/PKCS5Padding";
private static final String secretKeyInstance = "PBKDF2WithHmacSHA1";
private static final String plainText = "sampleText";
private static final String AESSalt = "exampleSalt";
private static final String initializationVector = "8119745113154120";
public static String encrypt(String textToEncrypt) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(getRaw(plainText, AESSalt), "AES");
Cipher cipher = Cipher.getInstance(cypherInstance);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(initializationVector.getBytes()));
byte[] encrypted = cipher.doFinal(textToEncrypt.getBytes());
return Base64.encodeToString(encrypted, Base64.DEFAULT);
}
public static String decrypt(String textToDecrypt) throws Exception {
byte[] encryted_bytes = Base64.decode(textToDecrypt, Base64.DEFAULT);
SecretKeySpec skeySpec = new SecretKeySpec(getRaw(plainText, AESSalt), "AES");
Cipher cipher = Cipher.getInstance(cypherInstance);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(initializationVector.getBytes()));
byte[] decrypted = cipher.doFinal(encryted_bytes);
return new String(decrypted, "UTF-8");
}
private static byte[] getRaw(String plainText, String salt) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(secretKeyInstance);
KeySpec spec = new PBEKeySpec(plainText.toCharArray(), salt.getBytes(), pswdIterations, keySize);
return factory.generateSecret(spec).getEncoded();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return new byte[0];
}
}
SELECT
category,
COUNT(*) AS `num`
FROM
posts
GROUP BY
category
Yes, once you have joined the iPhone Developer Program, and paid Apple $99, you can provision your applications on up to 100 iOS devices.
We use maven and svn. It was an mistaken checkin of target directory to SVN that cause this error. Removing that fixed everything, if this hint helps anyone.
Here's a complete solution for Swagger with Spring Security. We probably want to only enable Swagger in our development and QA environment and disable it in the production environment. So, I am using a property (prop.swagger.enabled
) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.
@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;
@Bean
public Docket SwaggerConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(enableSwagger)
.select()
.apis(RequestHandlerSelectors.basePackage("com.your.controller"))
.paths(PathSelectors.any())
.build();
}
@Override
public void configure(WebSecurity web) throws Exception {
if (enableSwagger)
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (enableSwagger) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}
If you are using a webkit browser you can change the color of the caret by following the next CSS snippet. I'm not sure if It's possible to change the format with CSS.
input,
textarea {
font-size: 24px;
padding: 10px;
color: red;
text-shadow: 0px 0px 0px #000;
-webkit-text-fill-color: transparent;
}
input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
color:
text-shadow: none;
-webkit-text-fill-color: initial;
}
Here is an example: http://jsfiddle.net/8k1k0awb/
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/
You can run the following query and find the duplicates with max(id)
and delete those rows.
SELECT orgName, COUNT(*), Max(ID) AS dupes
FROM organizations
GROUP BY orgName
HAVING (COUNT(*) > 1)
But you'll have to run this query a few times.
use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.
Device Sizes and class prefix:
.col-xs-
.col-sm-
.col-md-
.col-lg-
Grid options:
Reference: Grid System
Instead of using the = operator, you may want to use LIKE or LIKE BINARY
// this returns 1 (true)
select 'A' like 'a'
// this returns 0 (false)
select 'A' like binary 'a'
select * from user where username like binary 'a'
It will take 'a' and not 'A' in its condition
wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm
rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm
maybe some URL is broken,please research it. Enjoy~~
var b = String(stringInterpolationSegment: a)
This works for me. You may have a try
That is because is does not exist, since it is bounded to Windows.
Use the standard functions from <stdio.h>
instead, such as getc
The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.
Transaction Isolation and Transaction Propagation although related but are clearly two very different concepts. In both cases defaults are customized at client boundary component either by using Declarative transaction management or Programmatic transaction management. Details of each isolation levels and propagation attributes can be found in reference links below.
For given two or more running transactions/connections to a database, how and when are changes made by queries in one transaction impact/visible to the queries in a different transaction. It also related to what kind of database record locking will be used to isolate changes in this transaction from other transactions and vice versa. This is typically implemented by database/resource that is participating in transaction.
.
In an enterprise application for any given request/processing there are many components that are involved to get the job done. Some of this components mark the boundaries (start/end) of a transaction that will be used in respective component and it's sub components. For this transactional boundary of components, Transaction Propogation specifies if respective component will or will not participate in transaction and what happens if calling component already has or does not have a transaction already created/started. This is same as Java EE Transaction Attributes. This is typically implemented by the client transaction/connection manager.
Reference:
you can use this syntax:
INSERT INTO table_name ( name, age )
select 'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');
if its open an pop for asking as "enter substitution variable" then use this before the above queries:
set define off;
INSERT INTO table_name ( name, age )
select 'jonny', 18 from dual
where not exists(select 1 from table_name where name = 'jonny');
Options -Indexes
I have to try create .htaccess file that current directory that i want to disallow directory index listing. But, sorry i don't know about recursive in .htaccess code.
Try it.
this way we can iterate into table data.
DECLARE @_MinJobID INT
DECLARE @_MaxJobID INT
CREATE TABLE #Temp (JobID INT)
INSERT INTO #Temp SELECT * FROM DBO.STRINGTOTABLE(@JobID,',')
SELECT @_MinJID = MIN(JobID),@_MaxJID = MAX(JobID) FROM #Temp
WHILE @_MinJID <= @_MaxJID
BEGIN
INSERT INTO Mytable
(
JobID,
)
VALUES
(
@_MinJobID,
)
SET @_MinJID = @_MinJID + 1;
END
DROP TABLE #Temp
STRINGTOTABLE is user define function which will parse comma separated data and return table. thanks
I have this function in my toolbelt since years ago (all the function and variable names are messy and mixing Spanish and English, sorry for that).
It lets the user use ,
and .
to separate the decimals and will try to do the best if both symbols are used.
Public Shared Function TryCDec(ByVal texto As String, Optional ByVal DefaultValue As Decimal = 0) As Decimal
If String.IsNullOrEmpty(texto) Then
Return DefaultValue
End If
Dim CurAsTexto As String = texto.Trim.Replace("$", "").Replace(" ", "")
''// You can probably use a more modern way to find out the
''// System current locale, this function was done long time ago
Dim SepDecimal As String, SepMiles As String
If CDbl("3,24") = 324 Then
SepDecimal = "."
SepMiles = ","
Else
SepDecimal = ","
SepMiles = "."
End If
If InStr(CurAsTexto, SepDecimal) > 0 Then
If InStr(CurAsTexto, SepMiles) > 0 Then
''//both symbols was used find out what was correct
If InStr(CurAsTexto, SepDecimal) > InStr(CurAsTexto, SepMiles) Then
''// The usage was correct, but get rid of thousand separator
CurAsTexto = Replace(CurAsTexto, SepMiles, "")
Else
''// The usage was incorrect, but get rid of decimal separator and then replace it
CurAsTexto = Replace(CurAsTexto, SepDecimal, "")
CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
End If
End If
Else
CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
End If
''// At last we try to tryParse, just in case
Dim retval As Decimal = DefaultValue
Decimal.TryParse(CurAsTexto, retval)
Return retval
End Function
Similar to @Shravan, but without the use of numpy:
height = 10
width = 20
df_0 = pd.DataFrame(0, index=range(height), columns=range(width))
Then you can do whatever you want with it:
post_instantiation_fcn = lambda x: str(x)
df_ready_for_whatever = df_0.applymap(post_instantiation_fcn)
Given your current example you could achieve the result by either
var txt2 = txt1.split(' ').join(' bar ')
or
var txt2 = txt1.replace(' ', ' bar ');
but given that you can make such assumptions, you might as well skip directly to Gullen's example.
In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.
jQuery BBQ (Back Button & Query Library)
A high quality hash-based browser history plugin and very much up-to-date (Jan 26, 2010) as of this writing (jQuery 1.4.1).
If all you care about is the current process, an easy way is to use the file object attribute "closed"
f = open('file.py')
if f.closed:
print 'file is closed'
This will not detect if the file is open by other processes!
source: http://docs.python.org/2.4/lib/bltin-file-objects.html
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
The accepted answer is correct but needs to be wary that this way imposes a 255 character limit. Better to reference an actual worksheet range object.
You can use .issubset() as well
>>> {"key1", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
True
>>> {"key4", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
False
>>>
strip()
returns the string after removing leading and trailing whitespace. see doc
In your case, you may want to try replace():
string2 = string1.replace('\n', '')
Consider your REST API returns:
{"Intent":{"Command":"search","SubIntent":null}}
Then you can do the following to print it in a nice format:
<pre id="ciResponseText">Output will de displayed here.</pre>
var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);
Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta
for the simple stuff i.e.
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)
or you can start using relativedelta
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(years=+1)
for the last day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
Right now this will provide 29/02/2016
for the penultimate day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)
last Friday of the next month:
use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))
2nd Tuesday of next month:
new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))
As @mrroot5 points out dateutil's rrule
functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.
from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)
#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)
#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
print(ld)
#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
print(tuesday)
Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00
2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00
This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/
In addition you can add
profile.setPreference("browser.download.panel.shown",false);
To remove the downloaded file list that gets shown by default and covers up part of the web page.
My total settings are:
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.merge(capabillities);
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setPreference("browser.download.folderList", 4);
profile.setPreference("browser.download.dir", TestConstants.downloadDir.getAbsolutePath());
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, data:image/png, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("browser.download.panel.shown",false);
dc.setCapability(FirefoxDriver.PROFILE, profile);
this.driver = new FirefoxDriver(dc);
Probably because it just didn't make much sense for list semantics. However, you can easily create your own by subclassing.
class safelist(list):
def get(self, index, default=None):
try:
return self.__getitem__(index)
except IndexError:
return default
def _test():
l = safelist(range(10))
print l.get(20, "oops")
if __name__ == "__main__":
_test()
Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution.
Using componentWillReceiveProps
I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilà.
@propTypes =
element: React.PropTypes.shape({
version: React.PropTypes.number
params:
React.PropTypes.shape(
url: React.PropTypes.string.isRequired
filename: React.PropTypes.string.isRequired
title: React.PropTypes.string.isRequired
ext: React.PropTypes.string.isRequired
).isRequired
}).isRequired
componentWillReceiveProps: (nextProps) ->
element = ReactDOM.findDOMNode(this)
audio = element.querySelector('audio')
source = audio.querySelector('source')
# When the url changes, we refresh the component manually so it reloads the loaded file
if nextProps.element.params?.filename? and
nextProps.element.params.url isnt @props.element.params.url
source.src = nextProps.element.params.url
audio.load()
I had to do it this way, because even a change of state or a force redraw didn't work.
For me it worked like I had images in icons
folder under src
and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
Another way to get all change log in a specified period of time
git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10"
Output:
2637cc736 Revert changed code
1 file changed, 5 insertions(+), 5 deletions(-)
ba8d29402 Fix review
2 files changed, 4 insertions(+), 11 deletions(-)
With a long output content, you can export to file for more readable
git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10" > /mnt/MyChangeLog.txt
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
Use the @Input() decorator in your child component to allow the parent to bind to this input.
In the child component you declare it as is :
@Input() myInputName: myType
To bind a property from parent to a child you must add in you template the binding brackets and the name of your input between them.
Example :
<my-child-component [myChildInputName]="myParentVar"></my-child-component>
But beware, objects are passed as a reference, so if the object is updated in the child the parent's var will be too updated. This might lead to some unwanted behaviour sometime. With primary types the value is copied.
To go further read this :
Docs : https://angular.io/docs/ts/latest/cookbook/component-communication.html
<head>
<script type="text/javascript">
<%=YourScript %>
function functionname1(arg1,arg2){content}
</script>
</head>
public string YourScript = "";
public string functionname(arg)
{
if (condition)
{
YourScript = "functionname1(arg1,arg2);";
}
}
If you highlight the method Assert.assertEquals(val1, val2)
and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.
Consider following code
<ul id="myTask">
<li>Coding</li>
<li>Answering</li>
<li>Getting Paid</li>
</ul>
Now, here goes the difference
// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
$(this).remove()
});
Now, what if we add a myTask again?
$('#myTask').append('<li>Answer this question on SO</li>');
Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on
, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#myTask').on('click', 'li', function (event) {
$(event.target).remove()
});
Summary:
The difference between .on()
and .click()
would be that .click()
may not work when the DOM elements associated with the .click()
event are added dynamically at a later point while .on()
can be used in situations where the DOM elements associated with the .on()
call may be generated dynamically at a later point.
I solved my 'foreign key constraint fails' issues by adding the following code to the start of the SQL code (this was for importing values to a table)
SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT;
SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS;
SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION;
SET NAMES utf8;
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO';
SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0;
Then adding this code to the end of the file
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT;
SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS;
SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION;
SET SQL_NOTES=@OLD_SQL_NOTES;
You can actually build a solution that "just works" (no need to copy a module.modulemap and SWIFT_INCLUDE_PATHS
settings over to your project, as required by other solutions here), but it does require you to create a dummy framework/module that you'll import into your framework proper. We can also ensure it works regardless of platform (iphoneos
, iphonesimulator
, or macosx
).
Add a new framework target to your project and name it after the system library, e.g., "CommonCrypto". (You can delete the umbrella header, CommonCrypto.h.)
Add a new Configuration Settings File and name it, e.g., "CommonCrypto.xcconfig". (Don't check any of your targets for inclusion.) Populate it with the following:
MODULEMAP_FILE[sdk=iphoneos*] = \
$(SRCROOT)/CommonCrypto/iphoneos.modulemap
MODULEMAP_FILE[sdk=iphonesimulator*] = \
$(SRCROOT)/CommonCrypto/iphonesimulator.modulemap
MODULEMAP_FILE[sdk=macosx*] = \
$(SRCROOT)/CommonCrypto/macosx.modulemap
Create the three referenced module map files, above, and populate them with the following:
iphoneos.modulemap
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
iphonesimulator.modulemap
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
macosx.modulemap
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/CommonCrypto/CommonCrypto.h"
export *
}
(Replace "Xcode.app" with "Xcode-beta.app" if you're running a beta version. Replace 10.11
with your current OS SDK if not running El Capitan.)
On the Info tab of your project settings, under Configurations, set the Debug and Release configurations of CommonCrypto to CommonCrypto (referencing CommonCrypto.xcconfig).
On your framework target's Build Phases tab, add the CommonCrypto framework to Target Dependencies. Additionally add libcommonCrypto.dylib to the Link Binary With Libraries build phase.
Select CommonCrypto.framework in Products and make sure its Target Membership for your wrapper is set to Optional.
You should now be able to build, run and import CommonCrypto
in your wrapper framework.
For an example, see how SQLite.swift uses a dummy sqlite3.framework.
Luckily, Python has this built-in :)
import re
re.split('; |, ',str)
Update:
Following your comment:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
sudo /Applications/XAMPP/xamppfiles/bin/apachectl start
This fixed my issue AFTER ensuring my ports were all uniquely sorted out.
At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".
In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.
So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.
You have to include sort
function which is in algorithm
header file which is a standard template library in c++.
Usage: std::sort(str.begin(), str.end());
#include <iostream>
#include <algorithm> // this header is required for std::sort to work
int main()
{
std::string s = "dacb";
std::sort(s.begin(), s.end());
std::cout << s << std::endl;
return 0;
}
OUTPUT:
abcd
Try the :host > /deep/ :
Add the following to the parent.component.less file
:host {
/deep/ app-child-component {
//your child style
}
}
Replace the app-child-component by your child selector
And if you need authorized user in templates (e.g. JSP) use
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>
together with
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-security.version}</version>
</dependency>
The document
and window
are different objects and they have some different events. Using addEventListener()
on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.
For example, there is a "resize"
event on the window
object that is not on the document
object.
For example, the "DOMContentLoaded"
event is only on the document
object.
So basically, you need to know which object receives the event you are interested in and use .addEventListener()
on that particular object.
Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document
object before the window
object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document
over window
when either will work. But, I'd often move even closer to the source and use document.body
or even some closer common parent in the document (if possible).
Take it that forward declaration will get your code to compile (obj is created). Linking however (exe creation) will not be successfull unless the definitions are found.
Minimal settings to prevent resize events
form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;
Right now there is no view:clear command. For laravel 4 this can probably help you: https://gist.github.com/cjonstrup/8228165
Disabling caching can be done by skipping blade. View caching is done because blade compiling each time is a waste of time.
In my case I wrote like this:
python manage.py makemigrations
--empty yourappname
python manage.py migrate yourappname
or:
Django keeps track of all the applied migrations in django_migrations table. So just delete all the rows in the django_migrations table that are related to you app like:
DELETE FROM django_migrations WHERE app='
your-app-name'
and then do:
python manage.py makemigrations
python manage.py migrate
There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.
If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.
I faced same issue, I have installed two java version hence it caused this issue. to confirm this go and click java icon in control panel if doesnt open then issue is same, just go and uninstall one version. piece of cake. thanks.
I know it is a 100 year old post, but anyway, thought it might be useful to someone. You can put an invisible image somewhere on the page pointing to the url that needs to run in the background, like this:
<img src="run-in-background.php" border="0" alt="" width="1" height="1" />
bool data(sampleData *data)
{
}
You need to tell the method which type of struct you are using. In this case, sampleData.
Note: In this case, you will need to define the struct prior to the method for it to be recognized.
Example:
struct sampleData
{
int N;
int M;
// ...
};
bool data(struct *sampleData)
{
}
int main(int argc, char *argv[]) {
sampleData sd;
data(&sd);
}
Note 2: I'm a C guy. There may be a more c++ish way to do this.
If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.
In your case, Var1
is considered as a local variable, and it's used before being set, thus the error.
To solve this problem, you can explicitly say it's a global by putting global Var1
in you function.
Var1 = 1
Var2 = 0
def function():
global Var1
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
Put the part from BEGIN....END{}
inside a file and name it like my.awk.
And then execute it like below:
awk -f my.awk life.csv >output.txt
Also I see a field separator as ,
. You can add that in the begin block of the .awk file as FS=","
I fixed this by restarting VS.
I had opened a config file in another instance of VS and apparently sth went nuts...
The easy way to do it is to use background-image then just put an <img> in that element.
The other way to do is using css layers. There is a ton a resources available to help you with this, just search for css layers.
s = 'sdsd'
print (s.upper())
upper = raw_input('type in something lowercase.')
lower = raw_input('type in the same thing caps lock.')
print upper.upper()
print lower.lower()
Providing you know these vim commands:
1G -> go to first line in file
G -> go to last line in file
then, the following make more sense, are more unitary and easier to remember IMHO:
d1G -> delete starting from the line you are on, to the first line of file
dG -> delete starting from the line you are on, to the last line of file
Cheers.
Math.NET is an opensource library that offers a method for calculating the Median. The nuget package is called MathNet.Numerics.
The usage is pretty simple:
using MathNet.Numerics.Statistics;
IEnumerable<double> data;
double median = data.Median();
Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.
It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers
Deprecated. The UI service was deprecated on December 11, 2014. To create user interfaces, use the HTML service instead.
The example in the HTML Service linked page is pretty simple,
Code.gs
// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
A customized version of index.html to show two hyperlinks
<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>
For Android .so
files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf
, objdump
and nm
.
Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,
rdd = df.rdd.flatMap(list)
or
rdd = df.rdd.flatmap(lambda x: list(x))
Imports System.Net.NetworkInformation
Public Function PingHost(ByVal nameOrAddress As String) As Boolean
Dim pingable As Boolean = False
Dim pinger As Ping
Dim lPingReply As PingReply
Try
pinger = New Ping()
lPingReply = pinger.Send(nameOrAddress)
MessageBox.Show(lPingReply.Status)
If lPingReply.Status = IPStatus.Success Then
pingable = True
Else
pingable = False
End If
Catch PingException As Exception
pingable = False
End Try
Return pingable
End Function
This answer is for upgrading Python 2.7.10 to Python 2.7.11 on Mac OS X El Capitan . On Terminal type:
brew unlink python
After that type on Terminal
brew install python
I really think it's a more robust way to use getLocationOnScreen
than getGlobalVisibleRect
. Because I meet a problem. There is a Listview which contain some Edittext and and set ajustpan
in the activity. I find getGlobalVisibleRect
return a value that looks like including the scrollY in it, but the event.getRawY is always by the screen. The below code works well.
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
if (!isPointInsideView(event.getRawX(), event.getRawY(), v)) {
Log.i(TAG, "!isPointInsideView");
Log.i(TAG, "dispatchTouchEvent clearFocus");
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
/**
* Determines if given points are inside view
* @param x - x coordinate of point
* @param y - y coordinate of point
* @param view - view object to compare
* @return true if the points are within view bounds, false otherwise
*/
private boolean isPointInsideView(float x, float y, View view) {
int location[] = new int[2];
view.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
Log.i(TAG, "location x: " + location[0] + ", y: " + location[1]);
Log.i(TAG, "location xWidth: " + (viewX + view.getWidth()) + ", yHeight: " + (viewY + view.getHeight()));
// point is inside view bounds
return ((x > viewX && x < (viewX + view.getWidth())) &&
(y > viewY && y < (viewY + view.getHeight())));
}
Specifically, rm yarn.lock
and then yarn install
fixed this for me.
I use the following to alias cls
when debugging locally in Chrome (enter the following JavaScript into the console):
Object.defineProperty(window, 'cls', {
get: function () {
return console.clear();
}
});
now entering cls
in the console will clear the console.
Assuming a modern release, find -newermt
is powerful:
find -newermt '10 minutes ago' ## other units work too, see `Date input formats`
or, if you want to specify a time_t
(seconds since epoch):
find -newermt @1568670245
For reference, -newermt
is not directly listed in the man page for find. Instead, it is shown as -newerXY
, where XY
are placeholders for mt
. Other replacements are legal, but not applicable for this solution.
From man find -newerXY
:
Time specifications are interpreted as for the argument to the -d option of GNU date.
So the following are equivalent to the initial example:
find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'
The date -d
(and find -newermt
) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats
Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
Try this:
SET TERMOUT OFF;
spool M:\Documents\test;
select * from employees;
/
spool off;
if anyone has a problem on Mac, can try this
sudo pip install --upgrade matplotlib --ignore-installed six
Check the answer how to implement headers with StoryBoard: Table Header Views in StoryBoards
Also notice that if you don't implement
viewForHeaderInSection:(NSInteger)section
it will not float which is exactly what you want.
This article has an excellent vimrc script for handling tabs+spaces, and converting in between them.
These commands are provided:
Space2Tab Convert spaces to tabs, only in indents.
Tab2Space Convert tabs to spaces, only in indents.
RetabIndent Execute Space2Tab (if 'expandtab' is set), or Tab2Space (otherwise).
Each command accepts an argument that specifies the number of spaces in a tab column. By default, the 'tabstop' setting is used.
Source: http://vim.wikia.com/wiki/Super_retab#Script
" Return indent (all whitespace at start of a line), converted from
" tabs to spaces if what = 1, or from spaces to tabs otherwise.
" When converting to tabs, result has no redundant spaces.
function! Indenting(indent, what, cols)
let spccol = repeat(' ', a:cols)
let result = substitute(a:indent, spccol, '\t', 'g')
let result = substitute(result, ' \+\ze\t', '', 'g')
if a:what == 1
let result = substitute(result, '\t', spccol, 'g')
endif
return result
endfunction
" Convert whitespace used for indenting (before first non-whitespace).
" what = 0 (convert spaces to tabs), or 1 (convert tabs to spaces).
" cols = string with number of columns per tab, or empty to use 'tabstop'.
" The cursor position is restored, but the cursor will be in a different
" column when the number of characters in the indent of the line is changed.
function! IndentConvert(line1, line2, what, cols)
let savepos = getpos('.')
let cols = empty(a:cols) ? &tabstop : a:cols
execute a:line1 . ',' . a:line2 . 's/^\s\+/\=Indenting(submatch(0), a:what, cols)/e'
call histdel('search', -1)
call setpos('.', savepos)
endfunction
command! -nargs=? -range=% Space2Tab call IndentConvert(<line1>,<line2>,0,<q-args>)
command! -nargs=? -range=% Tab2Space call IndentConvert(<line1>,<line2>,1,<q-args>)
command! -nargs=? -range=% RetabIndent call IndentConvert(<line1>,<line2>,&et,<q-args>)
This helped me a bit more than the answers here did when I first went searching for a solution.
We can use Jquery methods $.each()/$.grep()
var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}
or
var data = $.grep(array, function( n, i ) {
return ( n !== 5 && i > 4 );
});
use ES6 syntax:
Array.find, Array.filter, Array.forEach, Array.map
Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter
Before starting, Make sure that USB DEBUGGING IS ENABLED in your phone settings !!!
1) BASIC STEP - Plug in device via USB, then go to device page in Android developers blog. There you can find necessary information regarding adding USB vendor ids. Add your device specific ids, and restart eclipse if needed.
2)If you were able to see the device connected(using command: 'adb devices'
) earlier, but not anymore, then just try restarting ADB. (you can use the commands: 'adb kill-server'
followed by 'adb start-server'
. adb commands need to be executed from platform tools folder in the Android SDK, if you havent exported it).
3)If neither of them works out and you are on windows machine, then check the installed usb drivers are correct. If not install proper drivers Please find more information on how to install/update drivers in http://developer.android.com/tools/extras/oem-usb.html
If this also is not working, try installing Universal ADB windows driver https://plus.google.com/103583939320326217147/posts/BQ5iYJEaaEH
4)You may also try increasing the timeout time Go to preferences-> android->DDMS in eclipse, then try increasing 'ADB connection timeout(ms)' value
Update based on newer answers:
5)Run > Run Configurations > Target. Please make sure, the option "Always prompt to pick device" is enabled.
Special case: Windows 8 and Nexus 10 (from this question: ADB No Devices Found)
Windows 8 wouldn't recognize my Nexus 10 device. Fixed by Setting the transfer mode to Camera (PTP) through the settings dialogue on the device.
Settings > Storage > Menu > USB Computer connection to "Camera (PTP)"
As described in the answer of Ricardo ,
netsh Winsock reset
has worked for me ,
P.S. if you have Internet download manager or such programs which changes you IP Setting is installed then after running this command when you reboot your computer IDM will ask to change setting , Set NO in this case and then run your application it will work correctly.
Hope it
I've always used this syntax, which yields more predictable results than using !=.
<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')" />
Use the collapse
argument to paste
:
paste(a,collapse=" ")
[1] "aa bb cc"
Even without pop
the list we can do with set_index
pd.DataFrame(table).T.set_index(0).T
Out[11]:
0 Heading1 Heading2
1 1 2
2 3 4
Update from_records
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]:
Heading1 Heading2
0 1 2
1 3 4
Here is a non-numpy solution:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]
Try this:
if (items.elementAt(1) instanceof Double) {
sum.add( i, items.elementAt(1));
}
If you're using jQuery, it's as simple as this:
$('form').attr('action', 'myNewActionTarget.html');
MessageBox like others said, or RegisterClientScriptBlock if you want something more arbitrary, but your use case is extremely dubious. Merely displaying exceptions is not something you want to do in production code - you don't want to expose that detail publicly and you do want to record it with proper logging privately.
In Swift 2.0 you can use this method:
let registrationView = LMRegistration()
self.presentViewController(registrationView, animated: true, completion: nil)
Check if
str.charAt(str.length() -1) == ','
.
Then do
str = str.substring(0, str.length()-1)
for Angular 6+ and >=RC.6
.html
<form [formGroup]="formGroup">
<input type="text" formControlName="myName">
</form>
.ts
public formGroup: FormGroup;
this.formGroup.value.myName
should also work.
df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <- letters[1:10]
df[c('a','b'),]
Git 2.22 (Q2 2019) introduces trace2
with commit ee4512e by Jeff Hostetler:
trace2
: create new combined trace facility
Create a new unified tracing facility for git.
The eventual intent is to replace the currenttrace_printf*
andtrace_performance*
routines with a unified set ofgit_trace2*
routines.In addition to the usual printf-style API,
trace2
provides higer-level event verbs with fixed-fields allowing structured data to be written.
This makes post-processing and analysis easier for external tools.Trace2 defines 3 output targets.
These are set using the environment variables "GIT_TR2
", "GIT_TR2_PERF
", and "GIT_TR2_EVENT
".
These may be set to "1" or to an absolute pathname (just like the currentGIT_TRACE
).
Note: regarding environment variable name, always use GIT_TRACExxx
, not GIT_TRxxx
.
So actually GIT_TRACE2
, GIT_TRACE2_PERF
or GIT_TRACE2_EVENT
.
See the Git 2.22 rename mentioned later below.
What follows is the initial work on this new tracing feature, with the old environment variable names:
GIT_TR2
is intended to be a replacement forGIT_TRACE
and logs command summary data.
GIT_TR2_PERF
is intended as a replacement forGIT_TRACE_PERFORMANCE
.
It extends the output with columns for the command process, thread, repo, absolute and relative elapsed times.
It reports events for child process start/stop, thread start/stop, and per-thread function nesting.
GIT_TR2_EVENT
is a new structured format. It writes event data as a series of JSON records.Calls to trace2 functions log to any of the 3 output targets enabled without the need to call different
trace_printf*
ortrace_performance*
routines.
See commit a4d3a28 (21 Mar 2019) by Josh Steadmon (steadmon
).
(Merged by Junio C Hamano -- gitster
-- in commit 1b40314, 08 May 2019)
trace2
: write to directory targets
When the value of a trace2 environment variable is an absolute path referring to an existing directory, write output to files (one per process) underneath the given directory.
Files will be named according to the final component of the trace2 SID, followed by a counter to avoid potential collisions.This makes it more convenient to collect traces for every git invocation by unconditionally setting the relevant
trace2
envvar to a constant directory name.
See also commit f672dee (29 Apr 2019), and commit 81567ca, commit 08881b9, commit bad229a, commit 26c6f25, commit bce9db6, commit 800a7f9, commit a7bc01e, commit 39f4317, commit a089724, commit 1703751 (15 Apr 2019) by Jeff Hostetler (jeffhostetler
).
(Merged by Junio C Hamano -- gitster
-- in commit 5b2d1c0, 13 May 2019)
The new documentation now includes config settings which are only read from the system and global config files (meaning repository local and worktree config files and -c
command line arguments are not respected.)
$ git config --global trace2.normalTarget ~/log.normal
$ git version
git version 2.20.1.155.g426c96fcdb
yields
$ cat ~/log.normal
12:28:42.620009 common-main.c:38 version 2.20.1.155.g426c96fcdb
12:28:42.620989 common-main.c:39 start git version
12:28:42.621101 git.c:432 cmd_name version (version)
12:28:42.621215 git.c:662 exit elapsed:0.001227 code:0
12:28:42.621250 trace2/tr2_tgt_normal.c:124 atexit elapsed:0.001265 code:0
And for performance measure:
$ git config --global trace2.perfTarget ~/log.perf
$ git version
git version 2.20.1.155.g426c96fcdb
yields
$ cat ~/log.perf
12:28:42.620675 common-main.c:38 | d0 | main | version | | | | | 2.20.1.155.g426c96fcdb
12:28:42.621001 common-main.c:39 | d0 | main | start | | 0.001173 | | | git version
12:28:42.621111 git.c:432 | d0 | main | cmd_name | | | | | version (version)
12:28:42.621225 git.c:662 | d0 | main | exit | | 0.001227 | | | code:0
12:28:42.621259 trace2/tr2_tgt_perf.c:211 | d0 | main | atexit | | 0.001265 | | | code:0
As documented in Git 2.23 (Q3 2019), the environment variable to use is GIT_TRACE2
.
See commit 6114a40 (26 Jun 2019) by Carlo Marcelo Arenas Belón (carenas
).
See commit 3efa1c6 (12 Jun 2019) by Ævar Arnfjörð Bjarmason (avar
).
(Merged by Junio C Hamano -- gitster
-- in commit e9eaaa4, 09 Jul 2019)
That follows the work done in Git 2.22: commit 4e0d3aa, commit e4b75d6 (19 May 2019) by SZEDER Gábor (szeder
).
(Merged by Junio C Hamano -- gitster
-- in commit 463dca6, 30 May 2019)
trace2
: rename environment variables to GIT_TRACE2*
For an environment variable that is supposed to be set by users, the
GIT_TR2*
env vars are just too unclear, inconsistent, and ugly.Most of the established
GIT_*
environment variables don't use abbreviations, and in case of the few that do (GIT_DIR
,GIT_COMMON_DIR
,GIT_DIFF_OPTS
) it's quite obvious what the abbreviations (DIR
andOPTS
) stand for.
But what doesTR
stand for? Track, traditional, trailer, transaction, transfer, transformation, transition, translation, transplant, transport, traversal, tree, trigger, truncate, trust, or ...?!The trace2 facility, as the '2' suffix in its name suggests, is supposed to eventually supercede Git's original trace facility.
It's reasonable to expect that the corresponding environment variables follow suit, and after the originalGIT_TRACE
variables they are calledGIT_TRACE2
; there is no such thing is 'GIT_TR
'.All trace2-specific config variables are, very sensibly, in the '
trace2
' section, not in 'tr2
'.OTOH, we don't gain anything at all by omitting the last three characters of "trace" from the names of these environment variables.
So let's rename all
GIT_TR2*
environment variables toGIT_TRACE2*
, before they make their way into a stable release.
Git 2.24 (Q3 2019) improves the Git repository initialization.
See commit 22932d9, commit 5732f2b, commit 58ebccb (06 Aug 2019) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit b4a1eec, 09 Sep 2019)
common-main: delay trace2 initialization
We initialize the
trace2
system in the common main() function so that all programs (even ones that aren't builtins) will enable tracing.But
trace2
startup is relatively heavy-weight, as we have to actually read on-disk config to decide whether to trace.
This can cause unexpected interactions with other common-main initialization. For instance, we'll end up in the config code before callinginitialize_the_repository()
, and the usual invariant thatthe_repository
is never NULL will not hold.Let's push the
trace2
initialization further down in common-main, to just before we executecmd_main()
.
Git 2.24 (Q4 2019) makes also sure that output from trace2
subsystem is formatted more prettily now.
See commit 742ed63, commit e344305, commit c2b890a (09 Aug 2019), commit ad43e37, commit 04f10d3, commit da4589c (08 Aug 2019), and commit 371df1b (31 Jul 2019) by Jeff Hostetler (jeffhostetler
).
(Merged by Junio C Hamano -- gitster
-- in commit 93fc876, 30 Sep 2019)
And, still Git 2.24
See commit 87db61a, commit 83e57b0 (04 Oct 2019), and commit 2254101, commit 3d4548e (03 Oct 2019) by Josh Steadmon (steadmon
).
(Merged by Junio C Hamano -- gitster
-- in commit d0ce4d9, 15 Oct 2019)
trace2
: discard new traces if target directory has too many filesSigned-off-by: Josh Steadmon
trace2
can write files into a target directory.
With heavy usage, this directory can fill up with files, causing difficulty for trace-processing systems.This patch adds a config option (
trace2.maxFiles
) to set a maximum number of files thattrace2
will write to a target directory.The following behavior is enabled when the
maxFiles
is set to a positive integer:
- When
trace2
would write a file to a target directory, first check whether or not the traces should be discarded.
Traces should be discarded if:
- there is a sentinel file declaring that there are too many files
- OR, the number of files exceeds
trace2.maxFiles
.
In the latter case, we create a sentinel file namedgit-trace2-discard
to speed up future checks.The assumption is that a separate trace-processing system is dealing with the generated traces; once it processes and removes the sentinel file, it should be safe to generate new trace files again.
The default value for
trace2.maxFiles
is zero, which disables the file count check.The config can also be overridden with a new environment variable:
GIT_TRACE2_MAX_FILES
.
And Git 2.24 (Q4 2019) teach trace2 about git push
stages.
See commit 25e4b80, commit 5fc3118 (02 Oct 2019) by Josh Steadmon (steadmon
).
(Merged by Junio C Hamano -- gitster
-- in commit 3b9ec27, 15 Oct 2019)
push
: add trace2 instrumentationSigned-off-by: Josh Steadmon
Add trace2 regions in
transport.c
andbuiltin/push.c
to better track time spent in various phases of pushing:
- Listing refs
- Checking submodules
- Pushing submodules
- Pushing refs
With Git 2.25 (Q1 2020), some of the Documentation/technical
is moved to header *.h
files.
See commit 6c51cb5, commit d95a77d, commit bbcfa30, commit f1ecbe0, commit 4c4066d, commit 7db0305, commit f3b9055, commit 971b1f2, commit 13aa9c8, commit c0be43f, commit 19ef3dd, commit 301d595, commit 3a1b341, commit 126c1cc, commit d27eb35, commit 405c6b1, commit d3d7172, commit 3f1480b, commit 266f03e, commit 13c4d7e (17 Nov 2019) by Heba Waly (HebaWaly
).
(Merged by Junio C Hamano -- gitster
-- in commit 26c816a, 16 Dec 2019)
trace2
: move doc totrace2.h
Signed-off-by: Heba Waly
Move the functions documentation from
Documentation/technical/api-trace2.txt
totrace2.h
as it's easier for the developers to find the usage information beside the code instead of looking for it in another doc file.Only the functions documentation section is removed from
Documentation/technical/api-trace2.txt
as the file is full of details that seemed more appropriate to be in a separate doc file as it is, with a link to the doc file added in the trace2.h. Also the functions doc is removed to avoid having redundandt info which will be hard to keep syncronized with the documentation in the header file.
(although that reorganization had a side effect on another command, explained and fixed with Git 2.25.2 (March 2020) in commit cc4f2eb (14 Feb 2020) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 1235384, 17 Feb 2020))
With Git 2.27 (Q2 2020): Trace2 enhancement to allow logging of the environment variables.
See commit 3d3adaa (20 Mar 2020) by Josh Steadmon (steadmon
).
(Merged by Junio C Hamano -- gitster
-- in commit 810dc64, 22 Apr 2020)
trace2
: teach Git to log environment variablesSigned-off-by: Josh Steadmon
Acked-by: Jeff Hostetler
Via trace2, Git can already log interesting config parameters (see the
trace2_cmd_list_config()
function). However, this can grant an incomplete picture because many config parameters also allow overrides via environment variables.To allow for more complete logs, we add a new
trace2_cmd_list_env_vars()
function and supporting implementation, modeled after the pre-existing config param logging implementation.
With Git 2.27 (Q2 2020), teach codepaths that show progress meter to also use the start_progress()
and the stop_progress()
calls as a "region
" to be traced.
See commit 98a1364 (12 May 2020) by Emily Shaffer (nasamuffin
).
(Merged by Junio C Hamano -- gitster
-- in commit d98abce, 14 May 2020)
trace2
: log progress time and throughputSigned-off-by: Emily Shaffer
Rather than teaching only one operation, like '
git fetch
', how to write down throughput to traces, we can learn about a wide range of user operations that may seem slow by adding tooling to the progress library itself.Operations which display progress are likely to be slow-running and the kind of thing we want to monitor for performance anyways.
By showing object counts and data transfer size, we should be able to make some derived measurements to ensure operations are scaling the way we expect.
And:
With Git 2.27 (Q2 2020), last-minute fix for our recent change to allow use of progress API as a traceable region.
See commit 3af029c (15 May 2020) by Derrick Stolee (derrickstolee
).
(Merged by Junio C Hamano -- gitster
-- in commit 85d6e28, 20 May 2020)
progress
: calltrace2_region_leave()
only after calling_enter()
Signed-off-by: Derrick Stolee
A user of progress API calls
start_progress()
conditionally and depends on thedisplay_progress()
andstop_progress()
functions to become no-op whenstart_progress()
hasn't been called.As we added a call to
trace2_region_enter()
tostart_progress()
, the calls to other trace2 API calls from the progress API functions must make sure that these trace2 calls are skipped whenstart_progress()
hasn't been called on the progress struct.Specifically, do not call
trace2_region_leave()
fromstop_progress()
when we haven't calledstart_progress()
, which would have called the matchingtrace2_region_enter()
.
That last part is more robust with Git 2.29 (Q4 2020):
See commit ac900fd (10 Aug 2020) by Martin Ågren (none
).
(Merged by Junio C Hamano -- gitster
-- in commit e6ec620, 17 Aug 2020)
progress
: don't dereference before checking forNULL
Signed-off-by: Martin Ågren
In
stop_progress()
, we're careful to check thatp_progress
is non-NULL before we dereference it, but by then we have already dereferenced it when callingfinish_if_sparse(*p_progress)
.
And, for what it's worth, we'll go on to blindly dereference it again insidestop_progress_msg()
.We could return early if we get a NULL-pointer, but let's go one step further and BUG instead.
The progress API handlesNULL
just fine, but that's the NULL-ness of*p_progress
, e.g., when running with--no-progress
.
Ifp_progress
isNULL
, chances are that's a mistake.
For symmetry, let's do the same check instop_progress_msg()
, too.
With Git 2.29 (Q4 2020), there is even more trace, this time in a Git development environment.
See commit 4441f42 (09 Sep 2020) by Han-Wen Nienhuys (hanwen
).
(Merged by Junio C Hamano -- gitster
-- in commit c9a04f0, 22 Sep 2020)
refs
: addGIT_TRACE_REFS
debugging mechanismSigned-off-by: Han-Wen Nienhuys
When set in the environment,
GIT_TRACE_REFS
makesgit
print operations and results as they flow through the ref storage backend. This helps debug discrepancies between different ref backends.Example:
$ GIT_TRACE_REFS="1" ./git branch 15:42:09.769631 refs/debug.c:26 ref_store for .git 15:42:09.769681 refs/debug.c:249 read_raw_ref: HEAD: 0000000000000000000000000000000000000000 (=> refs/heads/ref-debug) type 1: 0 15:42:09.769695 refs/debug.c:249 read_raw_ref: refs/heads/ref-debug: 3a238e539bcdfe3f9eb5010fd218640c1b499f7a (=> refs/heads/ref-debug) type 0: 0 15:42:09.770282 refs/debug.c:233 ref_iterator_begin: refs/heads/ (0x1) 15:42:09.770290 refs/debug.c:189 iterator_advance: refs/heads/b4 (0) 15:42:09.770295 refs/debug.c:189 iterator_advance: refs/heads/branch3 (0)
git
now includes in its man page:
GIT_TRACE_REFS
Enables trace messages for operations on the ref database. See
GIT_TRACE
for available trace output options.
With Git 2.30 (Q1 2021), like die()
and error()
, a call to warning()
will also trigger a trace2 event.
See commit 0ee10fd (23 Nov 2020) by Jonathan Tan (jhowtan
).
(Merged by Junio C Hamano -- gitster
-- in commit 2aeafbc, 08 Dec 2020)
Set value to currency in <input type="number" />
It seems that you'll need two fields, a choice list for the currency and a number field for the value.
A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.
You can use regular expressions.
String input = ...
if (input.matches("[^a-zA-Z0-9 ]"))
If your definition of a 'special character' is simply anything that doesn't apply to your other filters that you already have, then you can simply add an else
. Also note that you have to use else if
in this case:
if(c == ' ') {
blankCount++;
} else if (Character.isDigit(c)) {
digitCount++;
} else if (Character.isLetter(c)) {
letterCount++;
} else {
specialcharCount++;
}
just other option. goto PREFERENCES >> JAVA >> EDITOR >> TEMPLATES, Select @author and change the variable ${user}.
Aaron Bertrand's answer is great, but flawed. It doesn't accurately handle a space as a delimiter (as was the example in the original question) since the length function strips trailing spaces.
The following is his code, with a small adjustment to allow for a space delimiter:
CREATE FUNCTION [dbo].[SplitString]
(
@List NVARCHAR(MAX),
@Delim VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT
[Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_objects) AS x
WHERE Number <= LEN(@List)
AND SUBSTRING(@Delim + @List, [Number], LEN(@Delim+'x')-1) = @Delim
) AS y
);
I raise an event in the the form setting the value and subscribe to that event in the form(s) that need to deal with the value change.
There is this extensions that adds an event listener to attribute changes.
Usage:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
Bind attrchange handler function to selected elements
$(selector).attrchange({
trackValues: true, /* Default to false, if set to true the event object is
updated with old and new value.*/
callback: function (event) {
//event - event object
//event.attributeName - Name of the attribute modified
//event.oldValue - Previous value of the modified attribute
//event.newValue - New value of the modified attribute
//Triggered when the selected elements attribute is added/updated/removed
}
});
Class selectors are prefixed with a dot. Your .find()
is missing that so jQuery thinks you're looking for <myClass>
elements.
var myVar = $("#start").find('.myClass').val();
I had this error coming up between 2 Linux boxes. Easily solved by installing RSYNC on the remote box as well as the local one.
rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table
the result will show lastname,firstname as one column header !
I developed a software tool that opens (most) Pickle files directly in your browser (nothing is transferred so it's 100% private):
Even I faced the same issue with the encoding that occurs when you try to print it, read/write it or open it. As others mentioned above adding .encoding="utf-8" will help if you are trying to print it.
soup.encode("utf-8")
If you are trying to open scraped data and maybe write it into a file, then open the file with (......,encoding="utf-8")
with open(filename_csv , 'w', newline='',encoding="utf-8") as csv_file:
Here is a version that doesn't require an UDF and works even if the HTML contains tags without matching closing tags.
TRY_CAST(REPLACE(REPLACE(REPLACE([HtmlCol], '>', '/> '), '</', '<'), '--/>', '-->') AS XML).value('.', 'NVARCHAR(MAX)')
The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int
int g[] = {9,8};
int (*j) = g;
could also be rewritten as
int g[] = {9,8};
int *j = g;
which could also be rewritten as
int g[] = {9,8};
int *j = &g[0];
a pointer-to-an-array would look like
int g[] = {9,8};
int (*j)[2] = &g;
//Dereference 'j' and access array element zero
int n = (*j)[0];
There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations
See Android arsenal (category Graphics) for more libraries.
I think that maybe it is because you are declaring a variable that you already declared:
var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue(); // <-- Here's the issue: 'var'
I think this should be like this:
var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();
Tell me if it works! ;)
Putting this question in the context of NIO and NIO.2 in java 7, async IO is one step more advanced than non-blocking.
With java NIO non-blocking calls, one would set all channels (SocketChannel, ServerSocketChannel, FileChannel, etc) as such by calling AbstractSelectableChannel.configureBlocking(false)
.
After those IO calls return, however, you will likely still need to control the checks such as if and when to read/write again, etc.
For instance,
while (!isDataEnough()) {
socketchannel.read(inputBuffer);
// do something else and then read again
}
With the asynchronous api in java 7, these controls can be made in more versatile ways.
One of the 2 ways is to use CompletionHandler
. Notice that both read
calls are non-blocking.
asyncsocket.read(inputBuffer, 60, TimeUnit.SECONDS /* 60 secs for timeout */,
new CompletionHandler<Integer, Object>() {
public void completed(Integer result, Object attachment) {...}
public void failed(Throwable e, Object attachment) {...}
}
}
I have recently migrated from C3P0
to HikariCP
in a Spring and Hibernate based project and it was not as easy as I had imagined and here I am sharing my findings.
For Spring Boot
see my answer here
I have the following setup
Some of the below configs are similar to some of the answers above but, there are differences.
In order to pull in the right jars, I needed to pull in the following jars
//latest driver because *brettw* see https://github.com/pgjdbc/pgjdbc/pull/849
compile 'org.postgresql:postgresql:42.2.0'
compile('com.zaxxer:HikariCP:2.7.6') {
//they are pulled in separately elsewhere
exclude group: 'org.hibernate', module: 'hibernate-core'
}
// Recommended to use HikariCPConnectionProvider by Hibernate in 4.3.6+
compile('org.hibernate:hibernate-hikaricp:4.3.8.Final') {
//they are pulled in separately elsewhere, to avoid version conflicts
exclude group: 'org.hibernate', module: 'hibernate-core'
exclude group: 'com.zaxxer', module: 'HikariCP'
}
// Needed for HikariCP logging if you use log4j
compile('org.slf4j:slf4j-simple:1.7.25')
compile('org.slf4j:slf4j-log4j12:1.7.25') {
//log4j pulled in separately, exclude to avoid version conflict
exclude group: 'log4j', module: 'log4j'
}
In order to get Spring & Hibernate to make use of Hikari Connection pool, you need to define the HikariDataSource
and feed it into sessionFactory
bean as shown below.
<!-- HikariCP Database bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<!-- HikariConfig config that is fed to above dataSource -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="SpringHikariPool" />
<property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
<property name="maximumPoolSize" value="20" />
<property name="idleTimeout" value="30000" />
<property name="dataSourceProperties">
<props>
<prop key="serverName">localhost</prop>
<prop key="portNumber">5432</prop>
<prop key="databaseName">dbname</prop>
<prop key="user">dbuser</prop>
<prop key="password">dbpassword</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<!-- Your Hikari dataSource below -->
<property name="dataSource" ref="dataSource"/>
<!-- your other configs go here -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</prop>
<!-- Remaining props goes here -->
</props>
</property>
</bean>
Once the above are setup then, you need to add an entry to your log4j or logback
and set the level
to DEBUG
to see Hikari
Connection Pool start up.
<!-- Keep additivity=false to avoid duplicate lines -->
<logger additivity="false" name="com.zaxxer.hikari">
<level value="debug"/>
<!-- Your appenders goes here -->
</logger>
Via application.properties
in Spring Boot
debug=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
Using logback.xml
<logger name="com.zaxxer.hikari" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
With the above you should be all good to go! Obviously you need to customize the HikariCP
pool configs in order to get the performance that it promises.
I found this very helpful if you are a beginner read this
Update:
In Linux or Unix System there are two places programs send output to: Standard output (stdout) and Standard Error (stderr).You can redirect these output to any file.
Like if you do this ls -a > output.txt
Nothing will be printed in console all output (stdout) is redirected to output file.
And if you try print the content of any file that does not exits means output will be an error like if you print test.txt that not present in current directory
cat test.txt > error.txt
Output will be
cat: test.txt :No such file or directory
But error.txt file will be empty because we redirecting the stdout to a file not stderr.
so we need file descriptor( A file descriptor is nothing more that a positive integer that represents an open file. You can say descriptor is unique id of file) to tell shell which type of output we are sending to file .In Unix /Linux system 1 is for stdout and 2 for stderr.
so now if you do this
ls -a 1> output.txt
means you are sending Standard output (stdout) to output.txt.
and if you do this cat test.txt 2> error.txt
means you are sending Standard Error (stderr) to error.txt .
&1
is used to reference the value of the file descriptor 1 (stdout).
Now to the point 2>&1
means “Redirect the stderr to the same place we are redirecting the stdout”
Now you can do this
cat maybefile.txt > output.txt 2>&1
both Standard output (stdout) and Standard Error (stderr) will redirected to output.txt.
Thanks to Ondrej K. for pointing out
Really the answer to this question depends on what operating system and programming language you are using. There is no "ASCII code" per se. The operating system detects you hit an arrow key and triggers an event that programs can capture. For example, on modern Windows machines, you would get a WM_KEYUP or WM_KEYDOWN event. It passes a 16-bit value usually to determine which key was pushed.
Symbolic links give another name to a file, in a way similar to hard links. But a file can be deleted even if there are remaining symbolic links.
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
There's more to it than this, but you're probably looking for this list:
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
MS month start frequency
BMS business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA business year end frequency
AS year start frequency
BAS business year start frequency
H hourly frequency
T minutely frequency
S secondly frequency
L milliseconds
U microseconds
Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
Numbers with at most 2 decimal places:
/^\d+(?:\.\d{1,2})?$/
This should work fine. Please try out :)
Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200"
.
You can use:
Sub returnname(ByVal TableName As String)
MsgBox (Range("Table15").Rows.count)
End Sub
and call the function as below
Sub called()
returnname "Table15"
End Sub
It's simple. Just add:
PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;
Try to set response dataType property directly:
dataType: 'text'
and put
die('');
in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.
Since Result Set is an interface, When you obtain a reference to a ResultSet through a JDBC call, you are getting an instance of a class that implements the ResultSet interface. This class provides concrete implementations of all of the ResultSet methods.
Interfaces are used to divorce implementation from, well, interface. This allows the creation of generic algorithms and the abstraction of object creation. For example, JDBC drivers for different databases will return different ResultSet implementations, but you don't have to change your code to make it work with the different drivers
In very short, if your ResultSet contains result, then using rs.next return true if you have recordset else it returns false.
Using UIScrollView's setContentOffset:animated:
function to scroll to the bottom in Swift.
let bottomOffset : CGPoint = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
use from django.urls import reverse instead of from django.core.urlresolvers import reverse
there are a number of NSDate
helpers on the web, I tend to use:
https://github.com/billymeltdown/nsdate-helper/
Readme extract below:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
This produces the following kinds of output:
‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)
write the below style into same html file head section or write into a .css file
<style type="text/css">
.submit input
{
color: #000;
background: #ffa20f;
border: 2px outset #d7b9c9
}
</style>
<input type="submit" class="submit"/>
.submit - in css . means class , so i created submit class with set of attributes
and applied that class to the submit tag, using class attribute
Try the to_date function.
You can use php built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change filed name as your requirement
then the result is
and if you want to concat same filed using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
Check that your labels aren't set to automatically resize. In IB, it's called "Autoshrink" and is right beside the font setting. Programmatically, it's called adjustsFontSizeToFitWidth
.
Short answer: You should to use "weak references" between collections, using ObjectId properties:
References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.
https://docs.mongodb.com/manual/core/data-modeling-introduction/#references
This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).
I think
SELECT CALL.* FROM CALL LEFT JOIN Phone_book ON
CALL.id = Phone_book.id WHERE Phone_book.name IS NULL
yum install php-mbstring (as per http://php.net/manual/en/mbstring.installation.php)
I think you have to install the EPEL repository http://fedoraproject.org/wiki/EPEL
Create a table with the set you want to export and then use the command line utility pg_dump to export to a file:
create table export_table as
select id, name, city
from nyummy.cimory
where city = 'tokyo'
$ pg_dump --table=export_table --data-only --column-inserts my_database > data.sql
--column-inserts
will dump as insert commands with column names.
--data-only
do not dump schema.
As commented below, creating a view in instead of a table will obviate the table creation whenever a new export is necessary.
You can put them into a list and then sort them using their natural ordering, like so:
final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list
If the numbers are stored in the same variable, then you'll have to somehow put them into a List
and then call sort
, like so:
final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...
Collections.sort( list );
// Use the sorted list
Swift 3 (forget about NSURL).
let fileName = "20-01-2017 22:47"
let folderString = "file:///var/mobile/someLongPath"
To make a URL out of a string:
let folder: URL? = Foundation.URL(string: folderString)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath
If we want to add the filename. Note, that appendingPathComponent() adds the percent encoding automatically:
let folderWithFilename: URL? = folder?.appendingPathComponent(fileName)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath/20-01-2017%2022:47
When we want to have String but without the root part (pay attention that percent encoding is removed automatically):
let folderWithFilename: String? = folderWithFilename.path
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017 22:47"
If we want to keep the root part we do this (but mind the percent encoding - it is not removed):
let folderWithFilenameAbsoluteString: String? = folderWithFilenameURL.absoluteString
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017%2022:47"
To manually add the percent encoding for a string:
let folderWithFilenameAndEncoding: String? = folderWithFilename.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017%2022:47"
To remove the percent encoding:
let folderWithFilenameAbsoluteStringNoEncodig: String? = folderWithFilenameAbsoluteString.removingPercentEncoding
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017 22:47"
The percent-encoding is important because URLs for network requests need them, while URLs to file system won't always work - it depends on the actual method that uses them. The caveat here is that they may be removed or added automatically, so better debug these conversions carefully.
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
For a one time change you can do this:
export EMAIL='[email protected]'; mutt -s "Elvis is dead" [email protected]
You never mention what object you are inspecting, and since you are rejecting ones that reference a given object, I will assume you mean a static one.
using System.Reflection;
public object GetPropValue(string prop)
{
int splitPoint = prop.LastIndexOf('.');
Type type = Assembly.GetEntryAssembly().GetType(prop.Substring(0, splitPoint));
object obj = null;
return type.GetProperty(prop.Substring(splitPoint + 1)).GetValue(obj, null);
}
Note that I marked the object that is being inspected with the local variable obj
. null
means static, otherwise set it to what you want. Also note that the GetEntryAssembly()
is one of a few available methods to get the "running" assembly, you may want to play around with it if you are having a hard time loading the type.
If you are not tweaking the curl command too much you can also go and call the curl command directly
import shlex
cmd = '''curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
The big difference is that the first example actually invokes the lambda f(x)
, while the second example doesn't.
Your first example is equivalent to [(lambda x: x*x)(x) for x in range(10)]
while your second example is equivalent to [f for x in range(10)]
.
You can use as
keyword to refer a collection under a ng-repeat
element:
<table>
<tr ng-repeat="task in tasks | filter:category | filter:query as res">
<td>{{task.id}}</td>
<td>{{task.description}}</td>
</tr>
<tr ng-if="res.length === 0">
<td colspan="2">no results</td>
</tr>
</table>
In Angular 2 Final (RC5+) there are new APIs for updating form values. The patchValue()
API method supports partial form updates, where we only need to specify some of the fields:
this.form.patchValue({id: selected.id})
There is also the setValue()
API method that needs an object with all the form fields. If there is a field missing, we will get an error.
You could use cURL:
<?php
//The url you wish to send the POST request to
$url = $file_name;
//The data you want to send via POST
$fields = [
'__VIEWSTATE ' => $state,
'__EVENTVALIDATION' => $valid,
'btnSubmit' => 'Submit'
];
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
echo $result;
?>
Ok, so what about this one?
public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
return !enumerable.GetEnumerator().MoveNext();
}
EDIT: I've just realized that someone has sketched this solution already. It was mentioned that the Any() method will do this, but why not do it yourself? Regards
import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for key in wordcount.keys():
print ("%s %s " %(key , wordcount[key]))
file.close();
Instant.ofEpochMilli ( 1_393_572_325_000L )
.toString()
2014-02-28T07:25:25Z
(a) You seem be confused as to what a Date is. As the answer by JB Nizet said, a Date tracks the number of milliseconds since the Unix epoch (first moment of 1970) in the UTC time zone (that is, with no time zone offset). So a Date has no time zone†. And it has no "format". We create string representations from a Date's value, but the Date itself is not a String and has no String.
(b) You refer to a "UTC format". UTC is not a format, not I have heard of. UTC (Coordinated Universal Time) is the origin point of time zones. Time zones east of the Royal Observatory in Greenwich, London are some number of hours & minutes ahead of UTC. Westward time zones are behind UTC.
You seem to be referring to ISO 8601 formatted strings. You are using the optional format, omitting (1) the T
from the middle, and (2) the offset-from-UTC at the end. Unless presenting the string to a user in the user interface of your app, I suggest you generally stick with the usual format:
2014-02-27T23:03:14+05:30
2014-02-27T23:03:14Z
('Z' for Zulu, or UTC, with an offset of +00:00)(c) Avoid the 3 or 4 letter time zone codes. They are neither standardized nor unique. "IST" for example can mean either Indian Standard Time or Irish Standard Time.
(d) Put some effort into searching StackOverflow before posting. You would have found all your answers.
(e) Avoid the java.util.Date & Calendar classes bundled with Java. They are notoriously troublesome. Use either the Joda-Time library or Java 8’s new java.time package (inspired by Joda-Time, defined by JSR 310).
The java.time classes use standard ISO 8601 formats by default when parsing and generating strings.
OffsetDateTime odt = OffsetDateTime.parse( "2014-02-27T23:03:14+05:30" );
Instant instant = Instant.parse( "2014-02-27T23:03:14Z" );
Parse your count of milliseconds since the epoch of first moment of 1970 in UTC.
Instant instant = Instant.ofEpochMilli ( 1_393_572_325_000L );
instant.toString(): 2014-02-28T07:25:25Z
Adjust that Instant
into a desired time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2014-02-28T02:25:25-05:00[America/Montreal]
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Joda-Time uses ISO 8601 as its defaults.
A Joda-Time DateTime
object knows its on assigned time zone, unlike a java.util.Date object.
Generally better to specify a time zone explicitly rather than rely on default time zone.
long input = 1393572325000L;
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTimeZone timeZoneIreland = DateTimeZone.forID( "Europe/Dublin" );
DateTime dateTimeIndia = dateTimeUtc.withZone( timeZoneIndia );
DateTime dateTimeIreland = dateTimeIndia.withZone( timeZoneIreland );
// Use a formatter to create a String representation. The formatter can adjust time zone if you so desire.
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FM" ).withLocale( Locale.CANADA_FRENCH ).withZone( DateTimeZone.forID( "America/Montreal" ) );
String output = formatter.print( dateTimeIreland );
Dump to console…
// All three of these date-time objects represent the *same* moment in the timeline of the Universe.
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "dateTimeIreland: " + dateTimeIreland );
System.out.println( "output for Montréal: " + output );
When run…
dateTimeUtc: 2014-02-28T07:25:25.000Z
dateTimeIndia: 2014-02-28T12:55:25.000+05:30
dateTimeIreland: 2014-02-28T07:25:25.000Z
output for Montréal: vendredi 28 février 2014 02:25:25
† Actually, java.util.Date does have a time zone. That time zone is assigned deep in its source code. Yet the class ignores that time zone for most practical purposes. And its toString
method applies the JVM’s current default time zone rather than that internal time zone. Confusing? Yes. This is one of many reasons to avoid the old java.util.Date/.Calendar classes. Use java.time and/or Joda-Time instead.
If it's a major concern to start doing a lot of testing on a Mac, then I would definitely suggest buying a second hand Mac, or perhaps building a Hackintosh. The former gets you up and running quickly, the latter gives you a lot of power for the same price.
For just the odd piece of testing, running OS X in VMWare on your current PC is a cheaper option.
It is less than 10 lines of code.
The gist here: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3
import sys
def progress(count, total, suffix=''):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
sys.stdout.flush() # As suggested by Rom Ruben
For anyone who might stumble upon this, if all the other answers do not help and you are on Windows, know that there is currently a big issue with spawn
on Windows and the PATHEXT
environment variable that can cause certain calls to spawn to not work depending on how the target command is installed.
Does that work in IE6?
No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.
You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.
EDIT
If you are to ignore IE6, you could do (CSS2.1):
input[type=submit][disabled=disabled],
button[disabled=disabled] {
...
}
CSS3 (IE9+):
input[type=submit]:disabled,
button:disabled {
...
}
You can substitute [disabled=disabled]
(attribute value) with [disabled]
(attribute presence).
Try like this:
function validate(el, status){
var targetVal = document.getElementById(el).value;
var statusEl = document.getElementById(status);
if(targetVal.length > 0){
statusEl.innerHTML = '';
}
else{
statusEL.innerHTML = "Invalid Name";
}
}
Now HTML:
<!doctype html>
<html lang='en'>
<head>
<title>Derp...</title>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate('fname','fnameStatus')">
<br />
<span id="fnameStatus"></span>
<br />
Last_Name
<input type="text" id="lname" name="lname" onblur="validate('lname','lnameStatus')">
<br />
<span id="lnameStatus"></span>
<br />
<input type=button value=check>
</form>
</body>
</html>
The Quassnoi query with a change for large table. Parents with more childs then 10: Formating as str(5) the row_number()
WITH q AS ( SELECT m.*, CAST(str(ROW_NUMBER() OVER (ORDER BY m.ordernum),5) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc FROM #t m WHERE ParentID =0 UNION ALL SELECT m.*, q.bc + '.' + str(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.ordernum),5) COLLATE Latin1_General_BIN FROM #t m JOIN q ON m.parentID = q.DBID ) SELECT * FROM q ORDER BY bc
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
I am giving an extract from the book "C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari"
Here’s a demonstration on the use of LinkedList:
var tune = new LinkedList<string>();
tune.AddFirst ("do"); // do
tune.AddLast ("so"); // do - so
tune.AddAfter (tune.First, "re"); // do - re- so
tune.AddAfter (tune.First.Next, "mi"); // do - re - mi- so
tune.AddBefore (tune.Last, "fa"); // do - re - mi - fa- so
tune.RemoveFirst(); // re - mi - fa - so
tune.RemoveLast(); // re - mi - fa
LinkedListNode<string> miNode = tune.Find ("mi");
tune.Remove (miNode); // re - fa
tune.AddFirst (miNode); // mi- re - fa
foreach (string s in tune) Console.WriteLine (s);
This might do the trick:
$(document).ready(function() {
$("input[type=text]").change(function() {
$(this).data("old", $(this).data("new") || "");
$(this).data("new", $(this).val());
console.log($(this).data("old"));
console.log($(this).data("new"));
});
});
The answer from Blundell should work, but for some bizarre reason it didn't do with me. I had to pipe first the filenames outputted by the first command into a file and then loop through that file and delete that file one by one.
git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore'
git push origin master
var checkbox = $( "#checkbox" );
checkbox.val( checkbox[0].checked ? "true" : "false" );
This will set the value
of the checkbox to "true"
or "false"
(value property
is a string)
, depending whether it's unchecked
or checked
.
Works in jQuery >= 1.0
Here's how
double fRand(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
Remember to call srand() with a proper seed each time your program starts.
[Edit] This answer is obsolete since C++ got it's native non-C based random library (see Alessandro Jacopsons answer) But, this still applies to C
In the case of a non-fixed width div (i.e. you don't know how much space the div will occupy).
#wrapper {_x000D_
background-color: green; /* for visualization purposes */_x000D_
text-align: center;_x000D_
}_x000D_
#yourdiv {_x000D_
background-color: red; /* for visualization purposes */_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="wrapper"> _x000D_
<div id="yourdiv">Your text</div>_x000D_
</div>
_x000D_
Keep in mind that the width of #yourdiv
is dynamic -> it will grow and shrink to accommodate the text inside it.
You can check browser compatibility on Caniuse
some times need to use name of pc on windows
first step) put in config file of mysql:
mysqld.cnf SET bind-address= 0.0.0.0
(to let recibe connections over tcp/ip)
second step) make user in mysql, table users, with name of pc on windows propierties, NOT ip
I just give other option for this question - you need to use '.dt' in your code:
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
Ok after a whole productive day down the drain I got it to work.
First I uninstalled all traces of Genymotion and Virtualbox. I then proceeded to install Genymotion and then Virtual Box again, but the previous version (4.2.18)
I ran Genymotion, Downloaded an Image, I got an error message about the network trying to run it. So I ran it Directly inside Virtual Box, It started up 100% with network and everything. I shut it down, went to Image's settings and changed the first adapter to "Host-only".
I opened the Genymotion Launcher again and "Played" my device and it started up with no problems.
If you mean what ports are listening, you can open a command prompt and write:
netstat
You can write:
netstat /?
for an explanation of all options.
The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.
If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.
$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
This way, you will be able to get the month and year of the next month without having a month skipped.
Have a look at the ToolStrip.Items collection. It even has a find method available.
According to the latest documentation about PyMongo titled Insert a Document (insert is deprecated) and following defensive approach, you should insert and update as follows:
result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})
if post is not None:
post['newfield'] = "abc"
mycollection.save(post)
i did try this and its working in windows machine to run a sql file on a specific schema.
psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql