Both are supported. To quote the Arduino homepage,
The core libraries are written in C and C++ and compiled using avr-gcc
Note that C++ is a superset of C (well, almost), and thus can often look very similar. I am not an expert, but I guess that most of what you will program for the Arduino in your first year on that platform will not need anything but plain C.
other solution:
$marray=array(....);
$options = array(
"encoding" => "UTF-8",
"output_type" => "xml",
"version" => "simple",
"escaping" => array("non-ascii, on-print, markup")
);
$xmlres = xmlrpc_encode_request('root', $marray, $options);
print($xmlres);
The same trouble with the same device has been here.
So, it's Xiaomi trouble, and here is a solution to this problem:
Go to the "Security" application and tap "Options" at top right corner
Scroll down to "Feature Settings" group, and look for "Permissions"
At there switch off "Install via USB" option, which manages the installation of the apps via USB and doesn't allow it.
On Latest Redmi Device:
Settings > Additional Settings > Developer Options > Developer options: Check the Install via USB option.
The problem seems to be that you have misunderstood how async/await work with Entity Framework.
So, let's look at this code:
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
and example of it usage:
repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()
What happens there?
IQueryable
object (not accessing database yet) using repo.GetAllUrls()
IQueryable
object with specified condition using .Where(u => <condition>
IQueryable
object with specified paging limit using .Take(10)
.ToList()
. Our IQueryable
object is compiled to sql (like select top 10 * from Urls where <condition>
). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)Okay, let's look at first code:
public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
var urls = await context.Urls.ToListAsync();
return urls.AsQueryable();
}
With the same example of usage we got:
await context.Urls.ToListAsync();
.Why async/await is preferred to use? Let's look at this code:
var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));
What happens here?
var stuff1 = ...
userId
var stuff2 = ...
userId
So let's look to an async version of it:
var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));
What happens here?
So good code here:
using System.Data.Entity;
public IQueryable<URL> GetAllUrls()
{
return context.Urls.AsQueryable();
}
public async Task<List<URL>> GetAllUrlsByUser(int userId) {
return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}
Note, than you must add using System.Data.Entity
in order to use method ToListAsync()
for IQueryable.
Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable
. You can just use await context.Urls.ToListAsync()
and work with materialized List<Url>
.
This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..
Both should be same ..Java version
mismatched ..Check it
<script type="text/javascript">
// Increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 1000;
$(function() {
$('#dialog1').dialog({
autoOpen: false,
show: 'blind',
hide: 'explode'
});
$('#Wizard1_txtEmailID').click(function() {
$('#dialog1').dialog('open');
return false;
});
$('#Wizard1_txtEmailID').click(function() {
$('#dialog2').dialog('close');
return false;
});
//mouseover
$('#Wizard1_txtPassword').click(function() {
$('#dialog1').dialog('close');
return false;
});
});
/////////////////////////////////////////////////////
<div id="dialog1" title="Email ID">
<p>
(Enter your Email ID here.)
<br />
</p>
</div>
////////////////////////////////////////////////////////
<div id="dialog2" title="Password">
<p>
(Enter your Passowrd here.)
<br />
</p>
</div>
What about LineSentence module, it will ignore such lines:
Bases: object
Simple format: one sentence = one line; words already preprocessed and separated by whitespace.
source can be either a string or a file object. Clip the file to the first limit lines (or not clipped if limit is None, the default).
from gensim.models.word2vec import LineSentence
text = LineSentence('text.txt')
Just in case you ever want to do this not on Android it's helpful to think about which day where as not all devices mark their calendar in local time.
From Java 8 onwards:
LocalDate.now(ZoneId.of("America/Detroit")).getDayOfWeek()
The correct way of doing this as of API 26 is described in the official documentation here :
https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
This involves placing the ttf files in res/font folder and creating a font-family file.
Internally, SQL Server treats an inline table valued function much like it would a view and treats a multi-statement table valued function similar to how it would a stored procedure.
When an inline table-valued function is used as part of an outer query, the query processor expands the UDF definition and generates an execution plan that accesses the underlying objects, using the indexes on these objects.
For a multi-statement table valued function, an execution plan is created for the function itself and stored in the execution plan cache (once the function has been executed the first time). If multi-statement table valued functions are used as part of larger queries then the optimiser does not know what the function returns, and so makes some standard assumptions - in effect it assumes that the function will return a single row, and that the returns of the function will be accessed by using a table scan against a table with a single row.
Where multi-statement table valued functions can perform poorly is when they return a large number of rows and are joined against in outer queries. The performance issues are primarily down to the fact that the optimiser will produce a plan assuming that a single row is returned, which will not necessarily be the most appropriate plan.
As a general rule of thumb we have found that where possible inline table valued functions should be used in preference to multi-statement ones (when the UDF will be used as part of an outer query) due to these potential performance issues.
Offering another potential solution to this error.
If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.
e.g.
https://example.com/api/etc
and not
https://123.4.5.6/api/etc
In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE
.
cdate(Format([Datum im Format DDMMYYYY],'##/##/####') )
converts string without punctuation characters into date
Go ahead and use isinstance
if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for str
or unicode
like so:
import types
isinstance(var, types.StringTypes)
N.B. Don't mistake types.StringType
for types.StringTypes
. The latter incorporates str
and unicode
objects.
The types
module is considered by many to be obsolete in favor of just checking directly against the object's type, so if you'd rather not use the above, you can alternatively check explicitly against str
and unicode
, like this:
isinstance(var, (str, unicode)):
Edit:
Better still is:
isinstance(var, basestring)
End edit
After either of these, you can fall back to behaving as if you're getting a normal sequence, letting non-sequences raise appropriate exceptions.
See the thing that's "evil" about type checking is not that you might want to behave differently for a certain type of object, it's that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing. If you have a final fallback that is not type-checked, you remove this restriction. It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn't necessarily mean you should avoid it from the getgo.
The parent directory of an included file would be
dirname(getcwd())
e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php
then by calling /file/index.php
getcwd() is /var/www/html/folder
__DIR__ is /var/www/html/folder/inc
so dirname(__DIR__) is /var/www/html/folder
but what we want is /var/www/html which is dirname(getcwd())
HTML:
<html>
<head>
</head>
<body>
<div id='status'>jQuery is not loaded yet.</div>
<input type='button' value='Click here to load it.' onclick='load()' />
</body>
</html>
Script:
<script>
load = function() {
load.getScript("jquery-1.7.2.js");
load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
}
// dynamically load any javascript file.
load.getScript = function(filename) {
var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.setAttribute("src", filename)
if (typeof script!="undefined")
document.getElementsByTagName("head")[0].appendChild(script)
}
</script>
the_input = raw_input("Enter input: ")
And that's it.
Moreover, if you want to make a list of inputs, you can do something like:
a = []
for x in xrange(1,10):
a.append(raw_input("Enter Data: "))
In that case, you'll be asked for data 10 times to store 9 items in a list.
Output:
Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']
You can search that list the fundamental way with something like (after making that list):
if '2' in a:
print "Found"
else: print "Not found."
You can replace '2' with "raw_input()" like this:
if raw_input("Search for: ") in a:
print "Found"
else:
print "Not found"
If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):
example.py
while(True):
line = raw_input()
print "input data: %s" % line
In command line interface:
example.py < input.txt
Hope that helps.
You should always use the direct .attribute
form (but see the quirksmode link below) if you want programmatic access in JavaScript. It should handle the different types of attributes (think "onload") correctly.
Use getAttribute
/setAttribute
when you wish to deal with the DOM as it is (e.g. literal text only). Different browsers confuse the two. See Quirks modes: attribute (in)compatibility.
If we keep in mind that .replace()
is equal with .remove().add()
that we know by the documentation:
Replace an existing fragment that was added to a container. This is essentially the same as calling
remove(Fragment)
for all currently added fragments that were added with the samecontainerViewId
and thenadd(int, Fragment, String)
with the same arguments given here.
then what's happening is like this (I'm adding numbers to the frag to make it more clear):
// transaction.replace(R.id.detailFragment, frag1);
Transaction.remove(null).add(frag1) // frag1 on view
// transaction.replace(R.id.detailFragment, frag2).addToBackStack(null);
Transaction.remove(frag1).add(frag2).addToBackStack(null) // frag2 on view
// transaction.replace(R.id.detailFragment, frag3);
Transaction.remove(frag2).add(frag3) // frag3 on view
(here all misleading stuff starts to happen)
Remember that .addToBackStack()
is saving only transaction not the fragment as itself! So now we have frag3
on the layout:
< press back button >
// System pops the back stack and find the following saved back entry to be reversed:
// [Transaction.remove(frag1).add(frag2)]
// so the system makes that transaction backward!!!
// tries to remove frag2 (is not there, so it ignores) and re-add(frag1)
// make notice that system doesn't realise that there's a frag3 and does nothing with it
// so it still there attached to view
Transaction.remove(null).add(frag1) //frag1, frag3 on view (OVERLAPPING)
// transaction.replace(R.id.detailFragment, frag2).addToBackStack(null);
Transaction.remove(frag3).add(frag2).addToBackStack(null) //frag2 on view
< press back button >
// system makes saved transaction backward
Transaction.remove(frag2).add(frag3) //frag3 on view
< press back button >
// no more entries in BackStack
< app exits >
Consider implementing FragmentManager.BackStackChangedListener
to watch for changes in the back stack and apply your logic in onBackStackChanged()
methode:
FragmentTransaction.addToBackStack(String name);
This answer is for similar cases if the top answer by Alasdair does not help. (E.g. if the unwanted migration is created soon again with every new migration or if it is in a bigger migration that can not be reverted or the table has been removed manually.)
...delete the migration, without creating a new migration?
TL;DR: You can delete a few last reverted (confused) migrations and make a new one after fixing models. You can also use other methods to configure it to not create a table by migrate command. The last migration must be created so that it match the current models.
Cases why anyone do not want to create a table for a Model that must exist:
A) No such table should exist in no database on no machine and no conditions
class Meta: abstract = True
B) The table is created rarely, by something else or manually in a special way.
class Meta: managed = False
C) The table is used only on some machine (e.g. in development).
class Meta: managed = some_switch
.D) The project uses multiple databases in settings.DATABASES
allow_migrate
in order to differentiate the databases where the table should be created and where not.The migration is created in all cases A), B), C), D) with Django 1.9+ (and only in cases B, C, D with Django 1.8), but applied to the database only in appropriate cases or maybe never if required so. Migrations have been necessary for running tests since Django 1.8. The complete relevant current state is recorded by migrations even for models with managed=False in Django 1.9+ to be possible to create a ForeignKey between managed/unmanaged models or to can make the model managed=True later. (This question has been written at the time of Django 1.8. Everything here should be valid for versions between 1.8 to the current 2.2.)
If the last migration is (are) not easily revertible then it is possible to cautiously (after database backup) do a fake revert ./manage.py migrate --fake my_app 0010_previous_migration
, delete the table manually.
If necessary, create a fixed migration from the fixed model and apply it without changing the database structure ./manage.py migrate --fake my_app 0011_fixed_migration
.
Quote from Jeff Handley's Blog Post on Validation Objects and Properties with Validator:
When validating an object, the following process is applied in Validator.ValidateObject:
- Validate property-level attributes
- If any validators are invalid, abort validation returning the failure(s)
- Validate the object-level attributes
- If any validators are invalid, abort validation returning the failure(s)
- If on the desktop framework and the object implements IValidatableObject, then call its Validate method and return any failure(s)
This indicates that what you are attempting to do won't work out-of-the-box because the validation will abort at step #2. You could try to create attributes that inherit from the built-in ones and specifically check for the presence of an enabled property (via an interface) before performing their normal validation. Alternatively, you could put all of the logic for validating the entity in the Validate
method.
You also could take a look a the exact implemenation of Validator
class here
I realize this is a very old question with an accepted answer, but none of these answers actually use the approach suggested by the hint.
It is a pretty simple argument:
n!
(= 1*2*3*...*n) is a product of n
numbers each less than or equal to n
. Therefore it is less than the product of n
numbers all equal to n
; i.e., n^n
.
Half of the numbers -- i.e. n/2
of them -- in the n!
product are greater than or equal to n/2
. Therefore their product is greater than the product of n/2
numbers all equal to n/2
; i.e. (n/2)^(n/2)
.
Take logs throughout to establish the result.
"hard coding" means putting something into your source code. If you are not hard coding, then you do something like prompting the user for the data, or allow the user to put the data on the command line, or something like that.
So, to hard code the location of the file as being on the C: drive, you would just put the pathname of the file all together in your source code.
Here is an example.
int main()
{
const char *filename = "C:\\myfile.txt";
printf("Filename is: %s\n", filename);
}
The file name is "hard coded" as: C:\myfile.txt
The reason the backslash is doubled is because backslashes are special in C strings.
As a addition to this, 'the project type is not supported by this installation' can occur if you're trying to open a project on a computer which does not contain the framework version that is targeted.
In my case I was trying to open a class library which was created on a machine with VS2012 and had defaulted the targeted framework to 4.5.
Since I knew this library wasn't using any 4.5 bits, I resolved the issue by editing the .csproj file from <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
to <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
(or whatever is appropriate for your project) and the library opened.
Set after Init
$('#dp-ex-3').datepicker({ autoclose: true, language: 'es' });
$('#dp-ex-3').datepicker('update', new Date());
This example is working.
Many people have already mentioned that document.cookie
gets you all the cookies (except http-only
ones).
I'll just add a snippet to keep up with the times.
document.cookie.split(';').reduce((cookies, cookie) => {
const [ name, value ] = cookie.split('=').map(c => c.trim());
cookies[name] = value;
return cookies;
}, {});
The snippet will return an object with cookie names as the keys with cookie values as the values.
Slightly different syntax:
document.cookie.split(';').reduce((cookies, cookie) => {
const [ name, value ] = cookie.split('=').map(c => c.trim());
return { ...cookies, [name]: value };
}, {});
You can do it on a per file basis. Use the path attribute to include the filename
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="YourFileNameHere.xml">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
You will find these assemblies in the Extensions group under Assemblies in Visual Studio 2010, 2012 & 2013 (Reference Manager)
You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.
public static string GetFileProcessName(string filePath)
{
Process[] procs = Process.GetProcesses();
string fileName = Path.GetFileName(filePath);
foreach (Process proc in procs)
{
if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
{
ProcessModule[] arr = new ProcessModule[proc.Modules.Count];
foreach (ProcessModule pm in proc.Modules)
{
if (pm.ModuleName == fileName)
return proc.ProcessName;
}
}
}
return null;
}
stdout
stands for standard output stream and it is a stream which is available to your program by the operating system itself. It is already available to your program from the beginning together with stdin
and stderr
.
What they point to (or from) can be anything, actually the stream just provides your program an object that can be used as an interface to send or retrieve data. By default it is usually the terminal but it can be redirected wherever you want: a file, to a pipe goint to another process and so on.
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
Also note ?
along with a character, will return the ASCII character code for A
For example:
?F # => will return 70
Alternately in ruby 1.8 you can do:
"F"[0]
or in ruby 1.9:
"F".ord
Also notice that ?F
will return the string "F"
, so in order to make the code shorter, you can also use ?F.ord
in Ruby 1.9 to get the same result as "F".ord
.
Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.
disabled, readonly and ismap input's attributes go on the same way.
EDITED
empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin
Combine the answer of @mgilson and @gnibbler, I found what I need was this:
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()
It this way, I got a pretty-print json file.
The tricks print >> f, j
is found from here:
http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/
git-subtree
is nice, but it is probably not the one you want.
For example, if projectA
is the directory created in B, after git subtree
,
git log projectA
lists only one commit: the merge. The commits from the merged project are for different paths, so they don't show up.
Greg Hewgill's answer comes closest, although it doesn't actually say how to rewrite the paths.
The solution is surprisingly simple.
(1) In A,
PREFIX=projectA #adjust this
git filter-branch --index-filter '
git ls-files -s |
sed "s,\t,&'"$PREFIX"'/," |
GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info &&
mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE
' HEAD
Note: This rewrites history; you may want to first make a backup of A.
Note Bene: You have to modify the substitute script inside the sed command in the case that you use non-ascii characters (or white characters) in file names or path. In that case the file location inside a record produced by "ls-files -s" begins with quotation mark.
(2) Then in B, run
git pull path/to/A
Voila! You have a projectA
directory in B. If you run git log projectA
, you will see all commits from A.
In my case, I wanted two subdirectories, projectA
and projectB
. In that case, I did step (1) to B as well.
I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;
SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;
Result: Paddy O'Reilly
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
If you can afford working via the file data, you can do
find -mmin +14400 -delete
It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
In your .htaccess you can add:
PHP 5.x
<IfModule mod_php5.c>
php_value memory_limit 64M
</IfModule>
PHP 7.x
<IfModule mod_php7.c>
php_value memory_limit 64M
</IfModule>
If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.
If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.
Read more on http://support.tigertech.net/php-value
No, an iPhone application can only change stuff within its own little sandbox. (And even there there are things that you can't change on the fly.)
Your best bet is probably to use the servers IP address rather than hostname. Slightly harder, but not that hard if you just need to resolve a single address, would be to put a DNS server on your Mac and configure your iPhone to use that.
Pretty sad, eh? The way I usually do it is build up a container of iterators instead of deleting during traversal. Then loop through the container and use map.erase()
std::map<K,V> map;
std::list< std::map<K,V>::iterator > iteratorList;
for(auto i : map ){
if ( needs_removing(i)){
iteratorList.push_back(i);
}
}
for(auto i : iteratorList){
map.erase(*i)
}
git show-ref --tags
For example, git show-ref --abbrev=7 --tags
will show you something like the following:
f727215 refs/tags/v2.16.0
56072ac refs/tags/v2.17.0
b670805 refs/tags/v2.17.1
250ed01 refs/tags/v2.17.2
Every answer uses .next()
or uses .beforeFirst()
and then .next()
. But why not this:
result.first();
So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet
exists of one specific record.
When you are defining styles for division which is positioned absolute
ly, they specifying margins are useless. Because they are no longer inside the regular DOM tree.
You can use float to do the trick.
.divtagABS {
float: left;
margin-left: auto;
margin-right:auto;
}
I think you try to get the remote host of the conneting user...
You can get a String like 'myuser@localhost' from the command:
SELECT USER()
You can split this result on the '@' sign, to get the parts:
-- delivers the "remote_host" e.g. "localhost"
SELECT SUBSTRING_INDEX(USER(), '@', -1)
-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)
if you are conneting via ip address you will get the ipadress instead of the hostname.
It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.
Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).
If you want to avoid this sort of thing, I would suggest something like the following (untested):
import os
def open_if_not_exists(filename):
try:
fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except OSError, e:
if e.errno == 17:
print e
return None
else:
raise
else:
return os.fdopen(fd, 'w')
This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).
copy org.apache.http.legacy.jar
which is in Android/Sdk/platforms/android-23/optional
folder to to app/libs
and also added this line to app.gradle file
compile files('libs/org.apache.http.legacy.jar')
But if you're using more jar libraries, you can use this way
compile fileTree(dir: 'libs', include: ['*.jar'])
if you have npm, install run the command
npm install -g @angular/cli
then bind your ng using this:
cd
alias ng=".npm-global/bin/ng"
Follow the Pictures for more help.
There are a few things which new
does that malloc
doesn’t:
new
constructs the object by calling the constructor of that objectnew
doesn’t require typecasting of allocated memory.So, if you use malloc
, then you need to do above things explicitly, which is not always practical. Additionally, new
can be overloaded but malloc
can’t be.
In a word, if you use C++, try to use new
as much as possible.
sed 's/^.\{,5\}//' file.dat
worked like a charm for me
r = read mode only
r+ = read/write mode
w = write mode only
w+ = read/write mode, if the file already exists override it (empty it)
So yes, if the file already exists w+ will erase the file and give you an empty file.
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
I'm surprised that no-one's mentioned this but you could just create an interface called ObjectLiteral
, that accepts key: value
pairs of type string: any
:
interface ObjectLiteral {
[key: string]: any;
}
Then you'd use it, like this:
let data: ObjectLiteral = {
hello: "world",
goodbye: 1,
// ...
};
An added bonus is that you can re-use this interface many times as you need, on as many objects you'd like.
Good luck.
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
For a PRIMARY KEY
, an index will be created with the following message:
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "index" for table "table"
For a FOREIGN KEY
, the constraint will not be created if there is no index on the referenced table.
An index on referencing table is not required (though desired), and therefore will not be implicitly created.
This works for me for aligning the image to center of div.
.yourclass {
background-image: url(image.png);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server
I have the same problem when trying to update record using Attach() and then SaveChanges() combination, but I am using SQLite DB and its EF provider (the same code works in SQLServer DB without problem).
I found out, when your DB column has GUID (or UniqueIdentity) in SQLite and your model is nvarchar, SQLIte EF treats it as Binary(i.e., byte[]) by default. So when SQLite EF provider tries to convert GUID into the model (string in my case) it will fail as it will convert to byte[]. The fix is to tell the SQLite EF to treat GUID as TEXT (and therefore conversion is into strings, not byte[]) by defining "BinaryGUID=false;" in the connectionstring (or metadata, if you're using database first) like so:
<connectionStrings>
<add name="Entities" connectionString="metadata=res://savetyping...=System.Data.SQLite.EF6;provider connection string="data source=C:\...\db.sqlite3;Version=3;BinaryGUID=false;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Link to the solution that worked for me: How does the SQLite Entity Framework 6 provider handle Guids?
...this is obviously performing a 'string' comparison
No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:
WHERE int_column = '1'
...where the string value of "1" is converted to an INTeger because int_column
's data type is INT, not CHAR/VARCHAR/TEXT.
If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:
WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')
Before using foreach
for iteration, reverse the list by the reverse
method:
myList.Reverse();
foreach( List listItem in myList)
{
Console.WriteLine(listItem);
}
The accepted answer resulted in errors for me when attempting REASSIGN OWNED BY or DROP OWNED BY. The following worked for me:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
DROP USER username;
The user may have privileges in other schemas, in which case you will have to run the appropriate REVOKE line with "public" replaced by the correct schema. To show all of the schemas and privilege types for a user, I edited the \dp command to make this query:
SELECT
n.nspname as "Schema",
CASE c.relkind
WHEN 'r' THEN 'table'
WHEN 'v' THEN 'view'
WHEN 'm' THEN 'materialized view'
WHEN 'S' THEN 'sequence'
WHEN 'f' THEN 'foreign table'
END as "Type"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.array_to_string(c.relacl, E'\n') LIKE '%username%';
I'm not sure which privilege types correspond to revoking on TABLES, SEQUENCES, or FUNCTIONS, but I think all of them fall under one of the three.
I was looking for a solution to my problem for some minutes now, so I'll share my solution.
When you have a custom constructor within your model, your model also needs to have an empty/default constructor. Otherwise the model can't be created, obviously. Be careful while refactoring.
start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.
start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh
hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.
Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,
bin/hadoop-daemon.sh start datanode
Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.
Hope this answers your query.
Also a good example.....
struct point{int x,y;};
typedef struct point point_t;
typedef struct
{
struct point ne,se,sw,nw;
}rect_t;
rect_t temp;
int main()
{
//rotate
RotateRect(&temp);
return 0;
}
void RotateRect(rect_t *givenRect)
{
point_t temp_point;
/*Copy struct data from struct to struct within a struct*/
temp_point = givenRect->sw;
givenRect->sw = givenRect->se;
givenRect->se = givenRect->ne;
givenRect->ne = givenRect->nw;
givenRect->nw = temp_point;
}
In my case, I had such error since import path was wrong:
Wrong:
import Select from "react-select/src/Select"; // it was auto-generated by IDE ;)
Correct:
import Select from "react-select";
This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :
class PopupWindow : Control
{
private const int WM_ACTIVATE = 0x0006;
private const int WM_MOUSEACTIVATE = 0x0021;
private Control ownerControl;
public PopupWindow(Control ownerControl)
:base()
{
this.ownerControl = ownerControl;
base.SetTopLevel(true);
}
public Control OwnerControl
{
get
{
return (this.ownerControl as Control);
}
set
{
this.ownerControl = value;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.Style = WindowStyles.WS_POPUP |
WindowStyles.WS_VISIBLE |
WindowStyles.WS_CLIPSIBLINGS |
WindowStyles.WS_CLIPCHILDREN |
WindowStyles.WS_MAXIMIZEBOX |
WindowStyles.WS_BORDER;
createParams.ExStyle = WindowsExtendedStyles.WS_EX_LEFT |
WindowsExtendedStyles.WS_EX_LTRREADING |
WindowsExtendedStyles.WS_EX_RIGHTSCROLLBAR |
WindowsExtendedStyles.WS_EX_TOPMOST;
createParams.Parent = (this.ownerControl != null) ? this.ownerControl.Handle : IntPtr.Zero;
return createParams;
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr SetActiveWindow(HandleRef hWnd);
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_ACTIVATE:
{
if ((int)m.WParam == 1)
{
//window is being activated
if (ownerControl != null)
{
SetActiveWindow(new HandleRef(this, ownerControl.FindForm().Handle));
}
}
break;
}
case WM_MOUSEACTIVATE:
{
m.Result = new IntPtr(MouseActivate.MA_NOACTIVATE);
return;
//break;
}
}
base.WndProc(ref m);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(SystemBrushes.Info, 0, 0, Width, Height);
e.Graphics.DrawString((ownerControl as VerticalDateScrollBar).FirstVisibleDate.ToLongDateString(), this.Font, SystemBrushes.InfoText, 2, 2);
}
}
Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.
For anything related to the internet, your app must have the internet permission in ManifestFile. I solved this issue by adding permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
The #1 answer has problems:
xargs
command will fail, and delete any
files/directories which matched the individual words.-r
in rm -rf
is unnecessary and at worst could delete things you
don't want to.Instead, for unix-like:
sudo python setup.py install --record files.txt
# inspect files.txt to make sure it looks ok. Then:
tr '\n' '\0' < files.txt | xargs -0 sudo rm -f --
And for windows:
python setup.py bdist_wininst
dist/foo-1.0.win32.exe
There are also unsolvable problems with uninstalling setup.py
install which won't bother you in a typical case. For a more complete answer, see this wiki page:
You call nextElement()
twice in your loop. This call moves the enumeration pointer forward.
You should modify your code like the following:
while (e.hasMoreElements()) {
String param = e.nextElement();
System.out.println(param);
}
Your classes should look like this
[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}
public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}
Here is my testcode.
string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";
XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}
If you want to read a text file you should load the file into a FileStream and deserialize this.
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open))
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}
new Date().toLocaleDateString()
= "9/13/2015"
You don't need to set innerHTML, just by writing
<p>
<script> document.write(new Date().toLocaleDateString()); </script>
</p>
will work.
P.S.
new Date().toDateString()
= "Sun Sep 13 2015"
You can use wannabe_bool gem. https://github.com/prodis/wannabe_bool
This gem implements a #to_b
method for String, Integer, Symbol and NilClass classes.
params[:internal].to_b
You missed break statements. Don't forget to use break
-statements even in the default
case.
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
default:
Console.WriteLine("Default case handling");
break;
}
class Test
{
Dictionary<int, string> entities;
public string GetEntity(int code)
{
// java's get method returns null when the key has no mapping
// so we'll do the same
string val;
if (entities.TryGetValue(code, out val))
return val;
else
return null;
}
}
I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.
class Foo (object):
# ^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
#^ double underscore (dunder) methods are usually special. This one
# gets called immediately after a new instance is created.
self.variable = "Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self, arg1, arg2):
#This method has arguments. You would call it like this: instance.method(1, 2)
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
>>> s = 1.1
>>> 0<= s <=0.2
False
>>> 0<= s <=1.2
True
I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.
The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.
SHORT ANSWER (should be similar for MinGW too but I haven't tried it):
LONG ANSWER:
Below are the detailed steps that solved this issue for me:
Uninstall/delete the previous version of Cygwin (MinGW in your case)
Make sure that CLion is up-to-date
Run Cygwin setup (x64 for my 64-bit OS)
Install at least the following packages for Cygwin:
gcc
g++
make
Cmake
gdb
Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).
Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows
[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']
Add the 'bin' folder to the Path variable. For Cygwin, I added:
D:\cygwin64\bin
Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings
Select 'Build, Execution, Deployment' and then click on 'Toolchains'
Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)
For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)
'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]
Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'
See screenshot: Check all paths to the compiler, make and gdb
See screenshot: Check the configuration to run the project
There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active
Build your project and then run the project. You should see the output in the terminal window
Hope this helps! Good luck and enjoy CLion.
In my case it turned out to be commented out HTML in a master page!
Who knew that commented out HTML such as this were actually interpreted by ASP.NET!
<!--
<link rel="icon" href="../../favicon.ico">
-->
A List is an ordered Collection of elements. You can add them with the add method, and retrieve them with the get(int index) method. You can also iterate over a List, remove elements, etc. Here are some basic examples of using a List:
List<String> names = new ArrayList<String>(3); // 3 because we expect the list
// to have 3 entries. If we didn't know how many entries we expected, we
// could leave this empty or use a LinkedList instead
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.get(2)); // prints "Charlie"
System.out.println(names); // prints the whole list
for (String name: names) {
System.out.println(name); // prints the names in turn.
}
overrides:
- files: *-tests.js
rules:
no-param-reassign: 0
You can also set a specific env for a folder, like this :
overrides:
- files: test/*-tests.js
env:
mocha: true
This configuration will fix error message about describe
and it
not defined, only for your test folder:
/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef
If you are using PHP, make sure the index
NGINX directive in the server block contains a index.php:
index index.php index.html;
For more info checkout the index directive in the official documentation.
As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.
This function is only available at Python start-up time, when Python scans the environment. It has to be called in a system-wide module, sitecustomize.py
, After this module has been evaluated, the setdefaultencoding()
function is removed from the sys
module.
The only way to actually use it is with a reload hack that brings the attribute back.
Also, the use of sys.setdefaultencoding()
has always been discouraged, and it has become a no-op in py3k. The encoding of py3k is hard-wired to "utf-8" and changing it raises an error.
I suggest some pointers for reading:
You can use a temporary deletion list:
List<String> keyList = new ArrayList<String>;
for(Map.Entry<String,String> entry : hashTable){
if(entry.getValue().equals("delete")) // replace with your own check
keyList.add(entry.getKey());
}
for(String key : keyList){
hashTable.remove(key);
}
You can find more information about Hashtable methods in the Java API
I guess your code relates to Windows Forms.
You call BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If BeginInvoke
is called for Delegate
type the delegate is just invoked asynchronously.
(Invoke
for the sync version.)
If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)
And to add a little to already said by others:
Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var
with lambdas: compiler needs a hint.
UPDATE:
this requires .Net v4.0 and higher
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
If you started the task from other thread and need to wait for its completition task.Wait()
will block calling thread till the end of the task.
Read more about tasks here.
Let's say you have an array of data:
n = [1 2 3 4 6 12 18 51 69 81 ]
then you can 'foreach' it like this:
for i = n, i, end
This will echo every element in n (but replacing the i with more interesting stuff is also possible of course!)
Installation lxml
pip install lxml
If you get an error like "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?", try to do this first:
# Debian/Ubuntu
apt-get install python-dev python3-dev libxml2-dev libxslt-dev
# Fedora 23+
dnf install python-devel python3-devel libxml2-devel libxslt-devel
The simplest validator
Let's create simplest validator.py
from lxml import etree
def validate(xml_path: str, xsd_path: str) -> bool:
xmlschema_doc = etree.parse(xsd_path)
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_doc = etree.parse(xml_path)
result = xmlschema.validate(xml_doc)
return result
then write and run main.py
from validator import validate
if validate("path/to/file.xml", "path/to/scheme.xsd"):
print('Valid! :)')
else:
print('Not valid! :(')
A little bit of OOP
In order to validate more than one file, there is no need to create an XMLSchema object every time, therefore:
validator.py
from lxml import etree
class Validator:
def __init__(self, xsd_path: str):
xmlschema_doc = etree.parse(xsd_path)
self.xmlschema = etree.XMLSchema(xmlschema_doc)
def validate(self, xml_path: str) -> bool:
xml_doc = etree.parse(xml_path)
result = self.xmlschema.validate(xml_doc)
return result
Now we can validate all files in the directory as follows:
main.py
import os
from validator import Validator
validator = Validator("path/to/scheme.xsd")
# The directory with XML files
XML_DIR = "path/to/directory"
for file_name in os.listdir(XML_DIR):
print('{}: '.format(file_name), end='')
file_path = '{}/{}'.format(XML_DIR, file_name)
if validator.validate(file_path):
print('Valid! :)')
else:
print('Not valid! :(')
For more options read here: Validation with lxml
To get actual hour, minute and seconds as appear on watch try this code
val sec = (milliSec/1000) % 60
val min = ((milliSec/1000) / 60) % 60
val hour = ((milliSec/1000) / 60) / 60
Below script will store the ip address to the variable ip_address
@echo off
call :get_ip_address
echo %ip_address%
goto :eof
REM
REM get the ip address
REM
:get_ip_address
FOR /f "tokens=1 delims=:" %%d IN ('ping %computername% -4 -n 1 ^| find /i "reply"') do (FOR /F "tokens=3 delims= " %%g IN ("%%d") DO set ip_address=%%g)
goto :eof
Ideas from this blog post.
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)
How to debug Javascript with IE 8
I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.
- Click ? Tools on the toolbar, to the right of the tabs.
- Select Developer Tools. The Developer Tools dialogue should open.
- Click the Script tab in the dialogue.
- Click the Start Debugging button.
You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.
You can also use the statement
debugger;
in your JavaScript code the set a breakpoint.
Print lines where the third field is either snow
or snowman
only:
awk '$3~/^snow(man)?$/' file
The backslash ("\"
) character is a special escape character used to indicate other special characters such as new lines (\n
), tabs (\t
), or quotation marks (\"
).
If you want to include a backslash character itself, you need two backslashes or use the @
verbatim string:
var s = "\\Tasks";
// or
var s = @"\Tasks";
Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.
Generally speaking, most C# .NET developers tend to favour using the @
verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.
That all said, in this case, I would actually recommend you use the Path.Combine
utility method as in @lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.
The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();
In order to debugger work with remote, the java .class files must be complied along with debugging information. If "-g:none" option was passed to compiler then the class file will not have necessary information and hence debugger will not be able to match breakpoints on source code with that class in remote. Meanwhile, if jars/class files were obfuscated, then they also will not have any debug info. According to your responses, most probably this is not your case, but this info could be useful for others who face the same issue.
Clickatell is a popular SMS gateway. It works in 200+ countries.
Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.
The HTTP/S method is as simple as this:
http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here
The SMTP method consists of sending a plain-text e-mail to: [email protected]
, with the following body:
user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home
You can also test the gateway (incoming and outgoing) for free from your browser
I would just use a value in the querystring to pass the required information to the next page.
There are some webkit css properties that should work on Chrome/Safari at least:
-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: black;
That's a 2px wide black text outline.
Add an attribute colspan
(abbriviation for 'column span') in your top cell (<td>
) and set its value to 2.
Your table should resembles the following;
<table>
<tr>
<td colspan = "2">
<!-- Merged Columns -->
</td>
</tr>
<tr>
<td>
<!-- Column 1 -->
</td>
<td>
<!-- Column 2 -->
</td>
</tr>
</table>
See also
W3 official docs on HTML Tables
SELECT DATEDIFF(yyyy, '2011/08/25', '2017/08/25') AS DateDiff
It's gives you difference between two dates in Year
Here (2017-2011)=6 as a result
Syntax:
DATEDIFF(interval, date1, date2)
var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);
signed char
has range -128 to 127; unsigned char
has range 0 to 255.
char
will be equivalent to either signed char or unsigned char, depending on the compiler, but is a distinct type.
If you're using C-style strings, just use char
. If you need to use chars for arithmetic (pretty rare), specify signed or unsigned explicitly for portability.
import user
u=user.User() #error on this line
Because of the lack of __init__ mentioned above, you would expect an ImportError which would make the problem clearer.
You don't get one because 'user' is also an existing module in the standard library. Your import statement grabs that one and tries to find the User class inside it; that doesn't exist and only then do you get the error.
It is generally a good idea to make your import absolute:
import Server.Models.user
to avoid this kind of ambiguity. Indeed from Python 2.7 'import user' won't look relative to the current module at all.
If you really want relative imports, you can have them explicitly in Python 2.5 and up using the somewhat ugly syntax:
from .user import User
First case:
A normal product lookup would look like this
http://our.api.com/product/1
So Im thinking that best practice would be for you to do this
http://our.api.com/Product/101404,7267261
Second Case
Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using []
.
PS This can be subjective, so do what you feel comfortable with.
The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.
EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.
Any operating system has processes (p's) running, say p1, p2, p3 and so forth. Each process usually makes an ongoing usage of files.
Each process is consisted of a process tree (or a process table, in another phrasing).
Usually, Operating systems represent each file in each process by a number (that is to say, in each process tree/table).
The first file used in the process is file0, second is file1, third is file2, and so forth.
Any such number is a file descriptor.
File descriptors are usually integers (0, 1, 2 and not 0.5, 1.5, 2.5).
Given we often describe processes as "process-tables", and given that tables has rows (entries) we can say that the file descriptor cell in each entry, uses to represent the whole entry.
In a similar way, when you open a network socket, it has a socket descriptor.
In some operating systems, you can run out of file descriptors, but such case is extremely rare, and the average computer user shouldn't worry from that.
File descriptors might be global (process A starts in say 0, and ends say in 1 ; Process B starts say in 2, and ends say in 3) and so forth, but as far as I know, usually in modern operating systems, file descriptors are not global, and are actually process-specific (process A starts in say 0 and ends say in 5, while process B starts in 0 and ends say in 10).
I'm lacking context, but this is working just fine:
List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...
Use pathlib.
Python 3.5 and above:
from pathlib import Path
contents = Path(file_path).read_text()
For lower versions of Python use pathlib2:
$ pip install pathlib2
Then
from pathlib2 import Path
contents = Path(file_path).read_text()
Writing is just as easy:
Path(file_path).write_text('my text')
Date Casting for Laravel 6.x and 7.x
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'created_at' => 'datetime:Y-m-d',
'updated_at' => 'datetime:Y-m-d',
'deleted_at' => 'datetime:Y-m-d h:i:s'
];
It easy for Laravel 5 in your Model add property protected $dates = ['created_at', 'cached_at']
. See detail here https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
Date Mutators: Laravel 5.x
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
}
You can format date like this $user->created_at->format('M d Y');
or any format that support by PHP.
:) Your using the thread in a wrong way. Just do the following:
private void runthread()
{
splashTread = new Thread() {
@Override
public void run() {
try {
synchronized(this){
//wait 5 sec
wait(_splashTime);
}
} catch(InterruptedException e) {}
finally {
//call the handler to set the text
}
}
};
splashTread.start();
}
That's it.
I had a similar problem with virtualenv
that had python3.8
while installing dependencies from requirements.txt
file. I managed to get it to work by activating the virtualenv
and then running the command python -m pip install -r requirements.txt
and it worked.
$base_dir = __DIR__; // Absolute path to your installation, ex: /var/www/mywebsite
$doc_root = preg_replace("!{$_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']); # ex: /var/www
$base_url = preg_replace("!^{$doc_root}!", '', $base_dir); # ex: '' or '/mywebsite'
$base_url = str_replace('\\', '/', $base_url);//On Windows
$base_url = str_replace($doc_root, '', $base_url);//On Windows
$protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$port = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
$domain = $_SERVER['SERVER_NAME'];
$full_url = "$protocol://{$domain}{$disp_port}{$base_url}"; # Ex: 'http://example.com', 'https://example.com/mywebsite', etc.
source: http://blog.lavoie.sl/2013/02/php-document-root-path-and-url-detection.html
Since you are loading in the spans via ajax you will have to attach delegate handlers to the events to catch them as they bubble up.
$(document).on('click','span',function(e){
console.log(e.target.id)
})
you will want to attach the event to the closest static member you can to increase efficiency.
$('#main_div').on('click','span',function(e){
console.log(e.target.id)
})
is better than binding to the document for instance.
This question may help you understand
$('#checkbox').prop('checked', true);
When you want it unchecked:
$('#checkbox').prop('checked', false);
You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.
HttpResponse response = httpClient.execute(get);
// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();
// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());
you can use following CSS code..
body {
margin:0;
padding:0;
height: 100%;
width: 100%;
}
table {
border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
tr {
width: 100%;
}
.outer-container {
background-color: #ccc;
top:0;
left: 0;
right: 300px;
bottom:40px;
overflow:hidden;
}
.inner-container {
width: 100%;
height: 100%;
position: relative;
}
.table-header {
float:left;
width: 100%;
}
.table-body {
float:left;
height: 100%;
width: inherit;
}
.header-cell {
background-color: yellow;
text-align: left;
height: 40px;
}
.body-cell {
background-color: blue;
text-align: left;
}
.col1, .col3, .col4, .col5 {
width:120px;
min-width: 120px;
}
.col2 {
min-width: 300px;
}
for WPF: (where lblInfo is a label, chkRun is a checkBox)
this.Topmost is just to keep my app on the top of other windows, you will also need to add a using statement " using Microsoft.Win32; ", StartupWithWindows is my application's name
public partial class MainWindow : Window
{
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public MainWindow()
{
InitializeComponent();
if (this.IsFocused)
{
this.Topmost = true;
}
else
{
this.Topmost = false;
}
// Check to see the current state (running at startup or not)
if (rkApp.GetValue("StartupWithWindows") == null)
{
// The value doesn't exist, the application is not set to run at startup, Check box
chkRun.IsChecked = false;
lblInfo.Content = "The application doesn't run at startup";
}
else
{
// The value exists, the application is set to run at startup
chkRun.IsChecked = true;
lblInfo.Content = "The application runs at startup";
}
//Run at startup
//rkApp.SetValue("StartupWithWindows",System.Reflection.Assembly.GetExecutingAssembly().Location);
// Remove the value from the registry so that the application doesn't start
//rkApp.DeleteValue("StartupWithWindows", false);
}
private void btnConfirm_Click(object sender, RoutedEventArgs e)
{
if ((bool)chkRun.IsChecked)
{
// Add the value in the registry so that the application runs at startup
rkApp.SetValue("StartupWithWindows", System.Reflection.Assembly.GetExecutingAssembly().Location);
lblInfo.Content = "The application will run at startup";
}
else
{
// Remove the value from the registry so that the application doesn't start
rkApp.DeleteValue("StartupWithWindows", false);
lblInfo.Content = "The application will not run at startup";
}
}
}
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
I had the same problem and I solved it installing both crystal Report Runtime 32 and 64 bit both version
You need to refer to the alias again in the delete statement, like:
DELETE th FROM term_hierarchy AS th
....
Collection
is a base interface for most collection classes, whereas Collections
is a utility class. I recommend you read the documentation.
Note: Commenting out bind_ip can make your system vulnerable to security flaws. Please see Security Checklist. It is a better idea to add more IP addresses than to open up your system to everything.
You need to edit your /etc/mongod.conf file's bind_ip variable to include the IP of the computer you're using, or eliminate it altogether.
I was able to connect using the following mongod.conf file. I commented out bind_ip and uncommented port.
# mongod.conf
# Where to store the data.
# Note: if you run MongoDB as a non-root user (recommended) you may
# need to create and set permissions for this directory manually.
# E.g., if the parent directory isn't mutable by the MongoDB user.
dbpath=/var/lib/mongodb
# Where to log
logpath=/var/log/mongodb/mongod.log
logappend=true
port = 27017
# Listen to local interface only. Comment out to listen on all
interfaces.
#bind_ip = 127.0.0.1
# Disables write-ahead journaling
# nojournal = true
# Enables periodic logging of CPU utilization and I/O wait
#cpu = true
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
# Verbose logging output.
#verbose = true
# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck = true
# Enable db quota management
#quota = true
# Set oplogging level where n is
# 0=off (default)
# 1=W
# 2=R
# 3=both
# 7=W+some reads
#diaglog = 0
# Ignore query hints
#nohints = true
# Enable the HTTP interface (Defaults to port 28017).
#httpinterface = true
# Turns off server-side scripting. This will result in greatly limited
# functionality
#noscripting = true
# Turns off table scans. Any query that would do a table scan fails.
#notablescan = true
# Disable data file preallocation.
#noprealloc = true
# Specify .ns file size for new databases.
# nssize = <size>
# Replication Options
# In replicated MongoDB databases, specify the replica set name here
#replSet=setname
# Maximum size in megabytes for replication operation log
#oplogSize=1024
# Path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile
Don't forget to restart the mongod service before trying to connect:
service mongod restart
From Robomongo, I used the following connection settings:
Connection Tab:
SSH Tab:
SSH Address: [VPS IP] : 22
SSH User Name: [Username for sudo enabled user]
SSH Auth Method: Password
User Password: Supersecret
Use Observable pattern. You can put Observable value (not Subject) into Input parameter and manage it from parent component. You do not need callback function.
See example: https://stackoverflow.com/a/49662611/4604351
There is no error event for the script tag. You can tell when it is successful, and assume that it has not loaded after a timeout:
<script type="text/javascript" onload="loaded=1" src="....js"></script>
Reserved.objects.filter(client=client_id).order_by('-check_in')
A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.
We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.
More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
For those of you in a .NET environment the following can be a handy way to filter non-numbers out (this example is in VB.NET, but it's probably similar in C#):
If Double.IsNaN(MyVariableName) Then
MyVariableName = 0 ' Or whatever you want to do here to "correct" the situation
End If
If you try to use a variable that has a NaN value you will get the following error:
Value was either too large or too small for a Decimal.
You can also use a circle as a marker icon, for example:
var oMarker = new google.maps.Marker({
position: latLng,
sName: "Marker Name",
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8.5,
fillColor: "#F00",
fillOpacity: 0.4,
strokeWeight: 0.4
},
});
and then, if you want to change the marker dynamically (like on mouseover), you can, for example:
oMarker.setIcon({
path: google.maps.SymbolPath.CIRCLE,
scale: 10,
fillColor: "#00F",
fillOpacity: 0.8,
strokeWeight: 1
})
The most simple tool: use pdftk
(or pdftk.exe
, if you are on Windows):
pdftk 10_MB.pdf 100_MB.pdf cat output 110_MB.pdf
This will be a valid PDF. Download pdftk here.
Update: if you want really large (and valid!), non-optimized PDFs, use this command:
pdftk 100MB.pdf 100MB.pdf 100MB.pdf 100MB.pdf 100MB.pdf cat output 500_MB.pdf
or even (if you are on Linux, Unix or Mac OS X):
pdftk $(for i in $(seq 1 100); do echo -n "100MB.pdf "; done) cat output 10_GB.pdf
NOTE: This is exactly what OP said they did. (But didn't show code for.) I show the details here, so that you can compare it to the accepted answer. My point is that OP's original instinct was, IMHO, better than the answer he accepted.
Given how highly upvoted the accepted answer is, I'd like to point out the "naive" answer to one-time initialization of static methods, is hardly more code than that implementation of Singleton -- and has an essential advantage.
final class MyClass {
public static function someMethod1() {
MyClass::init();
// whatever
}
public static function someMethod2() {
MyClass::init();
// whatever
}
private static $didInit = false;
private static function init() {
if (!self::$didInit) {
self::$didInit = true;
// one-time init code.
}
}
// private, so can't create an instance.
private function __construct() {
// Nothing to do - there are no instances.
}
}
The advantage of this approach, is that you get to call with the straightforward static function syntax:
MyClass::someMethod1();
Contrast it to the calls required by the accepted answer:
MyClass::getInstance->someMethod1();
As a general principle, it is best to pay the coding price once, when you code a class, to keep callers simpler.
If you are NOT using PHP 7.4's opcode.cache
, then use Victor Nicollet's answer. Simple. No extra coding required. No "advanced" coding to understand. (I recommend including FrancescoMM's comment, to make sure "init" will never execute twice.) See Szczepan's explanation of why Victor's technique won't work with opcode.cache
.
If you ARE using opcode.cache
, then AFAIK my answer is as clean as you can get. The cost is simply adding the line MyClass::init();
at start of every public method. NOTE: If you want public properties, code them as a get
/ set
pair of methods, so that you have a place to add that init
call.
(Private members do NOT need that init
call, as they are not reachable from the outside - so some public method has already been called, by the time execution reaches the private member.)
Isn't string.replace returning a value, rather than modifying the source string?
So if you wanted to modify variableABC, you'd need to do this:
var variableABC = "A B C";
variableABC = variableABC.replace('B', 'D') //output: 'A D C'
The previous answer is correct but I'll give you all the code as well.
Your app.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
</configSections>
<ServicesSection>
<Services>
<add Port="6996" ReportType="File" />
<add Port="7001" ReportType="Other" />
</Services>
</ServicesSection>
</configuration>
Your ServiceConfig
and ServiceCollection
classes remain unchanged.
You need a new class:
public class ServiceConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Services", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(ServiceCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public ServiceCollection Services
{
get
{
return (ServiceCollection)base["Services"];
}
}
}
And that should do the trick. To consume it you can use:
ServiceConfigurationSection serviceConfigSection =
ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;
ServiceConfig serviceConfig = serviceConfigSection.Services[0];
Execute dump query in terminal then it will work
mysql -u root -p <Database_Name> > <path of the input file>
Quite simple with a closure:
def map = [
'iPhone':'iWebOS',
'Android':'2.3.3',
'Nokia':'Symbian',
'Windows':'WM8'
]
map.each{ k, v -> println "${k}:${v}" }
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
If you are writing to a file, using a BufferedWriter
instance, use the newLine()
method of that instance. It provides a platform-independent way to write the new line in a file.
To preserve key order, instead of hash(str(dictionary))
or hash(json.dumps(dictionary))
I would prefer quick-and-dirty solution:
from pprint import pformat
h = hash(pformat(dictionary))
It will work even for types like DateTime
and more that are not JSON serializable.
Useful commands to work in daily life:
git checkout -b "branchname" -> creates new branch
git branch -> lists all branches
git checkout "branchname" -> switches to your branch
git push origin "branchname" -> Pushes to your branch
git add */filename -> Stages *(All files) or by given file name
git commit -m "commit message" -> Commits staged files
git push -> Pushes to your current branch
If you want to merge to dev from feature branch, First check out dev branch with command "git branch dev/develop" Then enter merge commadn "git merge featurebranchname"
>>> chr(97)
'a'
>>> ord('a')
97
Proper answer is here: http://scratching.psybermonkey.net/2011/02/ssh-how-to-pipe-output-from-local-to.html
your_command | ssh username@server "cat > filename.txt"
You just have to define the property below inside the activity element in your AndroidManifest.xml
file. It will restrict your orientation to portrait.
android:screenOrientation="portrait"
Example:
<activity
android:name="com.example.demo_spinner.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
if you want this to apply to the whole app define the property below inside the application tag like so:
<application>
android:screenOrientation="sensorPortrait"
</application>
Additionaly, as per Eduard Luca's comment below, you can also use screenOrientation="sensorPortrait"
if you want to enable rotation by 180 degrees.
android:layout_gravity="bottom"
I wanted to keep my html very minimal, so defined a small filter that creates the array [0,1,2,...] as others have done:
angular.module('awesomeApp')
.filter('range', function(){
return function(n) {
var res = [];
for (var i = 0; i < n; i++) {
res.push(i);
}
return res;
};
});
After that, on the view is possible to use like this:
<ul>
<li ng-repeat="i in 5 | range">
{{i+1}} <!-- the array will range from 0 to 4 -->
</li>
</ul>
2015 Update: Folks, this is for very old versions of Android. See other answers for modern solutions!
To strike through the entire text view, you can use a specific background image to simulate the strikethrough effect:
android:background="@drawable/bg_strikethrough"
Where the bg_strikethrough
drawable is a 9-patch that keeps a solid line through the middle, growing either side, with however much padding you think is reasonable. I've used one like this:
(enlarged for clarity.. 1300% !)
That is my HDPI version, so save it (the first one http://i.stack.imgur.com/nt6BK.png) as res/drawable-hdpi/bg_strikethrough.9.png
and the configuration will work as so:
There are two solutions for it.
Solution number one: 1.Recreate the project. While creating a project ensure that precompiled header is checked(Application settings... *** Do not check empty project)
Solution Number two: 1.Create stdafx.h and stdafx.cpp in your project 2 Right click on project -> properties -> C/C++ -> Precompiled Headers 3.select precompiled header to create(/Yc) 4.Rebuild the solution
Drop me a message if you encounter any issue.
You can use JavaScript functions like replace, and you can wrap the jQuery code in brackets:
var value = ($("#text").val()).replace(".", ":");
If you take 5 minutes to download visual studio and make a Console Application for this, your problem is solved.
using System;
using System.Linq;
using System.Diagnostics;
using System.IO;
namespace BgRunner
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting: " + String.Join(" ", args));
String arguments = String.Join(" ", args.Skip(1).ToArray());
String command = args[0];
Process p = new Process();
p.StartInfo = new ProcessStartInfo(command);
p.StartInfo.Arguments = arguments;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(command);
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
}
}
}
Examples of usage:
BgRunner.exe php/php-cgi -b 9999
BgRunner.exe redis/redis-server --port 3000
BgRunner.exe nginx/nginx
As per this article, it's not. The article also argues that it's not a good idea to make it one.
To quote from one of the comments:
So, I do not believe that CSS is turing complete. There is no capability to define a function in CSS. In order for a system to be turing-complete it has to be possible to write an interpreter: a function that interprets expressions that denote programs to execute. CSS has no variables that are directly accessible to the user; so you cannot even model the structure that represents the program to be interpreted in CSS.
You could go two ways with this. Using LINQPad (invaluable if you're new to LINQ) and a dummy database, I built the following queries:
Posts.Join(
Post_metas,
post => post.Post_id,
meta => meta.Post_id,
(post, meta) => new { Post = post, Meta = meta }
)
or
from p in Posts
join pm in Post_metas on p.Post_id equals pm.Post_id
select new { Post = p, Meta = pm }
In this particular case, I think the LINQ syntax is cleaner (I change between the two depending upon which is easiest to read).
The thing I'd like to point out though is that if you have appropriate foreign keys in your database, (between post and post_meta) then you probably don't need an explicit join unless you're trying to load a large number of records. Your example seems to indicate that you are trying to load a single post and its metadata. Assuming that there are many post_meta records for each post, then you could do the following:
var post = Posts.Single(p => p.ID == 1);
var metas = post.Post_metas.ToList();
If you want to avoid the n+1 problem, then you can explicitly tell LINQ to SQL to load all of the related items in one go (although this may be an advanced topic for when you're more familiar with L2S). The example below says "when you load a Post, also load all of its records associated with it via the foreign key represented by the 'Post_metas' property":
var dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith<Post>(p => p.Post_metas);
var dataContext = new MyDataContext();
dataContext.LoadOptions = dataLoadOptions;
var post = Posts.Single(p => p.ID == 1); // Post_metas loaded automagically
It is possible to make many LoadWith
calls on a single set of DataLoadOptions
for the same type, or many different types. If you do this lots though, you might just want to consider caching.
If your platform matrix supports Java 7 then you can use like below
List<List<String>> myList = new ArrayList<>();
Sounds like myversioncontrol.com have added a pre-commit hook, or have one that is now failing. If it's a free account, it might be you've exceeded some sort of monthly commit or bandwidth limit. Check their terms of service and/or contact them to see what's up.
UPDATE:
I've just checked their website, and it looks like the free account is only valid for 30 days, so you might've exceeded that. You may need to pony up the £3.50pcm or find somewhere else (Google Code is one suggestion, though there are others).
Simon Groenewolt makes a good point that you may have changed something in the control panel on their website that has turned on a pre-commit hook but where it's configured incorrectly.
I think above examples are correct. but you dont' really need to set
request.setAttribute("selectedDept", selectedDept);
you can reuse that info from JSTL, just do something like this..
<!DOCTYPE html>
<html lang="en">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<head>
<script src="../js/jquery-1.8.1.min.js"></script>
</head>
<body>
<c:set var="authors" value="aaa,bbb,ccc,ddd,eee,fff,ggg" scope="application" />
<c:out value="Before : ${param.Author}"/>
<form action="TestSelect.action">
<label>Author
<select id="Author" name="Author">
<c:forEach items="${fn:split(authors, ',')}" var="author">
<option value="${author}" ${author == param.Author ? 'selected' : ''}>${author}</option>
</c:forEach>
</select>
</label>
<button type="submit" value="submit" name="Submit"></button>
<Br>
<c:out value="After : ${param.Author}"/>
</form>
</body>
</html>
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
I solved this by changing the file path in the browser:
c/XAMPP/htdocs/myfile.html
localhost/myfile.html
WARNING: this will allow any user to login
I had to try something else. Since my root password expired and altering was not an option because
Column count of mysql.user is wrong. Expected 45, found 46. The table is probably corrupted
temporarly adding skip-grant-tables
under [mysqld]
in my.cnf
and restarting mysql did the trick
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
$highest_weight = max(array_column($details, 'Weight'));
How to get the min value
$lowest_weight = min(array_column($details, 'Weight'));
You could use Jquery indeed or plain good old javascript:
var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";
You put this in a function that you call on a setTimeout until the desired opacity is reached
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
I tried the top few methods, but they didn't work, for me, which were trying to make tox work. What eventually worked was:
sudo pip install tox
even if tox was already installed. The output terminated with:
Successfully built filelock
Installing collected packages: py, pluggy, toml, filelock, tox
Successfully installed filelock-3.0.10 pluggy-0.11.0 py-1.8.0 toml-0.10.0 tox-3.9.0
A bash solution :
docker history --no-trunc $argv | tac | tr -s ' ' | cut -d " " -f 5- | sed 's,^/bin/sh -c #(nop) ,,g' | sed 's,^/bin/sh -c,RUN,g' | sed 's, && ,\n & ,g' | sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g' | head -n -1
Step by step explanations:
tac : reverse the file
tr -s ' ' trim multiple whitespaces into 1
cut -d " " -f 5- remove the first fields (until X months/years ago)
sed 's,^/bin/sh -c #(nop) ,,g' remove /bin/sh calls for ENV,LABEL...
sed 's,^/bin/sh -c,RUN,g' remove /bin/sh calls for RUN
sed 's, && ,\n & ,g' pretty print multi command lines following Docker best practices
sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g' remove layer size information
head -n -1 remove last line ("SIZE COMMENT" in this case)
Example:
~ ? dih ubuntu:18.04
ADD file:28c0771e44ff530dba3f237024acc38e8ec9293d60f0e44c8c78536c12f13a0b in /
RUN set -xe
&& echo '#!/bin/sh' > /usr/sbin/policy-rc.d
&& echo 'exit 101' >> /usr/sbin/policy-rc.d
&& chmod +x /usr/sbin/policy-rc.d
&& dpkg-divert --local --rename --add /sbin/initctl
&& cp -a /usr/sbin/policy-rc.d /sbin/initctl
&& sed -i 's/^exit.*/exit 0/' /sbin/initctl
&& echo 'force-unsafe-io' > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup
&& echo 'DPkg::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' > /etc/apt/apt.conf.d/docker-clean
&& echo 'APT::Update::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' >> /etc/apt/apt.conf.d/docker-clean
&& echo 'Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";' >> /etc/apt/apt.conf.d/docker-clean
&& echo 'Acquire::Languages "none";' > /etc/apt/apt.conf.d/docker-no-languages
&& echo 'Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz";' > /etc/apt/apt.conf.d/docker-gzip-indexes
&& echo 'Apt::AutoRemove::SuggestsImportant "false";' > /etc/apt/apt.conf.d/docker-autoremove-suggests
RUN rm -rf /var/lib/apt/lists/*
RUN sed -i 's/^#\s*\(deb.*universe\)$/\1/g' /etc/apt/sources.list
RUN mkdir -p /run/systemd
&& echo 'docker' > /run/systemd/container
CMD ["/bin/bash"]
you can do it so simple:
First: For Example in Models you have User.cs with this implementation
public class User
{
public string username { get; set; }
public string age { get; set; }
}
We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this
public ActionResult Add()
{
var model = new User();
return View(model);
}
When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:
@model MyApp.Models.Student
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.username, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.username, new {
htmlAttributes = new { @class = "form-
control" } })
@Html.ValidationMessageFor(model => model.userame, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"
/>
</div>
</div>
</div>
}
So on button submit you will use it like this
[HttpPost]
public ActionResult Add(User user)
{
// now user.username has the value that user entered on form
}
Now that TypeScript 2.2 supports Mixins through Class expressions we have a much better way to express Mixins on Components. Mind you that you can also use Component inheritance since angular 2.3 (discussion) or a custom decorator as discussed in other answers here. However, I think Mixins have some properties that make them preferable for reusing behavior across components:
I strongly suggest you read the TypeScript 2.2 announcement above to understand how Mixins work. The linked discussions in angular GitHub issues provide additional detail.
You'll need these types:
export type Constructor<T> = new (...args: any[]) => T;
export class MixinRoot {
}
And then you can declare a Mixin like this Destroyable
mixin that helps components keep track of subscriptions that need to be disposed in ngOnDestroy
:
export function Destroyable<T extends Constructor<{}>>(Base: T) {
return class Mixin extends Base implements OnDestroy {
private readonly subscriptions: Subscription[] = [];
protected registerSubscription(sub: Subscription) {
this.subscriptions.push(sub);
}
public ngOnDestroy() {
this.subscriptions.forEach(x => x.unsubscribe());
this.subscriptions.length = 0; // release memory
}
};
}
To mixin Destroyable
into a Component
, you declare your component like this:
export class DashboardComponent extends Destroyable(MixinRoot)
implements OnInit, OnDestroy { ... }
Note that MixinRoot
is only necessary when you want to extend
a Mixin composition. You can easily extend multiple mixins e.g. A extends B(C(D))
. This is the obvious linearization of mixins I was talking about above, e.g. you're effectively composing an inheritnace hierarchy A -> B -> C -> D
.
In other cases, e.g. when you want to compose Mixins on an existing class, you can apply the Mixin like so:
const MyClassWithMixin = MyMixin(MyClass);
However, I found the first way works best for Components
and Directives
, as these also need to be decorated with @Component
or @Directive
anyway.
You'll probably want to handle spaces in your file names, abhorrent though they are :-)
So I would opt initially for something like:
pax> cat qq.in
normalfile.txt
file with spaces.doc
pax> sed 's/ /\\ /g' qq.in | xargs -n 1 cat
<<contents of 'normalfile.txt'>>
<<contents of 'file with spaces.doc'>>
pax> _
Command:
$ git mv oldFolderName newFolderName
It usually works fine.
Error "bad source ..." typically indicates that after last commit there were some renames in the source directory and hence git mv
cannot find the expected file.
The solution is simple - just commit before applying git mv
.
You should give the content to InfoWindow from jQuery object.
var $infoWindowContent = $("<div class='infowin-content'>Content goes here</div>");
var infoWindow = new google.maps.InfoWindow();
infowindow.setContent($infoWindowContent[0]);
I would suggest 3 things:
The last one worked for me.
i wrote a small function.. but works for me
def conv(strng):
k=strng
k=k.replace('\a','\\a')
k=k.replace('\b','\\b')
k=k.replace('\f','\\f')
k=k.replace('\n','\\n')
k=k.replace('\r','\\r')
k=k.replace('\t','\\t')
k=k.replace('\v','\\v')
return k
You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.
int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
// it's a valid integer => you could use the distance variable here
}
Steps for configuring Sublime Text Editor3 for Python3 :-
Enjoy Coding.
(The above answers explained the reason quite clearly, but seems not totally clear about the size of padding, so, I will add an answer according to what I learned from The Lost Art of Structure Packing, it has evolved to not limit to C
, but also applicable to Go
, Rust
.)
Rules:
int
should start at address divisible by 4, and long
by 8, short
by 2.char
and char[]
are special, could be any memory address, so they don't need padding before them.struct
, other than the alignment need for each individual member, the size of whole struct itself will be aligned to a size divisible by size of largest individual member, by padding at end.long
then divisible by 8, int
then by 4, short
then by 2.Order of member:
stu_c
and stu_d
from example below have the same members, but in different order, and result in different size for the 2 structs.Rules:
(n * 16)
bytes. (You can see in the example below, all printed hex addresses of structs end with 0
.)long double
).char
as member, its address could start at any address.Empty space:
test_struct_address()
below, the variable x
resides between adjacent struct g
and h
.x
is declared, h
's address won't change, x
just reused the empty space that g
wasted.y
.(for 64 bit system)
memory_align.c:
/**
* Memory align & padding - for struct.
* compile: gcc memory_align.c
* execute: ./a.out
*/
#include <stdio.h>
// size is 8, 4 + 1, then round to multiple of 4 (int's size),
struct stu_a {
int i;
char c;
};
// size is 16, 8 + 1, then round to multiple of 8 (long's size),
struct stu_b {
long l;
char c;
};
// size is 24, l need padding by 4 before it, then round to multiple of 8 (long's size),
struct stu_c {
int i;
long l;
char c;
};
// size is 16, 8 + 4 + 1, then round to multiple of 8 (long's size),
struct stu_d {
long l;
int i;
char c;
};
// size is 16, 8 + 4 + 1, then round to multiple of 8 (double's size),
struct stu_e {
double d;
int i;
char c;
};
// size is 24, d need align to 8, then round to multiple of 8 (double's size),
struct stu_f {
int i;
double d;
char c;
};
// size is 4,
struct stu_g {
int i;
};
// size is 8,
struct stu_h {
long l;
};
// test - padding within a single struct,
int test_struct_padding() {
printf("%s: %ld\n", "stu_a", sizeof(struct stu_a));
printf("%s: %ld\n", "stu_b", sizeof(struct stu_b));
printf("%s: %ld\n", "stu_c", sizeof(struct stu_c));
printf("%s: %ld\n", "stu_d", sizeof(struct stu_d));
printf("%s: %ld\n", "stu_e", sizeof(struct stu_e));
printf("%s: %ld\n", "stu_f", sizeof(struct stu_f));
printf("%s: %ld\n", "stu_g", sizeof(struct stu_g));
printf("%s: %ld\n", "stu_h", sizeof(struct stu_h));
return 0;
}
// test - address of struct,
int test_struct_address() {
printf("%s: %ld\n", "stu_g", sizeof(struct stu_g));
printf("%s: %ld\n", "stu_h", sizeof(struct stu_h));
printf("%s: %ld\n", "stu_f", sizeof(struct stu_f));
struct stu_g g;
struct stu_h h;
struct stu_f f1;
struct stu_f f2;
int x = 1;
long y = 1;
printf("address of %s: %p\n", "g", &g);
printf("address of %s: %p\n", "h", &h);
printf("address of %s: %p\n", "f1", &f1);
printf("address of %s: %p\n", "f2", &f2);
printf("address of %s: %p\n", "x", &x);
printf("address of %s: %p\n", "y", &y);
// g is only 4 bytes itself, but distance to next struct is 16 bytes(on 64 bit system) or 8 bytes(on 32 bit system),
printf("space between %s and %s: %ld\n", "g", "h", (long)(&h) - (long)(&g));
// h is only 8 bytes itself, but distance to next struct is 16 bytes(on 64 bit system) or 8 bytes(on 32 bit system),
printf("space between %s and %s: %ld\n", "h", "f1", (long)(&f1) - (long)(&h));
// f1 is only 24 bytes itself, but distance to next struct is 32 bytes(on 64 bit system) or 24 bytes(on 32 bit system),
printf("space between %s and %s: %ld\n", "f1", "f2", (long)(&f2) - (long)(&f1));
// x is not a struct, and it reuse those empty space between struts, which exists due to padding, e.g between g & h,
printf("space between %s and %s: %ld\n", "x", "f2", (long)(&x) - (long)(&f2));
printf("space between %s and %s: %ld\n", "g", "x", (long)(&x) - (long)(&g));
// y is not a struct, and it reuse those empty space between struts, which exists due to padding, e.g between h & f1,
printf("space between %s and %s: %ld\n", "x", "y", (long)(&y) - (long)(&x));
printf("space between %s and %s: %ld\n", "h", "y", (long)(&y) - (long)(&h));
return 0;
}
int main(int argc, char * argv[]) {
test_struct_padding();
// test_struct_address();
return 0;
}
Execution result - test_struct_padding()
:
stu_a: 8
stu_b: 16
stu_c: 24
stu_d: 16
stu_e: 16
stu_f: 24
stu_g: 4
stu_h: 8
Execution result - test_struct_address()
:
stu_g: 4
stu_h: 8
stu_f: 24
address of g: 0x7fffd63a95d0 // struct variable - address dividable by 16,
address of h: 0x7fffd63a95e0 // struct variable - address dividable by 16,
address of f1: 0x7fffd63a95f0 // struct variable - address dividable by 16,
address of f2: 0x7fffd63a9610 // struct variable - address dividable by 16,
address of x: 0x7fffd63a95dc // non-struct variable - resides within the empty space between struct variable g & h.
address of y: 0x7fffd63a95e8 // non-struct variable - resides within the empty space between struct variable h & f1.
space between g and h: 16
space between h and f1: 16
space between f1 and f2: 32
space between x and f2: -52
space between g and x: 12
space between x and y: 12
space between h and y: 8
Thus address start for each variable is g:d0 x:dc h:e0 y:e8
import codecs
...
fichier = codecs.open(filePath, "r", encoding="utf-8")
...
fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)
...
Unlike in Python 2, the zip
function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like
test2 = list(zip(lis1,lis2))
zipped_list = test2[:]
zipped_list_2 = list(test2)
We had trouble finding one that worked the way we wanted it to so I wrote one. I maintain the source and fix bugs as they arise plus provide free support.
http://www.yart.com.au/Resources/Programming/ASP-NET-JQuery-Date-Time-Control.aspx
To link to a YouTube video so it plays in HD by default, use the following URL:
https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).
Adding to the other great answers, we can use the Python logging
library's debug()
, info()
, warning()
, error()
, and critical()
methods. Quoting from the docs for Python 3.7.4,
There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message.
What this means is, you can use the Python logging
library to output a debug()
, or other type of message, and the logging
library will include the stack trace in its output. With this in mind, we can do the following:
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def f():
a = { 'foo': None }
# the following line will raise KeyError
b = a['bar']
def g():
f()
try:
g()
except Exception as e:
logger.error(str(e), exc_info=True)
And it will output:
'bar'
Traceback (most recent call last):
File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
g()
File "<ipython-input-2-8ae09e08766b>", line 14, in g
f()
File "<ipython-input-2-8ae09e08766b>", line 10, in f
b = a['bar']
KeyError: 'bar'
You'll need to convert any RGB colors into the Lab color space to be able to compare them in the way that humans see them. Otherwise you'll be getting RGB colors that 'match' in some very strange ways.
The wikipedia link on Color Differences gives you an intro into the various Lab color space difference algorithms that have been defined over the years. The simplest that just checks the Euclidian distance of two lab colours, works but has a few flaws.
Conveniently there's a Java implementation of the more sophisticated CIEDE2000 algorithm in the OpenIMAJ project. Provide it your two sets of Lab colours and it'll give you back single distance value.
In a php section before the HTML section, use sprinf() to create a constant string from the variables:
$mystuff = sprinf("My name is %s and my mother's name is %s","Suzy","Caroline");
Then in the HTML section you can do whatever you like, such as:
<p>$mystuff</p>
Here a simple one liners to check if only one parameter is given otherwise exit the script:
[ "$#" -ne 1 ] && echo "USAGE $0 <PARAMETER>" && exit
The size of storage required and how big the numbers can be.
On SQL Server:
tinyint
1 byte, 0 to 255smallint
2 bytes, -215 (-32,768) to 215-1 (32,767)int
4 bytes, -231 (-2,147,483,648) to 231-1 (2,147,483,647)bigint
8 bytes, -263 (-9,223,372,036,854,775,808) to 263-1 (9,223,372,036,854,775,807)You can store the number 1 in all 4, but a bigint
will use 8 bytes, while a tinyint
will use 1 byte.
Some clarifications (not really an answer)
In kubernetes, every pod gets assigned an IP address, and every container in the pod gets assigned that same IP address. Thus, as Alex Robinson stated in his answer, you can just use hostname -i
inside your container to get the pod IP address.
I tested with a pod running two dumb containers, and indeed hostname -i
was outputting the same IP address inside both containers. Furthermore, that IP was equivalent to the one obtained using kubectl describe pod
from outside, which validates the whole thing IMO.
However, PiersyP's answer seems more clean to me.
From kubernetes docs:
The applications in a pod all use the same network namespace (same IP and port space), and can thus “find” each other and communicate using localhost. Because of this, applications in a pod must coordinate their usage of ports. Each pod has an IP address in a flat shared networking space that has full communication with other physical computers and pods across the network.
Another piece from kubernetes docs:
Until now this document has talked about containers. In reality, Kubernetes applies IP addresses at the Pod scope - containers within a Pod share their network namespaces - including their IP address. This means that containers within a Pod can all reach each other’s ports on localhost.
Simply sitting on a delimiter
local str = 'one,two'
local regxEverythingExceptComma = '([^,]+)'
for x in string.gmatch(str, regxEverythingExceptComma) do
print(x)
end
If you want to do binary, give a --binary
option when you run git diff
.
Here you are assigning an instance of momentjs to CurrentDate:
var CurrentDate = moment();
Here just a string, the result from default formatting of a momentjs instance:
var CurrentDate = moment().format();
And here the number of seconds since january of... well, unix timestamp:
var CurrentDate = moment().unix();
And here another string as ISO 8601 (What's the difference between ISO 8601 and RFC 3339 Date Formats?):
var CurrentDate = moment().toISOString();
And this can be done too:
var a = moment();
var b = moment(a.toISOString());
console.log(a.isSame(b)); // true
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;
I had the same problem. What i found was i called my recieving object the same name as the class name. example:
const AspectType = new AspectType();
this screwed things up that way... hope this helps
I think this is the easiest way
<!-- Submit Button-->
<button
mat-raised-button
color="primary"
[disabled]="!f.valid"
>
Submit
</button>
That package in fact is available through packagist. You don't need a custom repository definition in this case. Just make sure you add a require
(which is always needed) with a matching version constraint.
In general, if a package is available on packagist, do not add a VCS repo. It will just slow things down.
For packages that are not available via packagist, use a VCS (or git) repository, as shown in your question. When you do, make sure that:
require
for the package in questionrequire
matches the versions provided by the VCS repo. You can use composer show <packagename>
to find the available versions. In this case ~2.3
would be a good option.require
matches the name in the remote composer.json
. In this case, it is gedmo/doctrine-extensions
.Here is a sample composer.json
that installs the same package via a VCS repo:
{
"repositories": [
{
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git"
}
],
"require": {
"gedmo/doctrine-extensions": "~2.3"
}
}
The VCS repo docs explain all of this quite well.
If there is a git (or other VCS) repository with a composer.json
available, do not use a "package" repo. Package repos require you to provide all of the metadata in the definition and will completely ignore any composer.json
present in the provided dist and source. They also have additional limitations, such as not allowing for proper updates in most cases.
Avoid package repos (see also the docs).
All the answers are outdated. It is best to use picasso for such purposes. It has a lot of features including background image processing.
Did I mention it is super easy to use:
Picasso.with(context).load(new File(...)).into(imageView);
Looks like a combination of componentDidMount
and componentDidUpdate
will get the job done. The first is called after the initial rendering, when the DOM is available, the second is called after any subsequent renderings, once the updated DOM is available. In my case, I both have them delegate to a common function to do the same thing.
See the following test program:
public class javatemp {
static String stripExtension (String str) {
// Handle null case specially.
if (str == null) return null;
// Get position of last '.'.
int pos = str.lastIndexOf(".");
// If there wasn't any '.' just return the string as is.
if (pos == -1) return str;
// Otherwise return the string, up to the dot.
return str.substring(0, pos);
}
public static void main(String[] args) {
System.out.println ("test.xml -> " + stripExtension ("test.xml"));
System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));
System.out.println ("test -> " + stripExtension ("test"));
System.out.println ("test. -> " + stripExtension ("test."));
}
}
which outputs:
test.xml -> test
test.2.xml -> test.2
test -> test
test. -> test
EF Core: Using "ThenInclude" to load mutiple levels: For example:
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ThenInclude(author => author.Photo)
.ToList();
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
Hopefully this helps someone out there.
For platform I was specifying "Any CPU", changed it to "AnyCPU" and that fixed the problem.
msbuild C:\Users\Project\Project.publishproj /p:Platform="AnyCPU" /p:DeployOnBuild=true /p:PublishProfile=local /p:Configuration=Debug
If you look at your .csproj file you'll see the correct platform name to use.
The usual way to find just the common elements in a set is to use Python's set
class. Just add all the elements to the set, then convert the set to a list
, and bam the duplicates are gone.
The problem, of course, is that a set()
can only contain hashable entries, and a dict
is not hashable.
If I had this problem, my solution would be to convert each dict
into a string that represents the dict
, then add all the strings to a set()
then read out the string values as a list()
and convert back to dict
.
A good representation of a dict
in string form is JSON format. And Python has a built-in module for JSON (called json
of course).
The remaining problem is that the elements in a dict
are not ordered, and when Python converts the dict
to a JSON string, you might get two JSON strings that represent equivalent dictionaries but are not identical strings. The easy solution is to pass the argument sort_keys=True
when you call json.dumps()
.
EDIT: This solution was assuming that a given dict
could have any part different. If we can assume that every dict
with the same "id"
value will match every other dict
with the same "id"
value, then this is overkill; @gnibbler's solution would be faster and easier.
EDIT: Now there is a comment from André Lima explicitly saying that if the ID is a duplicate, it's safe to assume that the whole dict
is a duplicate. So this answer is overkill and I recommend @gnibbler's answer.
This past week I installed Microsoft SQL Server 2014 Developer Edition on my dev box, and immediately ran into a problem I had never seen before.
I’ve installed various versions of SQL Server countless times, and it is usually a painless procedure. Install the server, run the Management Console, it’s that simple. However, after completing this installation, when I tried to log in to the server using SSMS, I got an error like the one below:
SQL Server login error 18456 “Login failed for user… (Microsoft SQL Server, Error: 18456)” I’m used to seeing this error if I typed the wrong password when logging in – but that’s only if I’m using mixed mode (Windows and SQL Authentication). In this case, the server was set up with Windows Authentication only, and the user account was my own. I’m still not sure why it didn’t add my user to the SYSADMIN role during setup; perhaps I missed a step and forgot to add it. At any rate, not all hope was lost.
The way to fix this, if you cannot log on with any other account to SQL Server, is to add your network login through a command line interface. For this to work, you need to be an Administrator on Windows for the PC that you’re logged onto.
Stop the MSSQL service. Open a Command Prompt using Run As Administrator. Change to the folder that holds the SQL Server EXE file; the default for SQL Server 2014 is “C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Binn”. Run the following command: “sqlservr.exe –m”. This will start SQL Server in single-user mode. While leaving this Command Prompt open, open another one, repeating steps 2 and 3. In the second Command Prompt window, run “SQLCMD –S Server_Name\Instance_Name” In this window, run the following lines, pressing Enter after each one: 1
CREATE LOGIN [domainName\loginName] FROM WINDOWS 2 GO 3 SP_ADDSRVROLEMEMBER 'LOGIN_NAME','SYSADMIN' 4 GO Use CTRL+C to end both processes in the Command Prompt windows; you will be prompted to press Y to end the SQL Server process.
Restart the MSSQL service. That’s it! You should now be able to log in using your network login.
Dont get confusion : simply remember
Also if you use NHibernate you can turn on and setup second level cache for queries and add to queries scope and timeout. And there is kick ass profiler for EF, L2S and NHibernate - http://hibernatingrhinos.com/products/UberProf. It will help to tune your queries.
com.sun.mail.util.MailLogger
is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.
The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.
99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.
If you're using maven add the following dependency (you might want to change version):
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>
i donot think onSaveInstanceState
is a good solution. it just use for activity which had been destoryed.
From android 3.0 the Fragmen has been manager by FragmentManager, the condition is: one activity mapping manny fragments, when the fragment is added(not replace: it will recreated) in backStack, the view will be destored. when back to the last one, it will display as before.
So i think the fragmentManger and transaction is good enough to handle it.
You're getting this error because you're trying to add/update a row to table2
that does not have a valid value for the UserID
field based on the values currently stored in table1
. If you post some more code I can help you diagnose the specific cause.