Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.
First the actual accounts:
LocalService account (preferred)
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.
NT AUTHORITY\LocalService
HKEY_USERS\S-1-5-19
)
Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).
NT AUTHORITY\NetworkService
MANGO$
) to remote serversHKEY_USERS\S-1-5-20
)NETWORK SERVICE
into the Select User or Group dialog
LocalSystem account (dangerous, don't use!)
Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)
.\LocalSystem
(can also use LocalSystem
or ComputerName\LocalSystem
)HKCU
represents the default user)MANGO$
) to remote servers
Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService
can still access the internet.
The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).
It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.
In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).
In Windows Server 2003 you cannot run a scheduled task as
NT_AUTHORITY\LocalService
(aka the Local Service account), or NT AUTHORITY\NetworkService
(aka the Network Service account). That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.
A service running as NetworkService
presents the machine credentials on the network. This means that if your computer was called mango
, it would present as the machine account MANGO$
:
user225312's answer is correct:
A. To count number of characters in str
object, you can use len()
function:
>>> print(len('please anwser my question'))
25
B. To get memory size in bytes allocated to store str
object, you can use sys.getsizeof()
function
>>> from sys import getsizeof
>>> print(getsizeof('please anwser my question'))
50
It gets complicated for Python 2.
A. The len()
function in Python 2 returns count of bytes allocated to store encoded characters in a str
object.
Sometimes it will be equal to character count:
>>> print(len('abc'))
3
But sometimes, it won't:
>>> print(len('???')) # String contains Cyrillic symbols
6
That's because str
can use variable-length encoding internally. So, to count characters in str
you should know which encoding your str
object is using. Then you can convert it to unicode
object and get character count:
>>> print(len('???'.decode('utf8'))) #String contains Cyrillic symbols
3
B. The sys.getsizeof()
function does the same thing as in Python 3 - it returns count of bytes allocated to store the whole string object
>>> print(getsizeof('???'))
27
>>> print(getsizeof('???'.decode('utf8')))
32
That's easy to do in Interface Builder:
1) make UILabel Attributed in Attributes Inspector
2) select part of phrase you want to make bold
3) change its font (or bold typeface of the same font) in font selector
That's all!
Google has created a library for easy Permissions management. Its called EasyPermissions
Here is a simple example on requesting Location permission using this library.
public class MainActivity extends AppCompatActivity {
private final int REQUEST_LOCATION_PERMISSION = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestLocationPermission();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(this, perms)) {
Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
@AfterPermissionsGranted(REQUEST_CODE)
is used to indicate the method that needs to be executed after a permission request with the request code REQUEST_CODE
has been granted.
This above case, the method requestLocationPermission()
method is called if the user grants the permission to access location services. So, that method acts as both a callback and a method to request the permissions.
You can implement separate callbacks for permission granted and permission denied as well. It is explained in the github page.
The other answers and comments are correct in that to examine the contents of a stream, one must add a terminal operation, thereby "consuming" the stream. However, one can do this and turn the result back into a stream, without buffering up the entire contents of the stream. Here are a couple examples:
static <T> Stream<T> throwIfEmpty(Stream<T> stream) {
Iterator<T> iterator = stream.iterator();
if (iterator.hasNext()) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
} else {
throw new NoSuchElementException("empty stream");
}
}
static <T> Stream<T> defaultIfEmpty(Stream<T> stream, Supplier<T> supplier) {
Iterator<T> iterator = stream.iterator();
if (iterator.hasNext()) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
} else {
return Stream.of(supplier.get());
}
}
Basically turn the stream into an Iterator
in order to call hasNext()
on it, and if true, turn the Iterator
back into a Stream
. This is inefficient in that all subsequent operations on the stream will go through the Iterator's hasNext()
and next()
methods, which also implies that the stream is effectively processed sequentially (even if it's later turned parallel). However, this does allow you to test the stream without buffering up all of its elements.
There is probably a way to do this using a Spliterator
instead of an Iterator
. This potentially allows the returned stream to have the same characteristics as the input stream, including running in parallel.
You could try my Linked Tree Map implementation.
From Wikipedia (you can read which is correct for your OS at that article):
Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).
This works on ruby 2.4 HTTPS Post with JSON object and the response body written out.
require 'net/http' #net/https does not have to be required anymore
require 'json'
require 'uri'
uri = URI('https://your.secure-url.com')
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
request.body = {parameter: 'value'}.to_json
response = http.request request # Net::HTTPResponse object
puts "response #{response.body}"
end
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your function here
}
Swift 3
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
// your function here
}
Swift 2
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
// your function here
})
Another option would be to set a flag variable as a Boolean
and then change that value based on your criteria.
Dim count as Integer
Dim flag as Boolean
flag = True
While flag
count = count + 1
If count = 10 Then
'Set the flag to false '
flag = false
End If
Wend
To change the labels for Pandas df.plot()
use ax.legend([...])
:
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);
Another approach is to do the same by plt.legend([...])
:
import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);
For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015
and run the program in the search result.
You can now execute your command in it, for example: cl /?
If it's an object method, you need to pass the object to CallObjectMethod
:
jobject result = env->CallObjectMethod(obj, messageMe, jstr);
What you were doing was the equivalent of jstr.messageMe()
.
Since your is a void method, you should call:
env->CallVoidMethod(obj, messageMe, jstr);
If you want to return a result, you need to change your JNI signature (the ()V
means a method of void
return type) and also the return type in your Java code.
Prior to running python, type cd
in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py
needs to be in this directory, so you can move hello.py
from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py
is.
Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p
The foreign keys in your schema (on Account_Name
and Account_Type
) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.
There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.
You can use Google Chrome Extension: JSONView
All formatted json result will be displayed directly on the browser.
Coloured, word-level diff
ouput
Here's what you can do with the the below script and diff-highlight:
#!/bin/sh -eu
# Use diff-highlight to show word-level differences
diff -U3 --minimal "$@" |
sed 's/^-/\x1b[1;31m-/;s/^+/\x1b[1;32m+/;s/^@/\x1b[1;34m@/;s/$/\x1b[0m/' |
diff-highlight
(Credit to @retracile's answer for the sed
highlighting)
SELECT * FROM Table_Name LIMIT 5;
I had this same question, and after a lot of research, it looks like it's not possible.
The answer from cgat is on the right track, but you can't actually concatenate references like that.
Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):
default: &default_title This Post Has No Title
title: *default_title
{ or }
example_post: &example
title: My mom likes roosters
body: Seriously, she does. And I don't know when it started.
date: 8/18/2012
first_post: *example
second_post:
title: whatever, etc.
For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References
default: &DEFAULT
URL: stooges.com
throw_pies?: true
stooges: &stooge_list
larry: first_stooge
moe: second_stooge
curly: third_stooge
development:
<<: *DEFAULT
URL: stooges.local
stooges:
shemp: fourth_stooge
test:
<<: *DEFAULT
URL: test.stooges.qa
stooges:
<<: *stooge_list
shemp: fourth_stooge
This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804
Next release of ASP.NET MVC (available in January or so) should have MSBuild task that compiles views, so you might want to wait.
See announcement
For char or short to int, you just need to assign the value.
char ch = 16;
int in = ch;
Same to int64.
long long lo = ch;
All values will be 16.
A REGEXP might be more efficient, but you'd have to benchmark it to be sure, e.g.
SELECT * from fiberbox where field REGEXP '1740|1938|1940';
Here is how I did it:
CSS:
.my-flex-card > div > div.card {
height: calc(100% - 15px);
margin-bottom: 15px;
}
HTML:
<div class="row my-flex-card">
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
aaaa
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
bbbb
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
cccc
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-block">
dddd
</div>
</div>
</div>
</div>
The struct b
line doesn't work because it's a syntax error. If you expand it out to include the type it will work just fine
struct MyObj b = a; // Runs fine
What C is doing here is essentially a memcpy
from the source struct to the destination. This is true for both assignment and return of struct
values (and really every other value in C)
First off, this actually is being raised in the next version to 8MB
or 16MB
... but I think to put this into perspective, Eliot from 10gen (who developed MongoDB) puts it best:
EDIT: The size has been officially 'raised' to 16MB
So, on your blog example, 4MB is actually a whole lot.. For example, the full uncompresses text of "War of the Worlds" is only 364k (html): http://www.gutenberg.org/etext/36
If your blog post is that long with that many comments, I for one am not going to read it :)
For trackbacks, if you dedicated 1MB to them, you could easily have more than 10k (probably closer to 20k)
So except for truly bizarre situations, it'll work great. And in the exception case or spam, I really don't think you'd want a 20mb object anyway. I think capping trackbacks as 15k or so makes a lot of sense no matter what for performance. Or at least special casing if it ever happens.
-Eliot
I think you'd be pretty hard pressed to reach the limit ... and over time, if you upgrade ... you'll have to worry less and less.
The main point of the limit is so you don't use up all the RAM on your server (as you need to load all MB
s of the document into RAM when you query it.)
So the limit is some % of normal usable RAM on a common system ... which will keep growing year on year.
Note on Storing Files in MongoDB
If you need to store documents (or files) larger than 16MB
you can use the GridFS API which will automatically break up the data into segments and stream them back to you (thus avoiding the issue with size limits/RAM.)
Instead of storing a file in a single document, GridFS divides the file into parts, or chunks, and stores each chunk as a separate document.
GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata.
You can use this method to store images, files, videos, etc in the database much as you might in a SQL database. I have used this to even store multi gigabyte video files.
Tested in .NET 5
public static class LikeExtension {
private static string ColumnDataBase<TEntity, TKey>(IModel model, Expression<Func<TEntity, TKey>> predicate) where TEntity : class {
ITable table = model
.GetRelationalModel()
.Tables
.First(f => f
.EntityTypeMappings
.First()
.EntityType == model
.FindEntityType(predicate
.Parameters
.First()
.Type
));
string column = (predicate.Body as MemberExpression).Member.Name;
string columnDataBase = table.Columns.First(f => f.PropertyMappings.Count(f2 => f2.Property.Name == column) > 0).Name;
return columnDataBase;
}
public static IQueryable<TEntity> Like<TEntity, TKey>(this DbContext context, Expression<Func<TEntity, TKey>> predicate, string text) where TEntity : class {
string columnDataBase = ColumnDataBase(context.Model, predicate);
return context.Set<TEntity>().FromSqlRaw(context.Set<TEntity>().ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text);
}
public static async Task<IEnumerable<TEntity>> LikeAsync<TEntity, TKey>(this DbContext context, Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) where TEntity : class {
string columnDataBase = ColumnDataBase(context.Model, predicate);
return await context.Set<TEntity>().FromSqlRaw(context.Set<TEntity>().ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text).ToListAsync(cancellationToken);
}
public static async Task<IEnumerable<TEntity>> LikeAsync<TEntity, TKey>(this IQueryable<TEntity> query, Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) where TEntity : class {
DbSet<TEntity> entities = query as DbSet<TEntity>;
string columnDataBase = ColumnDataBase(entities.EntityType.Model, predicate);
return await entities.FromSqlRaw(query.ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text).ToListAsync(cancellationToken);
}
public static IQueryable<TEntity> Like<TEntity, TKey>(this IQueryable<TEntity> query, Expression<Func<TEntity, TKey>> predicate, string text) where TEntity : class {
DbSet<TEntity> entities = query as DbSet<TEntity>;
string columnDataBase = ColumnDataBase(entities.EntityType.Model, predicate);
return entities.FromSqlRaw(query.ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text);
}
}
public async Task<IEnumerable<TEntity>> LikeAsync<TKey>(Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) {
return await context.LikeAsync(predicate, text, cancellationToken);
}
public IQueryable<TEntity> Like<TKey>(Expression<Func<TEntity, TKey>> predicate, string text) {
return context.Like(predicate, text);
}
IQueryable<CountryEntity> result = countryRepository
.Like(k => k.Name, "%Bra[sz]il%") /*Use Sync*/
.Where(w => w.DateRegister < DateTime.Now) /*Example*/
.Take(10); /*Example*/
Or
IEnumerable<CountryEntity> result = await countryRepository
.LikeAsync(k => k.Name, "%Bra[sz]il%", cancellationToken); /*Use Async*/
Or
IQueryable<CountryEntity> result = context.Countries
.Like(k => k.Name, "%Bra[sz]il%")
.Where(w => w.Name != null); /*Example*/
Or
List<CountryEntity> result2 = await context.Countries
.Like(k => k.Name, "%Bra[sz]il%")
.Where(w => w.Name != null) /*Example*/
.ToListAsync(); /*Use Async*/
Or
IEnumerable<CountryEntity> result3 = await context.Countries
.Where(w => w.Name != null)
.LikeAsync(k => k.Name, "%Bra[sz]il%", cancellationToken); /*Use Async*/
The OP's code snippet clearly uses the correct comment markup but CSS can break in a progressive way — so, if there's a syntax error, everything after that is likely to fail. A couple times I've relied on trustworthy sources that supplied incorrect comment markup that broke my style sheet. Since the OP provided just a small section of their code, I'd suggest the following:
Make sure all of your CSS comments use this markup /*
... */
-- which is the correct comment markup for css according to MDN
Validate your css with a linter or a secure online validator. Here's one by W3
More info:
I went to check the latest recommended media query breakpoints from bootstrap 4 and ended up copying the boiler plate straight from their docs. Almost every code block was labeled with javascript-style comments //
, which broke my code — and gave me only cryptic compile errors with which to troubleshoot, which went over my head at the time and caused me sadness.
IntelliJ text editor allowed me to comment out specific lines of css in a LESS file using the ctrl+/ hotkey which was great except it inserts //
by default on unrecognized file types. It isn't freeware and less is fairly mainstream so I trusted it and went with it. That broke my code. There's a preference menu for teaching it the correct comment markup for each filetype.
It can also be as simple as this.
@media (orientation: landscape) {
}
In your onEditorAction handler, keep in mind that you must return a boolean that indicates if you are handling the action (true) or if you applied some logic and want the normal behaviour (false), as in the following example:
EditText te = ...
te.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event){
if (actionId == EditorInfo.IME_ACTION_NEXT) {
// Some logic here.
return true; // Focus will do whatever you put in the logic.
}
return false; // Focus will change according to the actionId
}
});
I found this when I returned true after performing my logic since focus did not move.
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic
about following the C++ standard), you can do:
int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:
int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!
Or, better yet, use a standard container:
int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>
If you still want a proper array, you can use a constant, not a variable, when creating it:
const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
Similarly, if you want to get the size from a function in C++11, you can use a constexpr
:
constexpr int n()
{
return 10;
}
double a[n()]; // n() is a compile time constant expression
Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.
If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:
Original answer:
Here is a not-so-great "ng-if" directive:
myApp.directive('ngIf', function() {
return {
link: function(scope, element, attrs) {
if(scope.$eval(attrs.ngIf)) {
// remove '<div ng-if...></div>'
element.replaceWith(element.children())
} else {
element.replaceWith(' ')
}
}
}
});
that allows for this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type">
<hr>
<div ng-if="showFrom(message)">
<div>From: {{message.from.name}}</div>
</div>
<div ng-if="showCreatedBy(message)">
<div>Created by: {{message.createdBy.name}}</div>
</div>
<div ng-if="showTo(message)">
<div>To: {{message.to.name}}</div>
</div>
</div>
replaceWith() is used to remove unneeded content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?
The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.
E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from
, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.
The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way
bool AppendCharToCharArray( char *array, size_t n, char c )
{
size_t sz = std::strlen( array );
if ( sz + 1 < n )
{
array[sz] = c;
array[sz + 1] = '\0';
}
return ( sz + 1 < n );
}
If you need a function that will contain a copy of the original array plus the given character then it could look the following way
char * CharArrayPlusChar( const char *array, char c )
{
size_t sz = std::strlen( array );
char *s = new char[sz + 2];
std::strcpy( s, array );
s[sz] = c;
s[sz + 1] = '\0';
return ( s );
}
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
When you write 'array[index]' in C it translates it to machine instructions.
The translation is goes something like:
The result addresses something which may, or may not, be part of the array. In exchange for the blazing speed of machine instructions you lose the safety net of the computer checking things for you. If you're meticulous and careful it's not a problem. If you're sloppy or make a mistake you get burnt. Sometimes it might generate an invalid instruction that causes an exception, sometimes not.
This is what I did for the instagram API. converted timestamp with date method by multiplying by 1000. and then added all entity individually like (year, months, etc)
created the custom month list name and mapped with getMonth()
method which returns the index of the month.
convertStampDate(unixtimestamp){
// Unixtimestamp
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// filtered fate
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and thats it.
From the Java language spec:
It is a compile time error to import a type from the unnamed package.
You'll have to access the class via reflection or some other indirect method.
An issue I was having (may help someone) was simply that I was using a partial to load the Modal.
<li data-toggle="modal" data-target="#priceInfoModal">
<label>Listing Price</label>
<i class="fa fa-money"></i>
@Html.Partial("EditPartials/PriceInfo_Edit")
</li>
I had placed the partial call inside the same list item So data-target="#priceInfoModal" and div id="priceInfoModal" were in the same container causing me to not be able to close my modal
DATE() is a MySQL function that extracts only the date part of a date or date/time expression
SELECT * FROM table_name WHERE DATE(date_field) BETWEEN '2016-12-01' AND '2016-12-10';
It seems to me to be a bug in PHP. The error
'Fatal error: Uncaught Error: Using $this when not in object context in'
appears in the function using $this
, but the error is that the calling function is using non-static function as a static. I.e:
Class_Name
{
function foo()
{
$this->do_something(); // The error appears there.
}
function do_something()
{
///
}
}
While the error is here:
Class_Name::foo();
AutoPostBack property:
Asp.net controls which cannot submit the Form (PostBack) on their own and hence ASP.Net has provided a feature using
AutoPostBack = "true"
: which controls like DropDownList, CheckBoxList, RadioButtonList, etc. can perform PostBack(when clicked on it).
And
AutoPostBack = "false"
It is the by default state of controls which can perform Postback on button submit.
Install the package python-tk
like
sudo apt-get install python-tk
That is described (with apt-cache search python-tk
as)
Tkinter - Writing Tk applications with Python
Start with a basic square and borders. Each border will be given a different color so we can tell them apart:
.triangle {
border-color: yellow blue red green;
border-style: solid;
border-width: 200px 200px 200px 200px;
height: 0px;
width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
which gives you this:
But there's no need for the top border, so set its width to 0px
. Now our border-bottom of 200px
will make our triangle 200px tall.
.triangle {
border-color: yellow blue red green;
border-style: solid;
border-width: 0px 200px 200px 200px;
height: 0px;
width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
and we will get this:
Then to hide the two side triangles, set the border-color to transparent. Since the top-border has been effectively deleted, we can set the border-top-color to transparent as well.
.triangle {
border-color: transparent transparent red transparent;
border-style: solid;
border-width: 0px 200px 200px 200px;
height: 0px;
width: 0px;
}
_x000D_
<div class="triangle"></div>
_x000D_
finally we get this:
DELETE FROM ... WHERE id=...;
protected function templateRemove($id){
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));
if ($entity != null){
$em->remove($entity);
$em->flush();
}
}
If using PhpStorm 2019 and higher
File > Settings > Editor > General
There is'Soft-warp files' input under the 'Soft Warps' Header.
*.md; *.txt; *.rst; .adoc;
Add the file types to this field in which files you want them to be used.
*.md; *.txt; *.rst; .adoc;.php;*.js
db.users.count()
db.users.remove({})
db.users.count()
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));
For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes
instead of yAxes
. Note that an array (and plural) is used for yAxes
(or xAxes
), because you may as well have multiple axes.
printf("%9.6f", myFloat)
specifies a format with 9 total characters: 2 digits before the dot, the dot itself, and six digits after the dot.
I just ran into a VERY insidious example of this problem. My original fragment was much more complex, which made it difficult to see the error.
<ItemsControl
Foreground="Black" Background="White" Grid.IsSharedSizingScope="True"
x:Name="MyGrid" ItemsSource="{Binding}">
>
<ItemsControl.ItemsPanel>
<!-- All is fine here -->
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<!-- All is fine here -->
</ItemsControl.ItemTemplate>
<!-- Have you caught the error yet? -->
</ItemsControl>
The bug? The extra > after the initial opening <ItemsControl>
tag! The <
got applied to the built-in Items collection. When the DataContext was later set, instant crashola. So look out for more than just errors surround your ItemsControl specific data children when debugging this problem.
Now this is a very old thread i've come across but as many have pushed their answer's, here is mine in a hope to help someone with this simple code.
var search_value = "This is a dummy sentence!";_x000D_
var letter = 'a'; /*Can take any letter, have put in a var if anyone wants to use this variable dynamically*/_x000D_
letter = letter && "string" === typeof letter ? letter : "";_x000D_
var count;_x000D_
for (var i = count = 0; i < search_value.length; count += (search_value[i++] == letter));_x000D_
console.log(count);
_x000D_
I'm not sure if it is the fastest solution but i preferred it for simplicity and for not using regex (i just don't like using them!)
Update 2019
In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.
First of all, the container (parent) needs to be full height:
Option 1_ Add a class for min-height: 100%;
. Remember that min-height will only work if the parent has a defined height:
html, body {
height: 100%;
}
.min-100 {
min-height: 100%;
}
https://codeply.com/go/dTaVyMah1U
Option 2_ Use vh
units:
.vh-100 {
min-height: 100vh;
}
https://codeply.com/go/kMahVdZyGj
Also of Bootstrap 4.1, the vh-100
and min-vh-100
classes are included in Bootstrap so there is no need to for the extra CSS
Then, use flexbox direction column d-flex flex-column
on the container, and flex-grow-1
on any child divs (ie: row
) that you want to fill the remaining height.
Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height
You should call plt.show()
only at the end after creating all the plots.
Using importlib
the only thing you've got to add is
from importlib import import_module
from pathlib import Path
__all__ = [
import_module(f".{f.stem}", __package__)
for f in Path(__file__).parent.glob("*.py")
if "__" not in f.stem
]
del import_module, Path
you can use this
List<Car> requiredCars = cars.stream()
.filter (t-> t!= null && StringUtils.startsWith(t.getName(),"M"))
.collect(Collectors.toList());
The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)
To link with gdi32:
This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a
has no advantage over gdi32
other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib
for MSVC).
For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).
I solved it by updating the Color Filter when the Switch was state was changed...
public void bind(DetailItem item) {
switchColor(item.toggle);
listSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switchColor(b);
}
});
}
private void switchColor(boolean checked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
listSwitch.getThumbDrawable().setColorFilter(checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
listSwitch.getTrackDrawable().setColorFilter(!checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
}
double total = 44;
String total2 = String.valueOf(total);
This will convert double to String
I just put --password
flag into my command and after hitting Enter it asked me for password, which I supplied.
You can also use list comprehension to create set.
s = {i for i in range(5)}
This line is the problem:
int estimatedPopulation (int currentPopulation,
float growthRate (birthRate, deathRate))
Make it:
int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)
instead and invoke the function with three arguments like
estimatePopulation( currentPopulation, birthRate, deathRate );
OR declare it with two arguments like:
int estimatedPopulation (int currentPopulation, float growthrt ) { ... }
and call it as
estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));
Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate
variable in the main()
hides the function with the same name. So within main()
you can only access grouthRate
as float
. On the other hand, outside of the main()
you can only access that name as a function, since that automatic variable is only visible within the scope of main()
.
Just hope I didn't confuse you further :)
Using this keyword we can call one constructor in another constructor within same class.
Example :-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
with Apache PDFBox it goes like this:
PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println("Text:" + text);
}
document.close();
Quite a busy one-liner, but here it is:
myarray
, is normalised with the max value at 1.0
.myarray
.0-255
range.np.uint8()
.Image.fromarray()
.And you're done:
from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))
with plt.savefig()
:
with im.save()
:
This will give you the date in 24 hour format.
Date date = new Date();
date.setHours(date.getHours() + 8);
System.out.println(date);
SimpleDateFormat simpDate;
simpDate = new SimpleDateFormat("kk:mm:ss");
System.out.println(simpDate.format(date));
CodeMaid seems to be pretty useful - it AutoFormats on save which saves a lot of time between developers and code-diffs. (Are there other tools that can use the VS AutoFormat document?)
Another way using template reference variable and ViewChild, as proposed by Frelseren:
import { ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #fileInput/>
</div>
`
})
export class AppComponent {
@ViewChild("fileInput") fileInputVariable: any;
randomMethod() {
const files = this.fileInputVariable.nativeElement.files;
console.log(files);
}
}
I know the question is for C# I just want to left in Javascript format because i just converted the Samuel's answer:
export const contentTypes = {
".323": "text/h323",
".3g2": "video/3gpp2",
".3gp": "video/3gpp",
".3gp2": "video/3gpp2",
".3gpp": "video/3gpp",
".7z": "application/x-7z-compressed",
".aa": "audio/audible",
".AAC": "audio/aac",
".aaf": "application/octet-stream",
".aax": "audio/vnd.audible.aax",
".ac3": "audio/ac3",
".aca": "application/octet-stream",
".accda": "application/msaccess.addin",
".accdb": "application/msaccess",
".accdc": "application/msaccess.cab",
".accde": "application/msaccess",
".accdr": "application/msaccess.runtime",
".accdt": "application/msaccess",
".accdw": "application/msaccess.webapplication",
".accft": "application/msaccess.ftemplate",
".acx": "application/internet-property-stream",
".AddIn": "text/xml",
".ade": "application/msaccess",
".adobebridge": "application/x-bridge-url",
".adp": "application/msaccess",
".ADT": "audio/vnd.dlna.adts",
".ADTS": "audio/aac",
".afm": "application/octet-stream",
".ai": "application/postscript",
".aif": "audio/x-aiff",
".aifc": "audio/aiff",
".aiff": "audio/aiff",
".air": "application/vnd.adobe.air-application-installer-package+zip",
".amc": "application/x-mpeg",
".application": "application/x-ms-application",
".art": "image/x-jg",
".asa": "application/xml",
".asax": "application/xml",
".ascx": "application/xml",
".asd": "application/octet-stream",
".asf": "video/x-ms-asf",
".ashx": "application/xml",
".asi": "application/octet-stream",
".asm": "text/plain",
".asmx": "application/xml",
".aspx": "application/xml",
".asr": "video/x-ms-asf",
".asx": "video/x-ms-asf",
".atom": "application/atom+xml",
".au": "audio/basic",
".avi": "video/x-msvideo",
".axs": "application/olescript",
".bas": "text/plain",
".bcpio": "application/x-bcpio",
".bin": "application/octet-stream",
".bmp": "image/bmp",
".c": "text/plain",
".cab": "application/octet-stream",
".caf": "audio/x-caf",
".calx": "application/vnd.ms-office.calx",
".cat": "application/vnd.ms-pki.seccat",
".cc": "text/plain",
".cd": "text/plain",
".cdda": "audio/aiff",
".cdf": "application/x-cdf",
".cer": "application/x-x509-ca-cert",
".chm": "application/octet-stream",
".class": "application/x-java-applet",
".clp": "application/x-msclip",
".cmx": "image/x-cmx",
".cnf": "text/plain",
".cod": "image/cis-cod",
".config": "application/xml",
".contact": "text/x-ms-contact",
".coverage": "application/xml",
".cpio": "application/x-cpio",
".cpp": "text/plain",
".crd": "application/x-mscardfile",
".crl": "application/pkix-crl",
".crt": "application/x-x509-ca-cert",
".cs": "text/plain",
".csdproj": "text/plain",
".csh": "application/x-csh",
".csproj": "text/plain",
".css": "text/css",
".csv": "text/csv",
".cur": "application/octet-stream",
".cxx": "text/plain",
".dat": "application/octet-stream",
".datasource": "application/xml",
".dbproj": "text/plain",
".dcr": "application/x-director",
".def": "text/plain",
".deploy": "application/octet-stream",
".der": "application/x-x509-ca-cert",
".dgml": "application/xml",
".dib": "image/bmp",
".dif": "video/x-dv",
".dir": "application/x-director",
".disco": "text/xml",
".dll": "application/x-msdownload",
".dll.config": "text/xml",
".dlm": "text/dlm",
".doc": "application/msword",
".docm": "application/vnd.ms-word.document.macroEnabled.12",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".dot": "application/msword",
".dotm": "application/vnd.ms-word.template.macroEnabled.12",
".dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
".dsp": "application/octet-stream",
".dsw": "text/plain",
".dtd": "text/xml",
".dtsConfig": "text/xml",
".dv": "video/x-dv",
".dvi": "application/x-dvi",
".dwf": "drawing/x-dwf",
".dwp": "application/octet-stream",
".dxr": "application/x-director",
".eml": "message/rfc822",
".emz": "application/octet-stream",
".eot": "application/octet-stream",
".eps": "application/postscript",
".etl": "application/etl",
".etx": "text/x-setext",
".evy": "application/envoy",
".exe": "application/octet-stream",
".exe.config": "text/xml",
".fdf": "application/vnd.fdf",
".fif": "application/fractals",
".filters": "Application/xml",
".fla": "application/octet-stream",
".flr": "x-world/x-vrml",
".flv": "video/x-flv",
".fsscript": "application/fsharp-script",
".fsx": "application/fsharp-script",
".generictest": "application/xml",
".gif": "image/gif",
".group": "text/x-ms-group",
".gsm": "audio/x-gsm",
".gtar": "application/x-gtar",
".gz": "application/x-gzip",
".h": "text/plain",
".hdf": "application/x-hdf",
".hdml": "text/x-hdml",
".hhc": "application/x-oleobject",
".hhk": "application/octet-stream",
".hhp": "application/octet-stream",
".hlp": "application/winhlp",
".hpp": "text/plain",
".hqx": "application/mac-binhex40",
".hta": "application/hta",
".htc": "text/x-component",
".htm": "text/html",
".html": "text/html",
".htt": "text/webviewhtml",
".hxa": "application/xml",
".hxc": "application/xml",
".hxd": "application/octet-stream",
".hxe": "application/xml",
".hxf": "application/xml",
".hxh": "application/octet-stream",
".hxi": "application/octet-stream",
".hxk": "application/xml",
".hxq": "application/octet-stream",
".hxr": "application/octet-stream",
".hxs": "application/octet-stream",
".hxt": "text/html",
".hxv": "application/xml",
".hxw": "application/octet-stream",
".hxx": "text/plain",
".i": "text/plain",
".ico": "image/x-icon",
".ics": "application/octet-stream",
".idl": "text/plain",
".ief": "image/ief",
".iii": "application/x-iphone",
".inc": "text/plain",
".inf": "application/octet-stream",
".inl": "text/plain",
".ins": "application/x-internet-signup",
".ipa": "application/x-itunes-ipa",
".ipg": "application/x-itunes-ipg",
".ipproj": "text/plain",
".ipsw": "application/x-itunes-ipsw",
".iqy": "text/x-ms-iqy",
".isp": "application/x-internet-signup",
".ite": "application/x-itunes-ite",
".itlp": "application/x-itunes-itlp",
".itms": "application/x-itunes-itms",
".itpc": "application/x-itunes-itpc",
".IVF": "video/x-ivf",
".jar": "application/java-archive",
".java": "application/octet-stream",
".jck": "application/liquidmotion",
".jcz": "application/liquidmotion",
".jfif": "image/pjpeg",
".jnlp": "application/x-java-jnlp-file",
".jpb": "application/octet-stream",
".jpe": "image/jpeg",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "application/x-javascript",
".json": "application/json",
".jsx": "text/jscript",
".jsxbin": "text/plain",
".latex": "application/x-latex",
".library-ms": "application/windows-library+xml",
".lit": "application/x-ms-reader",
".loadtest": "application/xml",
".lpk": "application/octet-stream",
".lsf": "video/x-la-asf",
".lst": "text/plain",
".lsx": "video/x-la-asf",
".lzh": "application/octet-stream",
".m13": "application/x-msmediaview",
".m14": "application/x-msmediaview",
".m1v": "video/mpeg",
".m2t": "video/vnd.dlna.mpeg-tts",
".m2ts": "video/vnd.dlna.mpeg-tts",
".m2v": "video/mpeg",
".m3u": "audio/x-mpegurl",
".m3u8": "audio/x-mpegurl",
".m4a": "audio/m4a",
".m4b": "audio/m4b",
".m4p": "audio/m4p",
".m4r": "audio/x-m4r",
".m4v": "video/x-m4v",
".mac": "image/x-macpaint",
".mak": "text/plain",
".man": "application/x-troff-man",
".manifest": "application/x-ms-manifest",
".map": "text/plain",
".master": "application/xml",
".mda": "application/msaccess",
".mdb": "application/x-msaccess",
".mde": "application/msaccess",
".mdp": "application/octet-stream",
".me": "application/x-troff-me",
".mfp": "application/x-shockwave-flash",
".mht": "message/rfc822",
".mhtml": "message/rfc822",
".mid": "audio/mid",
".midi": "audio/mid",
".mix": "application/octet-stream",
".mk": "text/plain",
".mmf": "application/x-smaf",
".mno": "text/xml",
".mny": "application/x-msmoney",
".mod": "video/mpeg",
".mov": "video/quicktime",
".movie": "video/x-sgi-movie",
".mp2": "video/mpeg",
".mp2v": "video/mpeg",
".mp3": "audio/mpeg",
".mp4": "video/mp4",
".mp4v": "video/mp4",
".mpa": "video/mpeg",
".mpe": "video/mpeg",
".mpeg": "video/mpeg",
".mpf": "application/vnd.ms-mediapackage",
".mpg": "video/mpeg",
".mpp": "application/vnd.ms-project",
".mpv2": "video/mpeg",
".mqv": "video/quicktime",
".ms": "application/x-troff-ms",
".msi": "application/octet-stream",
".mso": "application/octet-stream",
".mts": "video/vnd.dlna.mpeg-tts",
".mtx": "application/xml",
".mvb": "application/x-msmediaview",
".mvc": "application/x-miva-compiled",
".mxp": "application/x-mmxp",
".nc": "application/x-netcdf",
".nsc": "video/x-ms-asf",
".nws": "message/rfc822",
".ocx": "application/octet-stream",
".oda": "application/oda",
".odc": "text/x-ms-odc",
".odh": "text/plain",
".odl": "text/plain",
".odp": "application/vnd.oasis.opendocument.presentation",
".ods": "application/oleobject",
".odt": "application/vnd.oasis.opendocument.text",
".one": "application/onenote",
".onea": "application/onenote",
".onepkg": "application/onenote",
".onetmp": "application/onenote",
".onetoc": "application/onenote",
".onetoc2": "application/onenote",
".orderedtest": "application/xml",
".osdx": "application/opensearchdescription+xml",
".p10": "application/pkcs10",
".p12": "application/x-pkcs12",
".p7b": "application/x-pkcs7-certificates",
".p7c": "application/pkcs7-mime",
".p7m": "application/pkcs7-mime",
".p7r": "application/x-pkcs7-certreqresp",
".p7s": "application/pkcs7-signature",
".pbm": "image/x-portable-bitmap",
".pcast": "application/x-podcast",
".pct": "image/pict",
".pcx": "application/octet-stream",
".pcz": "application/octet-stream",
".pdf": "application/pdf",
".pfb": "application/octet-stream",
".pfm": "application/octet-stream",
".pfx": "application/x-pkcs12",
".pgm": "image/x-portable-graymap",
".pic": "image/pict",
".pict": "image/pict",
".pkgdef": "text/plain",
".pkgundef": "text/plain",
".pko": "application/vnd.ms-pki.pko",
".pls": "audio/scpls",
".pma": "application/x-perfmon",
".pmc": "application/x-perfmon",
".pml": "application/x-perfmon",
".pmr": "application/x-perfmon",
".pmw": "application/x-perfmon",
".png": "image/png",
".pnm": "image/x-portable-anymap",
".pnt": "image/x-macpaint",
".pntg": "image/x-macpaint",
".pnz": "image/png",
".pot": "application/vnd.ms-powerpoint",
".potm": "application/vnd.ms-powerpoint.template.macroEnabled.12",
".potx": "application/vnd.openxmlformats-officedocument.presentationml.template",
".ppa": "application/vnd.ms-powerpoint",
".ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12",
".ppm": "image/x-portable-pixmap",
".pps": "application/vnd.ms-powerpoint",
".ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
".ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
".ppt": "application/vnd.ms-powerpoint",
".pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".prf": "application/pics-rules",
".prm": "application/octet-stream",
".prx": "application/octet-stream",
".ps": "application/postscript",
".psc1": "application/PowerShell",
".psd": "application/octet-stream",
".psess": "application/xml",
".psm": "application/octet-stream",
".psp": "application/octet-stream",
".pub": "application/x-mspublisher",
".pwz": "application/vnd.ms-powerpoint",
".qht": "text/x-html-insertion",
".qhtm": "text/x-html-insertion",
".qt": "video/quicktime",
".qti": "image/x-quicktime",
".qtif": "image/x-quicktime",
".qtl": "application/x-quicktimeplayer",
".qxd": "application/octet-stream",
".ra": "audio/x-pn-realaudio",
".ram": "audio/x-pn-realaudio",
".rar": "application/octet-stream",
".ras": "image/x-cmu-raster",
".rat": "application/rat-file",
".rc": "text/plain",
".rc2": "text/plain",
".rct": "text/plain",
".rdlc": "application/xml",
".resx": "application/xml",
".rf": "image/vnd.rn-realflash",
".rgb": "image/x-rgb",
".rgs": "text/plain",
".rm": "application/vnd.rn-realmedia",
".rmi": "audio/mid",
".rmp": "application/vnd.rn-rn_music_package",
".roff": "application/x-troff",
".rpm": "audio/x-pn-realaudio-plugin",
".rqy": "text/x-ms-rqy",
".rtf": "application/rtf",
".rtx": "text/richtext",
".ruleset": "application/xml",
".s": "text/plain",
".safariextz": "application/x-safari-safariextz",
".scd": "application/x-msschedule",
".sct": "text/scriptlet",
".sd2": "audio/x-sd2",
".sdp": "application/sdp",
".sea": "application/octet-stream",
".searchConnector-ms": "application/windows-search-connector+xml",
".setpay": "application/set-payment-initiation",
".setreg": "application/set-registration-initiation",
".settings": "application/xml",
".sgimb": "application/x-sgimb",
".sgml": "text/sgml",
".sh": "application/x-sh",
".shar": "application/x-shar",
".shtml": "text/html",
".sit": "application/x-stuffit",
".sitemap": "application/xml",
".skin": "application/xml",
".sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12",
".sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide",
".slk": "application/vnd.ms-excel",
".sln": "text/plain",
".slupkg-ms": "application/x-ms-license",
".smd": "audio/x-smd",
".smi": "application/octet-stream",
".smx": "audio/x-smd",
".smz": "audio/x-smd",
".snd": "audio/basic",
".snippet": "application/xml",
".snp": "application/octet-stream",
".sol": "text/plain",
".sor": "text/plain",
".spc": "application/x-pkcs7-certificates",
".spl": "application/futuresplash",
".src": "application/x-wais-source",
".srf": "text/plain",
".SSISDeploymentManifest": "text/xml",
".ssm": "application/streamingmedia",
".sst": "application/vnd.ms-pki.certstore",
".stl": "application/vnd.ms-pki.stl",
".sv4cpio": "application/x-sv4cpio",
".sv4crc": "application/x-sv4crc",
".svc": "application/xml",
".swf": "application/x-shockwave-flash",
".t": "application/x-troff",
".tar": "application/x-tar",
".tcl": "application/x-tcl",
".testrunconfig": "application/xml",
".testsettings": "application/xml",
".tex": "application/x-tex",
".texi": "application/x-texinfo",
".texinfo": "application/x-texinfo",
".tgz": "application/x-compressed",
".thmx": "application/vnd.ms-officetheme",
".thn": "application/octet-stream",
".tif": "image/tiff",
".tiff": "image/tiff",
".tlh": "text/plain",
".tli": "text/plain",
".toc": "application/octet-stream",
".tr": "application/x-troff",
".trm": "application/x-msterminal",
".trx": "application/xml",
".ts": "video/vnd.dlna.mpeg-tts",
".tsv": "text/tab-separated-values",
".ttf": "application/octet-stream",
".tts": "video/vnd.dlna.mpeg-tts",
".txt": "text/plain",
".u32": "application/octet-stream",
".uls": "text/iuls",
".user": "text/plain",
".ustar": "application/x-ustar",
".vb": "text/plain",
".vbdproj": "text/plain",
".vbk": "video/mpeg",
".vbproj": "text/plain",
".vbs": "text/vbscript",
".vcf": "text/x-vcard",
".vcproj": "Application/xml",
".vcs": "text/plain",
".vcxproj": "Application/xml",
".vddproj": "text/plain",
".vdp": "text/plain",
".vdproj": "text/plain",
".vdx": "application/vnd.ms-visio.viewer",
".vml": "text/xml",
".vscontent": "application/xml",
".vsct": "text/xml",
".vsd": "application/vnd.visio",
".vsi": "application/ms-vsi",
".vsix": "application/vsix",
".vsixlangpack": "text/xml",
".vsixmanifest": "text/xml",
".vsmdi": "application/xml",
".vspscc": "text/plain",
".vss": "application/vnd.visio",
".vsscc": "text/plain",
".vssettings": "text/xml",
".vssscc": "text/plain",
".vst": "application/vnd.visio",
".vstemplate": "text/xml",
".vsto": "application/x-ms-vsto",
".vsw": "application/vnd.visio",
".vsx": "application/vnd.visio",
".vtx": "application/vnd.visio",
".wav": "audio/wav",
".wave": "audio/wav",
".wax": "audio/x-ms-wax",
".wbk": "application/msword",
".wbmp": "image/vnd.wap.wbmp",
".wcm": "application/vnd.ms-works",
".wdb": "application/vnd.ms-works",
".wdp": "image/vnd.ms-photo",
".webarchive": "application/x-safari-webarchive",
".webtest": "application/xml",
".wiq": "application/xml",
".wiz": "application/msword",
".wks": "application/vnd.ms-works",
".WLMP": "application/wlmoviemaker",
".wlpginstall": "application/x-wlpg-detect",
".wlpginstall3": "application/x-wlpg3-detect",
".wm": "video/x-ms-wm",
".wma": "audio/x-ms-wma",
".wmd": "application/x-ms-wmd",
".wmf": "application/x-msmetafile",
".wml": "text/vnd.wap.wml",
".wmlc": "application/vnd.wap.wmlc",
".wmls": "text/vnd.wap.wmlscript",
".wmlsc": "application/vnd.wap.wmlscriptc",
".wmp": "video/x-ms-wmp",
".wmv": "video/x-ms-wmv",
".wmx": "video/x-ms-wmx",
".wmz": "application/x-ms-wmz",
".wpl": "application/vnd.ms-wpl",
".wps": "application/vnd.ms-works",
".wri": "application/x-mswrite",
".wrl": "x-world/x-vrml",
".wrz": "x-world/x-vrml",
".wsc": "text/scriptlet",
".wsdl": "text/xml",
".wvx": "video/x-ms-wvx",
".x": "application/directx",
".xaf": "x-world/x-vrml",
".xaml": "application/xaml+xml",
".xap": "application/x-silverlight-app",
".xbap": "application/x-ms-xbap",
".xbm": "image/x-xbitmap",
".xdr": "text/plain",
".xht": "application/xhtml+xml",
".xhtml": "application/xhtml+xml",
".xla": "application/vnd.ms-excel",
".xlam": "application/vnd.ms-excel.addin.macroEnabled.12",
".xlc": "application/vnd.ms-excel",
".xld": "application/vnd.ms-excel",
".xlk": "application/vnd.ms-excel",
".xll": "application/vnd.ms-excel",
".xlm": "application/vnd.ms-excel",
".xls": "application/vnd.ms-excel",
".xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
".xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".xlt": "application/vnd.ms-excel",
".xltm": "application/vnd.ms-excel.template.macroEnabled.12",
".xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
".xlw": "application/vnd.ms-excel",
".xml": "text/xml",
".xmta": "application/xml",
".xof": "x-world/x-vrml",
".XOML": "text/plain",
".xpm": "image/x-xpixmap",
".xps": "application/vnd.ms-xpsdocument",
".xrm-ms": "text/xml",
".xsc": "application/xml",
".xsd": "text/xml",
".xsf": "text/xml",
".xsl": "text/xml",
".xslt": "text/xml",
".xsn": "application/octet-stream",
".xss": "application/xml",
".xtp": "application/octet-stream",
".xwd": "image/x-xwindowdump",
".z": "application/x-compress",
".zip": "application/x-zip-compressed"
}
this way work properly and I used it in many projects! for example I get data of views the last 30 days:
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(*) as views'))
->groupBy('date')
->get();
If you want to get the number of views based on different IPs, you can use the DISTINCT
like below :
$viewsData = DB::table('page_views')
->where('page_id', $page->id)
->whereDate('created_at', '>=', now()->subDays(30))
->select(DB::raw('DATE(created_at) as data'), DB::raw('count(DISTINCT user_ip) as visitors'))
->groupBy('date')
->get();
You can easily customize it by manipulating the columns name
I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.
Hopefully will help someone else.
Here is the corrected code from the question:
// code to load jquery - working fine
// code to load javascript file - working fine
// ENABLE AJAX :
function add_ajax()
{
wp_enqueue_script(
'function',
'http://host/blog/wp-content/themes/theme/js.js',
array( 'jquery' ),
'1.0',
1
);
wp_localize_script(
'function',
'ajax_script',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
$dirName = get_stylesheet_directory(); // use this to get child theme dir
require_once ($dirName."/ajax.php");
add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php
add_action('template_redirect', 'add_ajax');
If you happen to have jQuery around, you can intercept the click on the link like this:
$(document).on('click', 'a', function (event) {
event.preventDefault();
window.open($(this).attr('href'), '_system');
return false;
});
This way you don't have to modify the links in the html, which can save a lot of time. I have set this up using a delegate, that's why you see it being tied to the document object, with the 'a' tag as the second argument. This way all 'a' tags will be handled, regardless of when they are added.
Ofcourse you still have to install the InAppBrowser plug-in:
cordova plugin add org.apache.cordova.inappbrowser
The shortest method
$('#item').removeAttr('class').attr('class', '');
You can use the below code for it.
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jArray = jsonObj.getJSONArray("data");
int length = jArray.length();
for(int i=0; i<length; i++)
{
JSONObject jObj = jArray.getJSONObject(i);
String id = jObj.optString("id");
String name=jObj.optString("name");
JSONArray ingredientArray = jObj.getJSONArray("Ingredients");
int size = ingredientArray.length();
ArrayList<String> Ingredients = new ArrayList<>();
for(int j=0; j<size; j++)
{
JSONObject json = ja.getJSONObject(j);
Ingredients.add(json.optString("name"));
}
}
I am not sure if you got this resolved. To follow up on "CommonsWare's" comment.
That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.
Change
Uri uri=Uri.parse("/external/images/media/470939");
to
Uri uri=Uri.parse("content://external/images/media/470939");
in my case
Uri uri = Uri.parse("content://media/external/images/media/6562");
[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);
int main(int argc, char *argv[]){
DIR *dip;
struct dirent *dit;
struct stat statbuf;
char currentPath[FILENAME_MAX];
int depth = 0; /*Used to correctly space output*/
/*Open Current Directory*/
if((dip = opendir(".")) == NULL)
return errno;
/*Store Current Working Directory in currentPath*/
if((getcwd(currentPath, FILENAME_MAX)) == NULL)
return errno;
/*Read all items in directory*/
while((dit = readdir(dip)) != NULL){
/*Skips . and ..*/
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
/*Correctly forms the path for stat and then resets it for rest of algorithm*/
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
if(stat(currentPath, &statbuf) == -1){
perror("stat");
return errno;
}
getcwd(currentPath, FILENAME_MAX);
/*Checks if current item is of the type file (type 8) and no command line arguments*/
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*If a command line argument is given, checks for filename match*/
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
if(strcmp(dit->d_name, argv[1]) == 0)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*Checks if current item is of the type directory (type 4)*/
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
closedir(dip);
return 0;
}
/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
if((dip = opendir(currentPath)) == NULL)
printf("Error: Failed to open Directory ==> %s\n", currentPath);
while((dit = readdir(dip)) != NULL){
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
stat(currentPath, &statbuf);
getcwd(currentPath, FILENAME_MAX);
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
if(strcmp(dit->d_name, argv[1]) == 0){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
}
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
/*Changing back here is necessary because of how stat is done*/
chdir("..");
closedir(dip);
}
void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
/*If two directories exist at the same level the path
is built wrong and needs to be corrected*/
if((chdir(currentPath)) == -1){
chdir("..");
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
for(i = 0; i < depth; i++)
printf (" ");
printf("%s (subdirectory)\n", dit->d_name);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
else{
for(i =0; i < depth; i++)
printf(" ");
printf("%s (subdirectory)\n", dit->d_name);
chdir(currentPath);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
}
You have several options:
JS
var json_arr = JSON.stringify(arr);
PHP
$arr = json_decode($_POST['arr']);
Sending an array via FormData
.
JS
// Use <#> or any other delimiter you want
var serial_arr = arr.join("<#>");
PHP
$arr = explode("<#>", $_POST['arr']);
I used this command to find last 5 minutes logs for particular event "DHCPACK
", try below:
$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"
You could use wmic command:
wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>
Drivetype 2 indicates that its a removable disk.
mysqli:query()
returns a mysqli_result
object, which cannot be serialized into a string.
You need to fetch the results from the object. Here's how to do it.
Fetch a single row from the result and then access column index 0 or using an associative key. Use the null-coalescing operator in case no rows are present in the result.
$result = $con->query($tourquery); // or mysqli_query($con, $tourquery);
$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';
echo '<strong>Per room amount: </strong>'.$tourresult;
Use foreach
loop to iterate over the result and fetch each row one by one. You can access each column using the column name as an array index.
$result = $con->query($tourquery); // or mysqli_query($con, $tourquery);
foreach($result as $row) {
echo '<strong>Per room amount: </strong>'.$row['roomprice'];
}
MSDTC must be enabled on both systems, both server and client.
Also, make sure that there isn't a firewall between the systems that blocks RPC.
DTCTest is a nice litt app that helps you to troubleshoot any other problems.
In my opinion the best practice is to place the CSS file in the header
<head>
<link rel="stylesheet" href="css/layout.css" type="text/css">
</head>
and the Javascript file before the closing </body>
tag
<script type="text/javascript" src="script.js"></script>
</body>
Also if you have, like you said two CSS files. The browser would use both. If there were any selectors, ie. .content {}
that were the same in both CSS files the browser would overwrite the similar properties of the first one with the second one's properties. If that makes sense.
You can use CSS3 filters. They are relatively easy to implement, though are only supported on webkit at the minute. Samsung Galaxy 2's browser should support though, as I think that's a webkit browser?
When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:
return StatusCode(500, "My error");
Or
return StatusCode((int)HttpStatusCode.InternalServerError, "My error");
Or
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });
Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error:
in client side (ajax).
you can have ajax call like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
success: function (response) {
console.log("Custom message : " + response.responseText);
}, //Is Called when Status Code is 200[OK] or other Http success code
error: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
})
Additionally you can handle different HTTP errors from jQuery side like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
statusCode: {
500: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
501: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}
})
statusCode:
is useful when you want to call different functions for different status codes that you return from server.
You can see list of different Http Status codes here:Wikipedia
Additional resources:
This should work (where enquiryId
is the id you need to match against):
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == enquiryId);
What this does is passes each vehicle in the list into the lambda predicate, evaluating the predicate. If the predicate returns true (ie. vehicle.EnquiryID == enquiryId
), then the current vehicle will be removed from the list.
If you know the types of the objects in your collections, then using the generic collections is a better approach. It avoids casting when retrieving objects from the collections, but can also avoid boxing if the items in the collection are value types (which can cause performance issues).
Of-course this is an old thread but to make it complete.
From SQL 2008 you can use DATE datatype so you can simply do:
SELECT CONVERT(DATE,GETDATE())
OR
Select * from [User] U
where CONVERT(DATE,U.DateCreated) = '2014-02-07'
Along the lines of ggovan's answer, I do this as follows:
/**
* Provides various high-order functions.
*/
public final class F {
/**
* When the returned {@code Function} is passed as an argument to
* {@link Stream#flatMap}, the result is a stream of instances of
* {@code cls}.
*/
public static <E> Function<Object, Stream<E>> instancesOf(Class<E> cls) {
return o -> cls.isInstance(o)
? Stream.of(cls.cast(o))
: Stream.empty();
}
}
Using this helper function:
Stream.of(objects).flatMap(F.instancesOf(Client.class))
.map(Client::getId)
.forEach(System.out::println);
This solution is for windows:
radiobuttonObj.isChecked()
will give you boolean
if(radiobuttonObj1.isChecked()){
//do what you want
}else if(radiobuttonObj2.isChecked()){
//do what you want
}
Free tools supporting panning / zooming:
Free tools without built in pan / zoom support:
Paid tools with built in pan / zoom support:
Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.
This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
It would be nice to have full support for set methods for dictionaries (and not the unholy mess we're getting with Python 3.9) so that you could simply "remove" a set of keys. However, as long as that's not the case, and you have a large dictionary with potentially a large number of keys to remove, you might want to know about the performance. So, I've created some code that creates something large enough for meaningful comparisons: a 100,000 x 1000 matrix, so 10,000,00 items in total.
from itertools import product
from time import perf_counter
# make a complete worksheet 100000 * 1000
start = perf_counter()
prod = product(range(1, 100000), range(1, 1000))
cells = {(x,y):x for x,y in prod}
print(len(cells))
print(f"Create time {perf_counter()-start:.2f}s")
clock = perf_counter()
# remove everything above row 50,000
keys = product(range(50000, 100000), range(1, 100))
# for x,y in keys:
# del cells[x, y]
for n in map(cells.pop, keys):
pass
print(len(cells))
stop = perf_counter()
print(f"Removal time {stop-clock:.2f}s")
10 million items or more is not unusual in some settings. Comparing the two methods on my local machine I see a slight improvement when using map
and pop
, presumably because of fewer function calls, but both take around 2.5s on my machine. But this pales in comparison to the time required to create the dictionary in the first place (55s), or including checks within the loop. If this is likely then its best to create a set that is a intersection of the dictionary keys and your filter:
keys = cells.keys() & keys
In summary: del
is already heavily optimised, so don't worry about using it.
You can use HttpParams from @angular/common/http and pass a string with the query. For example:
import { HttpClient, HttpParams } from '@angular/common/http';
const query = 'key=value' // date=2020-03-06
const options = {
params: new HttpParams({
fromString: query
})
}
Now in your code
this.http.get(urlFull, options);
And this works for you :)
I hoppe help you
If you want the caret down symbol, remove the "appearence: none" it implies to remove webkit and moz- as well from select in css.
Also check this answer from here: Cannot manually edit applicationhost.config
The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.
So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.
How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.
In IE 8, cookies (verified only against localhost) are shared between ports. In FF 10, they are not.
I've posted this answer so that readers will have at least one concrete option for testing each scenario.
This error, as correctly identified above, is due to the compiler not using c++11 or above standard. This answer is for Windows 10.
For c++11 and above standard support in codeblocks version 17:
Click settings in the toolbar.
A drop-down menu appears. Select compiler option.
Choose Global Compiler Settings.
In the toolbar in this new window in second section, choose compiler settings.
Then choose compiler flags option in below toolbar.
Unfold general tab. Check the C++ standard that you want your compiler to follow.
Click OK.
For those who are trying to get C++11 support in Sublime text.
Download mingw compiler version 7 or above. In versions below this, the default c++ standard used is c++98 whereas in versions higher than 7, the default standard used is c++11.
Copy the folder in main C drive. It should not be inside any other folder in C drive.
Rename the folder as MinGW. This name is case insensitive, so it should any variation of mingw and must not include any other characters in the name.
Then go to environment variables and edit the path variable. Add this "C:\mingw\bin" and click OK.
You can check the version of g++ in cmd by typing g++ -v
.
This should be sufficient to enable c++11 in sublime text.
If you want to take inputs and outputs as well from input files for competitive programming purposes, then follow this link.
TL;DR Login for each request is not a required component to implement API security, authentication is.
It is hard to answer your question about login without talking about security in general. With some authentication schemes, there's no traditional login.
REST does not dictate any security rules, but the most common implementation in practice is OAuth with 3-way authentication (as you've mentioned in your question). There is no log-in per se, at least not with each API request. With 3-way auth, you just use tokens.
This scheme gives the user the option to revoke access at any time. Practially all publicly available RESTful APIs I've seen use OAuth to implement this.
I just don't think you should frame your problem (and question) in terms of login, but rather think about securing the API in general.
For further info on authentication of REST APIs in general, you can look at the following resources:
You probably want to use something like jQuery, which makes JS programming easier.
Something like:
$(document).ready(function(){
// Your code here
});
Would seem to do what you are after.
The proper (and easy) way to do date/time validation using Java 8+ is to use the java.time.format.DateTimeFormatter
class. Using a regex for validation isn't really ideal for dates. For the example case in this question:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
LocalDate date = formatter.parse(text, LocalDate::from);
} catch (DateTimeParseException e) {
// Thrown if text could not be parsed in the specified format
}
This code will parse the text, validate that it is a valid date, and also return the date as a LocalDate
object. Note that the DateTimeFormatter
class has a number of static predefined date formats matching ISO standards if your use case matches any of them.
In Visual Studio 2017 you need to make sure you're not in release configuration mode.
I usually use this workaround:
try:
from .mymodule import myclass
except Exception: #ImportError
from mymodule import myclass
Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.
Use below two lines of code to get current page or post ID
global $post;
echo $post->ID;
The new way to do it is to use enabledBorder
like this:
new TextField(
decoration: new InputDecoration(
enabledBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Colors.grey, width: 0.0),
),
focusedBorder: ...
border: ...
),
)
Seems like the python executable is not found in your PATH, which defines where it is looking for executables. See the official instructions for instructions on how to get the python executables in your PATH.
Javascript now has a specific built in object called Map, you can call as follows :
var myMap = new Map()
You can update it with .set :
myMap.set("key0","value")
This has the advantage of methods you can use to handle look ups, like the boolean .has
myMap.has("key1"); // evaluates to false
You can use this before calling .get on your Map object to handle looking up non-existent keys
You could try computing sin(pi/2)
(or cos(pi/2)
for that matter) using the (fairly) quickly converging power series for sin and cos. (Even better: use various doubling formulas to compute nearer x=0
for faster convergence.)
BTW, better than using series for tan(x)
is, with computing say cos(x)
as a black box (e.g. you could use taylor series as above) is to do root finding via Newton. There certainly are better algorithms out there, but if you don't want to verify tons of digits this should suffice (and it's not that tricky to implement, and you only need a bit of calculus to understand why it works.)
There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974
@variable: 2em;
body{ width: calc(~"100% - @{variable} * 2");}
By using the curly brackets you don't need to close and reopen the escaping quotes.
Check out this link about multi project setups.
Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.
settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'
Also make sure that the app's build.gradle has the followng:
dependencies {
compile project(':libraries:lib1')
}
You should have the following structure:
MyProject/
| settings.gradle
+ app/
| build.gradle
+ libraries/
+ lib1/
| build.gradle
+ lib2/
| build.gradle
The app's build.gradle should use the com.android.application
plugin while any libraries' build.gradle should use the com.android.library
plugin.
The Android Studio IDE should update if you're able to build from the command line with this setup.
For MariaDB, use modify column:
ALTER TABLE table_name MODIFY COLUMN column_name VARCHAR (500);
It will work.
In the W3 wiki page about structuring HTML5, it says:
<section>
: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.
And then displays an image that I cleaned up:
It's also important to know how to use the <article>
tag (from the same W3 link above):
<article>
is related to<section>
, but is distinctly different. Whereas<section>
is for grouping distinct sections of content or functionality,<article>
is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then<article>
is suitable for marking them up.In our example,
<section id="main">
contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore<article>
is perfect for them:
<section id="main">
<article>
<!-- first blog post -->
</article>
<article>
<!-- second blog post -->
</article>
<article>
<!-- third blog post -->
</article>
</section>
Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:
<article>
<section id="introduction">
</section>
<section id="content">
</section>
<section id="summary">
</section>
</article>
You don't say if this is a desktop or web app. I would use the getResourceAsStream()
method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.
What fixed this for me was that I had a React component being rendered prior to my core.js shim being loaded.
import ReactComponent from '.'
import 'core-js/es6'
Loading the core-js prior to the ReactComponent fixed my issue
import 'core-js/es6'
import ReactComponent from '.'
When you assign a function to a variable you don't use the () but simply the name of the function.
In your case given def x(): ...
, and variable silly_var
you would do something like this:
silly_var = x
and then you can call the function either with
x()
or
silly_var()
I like Jake's solution. The problem with no header is resolved by doing the following
xlWorkSheet.Cells[1, 1] = "Header 1";
xlWorkSheet.Cells[1, 2] = "Header 2";
xlWorkSheet.Cells[1, 3] = "Header 3";
of course this only works is you know what the headers should be ahead of time.
You can't do this no. There is one attribute selector that matches exactly or partial until a - sign, but it wouldn't work here because you have multiple attributes. If the class name you are looking for would always be first, you could do this:
<html>
<head>
<title>Test Page</title>
<style type="text/css">
div[class|=status] { background-color:red; }
</style>
</head>
<body>
<div id='A' class='status-important bar-class'>A</div>
<div id='B' class='bar-class'>B</div>
<div id='C' class='status-low-priority bar-class'>C</div>
</body>
</html>
Note that this is just to point out which CSS attribute selector is the closest, it is not recommended to assume class names will always be in front since javascript could manipulate the attribute.
I would like to improve answer from chris-b a little bit more.
See below for my code:
from threading import Thread, Lock
import threading
mutex = Lock()
def processData(data, thread_safe):
if thread_safe:
mutex.acquire()
try:
thread_id = threading.get_ident()
print('\nProcessing data:', data, "ThreadId:", thread_id)
finally:
if thread_safe:
mutex.release()
counter = 0
max_run = 100
thread_safe = False
while True:
some_data = counter
t = Thread(target=processData, args=(some_data, thread_safe))
t.start()
counter = counter + 1
if counter >= max_run:
break
In your first run if you set thread_safe = False
in while loop, mutex will not be used, and threads will step over each others in print method as below;
but, if you set thread_safe = True
and run it, you will see all the output comes perfectly fine;
hope this helps.
<img style="float: right;" alt="" src="http://example.com/image.png" />
<div style="clear: right">
...text...
</div>
I think Asa's answer is essentially correct, but you could extend it a little to act more like mkdir -p
, either:
import os
def mkdir_path(path):
if not os.access(path, os.F_OK):
os.mkdirs(path)
or
import os
import errno
def mkdir_path(path):
try:
os.mkdirs(path)
except os.error, e:
if e.errno != errno.EEXIST:
raise
These both handle the case where the path already exists silently but let other errors bubble up.
From JDK source code, I found below code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
I was able to successfully pass through the data attribute in the ajax method. Here is my code
$.ajax({
url: "/api/Gigs/Cancel",
type: "DELETE",
data: {
"GigId": link.attr('data-gig-id')
}
})
The link.attr method simply returned the value of 'data-gig-id' .
I think it's not possible to select by a css value (display)
edit:
in my opinion, it would make sense to use a bit of jquery here:
$('#your_container > div:visible:last').addClass('last-visible-div');
First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).
Second, the -vm argument in eclipse.ini
should point to the java executable. See
http://wiki.eclipse.org/Eclipse.ini for examples.
If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?
First you need to get the current date
var currentDate = new Date();
Then you need to place it in the arguments of datepicker like given below
$("#datepicker").datepicker("setDate", currentDate);
Check the following jsfiddle.
You can use the df.reindex() function in pandas. df is
Net Upper Lower Mid Zsore
Answer option
More than once a day 0% 0.22% -0.12% 2 65
Once a day 0% 0.32% -0.19% 3 45
Several times a week 2% 2.45% 1.10% 4 78
Once a week 1% 1.63% -0.40% 6 65
define an list of column names
cols = df.columns.tolist()
cols
Out[13]: ['Net', 'Upper', 'Lower', 'Mid', 'Zsore']
move the column name to wherever you want
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[16]: ['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
then use df.reindex()
function to reorder
df = df.reindex(columns= cols)
out put is: df
Mid Upper Lower Net Zsore
Answer option
More than once a day 2 0.22% -0.12% 0% 65
Once a day 3 0.32% -0.19% 0% 45
Several times a week 4 2.45% 1.10% 2% 78
Once a week 6 1.63% -0.40% 1% 65
Perhaps the question needs to be slightly more precise here about what is required because it can be read it two different ways. i.e.
Given the accepted answer, the OP clearly intended it to be interpreted the first way. For anybody reading the question the other way try
SELECT `table_schema`
FROM `information_schema`.`tables`
WHERE `table_name` = 'whatever';
Yes, something like:
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });
That will only work for a single string parameter of course, but you can modify it pretty easily.
Note that the class name has to be a fully-qualified one, i.e. including the namespace. For nested classes, you need to use a dollar (as that's what the compiler uses). For example:
package foo;
public class Outer
{
public static class Nested {}
}
To obtain the Class
object for that, you'd need Class.forName("foo.Outer$Nested")
.
You can fetch from a remote repository, see the differences and then pull or merge.
This is an example for a remote repository called origin
and a branch called master
tracking the remote branch origin/master
:
git checkout master
git fetch
git diff origin/master
git rebase origin master
Type related errors can be avoided by imposing a schema as follows:
note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").
import pyspark
from pyspark.sql import SparkSession
import pandas as pd
spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()
pdDF = pd.read_csv("test.csv")
contents of the pandas data frame:
col1 col2 col3 col4 col5 col6 col7 col8 ...
0 10000001 1 0 1 12:35 OK 10002 1 ...
1 10000001 2 0 1 12:36 OK 10002 1 ...
2 10000002 1 0 4 12:19 PA 10003 1 ...
Next, create the schema:
from pyspark.sql.types import *
mySchema = StructType([ StructField("col1", LongType(), True)\
,StructField("col2", IntegerType(), True)\
,StructField("col3", IntegerType(), True)\
,StructField("col4", IntegerType(), True)\
,StructField("col5", StringType(), True)\
,StructField("col6", StringType(), True)\
,StructField("col7", IntegerType(), True)\
,StructField("col8", IntegerType(), True)\
,StructField("col9", IntegerType(), True)\
,StructField("col10", IntegerType(), True)\
,StructField("col11", StringType(), True)\
,StructField("col12", StringType(), True)\
,StructField("col13", IntegerType(), True)\
,StructField("col14", IntegerType(), True)\
,StructField("col15", IntegerType(), True)\
,StructField("col16", IntegerType(), True)\
,StructField("col17", IntegerType(), True)\
,StructField("col18", IntegerType(), True)\
,StructField("col19", IntegerType(), True)\
,StructField("col20", IntegerType(), True)\
,StructField("col21", IntegerType(), True)\
,StructField("col22", IntegerType(), True)\
,StructField("col23", IntegerType(), True)\
,StructField("col24", IntegerType(), True)\
,StructField("col25", IntegerType(), True)])
Note: True
(implies nullable allowed)
create the pyspark dataframe:
df = spark.createDataFrame(pdDF,schema=mySchema)
confirm the pandas data frame is now a pyspark data frame:
type(df)
output:
pyspark.sql.dataframe.DataFrame
Aside:
To address Kate's comment below - to impose a general (String) schema you can do the following:
df=spark.createDataFrame(pdDF.astype(str))
I just found this answer on the Web:
import unicodedata
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
only_ascii = nfkd_form.encode('ASCII', 'ignore')
return only_ascii
It works fine (for French, for example), but I think the second step (removing the accents) could be handled better than dropping the non-ASCII characters, because this will fail for some languages (Greek, for example). The best solution would probably be to explicitly remove the unicode characters that are tagged as being diacritics.
Edit: this does the trick:
import unicodedata
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
unicodedata.combining(c)
will return true if the character c
can be combined with the preceding character, that is mainly if it's a diacritic.
Edit 2: remove_accents
expects a unicode string, not a byte string. If you have a byte string, then you must decode it into a unicode string like this:
encoding = "utf-8" # or iso-8859-15, or cp1252, or whatever encoding you use
byte_string = b"café" # or simply "café" before python 3.
unicode_string = byte_string.decode(encoding)
let's think urls = "http://example1.com http://example2.com"
function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}
output will be text = "'http://example1.com'"
If you are going to manage your memory manually, you have two cases:
If you need to break any of these rules, please document it.
It is all about pointer ownership.
go to canvas page.. view it in browser.. copy the address bar text. now go to your facebook app go to edit settings
in website, in site url paste that address
in facebook integration , again paste the that address in canvas url
and also the same code wherever you require canvas url or redirect url..
hope it will help..
I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.
I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.
I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.
cout.fill('*');
cout << -12345 << endl; // print default value with no field width
cout << setw(10) << -12345 << endl; // print default with field width
cout << setw(10) << left << -12345 << endl; // print left justified
cout << setw(10) << right << -12345 << endl; // print right justified
cout << setw(10) << internal << -12345 << endl; // print internally justified
This produces the output:
-12345
****-12345
-12345****
****-12345
-****12345
Make sure you import csv file using Pandas
import pandas as pd
condition = pd.isnull(data[i][j])
You can recursively merge them into one as follows:
function mergeRecursive(obj1, obj2) {_x000D_
for (var p in obj2) {_x000D_
try {_x000D_
// Property in destination object set; update its value._x000D_
if (obj2[p].constructor == Object) {_x000D_
obj1[p] = this.mergeRecursive(obj1[p], obj2[p]);_x000D_
_x000D_
} else {_x000D_
obj1[p] = obj2[p];_x000D_
_x000D_
}_x000D_
_x000D_
} catch (e) {_x000D_
obj1[p] = obj2[p];_x000D_
_x000D_
}_x000D_
}_x000D_
return obj1;_x000D_
}_x000D_
_x000D_
arr1 = [_x000D_
{ id: "abdc4051", date: "2017-01-24" },_x000D_
{ id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
arr2 = [_x000D_
{ id: "abdc4051", name: "ab" },_x000D_
{ id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
mergeRecursive(arr1, arr2)_x000D_
console.log(JSON.stringify(arr1))
_x000D_
Here's how you do it:
Getting the max heap size that the app can use:
Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory();
Getting how much of the heap your app currently uses:
long usedMemory=runtime.totalMemory() - runtime.freeMemory();
Getting how much of the heap your app can now use (available memory) :
long availableMemory=maxMemory-usedMemory;
And, to format each of them nicely, you can use:
String formattedMemorySize=Formatter.formatShortFileSize(context,memorySize);
Interesting artcle...
I've had a quick hunt around on google and found nothing, but you might want to check some of the comments - plenty of people seem to have had a go at implementing a simple component demo, you might want to take a look at some of theirs for inspiration:
http://www.unseen-academy.de/componentSystem.html
http://www.mcshaffry.com/GameCode/thread.php?threadid=732
http://www.codeplex.com/Wikipage?ProjectName=elephant
Also, the comments themselves seem to have a fairly in-depth discussion on how you might code up such a system.
Call http://php.net/str_replace: $input = str_replace(' ', '_', $input);
Here you go:
Just change the line1 style as per below:
line1: {
backgroundColor: '#FDD7E4',
width:'100%',
alignSelf:'center'
}
With Gson, you'd just need to do something like:
List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());
You might also need to provide a no-arg constructor on the Video
class you're deserializing to.
It is better to wrap it into function:
let countNumber = (array,specificNumber) => {
return array.filter(n => n == specificNumber).length
}
countNumber([1,2,3,4,5],3) // returns 1
If your intention is to attach event only on checked checkboxes (so it would fire when they are unchecked and checked later again) then this is what you want.
$(function() {
$("input[type='checkbox']:checked").change(function() {
})
})
if your intention is to attach event to all checkboxes (checked and unchecked)
$(function() {
$("input[type='checkbox']").change(function() {
})
})
if you want it to fire only when they are being checked (from unchecked) then @James Allardice answer above.
BTW input[type='checkbox']:checked
is CSS selector.
It's very simple
self.navigationController?.view.semanticContentAttribute = .forceRightToLeft
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Meanwhile there is a native JS function that does that. See String#padStart
console.log(String(5).padStart(2, '0'));
_x000D_
Try this
#movie_item {
display: block;
margin-top: 10px;
height: 175px;
}
.movie_item_poster {
float: left;
height: 150px;
width: 100px;
background: red;
}
#movie_item_content {
float: left;
background: gold;
}
.movie_item_content_title {
display: block;
}
.movie_item_content_year {
float: right;
}
.movie_item_content_plot {
display: block;
}
.movie_item_toolbar {
clear: both;
vertical-align: bottom;
width: 100%;
height: 25px;
}
In Html
<div id="movie_item">
<div class="movie_item_poster">
<img src="..." style="max-width: 100%; max-height: 100%;">
</div>
<div id="movie_item_content">
<div class="movie_item_content_year">(1890-)</div>
<div class="movie_item_content_title">title my film is a long word</div>
<div class="movie_item_content_plot">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia, ratione, aliquam, earum, quibusdam libero rerum iusto exercitationem reiciendis illo corporis nulla ducimus suscipit nisi dolore explicabo. Accusantium porro reprehenderit ad!</div>
</div>
<div class="movie_item_toolbar">
Lorem Ipsum...
</div>
</div>
I change position div year.
Material Design styling alert dialogs: Custom Font, Button, Color & shape,..
MaterialAlertDialogBuilder(requireContext(),
R.style.MyAlertDialogTheme
)
.setIcon(R.drawable.ic_dialogs_24px)
.setTitle("Feedback")
//.setView(R.layout.edit_text)
.setMessage("Do you have any additional comments?")
.setPositiveButton("Send") { dialog, _ ->
val input =
(dialog as AlertDialog).findViewById<TextView>(
android.R.id.text1
)
Toast.makeText(context, input!!.text, Toast.LENGTH_LONG).show()
}
.setNegativeButton("Cancel") { _, _ ->
Toast.makeText(requireContext(), "Clicked cancel", Toast.LENGTH_SHORT).show()
}
.show()
Style:
<style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
<item name="android:textAppearanceSmall">@style/MyTextAppearance</item>
<item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
<item name="android:textAppearanceLarge">@style/MyTextAppearance</item>
<item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
<item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
<item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
</item>
</style>
<style name="MyTextAppearance" parent="TextAppearance.AppCompat">
<item name="android:fontFamily">@font/rosarivo</item>
</style>
<style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
<!-- <item name="backgroundTint">@color/colorPrimaryDark</item>-->
<item name="backgroundTint">@android:color/transparent</item>
<item name="rippleColor">@color/colorAccent</item>
<item name="android:textColor">@color/colorPrimary</item>
<!-- <item name="android:textColor">@android:color/white</item>-->
<item name="android:textSize">14sp</item>
<item name="android:textAllCaps">false</item>
</style>
<style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
<item name="backgroundTint">@android:color/transparent</item>
<item name="rippleColor">@color/colorAccent</item>
<item name="android:textColor">@color/colorPrimary</item>
<!--<item name="android:textColor">@android:color/darker_gray</item>-->
<item name="android:textSize">14sp</item>
<item name="android:textAllCaps">false</item>
</style>
<style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">8dp</item>
</style>
If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:
@mixin not($ignorList...) {
//if only a single value given
@if (length($ignorList) == 1){
//it is probably a list variable so set ignore list to the variable
$ignorList: nth($ignorList,1);
}
//set up an empty $notOutput variable
$notOutput: '';
//for each item in the list
@each $not in $ignorList {
//generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
$notOutput: $notOutput + ':not(#{$not})';
}
//output the full :not() rule including all ignored items
&#{$notOutput} {
@content;
}
}
it can be used in 2 ways:
Option 1: list the ignored items inline
input {
/*non-ignored styling goes here*/
@include not('[type="radio"]','[type="checkbox"]'){
/*ignored styling goes here*/
}
}
Option 2: list the ignored items in a variable first
$ignoredItems:
'[type="radio"]',
'[type="checkbox"]'
;
input {
/*non-ignored styling goes here*/
@include not($ignoredItems){
/*ignored styling goes here*/
}
}
Outputted CSS for either option
input {
/*non-ignored styling goes here*/
}
input:not([type="radio"]):not([type="checkbox"]) {
/*ignored styling goes here*/
}
I know this thread is old now, but here is some decent documentation on Google Docs API. It was ridiculously hard to find, but useful, so maybe it will help you some. http://pythonhosted.org/gdata/docs/api.html.
I used gspread recently for a project to graph employee time data. I don't know how much it might help you, but here's a link to the code: https://github.com/lightcastle/employee-timecards
Gspread made things pretty easy for me. I was also able to add logic in to check for various conditions to create month-to-date and year-to-date results. But I just imported the whole dang spreadsheet and parsed it from there, so I'm not 100% sure that it is exactly what you're looking for. Best of luck.
One quick and easy way:
function paintSvgToCanvas(uSvg, uCanvas) {
var pbx = document.createElement('img');
pbx.style.width = uSvg.style.width;
pbx.style.height = uSvg.style.height;
pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
uCanvas.getContext('2d').drawImage(pbx, 0, 0);
}
struct node{
int position;
char name[30];
struct node * next;
};
void free_list(node * list){
node* next_node;
printf("\n\n Freeing List: \n");
while(list != NULL)
{
next_node = list->next;
printf("clear mem for: %s",list->name);
free(list);
list = next_node;
printf("->");
}
}
have a look at example 3 from http://www.php.net/manual/en/language.oop5.basic.php
$className = 'Foo';
$instance = new $className(); // Foo()
If you want to add a new record in the form
newRecord = [4L, 1L, u'DDD', 1689544L, datetime.datetime(2010, 9, 21, 21, 45), u'jhhjjh']
to messageName
where messageName
in the form X_somemessage
can, but does not have to be in your dictionary, then do it this way:
myDict.setdefault(messageName, []).append(newRecord)
This way it will be appended to an existing messageName
or a new list will be created for a new messageName
.
DECLARE @Dates table ([Date] datetime);
DECLARE @Times table ([Time] datetime);
INSERT INTO @Dates VALUES('2009-03-12 00:00:00.000');
INSERT INTO @Dates VALUES('2009-03-26 00:00:00.000');
INSERT INTO @Dates VALUES('2009-03-30 00:00:00.000');
INSERT INTO @Times VALUES('1899-12-30 12:30:00.000');
INSERT INTO @Times VALUES('1899-12-30 10:00:00.000');
INSERT INTO @Times VALUES('1899-12-30 10:00:00.000');
WITH Dates (ID, [Date])
AS (
SELECT ROW_NUMBER() OVER (ORDER BY [Date]), [Date] FROM @Dates
), Times (ID, [Time])
AS (
SELECT ROW_NUMBER() OVER (ORDER BY [Time]), [Time] FROM @Times
)
SELECT Dates.[Date] + Times.[Time] FROM Dates
JOIN Times ON Times.ID = Dates.ID
Prints:
2009-03-12 10:00:00.000
2009-03-26 10:00:00.000
2009-03-30 12:30:00.000
You are just using a single parameter inside the function hence it is working fine in both the cases like follows:
MsgBox "Hello world!"
MsgBox ("Hello world!")
But when you'll use more than one parameter, In VBScript method will parenthesis will throw an error and without parenthesis will work fine like:
MsgBox "Hello world!", vbExclamation
The above code will run smoothly but
MsgBox ("Hello world!", vbExclamation)
will throw an error. Try this!! :-)
You should only use extern template
to force the compiler to not instantiate a template when you know that it will be instantiated somewhere else. It is used to reduce compile time and object file size.
For example:
// header.h
template<typename T>
void ReallyBigFunction()
{
// Body
}
// source1.cpp
#include "header.h"
void something1()
{
ReallyBigFunction<int>();
}
// source2.cpp
#include "header.h"
void something2()
{
ReallyBigFunction<int>();
}
This will result in the following object files:
source1.o
void something1()
void ReallyBigFunction<int>() // Compiled first time
source2.o
void something2()
void ReallyBigFunction<int>() // Compiled second time
If both files are linked together, one void ReallyBigFunction<int>()
will be discarded, resulting in wasted compile time and object file size.
To not waste compile time and object file size, there is an extern
keyword which makes the compiler not compile a template function. You should use this if and only if you know it is used in the same binary somewhere else.
Changing source2.cpp
to:
// source2.cpp
#include "header.h"
extern template void ReallyBigFunction<int>();
void something2()
{
ReallyBigFunction<int>();
}
Will result in the following object files:
source1.o
void something1()
void ReallyBigFunction<int>() // compiled just one time
source2.o
void something2()
// No ReallyBigFunction<int> here because of the extern
When both of these will be linked together, the second object file will just use the symbol from the first object file. No need for discard and no wasted compile time and object file size.
This should only be used within a project, like in times when you use a template like vector<int>
multiple times, you should use extern
in all but one source file.
This also applies to classes and function as one, and even template member functions.
Either your data is bad, or it's not structured the way you think it is. Possibly both.
To prove/disprove this hypothesis, run this query:
SELECT * from
(
SELECT count(*) as c, Supplier_Item.SKU
FROM Supplier_Item
INNER JOIN orderdetails
ON Supplier_Item.sku = orderdetails.sku
INNER JOIN Supplier
ON Supplier_item.supplierID = Supplier.SupplierID
GROUP BY Supplier_Item.SKU
) x
WHERE c > 1
ORDER BY c DESC
If this returns just a few rows, then your data is bad. If it returns lots of rows, then your data is not structured the way you think it is. (If it returns zero rows, I'm wrong.)
I'm guessing that you have orders containing the same SKU
multiple times (two separate line items, both ordering the same SKU
).
You can use ref.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})
If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {},
bus: new Vue(),
},
template: `
<div>
<ChildForm :item="item" :bus="bus" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.bus.$emit('submit')
}
},
components: { ChildForm },
})
Code of component.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
Another way to do it:
<?php
$data = 'My data';
$menugen = function() use ($data) {
echo "[".$data."]";
};
$menugen();
UPDATE 2020-01-13: requested by Peter Mortensen
As of PHP 5.3.0 we have anonymous functions support that can create closures. A closure can access the variable which is created outside of its scope.
In the example, the closure is able to access $data
because it was declared in the use
clause.
Try this...
//global declaration
private TextView timeUpdate;
Calendar calendar;
.......
timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()
.......
//in onStart()
calendar = Calendar.getInstance();
//date format is: "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());
//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");
The result is...
happy coding.....
Use
for /r path %%var in (*.*) do some_command %%var
with:
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
You need to add the referer field in the headers of the HTTP request. With wget, you just need the --header arg :
wget http://www.icerts.com/images/logo.jpg --header "Referer: www.icerts.com"
And the result :
--2011-10-02 02:00:18-- http://www.icerts.com/images/logo.jpg
Résolution de www.icerts.com (www.icerts.com)... 97.74.86.3
Connexion vers www.icerts.com (www.icerts.com)|97.74.86.3|:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 6102 (6,0K) [image/jpeg]
Sauvegarde en : «logo.jpg»
Maybe I'm being dumb, but isn't table the obvious solution here?
<div class="parent">
<div class="fixed">
<div class="stretchToFit">
</div>
.parent{ display: table; width 100%; }
.fixed { display: table-cell; width: 150px; }
.stretchToFit{ display: table-cell; vertical-align: top}
Another way that I've figured out in chrome is even simpler, but man is it a hack!
.fixed{
float: left
}
.stretchToFit{
display: table-cell;
width: 1%;
}
This alone should fill the rest of the line horizontally, as table-cells do. However, you get some strange issues with it going over 100% of its parent, setting the width to a percent value fixes it though.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
An easier way would be to:
git checkout --theirs /path/to/file.extension
git pull origin master
This will override your local file with the file on git
With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.
See issue 89989:
It should be possible to e.g. invoke the "
Open Active File in New Window
" command and open that file into an empty workspace in the web.
You can also do it by targeting the current input, with anything.target.reset()
. This is the most easiest way!
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
<form onSubmit={this.handleSubmit}>
...
</form>
I have the same problem of having to get the status bar height in an onCreate. This works for me.
private static final int LOW_DPI_STATUS_BAR_HEIGHT = 19;
private static final int MEDIUM_DPI_STATUS_BAR_HEIGHT = 25;
private static final int HIGH_DPI_STATUS_BAR_HEIGHT = 38;
Inside the onCreate:
DisplayMetrics displayMetrics = new DisplayMetrics();
((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
int statusBarHeight;
switch (displayMetrics.densityDpi) {
case DisplayMetrics.DENSITY_HIGH:
statusBarHeight = HIGH_DPI_STATUS_BAR_HEIGHT;
break;
case DisplayMetrics.DENSITY_MEDIUM:
statusBarHeight = MEDIUM_DPI_STATUS_BAR_HEIGHT;
break;
case DisplayMetrics.DENSITY_LOW:
statusBarHeight = LOW_DPI_STATUS_BAR_HEIGHT;
break;
default:
statusBarHeight = MEDIUM_DPI_STATUS_BAR_HEIGHT;
}
See:
http://developer.android.com/reference/android/util/DisplayMetrics.html http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
This is what I put as a menu option where I made a button on a JFrame
to display another JFrame
. I wanted only the new frame to be visible, and not to destroy the one behind it. I initially hid the first JFrame
, while the new one became visible. Upon closing of the new JFrame
, I disposed of it followed by an action of making the old one visible again.
Note: The following code expands off of Ravinda's answer and ng
is a JButton
:
ng.addActionListener((ActionEvent e) -> {
setVisible(false);
JFrame j = new JFrame("NAME");
j.setVisible(true);
j.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
setVisible(true);
}
});
});
Using style:
<style type="text/css">
.hidden {
display: none;
{
.visible {
display: block;
}
</style>
Using an event handler in JavaScript is better than the onclick=""
attribute in HTML:
<button id="RenderPortfolio_Btn">View Portfolio</button>
<button id="RenderResults_Btn">View Results</button>
<div class="visible" id="portfolio">
<span>div1</span>
</div>
<div class"hidden" id="results">
<span>div2</span>
</div>
JavaScript:
<script type="text/javascript">
var portfolioDiv = document.getElementById('portfolio');
var resultsDiv = document.getElementById('results');
var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
var resultsBtn = document.getElementById('RenderResults_Btn');
portfolioBtn.onclick = function() {
resultsDiv.setAttribute('class', 'hidden');
portfolioDiv.setAttribute('class', 'visible');
};
resultsBtn.onclick = function() {
portfolioDiv.setAttribute('class', 'hidden');
resultsDiv.setAttribute('class', 'visible');
};
</script>
jQuery may help you to manipulate DOM elements easy!
In my case, the file ~/.curlrc had a wrong proxy configured.
using System;
using System.Data;
using System.Data.SqlClient;
namespace SqlCommend
{
class sqlcreateapp
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
conn.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Table Created Successfully...");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
Try the following simple function:
function _flatten_array($arr) {
while ($arr) {
list($key, $value) = each($arr);
is_array($value) ? $arr = $value : $out[$key] = $value;
unset($arr[$key]);
}
return (array)$out;
}
So from this:
array (
'und' =>
array (
'profiles' =>
array (
0 =>
array (
'commerce_customer_address' =>
array (
'und' =>
array (
0 =>
array (
'first_name' => 'First name',
'last_name' => 'Last name',
'thoroughfare' => 'Address 1',
'premise' => 'Address 2',
'locality' => 'Town/City',
'administrative_area' => 'County',
'postal_code' => 'Postcode',
),
),
),
),
),
),
)
you get:
array (
'first_name' => 'First name',
'last_name' => 'Last name',
'thoroughfare' => 'Address 1',
'premise' => 'Address 2',
'locality' => 'Town/City',
'administrative_area' => 'County',
'postal_code' => 'Postcode',
)
here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.
$('html').click(function(e){
if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
// clicked menu content or children
} else {
// didnt click menu content
}
});
my actual code:
$('html').click(function(e){
if (e.target.id != 'datepicker'
&& $(e.target).parents('#datepicker').length == 0
&& !$(e.target).hasClass('datepicker')
) {
$('#datepicker').remove();
}
});
make your hint at final position in your string array like this City is the hint here
array_city = new String[]{"Irbed", "Amman", "City"};
and then in your array adapter
ArrayAdapter<String> adapter_city = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array_city) {
@Override
public int getCount() {
// to show hint "Select Gender" and don't able to select
return array_city.length-1;
}
};
so the adapter return just first two item and finally in onCreate() method or what ,,, make Spinner select the hint
yourSpinner.setSelection(array_city.length - 1);
NOTE: Potentially outdated. ECMAScript 2017 includes
String.prototype.padStart
.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the -
and read it.
While the previous answers are correct, some compilers have options to break the standard and use the smallest type that will contain all values.
Example with GCC (documentation in the GCC Manual):
enum ord {
FIRST = 1,
SECOND,
THIRD
} __attribute__ ((__packed__));
STATIC_ASSERT( sizeof(enum ord) == 1 )
If you only care about the elements of @Array
, use:
for my $el (@Array) {
# ...
}
or
If the indices matter, use:
for my $i (0 .. $#Array) {
# ...
}
Or, as of perl
5.12.1, you can use:
while (my ($i, $el) = each @Array) {
# ...
}
If you need both the element and its index in the body of the loop, I would expect using each
to be the fastest, but then you'll be giving up compatibility with pre-5.12.1 perl
s.
Some other pattern than these might be appropriate under certain circumstances.
If you want to use Eloquent, you also can use this
This is just sample code from my project
/*
* Saving Question
*/
$question = new Question;
$questionCategory = new QuestionCategory;
/*
* Insert new record for question
*/
$question->title = $title;
$question->user_id = Auth::user()->user_id;
$question->description = $description;
$question->time_post = date('Y-m-d H:i:s');
if(Input::has('expiredtime'))
$question->expired_time = Input::get('expiredtime');
$questionCategory->category_id = $category;
$questionCategory->time_added = date('Y-m-d H:i:s');
DB::transaction(function() use ($question, $questionCategory) {
$question->save();
/*
* insert new record for question category
*/
$questionCategory->question_id = $question->id;
$questionCategory->save();
});
Assuming that your docker container is up and running, you can run commands as:
docker exec mycontainer /bin/sh -c "cmd1;cmd2;...;cmdn"
SUM
is an aggregate function. It will calculate the total for each group. +
is used for calculating two or more columns in a row.
Consider this example,
ID VALUE1 VALUE2
===================
1 1 2
1 2 2
2 3 4
2 4 5
SELECT ID, SUM(VALUE1), SUM(VALUE2)
FROM tableName
GROUP BY ID
will result
ID, SUM(VALUE1), SUM(VALUE2)
1 3 4
2 7 9
SELECT ID, VALUE1 + VALUE2
FROM TableName
will result
ID, VALUE1 + VALUE2
1 3
1 4
2 7
2 9
SELECT ID, SUM(VALUE1 + VALUE2)
FROM tableName
GROUP BY ID
will result
ID, SUM(VALUE1 + VALUE2)
1 7
2 16
Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.
To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source
Add a file to your repository like this:
mvn install:install-file \
-Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID
-DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
-Dpackaging=jar \
-DlocalRepositoryPath=/var/www/html/mavenRepository
If your domain is example.com
and the root directory of the web server is located at /var/www/html/
, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>
.
If you're using web components, then they have this as an example:
map.addEventListener('google-map-ready', function(e) {
alert('Map loaded!');
});
As others have stated, you have to dereference the reference. The keys
function requires that its argument starts with a %:
My preference:
foreach my $key (keys %{$ad_grp_ref}) {
According to Conway:
foreach my $key (keys %{ $ad_grp_ref }) {
Guess who you should listen to...
You might want to read through the Perl Reference Documentation.
If you find yourself doing a lot of stuff with references to hashes and hashes of lists and lists of hashes, you might want to start thinking about using Object Oriented Perl. There's a lot of nice little tutorials in the Perl documentation.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem()
function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type
on the buttons back to submit
and handling the event server-side - this is known as unobtrusive JavaScript.
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
oracleserviceorcl
service. (From services in Task Manager)ORACLE_SID
variable with orcl
value. (In environment variables)Try adding this in your vhost config:
RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
Though nearly the same as most of the other responses, I think this is the most efficient and concise way to implement it. Using TryGetValue is faster than using ContainsKey and reindexing into the dictionary as some other solutions have shown.
void Add(string key, string val)
{
List<string> list;
if (!dictionary.TryGetValue(someKey, out list))
{
values = new List<string>();
dictionary.Add(key, list);
}
list.Add(val);
}
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
In Python, strings are immutable, so you can't change their characters in-place.
You can, however, do the following:
for i in str:
srr += i
The reasons this works is that it's a shortcut for:
for i in str:
srr = srr + i
The above creates a new string with each iteration, and stores the reference to that new string in srr
.
Here's a 2020, Reactjs Hook example that I thought could help others. I am using it to add new rows to a Reactjs table. Let me know if I could improve on something.
Adding a new element to a functional state component:
Define the state data:
const [data, setData] = useState([
{ id: 1, name: 'John', age: 16 },
{ id: 2, name: 'Jane', age: 22 },
{ id: 3, name: 'Josh', age: 21 }
]);
Have a button trigger a function to add a new element
<Button
// pass the current state data to the handleAdd function so we can append to it.
onClick={() => handleAdd(data)}>
Add a row
</Button>
function handleAdd(currentData) {
// return last data array element
let lastDataObject = currentTableData[currentTableData.length - 1]
// assign last elements ID to a variable.
let lastID = Object.values(lastDataObject)[0]
// build a new element with a new ID based off the last element in the array
let newDataElement = {
id: lastID + 1,
name: 'Jill',
age: 55,
}
// build a new state object
const newStateData = [...currentData, newDataElement ]
// update the state
setData(newStateData);
// print newly updated state
for (const element of newStateData) {
console.log('New Data: ' + Object.values(element).join(', '))
}
}