If you're not completely attached to using "from" and "to" as your option names, it's fairly easy to implement this using getopts:
while getopts f:t: opts; do
case ${opts} in
f) FROM_VAL=${OPTARG} ;;
t) TO_VAL=${OPTARG} ;;
esac
done
getopts
is a program that processes command line arguments and conveniently parses them for you.
f:t:
specifies that you're expecting 2 parameters that contain values (indicated by the colon). Something like f:t:v
says that -v
will only be interpreted as a flag.
opts
is where the current parameter is stored. The case
statement is where you will process this.
${OPTARG}
contains the value following the parameter. ${FROM_VAL}
for example will get the value /home/kristoffer/test.png
if you ran your script like:
ocrscript.sh -f /home/kristoffer/test.png -t /home/kristoffer/test.txt
As the others are suggesting, if this is your first time writing bash scripts you should really read up on some basics. This was just a quick tutorial on how getopts
works.
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
Using scanf
removing any blank spaces before the string is typed and limiting the amount of characters to be read:
#define SIZE 100
....
char str[SIZE];
scanf(" %99[^\n]", str);
/* Or even you can do it like this */
scanf(" %99[a-zA-Z0-9 ]", str);
If you do not limit the amount of characters to be read with scanf
it can be as dangerous as gets
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
Use the native pathname
property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href")
can return values like ../..
which would not give you the correct result.
If you need to keep the search
and hash
(e.g. foo?bar#baz
from http://quux.com/path/to/foo?bar#baz
) use this:
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.
Another approach using regex:
''.join(re.split(r'[.;!?,]', s))
Your select
doesn't have an ID, only a name. You'll need to modify your selector:
$("#pizza").on("click", function(){
$("select[name='pizza_kind']").prop("disabled", !this.checked);
});
And here is a simple Send-MailMessage
example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
The he library is the only 100% reliable solution that I know of!
He is written by Mathias Bynens - one of the world's most renowned JavaScript gurus - and has the following features :
he.encode('foo © bar ? baz qux');
// Output : 'foo © bar ≠ baz 𝌆 qux'
he.decode('foo © bar ≠ baz 𝌆 qux');
// Output : 'foo © bar ? baz qux'
Please make it an immutable type! The value of a fraction doesn't change - a half doesn't become a third, for example. Instead of setDenominator, you could have withDenominator which returns a new fraction which has the same numerator but the specified denominator.
Life is much easier with immutable types.
Overriding equals and hashcode would be sensible too, so it can be used in maps and sets. Outlaw Programmer's points about arithmetic operators and string formatting are good too.
As a general guide, have a look at BigInteger and BigDecimal. They're not doing the same thing, but they're similar enough to give you good ideas.
In many cases,
display:inline;
is enough.
But in some cases, you have to add following:
clear:none;
you can use redis-cli INFO keyspace
localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0
Mail::send('emails.activation', $data, function($message){
$message->from('email@from', 'name');
$message->to($email)->subject($subject);
});
I dont know why, but in my case I put the from's information in the function and it's work fine.
If you're in local machine then use this command
/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
For remote machine, use below one
/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;
Open Applicaction -> Accessories -> Terminal
Type commandline as below...
sudo apt-get install openjdk-7-jdk
Type commandline as below...
apt-cache search jdk
(Note: openjdk-7-jdk is symbolically used here. You can choose the JDK version as per your requirement.)
For "JAVA_HOME" (Environment Variable) type command as shown below, in "Terminal" using your installation path...
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk
(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)
For "PATH" (Environment Variable) type command as shown below, in "Terminal" using your installation path...
export PATH=$PATH:/usr/lib/jvm/java-7-openjdk/bin
(Note: "/usr/lib/jvm/java-7-openjdk" is symbolically used here just for demostration. You should use your path as per your installation.)
Check for "open jdk" installation, just type command in "Terminal" as shown below
javac -version
Once you've done this
group p by p.SomeId into pg
you no longer have access to the range variables used in the initial from
. That is, you can no longer talk about p
or bp
, you can only talk about pg
.
Now, pg
is a group and so contains more than one product. All the products in a given pg
group have the same SomeId
(since that's what you grouped by), but I don't know if that means they all have the same BaseProductId
.
To get a base product name, you have to pick a particular product in the pg
group (As you are doing with SomeId
and CountryCode
), and then join to BaseProducts
.
var result = from p in Products
group p by p.SomeId into pg
// join *after* group
join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id
select new ProductPriceMinMax {
SomeId = pg.FirstOrDefault().SomeId,
CountryCode = pg.FirstOrDefault().CountryCode,
MinPrice = pg.Min(m => m.Price),
MaxPrice = pg.Max(m => m.Price),
BaseProductName = bp.Name // now there is a 'bp' in scope
};
That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.
The 502 error appears because nginx cannot hand off to php5-cgi. You can try reconfiguring php5-cgi to use unix sockets as opposed to tcp .. then adjust the server config to point to the socket instead of the tcp ...
ps auxww | grep php5-cgi #-- is the process running?
netstat -an | grep 9000 # is the port open?
I had the same problem. my problem was that the version of the dependency had conflict with the elasticsearch version. check the version in ip:9200 and use the dependency version that match it
I'd suggest looking at the source to something like lighthttpd.
Write if " " in word:
instead of if " " in word == True:
.
Explanation:
a < b < c
is equivalent to (a < b) and (b < c)
.in
!' ' in w == True
is equivalent to (' ' in w) and (w == True)
which is not what you want.Standard UITableViewCell already contains UIImageView that appears to the left to all your labels if its image is set. You can access it using imageView property:
cell.imageView.image = someImage;
If for some reason standard behavior does not suit your needs (note that you can customize properties of that standard image view) then you can add your own UIImageView to the cell as Aman suggested in his answer. But in that approach you'll have to manage cell's layout yourself (e.g. make sure that cell labels do not overlap image). And do not add subviews to the cell directly - add them to cell's contentView:
// DO NOT!
[cell addSubview:imv];
// DO:
[cell.contentView addSubview:imv];
The date difference conversion could be handled in a better way using Java built-in class, TimeUnit. It provides utility methods to do that:
Date startDate = // Set start date
Date endDate = // Set end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
As Yanflea mentioned, there is a way to go around this.
In Maven 3.5.0 you can use the following way of transferring the version down from the parent project:
<project ...>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mydomain</groupId>
<artifactId>myprojectparent</artifactId>
<packaging>pom</packaging>
<version>${myversion}</version>
<name>MyProjectParent</name>
<properties>
<myversion>0.1-SNAPSHOT</myversion>
</properties>
<modules>
<module>modulefolder</module>
</modules>
...
</project>
<project ...>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mydomain</groupId>
<artifactId>myprojectmodule</artifactId>
<version>${myversion}</version> <!-- This still needs to be set, but you can use properties from parent -->
</parent>
<groupId>se.car_o_liner</groupId>
<artifactId>vinno</artifactId>
<packaging>war</packaging>
<name>Vinno</name>
<!-- Note that there's no version specified; it's inherited from parent -->
...
</project>
You are free to change myversion
to whatever you want that isn't a reserved property.
EDIT: As @Jukka K. Korpela correctly points out, RFC 1738 was updated by RFC 3986. This has expanded and clarified the characters valid for host, unfortunately it's not easily copied and pasted, but I'll do my best.
In first matched order:
host = IP-literal / IPv4address / reg-name
IP-literal = "[" ( IPv6address / IPvFuture ) "]"
IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
IPv6address = 6( h16 ":" ) ls32
/ "::" 5( h16 ":" ) ls32
/ [ h16 ] "::" 4( h16 ":" ) ls32
/ [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
/ [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
/ [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
/ [ *4( h16 ":" ) h16 ] "::" ls32
/ [ *5( h16 ":" ) h16 ] "::" h16
/ [ *6( h16 ":" ) h16 ] "::"
ls32 = ( h16 ":" h16 ) / IPv4address
; least-significant 32 bits of address
h16 = 1*4HEXDIG
; 16 bits of address represented in hexadecimal
IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
dec-octet = DIGIT ; 0-9
/ %x31-39 DIGIT ; 10-99
/ "1" 2DIGIT ; 100-199
/ "2" %x30-34 DIGIT ; 200-249
/ "25" %x30-35 ; 250-255
reg-name = *( unreserved / pct-encoded / sub-delims )
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" <---This seems like a practical shortcut, most closely resembling original answer
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
pct-encoded = "%" HEXDIG HEXDIG
Original answer from RFC 1738 specification:
Thus, only alphanumerics, the special characters "
$-_.+!*'(),
", and reserved characters used for their reserved purposes may be used unencoded within a URL.
^ obsolete since 1998.
Each browser provides a default stylesheet, called the user agent stylesheet, in case an HTML file does not specify one. Styles that you specify override the defaults.
Because you have not specified values for the table element’s box, the default styles have been applied.
It's relative to default browser font-size unless you override it with a value in pt or px.
I've a directory with a bunch of files. I want to find all the files that DO NOT contain the string "speedup" so I successfully used the following command:
grep -iL speedup *
You can use iconselect.js; Icon/image select (combobox, dropdown)
Demo and download; http://bug7a.github.io/iconselect.js/
HTML usage;
<div id="my-icon-select"></div>
Javascript usage;
var iconSelect;
window.onload = function(){
iconSelect = new IconSelect("my-icon-select");
var icons = [];
icons.push({'iconFilePath':'images/icons/1.png', 'iconValue':'1'});
icons.push({'iconFilePath':'images/icons/2.png', 'iconValue':'2'});
icons.push({'iconFilePath':'images/icons/3.png', 'iconValue':'3'});
iconSelect.refresh(icons);
};
As of TypeScript 0.9 the lib.d.ts
file uses specialized overload signatures that return the correct types for calls to getElementsByTagName
.
This means you no longer need to use type assertions to change the type:
// No type assertions needed
var script: HTMLScriptElement = document.getElementsByTagName('script')[0];
alert(script.type);
TLDR for Python 3:
import subprocess
import sys
with open('test.log', 'wb') as f:
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
for c in iter(lambda: process.stdout.read(1), b''):
sys.stdout.buffer.write(c)
f.buffer.write(c)
You have two ways of doing this, either by creating an iterator from the read
or readline
functions and do:
import subprocess
import sys
with open('test.log', 'w') as f: # replace 'w' with 'wb' for Python 3
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
for c in iter(lambda: process.stdout.read(1), ''): # replace '' with b'' for Python 3
sys.stdout.write(c)
f.write(c)
or
import subprocess
import sys
with open('test.log', 'w') as f: # replace 'w' with 'wb' for Python 3
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
for line in iter(process.stdout.readline, ''): # replace '' with b'' for Python 3
sys.stdout.write(line)
f.write(line)
Or you can create a reader
and a writer
file. Pass the writer
to the Popen
and read from the reader
import io
import time
import subprocess
import sys
filename = 'test.log'
with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader:
process = subprocess.Popen(command, stdout=writer)
while process.poll() is None:
sys.stdout.write(reader.read())
time.sleep(0.5)
# Read the remaining
sys.stdout.write(reader.read())
This way you will have the data written in the test.log
as well as on the standard output.
The only advantage of the file approach is that your code doesn't block. So you can do whatever you want in the meantime and read whenever you want from the reader
in a non-blocking way. When you use PIPE
, read
and readline
functions will block until either one character is written to the pipe or a line is written to the pipe respectively.
"But the thing is I also want to be able to add textboxes etc in this popup window thru the form designer."
It's unclear from your description at what stage in the development process you're in. If you haven't already figured it out, to create a new Form you click on Project --> Add Windows Form, then type in a name for the form and hit the "Add" button. Now you can add controls to your form as you'd expect.
When it comes time to display it, follow the advice of the other posts to create an instance and call Show() or ShowDialog() as appropriate.
There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):
public ListNode Reverse(ListNode list)
{
if (list == null) return null; // first question
if (list.next == null) return list; // second question
// third question - in Lisp this is easy, but we don't have cons
// so we grab the second element (which will be the last after we reverse it)
ListNode secondElem = list.next;
// bug fix - need to unlink list from the rest or you will get a cycle
list.next = null;
// then we reverse everything from the second element on
ListNode reverseRest = Reverse(secondElem);
// then we join the two lists
secondElem.next = list;
return reverseRest;
}
I have jus implement this library:https://github.com/jose78/go-collection. This is an example about how to use the Foreach loop:
package main
import (
"fmt"
col "github.com/jose78/go-collection/collections"
)
type user struct {
name string
age int
id int
}
func main() {
newList := col.ListType{user{"Alvaro", 6, 1}, user{"Sofia", 3, 2}}
newList = append(newList, user{"Mon", 0, 3})
newList.Foreach(simpleLoop)
if err := newList.Foreach(simpleLoopWithError); err != nil{
fmt.Printf("This error >>> %v <<< was produced", err )
}
}
var simpleLoop col.FnForeachList = func(mapper interface{}, index int) {
fmt.Printf("%d.- item:%v\n", index, mapper)
}
var simpleLoopWithError col.FnForeachList = func(mapper interface{}, index int) {
if index > 1{
panic(fmt.Sprintf("Error produced with index == %d\n", index))
}
fmt.Printf("%d.- item:%v\n", index, mapper)
}
The result of this execution should be:
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
2.- item:{Mon 0 3}
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
Recovered in f Error produced with index == 2
ERROR: Error produced with index == 2
This error >>> Error produced with index == 2
<<< was produced
The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.
That's what content negotiation is for.
<img>
element.<style>
element.<script>
element.<object>
and embed
elements.<audio>
element.Why should it specify one for the <video>
element?
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
Assuming that you do not have the log file from the expdp job that generated the file in the first place, the easiest option would probably be to use the SQLFILE parameter to have impdp generate a file of DDL (based on a full import). Then you can grab the schema names from that file. Not ideal, of course, since impdp has to read the entire dump file to extract the DDL and then again to get to the schema you're interested in, and you have to do a bit of text file searching for the various CREATE USER statements, but it should be doable.
VB.NET
MyList.OrderBy(Function(f) f.StartDate).ThenByDescending(Function(f) f.EndDate)
OR
From l In MyList Order By l.StartDate Ascending, l.EndDate Descending
putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.
Syntax: intent.putExtra("key", value);
Eg: intent.putExtra("full_name", "Vishnu Sivan");
Intent intent=getIntent()
: It gets the Intent from the previous activity.
fullname = intent.getStringExtra(“full_name”)
: This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.
Sample Code:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);
You can use UNION in this case
select id, name, games, goals from tblMadrid
union
select id, name, games, goals from tblBarcelona
you jsut have to maintain order of selected columns ie id, name, games, goals in both SQLs
FWIW with Ansible 2.2 one can use include_role:
playbook test.yml
:
- name: test
hosts:
- 127.0.0.1
connection: local
tasks:
- include_role:
name: test
tasks_from: other
then in roles/test/tasks/other.yml
:
- name: say something else
shell: echo "I'm the other guy"
And invoke the playbook with: ansible-playbook test.yml
to get:
TASK [test : say something else] *************
changed: [127.0.0.1]
Use this
data: '{"username":"' + username + '"}',
I try a lot of syntax to work with laravel it work for me for laravel 4.2 + ajax.
You can repaint and / or requery:
On the close event of form B:
Forms!FormA.Requery
Is this what you mean?
You should add these styles to a CSS sheet
div .no-padding {
padding:0;
}
button .full-width{
width:100%;
//display:block; //only if you're having issues
}
Then change add the classes to your code
<div class="span9 btn-block no-padding">
<button class="btn btn-large btn-block btn-primary full-width" type="button">Block level button</button>
</div>
I haven't tested this and I'm not 100% sure what you want, but I think this will get you close.
Variable names should be known at compile time. If you intend to populate those names dynamically at runtime you could use a List<T>
var variables = List<Variable>();
variables.Add(new Variable { Name = inputStr1 });
variables.Add(new Variable { Name = inputStr2 });
here input string maybe any text or any list
Besides the Stanford lib that tylerl mentioned. I found jsrsasign very useful (Github repo here:https://github.com/kjur/jsrsasign). I don't know how exactly trustworthy it is, but i've used its API of SHA256, Base64, RSA, x509 etc. and it works pretty well. In fact, it includes the Stanford lib as well.
If all you want to do is SHA256, jsrsasign might be a overkill. But if you have other needs in the related area, I feel it's a good fit.
Hope this will help.
input[readonly="readonly"]
{
background-color:blue;
}
reference:
The only solution worked for me is add maven-compiler-plugin to the pom.xml
<project ...>
...
<build>
...
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<fork>true</fork>
<executable>C:\Program Files\Java\jdk1.7.0_79\bin\javac</executable>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
Just to add to yamen's answer, which is perfect for images but not so much for text.
If you are trying to use this to scale text, like say a Word document (which is in this case in bytes from Word Interop), you will need to make a few modifications or you will get giant bars on the side.
May not be perfect but works for me!
using (MemoryStream ms = new MemoryStream(wordBytes))
{
float width = 3840;
float height = 2160;
var brush = new SolidBrush(Color.White);
var rawImage = Image.FromStream(ms);
float scale = Math.Min(width / rawImage.Width, height / rawImage.Height);
var scaleWidth = (int)(rawImage.Width * scale);
var scaleHeight = (int)(rawImage.Height * scale);
var scaledBitmap = new Bitmap(scaleWidth, scaleHeight);
Graphics graph = Graphics.FromImage(scaledBitmap);
graph.InterpolationMode = InterpolationMode.High;
graph.CompositingQuality = CompositingQuality.HighQuality;
graph.SmoothingMode = SmoothingMode.AntiAlias;
graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(rawImage, new Rectangle(0, 0 , scaleWidth, scaleHeight));
scaledBitmap.Save(fileName, ImageFormat.Png);
return scaledBitmap;
}
I use 2 and 4 where applicable (i.e. when I know the content's height or if overflowing doesn't harm). Anywhere else, I go with solution 3. By the way, your first solution has no advantage over 3 (that I can spot) because it isn't any more semantic since it uses the same dummy element.
By the way, I wouldn't be concerned about the fourth solution being a hack. Hacks in CSS would only be harmful if their underlying behaviour is subject to reinterpretation or other change. This way, your hack wouldn't be guaranteed to work. However in this case, your hack relies on the exact behaviour that overflow: auto
is meant to have. No harm in hitching a free ride.
The FolderBrowserDialog
class from System.Windows.Forms
is the recommended way to display a dialog that allows a user to select a folder.
Until recently, the appearance and behaviour of this dialog was not in keeping with the other filesystem dialogs, which is one of the reasons why people were reluctant to use it.
The good news is that FolderBrowserDialog
was "modernized" in NET Core 3.0, so is now a viable option for those writing either Windows Forms or WPF apps targeting that version or later.
In .NET Core 3.0, Windows Forms users [sic] a newer COM-based control that was introduced in Windows Vista:
To reference System.Windows.Forms
in a NET Core WPF app, it is necessary to edit the project file and add the following line:
<UseWindowsForms>true</UseWindowsForms>
This can be placed directly after the existing <UseWPF>
element.
Then it's just a case of using the dialog:
using System;
using System.Windows.Forms;
...
using var dialog = new FolderBrowserDialog
{
Description = "Time to select a folder",
UseDescriptionForTitle = true,
SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
+ Path.DirectorySeparatorChar,
ShowNewFolderButton = true
};
if (dialog.ShowDialog() == DialogResult.OK)
{
...
}
FolderBrowserDialog
has a RootFolder
property that supposedly "sets the root folder where the browsing starts from" but whatever I set this to it didn't make any difference; SelectedPath
seemed to be the better property to use for this purpose, however the trailing backslash is required.
Also, the ShowNewFolderButton
property seems to be ignored as well, the button is always shown regardless.
Also it may cause some warnigs in logs like a Cglib2AopProxy Unable to proxy method. And many other reasons for this are described here Why always have single implementaion interfaces in service and dao layers?
$('li[rel=7]').siblings().andSelf();
// or:
$('li[rel=7]').parent().children();
Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:
var rels = [];
$('ul').each(function() {
var localRels = [];
$(this).find('li').each(function(){
localRels.push( $(this).attr('rel') );
});
rels.push(localRels);
});
Try:
window.location.reload(true);
The parameter set to 'true' reloads a fresh copy from the server. Leaving it out will serve the page from cache.
More information can be found at MSDN and in the Mozilla documentation.
In the following line.
temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();
You are calling First but the collection returned from db.Responses.Where is empty.
In my case, I forgot (' or ") at the end of string. E.g 'ABC' or "ABC"
On iOS 3.0 and later you should use the MFMailComposeViewController
class, and the MFMailComposeViewControllerDelegate
protocol, that is tucked away in the MessageUI framework.
First add the framework and import:
#import <MessageUI/MFMailComposeViewController.h>
Then, to send a message:
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"My Subject"];
[controller setMessageBody:@"Hello there." isHTML:NO];
if (controller) [self presentModalViewController:controller animated:YES];
[controller release];
Then the user does the work and you get the delegate callback in time:
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
Remember to check if the device is configured for sending email:
if ([MFMailComposeViewController canSendMail]) {
// Show the composer
} else {
// Handle the error
}
Starting with .Net 4, you can use a shorthand version without explicitly specifying &:
if(Letters.AB.HasFlag(Letters.C))
as for react-router-dom 4.x.x (https://www.npmjs.com/package/react-router-dom) you can pass params to the component to route to via:
<Route path="/ideas/:value" component ={CreateIdeaView} />
linking via (considering testValue prop is passed to the corresponding component (e.g. the above App component) rendering the link)
<Link to={`/ideas/${ this.props.testValue }`}>Create Idea</Link>
passing props to your component constructor the value param will be available via
props.match.params.value
If the types of your items are all different, here is a class I made to get them more intuitively.
The usage of this class:
var t = TypedTuple.Create("hello", 1, new MyClass());
var s = t.Get<string>();
var i = t.Get<int>();
var c = t.Get<MyClass>();
Source code:
public static class TypedTuple
{
public static TypedTuple<T1> Create<T1>(T1 t1)
{
return new TypedTuple<T1>(t1);
}
public static TypedTuple<T1, T2> Create<T1, T2>(T1 t1, T2 t2)
{
return new TypedTuple<T1, T2>(t1, t2);
}
public static TypedTuple<T1, T2, T3> Create<T1, T2, T3>(T1 t1, T2 t2, T3 t3)
{
return new TypedTuple<T1, T2, T3>(t1, t2, t3);
}
public static TypedTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4)
{
return new TypedTuple<T1, T2, T3, T4>(t1, t2, t3, t4);
}
public static TypedTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)
{
return new TypedTuple<T1, T2, T3, T4, T5>(t1, t2, t3, t4, t5);
}
public static TypedTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6)
{
return new TypedTuple<T1, T2, T3, T4, T5, T6>(t1, t2, t3, t4, t5, t6);
}
public static TypedTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7)
{
return new TypedTuple<T1, T2, T3, T4, T5, T6, T7>(t1, t2, t3, t4, t5, t6, t7);
}
public static TypedTuple<T1, T2, T3, T4, T5, T6, T7, T8> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8)
{
return new TypedTuple<T1, T2, T3, T4, T5, T6, T7, T8>(t1, t2, t3, t4, t5, t6, t7, t8);
}
}
public class TypedTuple<T>
{
protected Dictionary<Type, object> items = new Dictionary<Type, object>();
public TypedTuple(T item1)
{
Item1 = item1;
}
public TSource Get<TSource>()
{
object value;
if (this.items.TryGetValue(typeof(TSource), out value))
{
return (TSource)value;
}
else
return default(TSource);
}
private T item1;
public T Item1 { get { return this.item1; } set { this.item1 = value; this.items[typeof(T)] = value; } }
}
public class TypedTuple<T1, T2> : TypedTuple<T1>
{
public TypedTuple(T1 item1, T2 item2)
: base(item1)
{
Item2 = item2;
}
private T2 item2;
public T2 Item2 { get { return this.item2; } set { this.item2 = value; this.items[typeof(T2)] = value; } }
}
public class TypedTuple<T1, T2, T3> : TypedTuple<T1, T2>
{
public TypedTuple(T1 item1, T2 item2, T3 item3)
: base(item1, item2)
{
Item3 = item3;
}
private T3 item3;
public T3 Item3 { get { return this.item3; } set { this.item3 = value; this.items[typeof(T3)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4> : TypedTuple<T1, T2, T3>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4)
: base(item1, item2, item3)
{
Item4 = item4;
}
private T4 item4;
public T4 Item4 { get { return this.item4; } set { this.item4 = value; this.items[typeof(T4)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5> : TypedTuple<T1, T2, T3, T4>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
: base(item1, item2, item3, item4)
{
Item5 = item5;
}
private T5 item5;
public T5 Item5 { get { return this.item5; } set { this.item5 = value; this.items[typeof(T5)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5, T6> : TypedTuple<T1, T2, T3, T4, T5>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
: base(item1, item2, item3, item4, item5)
{
Item6 = item6;
}
private T6 item6;
public T6 Item6 { get { return this.item6; } set { this.item6 = value; this.items[typeof(T6)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5, T6, T7> : TypedTuple<T1, T2, T3, T4, T5, T6>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
: base(item1, item2, item3, item4, item5, item6)
{
Item7 = item7;
}
private T7 item7;
public T7 Item7 { get { return this.item7; } set { this.item7 = value; this.items[typeof(T7)] = value; } }
}
public class TypedTuple<T1, T2, T3, T4, T5, T6, T7, T8> : TypedTuple<T1, T2, T3, T4, T5, T6, T7>
{
public TypedTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8)
: base(item1, item2, item3, item4, item5, item6, item7)
{
Item8 = item8;
}
private T8 item8;
public T8 Item8 { get { return this.item8; } set { this.item8 = value; this.items[typeof(T8)] = value; } }
}
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55
For an example using both, authentication on application level and HTTP Basic Authentication see one of my previous posts.
There's a solution at CMD: Set buffer height independently of window height effectively employing a powershell command executed from the batch script. This solution let me resize the scrollback buffer in the existing batch script window independently of the window size, exactly what the OP was asking for.
Caveat: It seems to make the script forget variables (or at least it did with my script), so I recommend calling the command only at the beginning and / or end of your script, or otherwise where you don't depend on a session local variable.
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.
a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))
Usually the situation where continue is necessary/useful, is when you want to skip the remaining code in the loop and continue iteration.
I don't really believe it's necessary, since you can always use if statements to provide the same logic, but it might be useful to increase readability of code.
Here a very simple but effective code using cElementTree
.
try:
import cElementTree as ET
except ImportError:
try:
# Python 2.5 need to import a different module
import xml.etree.cElementTree as ET
except ImportError:
exit_err("Failed to import cElementTree from any known place")
def find_in_tree(tree, node):
found = tree.find(node)
if found == None:
print "No %s in file" % node
found = []
return found
# Parse a xml file (specify the path)
def_file = "xml_file_name.xml"
try:
dom = ET.parse(open(def_file, "r"))
root = dom.getroot()
except:
exit_err("Unable to open and parse input definition file: " + def_file)
# Parse to find the child nodes list of node 'myNode'
fwdefs = find_in_tree(root,"myNode")
This is from "python xml parse".
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.
File SongsTableSeeder.php should be in database/seeds directory or in its subdirectory.
You need to run:
composer dump-autoload
and then:
php artisan db:seed
or:
php artisan db:seed --class=SongsTableSeeder
Based on analysis done by Google-Chrome Dev Tools' Lighthouse Audit,
For users on slow connections, external scripts dynamically injected via
document.write()
can delay page load by tens of seconds.
With the new version of React Router (using 2.0.1 now), you can use an asterisk as a path to route all 'other paths'.
So it would look like this:
<Route route="/" component={App}>
<Route path=":area" component={Area}>
<Route path=":city" component={City} />
<Route path=":more-stuff" component={MoreStuff} />
</Route>
<Route path="*" component={NotFoundRoute} />
</Route>
When do you choose functional programming over object oriented?
When you anticipate a different kind of software evolution:
Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.
Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.
When evolution goes the wrong way, you have problems:
Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.
Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.
This problem has been well known for many years; in 1998, Phil Wadler dubbed it the "expression problem". Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.
What are the typical problem definitions where functional programming is a better choice?
Functional languages excel at manipulating symbolic data in tree form. A favorite example is compilers, where source and intermediate languages change seldom (mostly the same things), but compiler writers are always adding new translations and code improvements or optimizations (new operations on things). Compilation and translation more generally are "killer apps" for functional languages.
This will create a delay without putting the thread to sleep or throwing an error on timeout:
let delayExpectation = XCTestExpectation()
delayExpectation.isInverted = true
wait(for: [delayExpectation], timeout: 5)
Because the expectation is inverted, it will timeout quietly.
Add @Injectable to your service as:
export class NameService {
names: Array<string>;
constructor() {
this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
}
getNames() {
return this.names;
}
}
and in your component add the providers as:
@Component({
selector: 'my-app',
providers: [NameService]
})
or if you want to access your service all over the application you can pass in app provider
If you have a directory open in VSCode, and want to search a subdirectory, then either:
files to include
field enter the path with a leading ./
,or
Find in Folder...
option.You know, using a custom deleter isn't the best way to go, as you will have to mention it all over your code.
Instead, as you are allowed to add specializations to namespace-level classes in ::std
as long as custom types are involved and you respect the semantics, do that:
Specialize std::default_delete
:
template <>
struct ::std::default_delete<Bar> {
default_delete() = default;
template <class U>
constexpr default_delete(default_delete<U>) noexcept {}
void operator()(Bar* p) const noexcept { destroy(p); }
};
And maybe also do std::make_unique()
:
template <>
inline ::std::unique_ptr<Bar> ::std::make_unique<Bar>() {
auto p = create();
if (!p)
throw std::runtime_error("Could not `create()` a new `Bar`.");
return { p };
}
You can follow this path as a css solution
img {_x000D_
width:200px;_x000D_
height:200px;_x000D_
position:relative_x000D_
}_x000D_
img:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: inherit;_x000D_
height: inherit;_x000D_
background: #ebebeb url('http://via.placeholder.com/300?text=PlaceHolder') no-repeat center;_x000D_
color: transparent;_x000D_
}
_x000D_
<img src="gdfgd.jpg">
_x000D_
Open your build.gradle file and make sure you have versionCode
and versionName
inside defaultConfig
element. If not, add them. Refer to this link for more details.
If you have a form then the following is also possible:
<form #f="ngForm">
<input name="myfield" type="text" minlenght="3" required ngModel>
<button type="submit" [disabled]="!f.valid">Submit</button>
</form>
Demo here: http://plnkr.co/edit/Xm2dCwqB9p6WygrquUGh?p=preview&open=app%2Fapp.component.ts
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
<style name="AppCompatTheme" parent="@style/Theme.AppCompat.Light">
<item name="android:windowActionBar">false</item>
</style>
Change this to NoActionBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
This one worked for me
Fetch API, need to deal with two promises to get the response data in JSON Object property. While axios result into JSON object.
Also error handling is different in fetch, as it does not handle server side error in the catch block, the Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. While in axios you can catch all error in catch block.
I will say better to use axios, straightforward to handle interceptors, headers config, set cookies and error handling.
You can also use JSONObject class from json.org to this will convert your HashMap to JSON string which is well formatted
Example:
Map<String,Object> map = new HashMap<>();
map.put("myNumber", 100);
map.put("myString", "String");
JSONObject json= new JSONObject(map);
String result= json.toString();
System.out.print(result);
result:
{'myNumber':100, 'myString':'String'}
Your can also get key from it like
System.out.print(json.get("myNumber"));
result:
100
First of all, REST is not a religion and should not be approached as such. While there are advantages to RESTful services, you should only follow the tenets of REST as far as they make sense for your application.
That said, authentication and client side state do not violate REST principles. While REST requires that state transitions be stateless, this is referring to the server itself. At the heart, all of REST is about documents. The idea behind statelessness is that the SERVER is stateless, not the clients. Any client issuing an identical request (same headers, cookies, URI, etc) should be taken to the same place in the application. If the website stored the current location of the user and managed navigation by updating this server side navigation variable, then REST would be violated. Another client with identical request information would be taken to a different location depending on the server-side state.
Google's web services are a fantastic example of a RESTful system. They require an authentication header with the user's authentication key to be passed upon every request. This does violate REST principles slightly, because the server is tracking the state of the authentication key. The state of this key must be maintained and it has some sort of expiration date/time after which it no longer grants access. However, as I mentioned at the top of my post, sacrifices must be made to allow an application to actually work. That said, authentication tokens must be stored in a way that allows all possible clients to continue granting access during their valid times. If one server is managing the state of the authentication key to the point that another load balanced server cannot take over fulfilling requests based on that key, you have started to really violate the principles of REST. Google's services ensure that, at any time, you can take an authentication token you were using on your phone against load balance server A and hit load balance server B from your desktop and still have access to the system and be directed to the same resources if the requests were identical.
What it all boils down to is that you need to make sure your authentication tokens are validated against a backing store of some sort (database, cache, whatever) to ensure that you preserve as many of the REST properties as possible.
I hope all of that made sense. You should also check out the Constraints section of the wikipedia article on Representational State Transfer if you haven't already. It is particularly enlightening with regard to what the tenets of REST are actually arguing for and why.
Why not just use a library routine wcstombs
.
Try this function
function fieldsValidations(element) {
var isFilled = true;
var fields = $("#"+element)
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
isFilled = false;
return false;
}
});
return isFilled;
}
And use it as
$("#submit").click(function () {
if(fieldsValidations('initiate')){
$("#submit").html("<i class=\"fas fa-circle-notch fa-spin\"></i>");
}
});
Enjoy :)
\p{L}
matches a single code point in the category "letter".
\p{N}
matches any kind of numeric character in any script.
Source: regular-expressions.info
If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.
If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test
rather than the default unittest
module.
Consider these two examples, which do the same thing:
Example 1 (unittest):
import unittest
class LearningCase(unittest.TestCase):
def test_starting_out(self):
self.assertEqual(1, 1)
def main():
unittest.main()
if __name__ == "__main__":
main()
Example 2 (pytest):
def test_starting_out():
assert 1 == 1
Assuming that both files are named test_unittesting.py
, how do we run the tests?
Example 1 (unittest):
cd /path/to/dir/
python test_unittesting.py
Example 2 (pytest):
cd /path/to/dir/
py.test
A more direct way would be:
myvar=$(mysql mydatabase -u $user -p$password -se "SELECT a, b, c FROM table_a")
If you want to escape from Form Freeze and use editing (like text for a button) use this code
Form form = new Form();
Form.Button.Text = "randomText";
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.Run(form);
this is a follow up on the patricus [answer][1] above but for nested arrays:
$topLevelFields = ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];
return $onlineShoppers->map(function ($user) {
return collect($user)->only($topLevelFields)
->merge(collect($user['user'])->only($userFields))->all();
})->all();
Note: I am not sure this will be of any help to you, but you never know.
I found this link:http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html
ENJOY :-)
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
you can use instead of click :
$('#whatever').on('touchstart click', function(){ /* do something... */ });
'nunique' is an option for .agg() since pandas 0.20.0, so:
df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})
The constructor String(byte[] bytes)
takes the bytes from the buffer and encodes them to characters.
It uses the platform default charset to encode bytes to characters. If you know, your file contains text, that is encoded in a different charset, you can use the String(byte[] bytes, String charsetName)
to use the correct encoding (from bytes to characters).
I've had this same problem, and I wrote a one-liner in shell to do it.
rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*
I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:
#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
-Dexpression=settings.localRepository \
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
--batch-mode \
| grep -vF '[INFO]')
rm -rf $REPOSITORY/*
Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.
It's a bit wieldy, but it's a decent way of doing business, IMO.
with this globals variables idea, I saved MainActivity instance in onCreate(); Android global variable
public class ApplicationController extends Application {
public static MainActivity this_MainActivity;
}
and Open dialog like this. it worked.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Global Var
globals = (ApplicationController) this.getApplication();
globals.this_MainActivity = this;
}
and in a thread, I open dialog like this.
AlertDialog.Builder alert = new AlertDialog.Builder(globals.this_MainActivity);
: )
In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".
You can write the query as below:
SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';
it will solve your problem.
In .Net Core You can use
return new ForbidResult();
instead of
return Unauthorized();
which has the advantage to redirecting to the default unauthorized page (Account/AccessDenied) rather than giving a straight 401
to change the default location modify your startup.cs
services.AddAuthentication(options =>...)
.AddOpenIdConnect(options =>...)
.AddCookie(options =>
{
options.AccessDeniedPath = "/path/unauthorized";
})
I've solved this problem by changing charset in js-files from UTF-8 without BOM to simple UTF-8 in Notepad++
The web page developer guessed wrong about which encoding is used by the viewer's browser. This can usually be solved by specifying an encoding in the page's header.
How do I emulate the ISNULL() functionality ?
SELECT (Field IS NULL) FROM ...
From http://php.quicoto.com/inline-ifelse-statement-ngclick-angularjs/, this is how you do it, if you really have to:
ng-click="variable = (condition=='X' ? 'Y' : 'X')"
The built-in module querystring
is what you're looking for:
var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'
Prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:
<?php
$dbh = new PDO("mysql:$connstr", $user, $password);
$dbh -> exec("set names utf8");
?>
Points to keep in mind:
Pointers can be NULL
, references cannot be NULL
.
References are easier to use, const
can be used for a reference when we don't want to change value and just need a reference in a function.
Pointer used with a *
while references used with a &
.
Use pointers when pointer arithmetic operation are required.
You can have pointers to a void type int a=5; void *p = &a;
but cannot have a reference to a void type.
Pointer Vs Reference
void fun(int *a)
{
cout<<a<<'\n'; // address of a = 0x7fff79f83eac
cout<<*a<<'\n'; // value at a = 5
cout<<a+1<<'\n'; // address of a increment by 4 bytes(int) = 0x7fff79f83eb0
cout<<*(a+1)<<'\n'; // value here is by default = 0
}
void fun(int &a)
{
cout<<a<<'\n'; // reference of original a passed a = 5
}
int a=5;
fun(&a);
fun(a);
Verdict when to use what
Pointer: For array, linklist, tree implementations and pointer arithmetic.
Reference: In function parameters and return types.
To rename a table in SQL Server, use the sp_rename
command:
exec sp_rename 'schema.old_table_name', 'new_table_name'
You don't need to assign names
to list
or []
or anything else until you wish to use it.
It's neater to use a list comprehension to make the list of names.
shuffle
modifies the list you pass to it. It always returns None
If you are using a context manager (with ...
) you don't need to close the file explicitly
from random import shuffle
with open('names') as f:
names = [name.rstrip() for name in f if not name.isspace()]
shuffle(names)
assert len(names) > 100
You want to init an array of ints in your constructor? Point it to a static array.
class C
{
public:
int *cArray;
};
C::C {
static int c_init[]{1,2,3};
cArray = c_init;
}
You can try something like this. Here on click of image button I toggle the imageview.
holder.imgitem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(!onclick){
mSparseBooleanArray.put((Integer) view.getTag(), true);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
onclick=true;}
else if(onclick)
{
mSparseBooleanArray.put((Integer) view.getTag(), false);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);
onclick=false;
}
}
});
function remove_script_tags($html){
$dom = new DOMDocument();
$dom->loadHTML($html);
$script = $dom->getElementsByTagName('script');
$remove = [];
foreach($script as $item){
$remove[] = $item;
}
foreach ($remove as $item){
$item->parentNode->removeChild($item);
}
$html = $dom->saveHTML();
$html = preg_replace('/<!DOCTYPE.*?<html>.*?<body><p>/ims', '', $html);
$html = str_replace('</p></body></html>', '', $html);
return $html;
}
Dejan's answer was good, but saveHTML() adds unnecessary doctype and body tags, this should get rid of it. See https://3v4l.org/82FNP
Just as an update to @Patricia's comment in the accepted answer and @Fraser's comment for the original question, if you have access to CMake 3.11+ you can make use of CMake's FetchContent function.
CMake's FetchContent page uses googletest as an example!
I've provided a small modification of the accepted answer:
cmake_minimum_required(VERSION 3.11)
project(basic_test)
set(GTEST_VERSION 1.6.0 CACHE STRING "Google test version")
################################
# GTest
################################
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-${GTEST_VERSION})
FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
FetchContent_Populate(googletest)
add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
endif()
enable_testing()
################################
# Unit Tests
################################
# Add test cpp file
add_executable(runUnitTests testgtest.cpp)
# Include directories
target_include_directories(runUnitTests
$<TARGET_PROPERTY:gtest,INTERFACE_SYSTEM_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:gtest_main,INTERFACE_SYSTEM_INCLUDE_DIRECTORIES>)
# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests gtest
gtest_main)
add_test(runUnitTests runUnitTests)
You can use the INTERFACE_SYSTEM_INCLUDE_DIRECTORIES
target property of the gtest and gtest_main targets as they are set in the google test CMakeLists.txt script.
Sometimes when we do these steps:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
The last statement fails with
ORA-00955 "name is already used by an existing object"
Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.
You can combine the dropping of primary key constraint and unique index into a single sql statement:
alter table my_table drop constraint my_pk drop index;
check this: ORA-00955 "name is already used by an existing object"
example:
sudo vim /usr/local/netbeans-8.2/etc/netbeans.conf
Simple and effective alternative:
public class ClassName
{
public List<dynamic> MyProperty { get; set; }
}
or
public class ClassName
{
public List<object> MyProperty { get; set; }
}
For differences see this post: List<Object> vs List<dynamic>
Some edits to include the very relevant suggestions in the comments and in other answers. I'd like to note that the way you break on this depends a lot on what environment you plan to run in. Minimal embedded systems may not have enough resources to support dynamic linking. Slightly larger small systems may well support dynamic linking, because their memory is small enough to make the RAM savings from dynamic linking very attractive. Full blown consumer PCs have, as Mark notes, enormous resources, and you can probably let the convenience issues drive your thinking on this matter.
To address the performance and efficiency issues: it depends.
Classically, dynamic libraries require a some kind of glue layer which often means double dispatch or an extra layer of indirection in function addressing and can cost a little speed (but is function calling time actually a big part of your running time???).
However, if you are running multiple processes which all call the same library a lot, you can end up saving cache lines (and thus winning on running performance) when using dynamic linking relative to using static linking. (Unless modern OS's are smart enough to notice identical segments in statically linked binaries. Seems hard, anyone know?)
Another issue: loading time. You pay loading costs at some point. When you pay this cost depends on how the OS works as well as what linking you use. Maybe you'd rather put off paying it until you know you need it.
Note that static-vs-dynamic linking is traditionally not an optimization issue, because they both involve separate compilation down to object files. However, this is not required: a compiler can in principle, "compile" "static libraries" to a digested AST form initially, and "link" them by adding those ASTs to the ones generated for the main code, thus empowering global optimization. None of the systems I use do this, so I can't comment on how well it works.
The way to answer performance questions is always by testing (and use a test environment as much like the deployment environment as possible).
If display: inline;
isn't working, try out display: inline-block;
. :)
Array's has
array.length
whereas List has
list.size()
Replace array.size()
to array.length
Unless you are writing a library or have special reasons, you can forget about inline
and use link-time optimization instead. It removes the requirement that a function definition must be in a header for it to be considered for inlining across compilation units, which is precisely what inline
allows.
(But see Is there any reason why not to use link time optimization?)
The filter
function can also provide an interesting solution:
result = list(filter(lambda x: x.count(1) > 0, a))
which searches the tuples in the list a
for any occurrences of 1
. If the search is limited to the first element, the solution can be modified into:
result = list(filter(lambda x: x[0] == 1, a))
Matei Mihai given a simple and efficient solution but it will not work until put a MAX(date)
in SELECT part so this query will become:
SELECT u.*, p.*, max(date)
FROM payments p
JOIN users u ON u.id=p.user_id AND u.package = 1
GROUP BY u.id
And order by will not make any difference in grouping but it can order the final result provided by group by. I tried it and it worked for me.
Based on this code (which you provided in response to Alex's answer):
Editable newTxt=(Editable)userName1.getText();
String newString = newTxt.toString();
It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:
String newString = userName1.getText().toString();
pd.set_option('display.max_rows', 500)
df
Does not work in Jupyter!
Instead use:
pd.set_option('display.max_rows', 500)
df.head(500)
If you want STDOUT and STDERR both [everything], then the simplest way is:
#!/bin/bash
myprogram >& sample.s
then run it like ./script
, and you will get no output to your terminal. :)
the ">&" means STDERR and STDOUT. the &
also works the same way with a pipe: ./script |& sed
that will send everything to sed
There are quite a few elements of the $.Ajax()
that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
In my case, I was using it on an element
instead of document
, and according to MDN:
Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll(), getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.
I actually had the same problem with a completely new repository. I had even tried creating one with git checkout -b master
, but it would not create the branch. I then realized if I made some changes and committed them, git created my master branch.
If you have issues like the question ask above regarding the exception thrown when the solution is executed, the problem is permission, not properly granted to the users of that group to access the database/stored procedure. All you need do is to do something like what i have below, replacing mine with your database name, stored procedures (function)and the type of permission or role or who you are granting the access to.
USE [StableEmployee]
GO
GRANT EXEC ON dbo.GetAllEmployees TO PUBLIC
/****** Object: StoredProcedure [dbo].[GetAllEmployees] Script Date: 01/27/2016 16:27:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[GetAllEmployees]
as
Begin
Select EmployeeId, Name, Gender, City, DepartmentId
From tblEmployee
End
The <img>
element is empty — it doesn't have an end tag.
If the image is a background image, use CSS. If it is a content image, then set position: relative
on a container, then absolutely position the image and/or text within it.
Nov 2020
With Material-UI and React Hooks
import * as React from "react";
import {
Button,
IconButton,
Tooltip,
makeStyles,
Theme,
} from "@material-ui/core";
import { PhotoCamera } from "@material-ui/icons";
const useStyles = makeStyles((theme: Theme) => ({
root: {
"& > *": {
margin: theme.spacing(1),
},
},
input: {
display: "none",
},
faceImage: {
color: theme.palette.primary.light,
},
}));
interface FormProps {
saveFace: any; //(fileName:Blob) => Promise<void>, // callback taking a string and then dispatching a store actions
}
export const FaceForm: React.FunctionComponent<FormProps> = ({ saveFace }) => {
const classes = useStyles();
const [selectedFile, setSelectedFile] = React.useState(null);
const handleCapture = ({ target }: any) => {
setSelectedFile(target.files[0]);
};
const handleSubmit = () => {
saveFace(selectedFile);
};
return (
<>
<input
accept="image/jpeg"
className={classes.input}
id="faceImage"
type="file"
onChange={handleCapture}
/>
<Tooltip title="Select Image">
<label htmlFor="faceImage">
<IconButton
className={classes.faceImage}
color="primary"
aria-label="upload picture"
component="span"
>
<PhotoCamera fontSize="large" />
</IconButton>
</label>
</Tooltip>
<label>{selectedFile ? selectedFile.name : "Select Image"}</label>. . .
<Button onClick={() => handleSubmit()} color="primary">
Save
</Button>
</>
);
};
Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:
You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.
Transactions shouldn't be a problem if you use them correctly.
Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.
See other answers for Oracle comparison.
Windows7 FireFox/Chrome:
{
"cmd":["F:\\Program Files\\Mozilla Firefox\\firefox.exe","$file"]
}
just use your own path of firefox.exe or chrome.exe to replace mine.
Replace firefox.exe or chrome.exe with your own path.
Read carefully the warning message :
The POM for org.raml:jaxrs-code-generator:jar:2.0.0 is missing, no dependency information available
The problem is not the jar, but the pom.xml that is missing.
The pom.xml lists the required dependencies for this jar that Maven will pull during the build and overall the packaging of your application.
So, you may really need it.
Note that this problem may of course occur for other Maven dependencies and the ideas to solve that is always the same.
The Mule website documents very well that in addition to some information related to.
1) Quick workaround : looking for in the internet the pom.xml
of the artifact
Googling the artifact id, the group id and its version gives generally
interesting results : maven repository links to download it.
In the case of the org.raml:jaxrs-code-generator:jar:2.0.0
dependency, you can download the pom.xml
from the Maven mule repository :
2) Clean workaround for a single Maven project : adding the repository declaration in your pom.
In your case, add the Maven mule repositories :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
...
<repositories>
<repository>
<id>mulesoft-releases</id>
<name>MuleSoft Repository</name>
<url>http://repository.mulesoft.org/releases/</url>
<layout>default</layout>
</repository>
<repository>
<id>mulesoft-snapshots</id>
<name>MuleSoft Snapshot Repository</name>
<url>http://repository.mulesoft.org/snapshots/</url>
<layout>default</layout>
</repository>
</repositories>
...
</project>
3) Clean workaround for any Maven projects : add the repository declaration in your settings.xml
<profile>
<repositories>
...
<repository>
<id>mulesoft-releases</id>
<name>MuleSoft Repository</name>
<url>http://repository.mulesoft.org/releases/</url>
<layout>default</layout>
</repository>
<repository>
<id>mulesoft-snapshots</id>
<name>MuleSoft Snapshot Repository</name>
<url>http://repository.mulesoft.org/snapshots/</url>
<layout>default</layout>
</repository>
...
</repositories>
</profile>
Note that in some rare cases, the pom.xml
declaring the dependencies is nowhere. So, you have to identify yourself whether the artifact requires dependencies.
If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.
$("span").toggle();
Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
It works most of the time. I did have a problem where a div
was in a div
in a li
. The list item had a height set and the outer div
s made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.
Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then?
Another approach is to wrap your table in a scrollable element and set the header cells to stick to the top.
The advantage of this approach is that you don't have to change the display on tbody and you can leave it to the browser to calculate column width while keeping the header cell widths in line with the data cell column widths.
/* Set a fixed scrollable wrapper */_x000D_
.tableWrap {_x000D_
height: 200px;_x000D_
border: 2px solid black;_x000D_
overflow: auto;_x000D_
}_x000D_
/* Set header to stick to the top of the container. */_x000D_
thead tr th {_x000D_
position: sticky;_x000D_
top: 0;_x000D_
}_x000D_
_x000D_
/* If we use border,_x000D_
we must use table-collapse to avoid_x000D_
a slight movement of the header row */_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
/* Because we must set sticky on th,_x000D_
we have to apply background styles here_x000D_
rather than on thead */_x000D_
th {_x000D_
padding: 16px;_x000D_
padding-left: 15px;_x000D_
border-left: 1px dotted rgba(200, 209, 224, 0.6);_x000D_
border-bottom: 1px solid #e8e8e8;_x000D_
background: #ffc491;_x000D_
text-align: left;_x000D_
/* With border-collapse, we must use box-shadow or psuedo elements_x000D_
for the header borders */_x000D_
box-shadow: 0px 0px 0 2px #e8e8e8;_x000D_
}_x000D_
_x000D_
/* Basic Demo styling */_x000D_
table {_x000D_
width: 100%;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
table td {_x000D_
padding: 16px;_x000D_
}_x000D_
tbody tr {_x000D_
border-bottom: 2px solid #e8e8e8;_x000D_
}_x000D_
thead {_x000D_
font-weight: 500;_x000D_
color: rgba(0, 0, 0, 0.85);_x000D_
}_x000D_
tbody tr:hover {_x000D_
background: #e6f7ff;_x000D_
}
_x000D_
<div class="tableWrap">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th><span>Month</span></th>_x000D_
<th>_x000D_
<span>Event</span>_x000D_
</th>_x000D_
<th><span>Action</span></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>January</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>February. An extra long string.</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>March</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>April</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>May</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>June</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>July</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>August</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>September</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>October</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>November</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>December</td>_x000D_
<td>AAA</td>_x000D_
<td><span>Invite | Delete</span></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>
_x000D_
Create Dynamic angular variables from results
angular.forEach(results, function (value, key) {
if (key != null) {
$parse(key).assign($scope, value);
}
});
ps. don't forget to pass in the $parse attribute into your controller's function
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.
Dockerfile
...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash
Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.
Use a generator:
common = (x for x in list1 if x in list2)
The advantage here is that this will return in constant time (nearly instant) even when using huge lists or other huge iterables.
For example,
list1 = list(range(0,10000000))
list2=list(range(1000,20000000))
common = (x for x in list1 if x in list2)
All other answers here will take a very long time with these values for list1 and list2.
You can then iterate the answer with
for i in common: print(i)
Or convert it to a list with
list(i)
The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible
. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
}
.day-item-wrapper {
position: relative;
}
.day-item {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 10px;
background: rgba(0,0,0,0.1);
}
I found it easier to just take over the template from Bootstrap-ui. I have left the commented HTML still in-place to show what I changed.
Overwrite their default template:
<script type="text/ng-template" id="myDlgTemplateWrapper.html">
<div tabindex="-1" role="dialog" class="modal fade" ng-class="{in: animate}"
ng-style="{'z-index': 1050 + index*10, display: 'block'}" ng-click="close($event)">
<!-- <div class="modal-dialog"
ng-class="{'modal-sm': size == 'sm', 'modal-lg': size == 'lg'}"
>
<div class="modal-content" modal-transclude></div>
</div>-->
<div modal-transclude>
<!-- Your content goes here -->
</div>
</div>
</script>
Modify your dialog template (note the wrapper DIVs containing "modal-dialog" class and "modal-content" class):
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-dialog {{extraDlgClass}}"
style="width: {{width}}; max-width: {{maxWidth}}; min-width: {{minWidth}}; ">
<div class="modal-content">
<div class="modal-header bg-primary">
<h3>I am a more flexible modal!</h3>
</div>
<div class="modal-body"
style="min-height: {{minHeight}}; height: {{height}}; max-height {{maxHeight}}; ">
<p>Make me any size you want</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
</div>
</script>
And then call the modal with whatever CSS class or style parameters you wish to change (assuming you have already defined "app" somewhere else):
<script type="text/javascript">
app.controller("myTest", ["$scope", "$modal", function ($scope, $modal)
{
// Adjust these with your parameters as needed
$scope.extraDlgClass = undefined;
$scope.width = "70%";
$scope.height = "200px";
$scope.maxWidth = undefined;
$scope.maxHeight = undefined;
$scope.minWidth = undefined;
$scope.minHeight = undefined;
$scope.open = function ()
{
$scope.modalInstance = $modal.open(
{
backdrop: 'static',
keyboard: false,
modalFade: true,
templateUrl: "myModalContent.html",
windowTemplateUrl: "myDlgTemplateWrapper.html",
scope: $scope,
//size: size, - overwritten by the extraDlgClass below (use 'modal-lg' or 'modal-sm' if desired)
extraDlgClass: $scope.extraDlgClass,
width: $scope.width,
height: $scope.height,
maxWidth: $scope.maxWidth,
maxHeight: $scope.maxHeight,
minWidth: $scope.minWidth,
minHeight: $scope.minHeight
});
$scope.modalInstance.result.then(function ()
{
console.log('Modal closed at: ' + new Date());
},
function ()
{
console.log('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function ($event)
{
if ($event)
$event.preventDefault();
$scope.modalInstance.close("OK");
};
$scope.cancel = function ($event)
{
if ($event)
$event.preventDefault();
$scope.modalInstance.dismiss('cancel');
};
$scope.openFlexModal = function ()
{
$scope.open();
}
}]);
</script>
Add an "open" button and fire away.
<button ng-controller="myTest" class="btn btn-default" type="button" ng-click="openFlexModal();">Open Flex Modal!</button>
Now you can add whatever extra class you want, or simply change width/height sizes as necessary.
I further enclosed it within a wrapper directive, which is should be trivial from this point forward.
Cheers.
"workbench.panel.defaultLocation": "right",
strcmp will return different values based on the environment it is running(Linux/Windows)!
The reason is the that it has a bug as the bug report says https://bugs.php.net/bug.php?id=53999
Please handle with care!!Thank you.
you can also mark the application as private if you don’t plan to put it in an actual repository.
{
"name": "my-application",
"version": "0.0.1",
"private": true
}
Starting with Vue2, the triple braces were deprecated, you are to use v-html
.
<div v-html="task.html_content"> </div>
It is unclear from the documentation link as to what we are supposed to place inside v-html
, your variables goes inside v-html
.
Also, v-html
works only with <div>
or <span>
but not with <template>
.
If you want to see this live in an app, click here.
For those who want some background info, here's a short article explaining why overflow: hidden
works. It has to do with the so-called block formatting context. This is part of W3C's spec (ie is not a hack) and is basically the region occupied by an element with a block-type flow.
Every time it is applied, overflow: hidden
creates a new block formatting context. But it's not the only property capable of triggering that behaviour. Quoting a presentation by Fiona Chan from Sydney Web Apps Group:
- float: left / right
- overflow: hidden / auto / scroll
- display: table-cell and any table-related values / inline-block
- position: absolute / fixed
If your code is prepared to deal with overflow errors, you can throw an exception if data
is too large.
size_t data = 99999999;
if ( data > INT_MAX )
{
throw std::overflow_error("data is larger than INT_MAX");
}
int convertData = static_cast<int>(data);
"." | "!" | "~" | "*" | "'" | "(" | ")"
are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.
Since you are providing a relative pathway to the image, the image location is looked for from the location in which you have the css file. So if you have the image in a different location to the css file you could either try giving the absolute URL(pathway starting from the root folder) or give the relative file location path. In your case since img and css are in the folder assets to move from location of css file to the img file, you can use '..' operator to refer that the browser has to move 1 folder back and then follow the pathway you have after the '..' operator. This is basically how relative pathway works and you can use it to access resoures in different folders. Hope it helps.
Use "selrow" to get the selected row Id
var myGrid = $('#myGridId');
var selectedRowId = myGrid.jqGrid("getGridParam", 'selrow');
and then use getRowData to get the selected row at index selectedRowId.
var selectedRowData = myGrid.getRowData(selectedRowId);
If the multiselect is set to true on jqGrid, then use "selarrrow" to get list of selected rows:
var selectedRowIds = myGrid.jqGrid("getGridParam", 'selarrrow');
Use loop to iterate the list of selected rows:
var selectedRowData;
for(selectedRowIndex = 0; selectedRowIndex < selectedRowIds .length;
selectedRowIds ++) {
selectedRowData = myGrid.getRowData(selectedRowIds[selectedRowIndex]);
}
I think is because you have try to persist an object that have a reference to another object that is not persist yet, and so it try in the "DB side" to put a reference to a row that not exists
Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity
into (m, k)
.
My crystal ball says m.type
and m.purity
are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity
is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)
To fix this, you can iterate explicitly over the items
of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.
(In 2.x, itervalues
, iterkeys
, and iteritems
are typically a better idea; the non-iter
versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter
versions which just set up an iterator.)
In Android M the top solution won't work. I've written a helper class to fix that which you should call from your Application class and all Activities (I would suggest creating a BaseActivity and then make all the Activities inherit from it.
Note: This will also support properly RTL layout direction.
Helper class:
public class LocaleUtils {
private static Locale sLocale;
public static void setLocale(Locale locale) {
sLocale = locale;
if(sLocale != null) {
Locale.setDefault(sLocale);
}
}
public static void updateConfig(ContextThemeWrapper wrapper) {
if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Configuration configuration = new Configuration();
configuration.setLocale(sLocale);
wrapper.applyOverrideConfiguration(configuration);
}
}
public static void updateConfig(Application app, Configuration configuration) {
if (sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//Wrapping the configuration to avoid Activity endless loop
Configuration config = new Configuration(configuration);
// We must use the now-deprecated config.locale and res.updateConfiguration here,
// because the replacements aren't available till API level 24 and 17 respectively.
config.locale = sLocale;
Resources res = app.getBaseContext().getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
}
}
}
Application:
public class App extends Application {
public void onCreate(){
super.onCreate();
LocaleUtils.setLocale(new Locale("iw"));
LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtils.updateConfig(this, newConfig);
}
}
BaseActivity:
public class BaseActivity extends Activity {
public BaseActivity() {
LocaleUtils.updateConfig(this);
}
}
data.reshape((50,1104,-1))
works for me
You use the -classpath
argument. You can use either a relative or absolute path. What that means is you can use a path relative to your current directory, OR you can use an absolute path that starts at the root /
.
Example:
bash$ java -classpath path/to/jar/file MyMainClass
In this example the main
function is located in MyMainClass
and would be included somewhere in the jar file.
For compiling you need to use javac
Example:
bash$ javac -classpath path/to/jar/file MyMainClass.java
You can also specify the classpath via the environment variable, follow this example:
bash$ export CLASSPATH="path/to/jar/file:path/tojar/file2"
bash$ javac MyMainClass.java
For any normally complex java project you should look for the ant script named build.xml
This query will return details about foreign keys in a table, it supports multiple column keys.
SELECT *
FROM
(
SELECT
T1.constraint_name ConstraintName,
T2.COLUMN_NAME ColumnName,
T3.TABLE_NAME RefTableName,
T3.COLUMN_NAME RefColumnName,
T1.MATCH_OPTION MatchOption,
T1.UPDATE_RULE UpdateRule,
T1.DELETE_RULE DeleteRule
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS T1
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T2
ON T1.CONSTRAINT_NAME = T2.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T3
ON T1.UNIQUE_CONSTRAINT_NAME = T3.CONSTRAINT_NAME
AND T2.ORDINAL_POSITION = T3.ORDINAL_POSITION) A
WHERE A.ConstraintName = 'table_name'
In CentOS 7 instead of yum install mysql-devel
do yum install mysql-community-devel
This does not require you to add the mysql repo.
I have several test cases in a test suite and before I was running the test suite in the Mac Terminal like this:
python LoginSuite.py
Running the command this way my directory was being populated with .pyc files. I tried the below stated method and it solved the issue:
python -B LoginSuite.py
This method works if you are importing test cases into the test suite and running the suite on the command line.
From a posting by Matz:
(1) ++ and -- are NOT reserved operator in Ruby.
(2) C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
(3) self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
matz.
Just add your text between the font tags:
for blue color
<string name="hello_world"><font color='blue'>Hello world!</font></string>
or for red color
<string name="hello_world"><font color='red'>Hello world!</font></string>
You can also use shift()
.
var streetaddress = addy.split(',').shift();
According to MDN Web Docs:
The
shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
The answers above didn't help me solve my problem. After a long search I bumped into this partial solution.
I've finally solved my problem with this code to set the input field manually to ng-invalid (to set to ng-valid set it to 'true'):
$scope.myForm.inputName.$setValidity('required', false);
Try modifying the path in the windows registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment).
Caveat: Don't break the registry :)
After having compared the options a few answers here provided to F# features, I discovered F# to have a way better support for type-based switching (although I'm still sticking to C#).
You might want to see here and here.
As far as I know, this is the C++ Runtime Library. So it depends on the compiler you use to create your program (A new version will include some C++0x stuff, an older version will probably not for instance. It depends of the compiler and of its version).
If you use MinGW then you should use the libstdc++-6.dll found into the folder of this compiler. MinGW/bin folder should be the place to search for it on your computer.
If you copy this file in the same directory as your executable, it should be OK.
Java 8 way to do this:
List<Integer> list = Arrays.asList(1,2,3,4);
Comparator<Integer> comparator = Integer::compare;
list.stream().sorted(comparator.reversed()).forEach(System.out::println);
If you simply want to execute some code at the end of the loop, here's a slightly simpler variation that doesn't require extra event handling:
<div ng-controller="Ctrl">
<div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
thing {{thing}}
</div>
</div>
function Ctrl($scope) {
$scope.things = [
'A', 'B', 'C'
];
}
angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
return function(scope, element, attrs) {
if (scope.$last){
// iteration is complete, do whatever post-processing
// is necessary
element.parent().css('border', '1px solid black');
}
};
});
ALTER TABLE [table name] MODIFY COLUMN [column name] datatype
To pass an object to a fragment, do the following:
First store the objects in Bundle, don't forget to put implements serializable in class.
CategoryRowFragment fragment = new CategoryRowFragment();
// pass arguments to fragment
Bundle bundle = new Bundle();
// event list we want to populate
bundle.putSerializable("eventsList", eventsList);
// the description of the row
bundle.putSerializable("categoryRow", categoryRow);
fragment.setArguments(bundle);
Then retrieve bundles in Fragment
// events that will be populated in this row_x000D_
mEventsList = (ArrayList<Event>)getArguments().getSerializable("eventsList");_x000D_
_x000D_
// description of events to be populated in this row_x000D_
mCategoryRow = (CategoryRow)getArguments().getSerializable("categoryRow");
_x000D_
To copy with indexes and triggers do these 2 queries:
CREATE TABLE newtable LIKE oldtable;
INSERT INTO newtable SELECT * FROM oldtable;
To copy just structure and data use this one:
CREATE TABLE tbl_new AS SELECT * FROM tbl_old;
I've asked this before:
public static <T> List<T> toList(String json, Class<T> clazz) {
if (null == json) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<T>(){}.getType());
}
sample call:
List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
Same issue on macOS and got it fixed by running the same installer again.
Whereas I COULD NOT get it fixed by
Note: Make sure to select 'XAMPP Core Files' component while running the installer as by default it is not selected.
Though re-running the installer is not smart option when one has to do it every now and then. My installer is xampp-osx-7.0.13-1-installer.dmg
Update: I've got my MAMP working with this simple solution here. So, same should work for XAMPP.
Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.
int* a = new int[N];
// fill a
class C {
const std::vector<int> v;
public:
C():v(a, a+N) {}
};
All the above answers are valid, however, there are some cases that the String Literal Type is part of another complex type. Consider the following example:
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small',
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
// Here you will get the following error:
// Type 'string' is not assignable to type '"small" | "large"'.ts(2322)
['large', 'small'].forEach(size => (
useToolbarTheme({ size })
));
You have multiple solutions to fix this. Each solution is valid and has its own use cases.
1) The first solution is to define a type for the size and export it from the foo.ts. This is good if when you need to work with the size parameter by its own. For example, you have a function that accepts or returns a parameter of type size and you want to type it.
// in foo.ts
export type ToolbarThemeSize = 'large' | 'small';
export type ToolbarTheme = {
size: ToolbarThemeSize
};
// in bar.ts
import { ToolbarTheme, ToolbarThemeSize } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
function getToolbarSize(): ToolbarThemeSize {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size: size as ToolbarThemeSize })
));
2) The second option is to just cast it to the type ToolbarTheme. In this case, you don't need to expose the internal of ToolbarTheme if you don't need.
// in foo.ts
export type ToolbarTheme = {
size: 'large' | 'small'
};
// in bar.ts
import { ToolbarTheme } from './foo.ts';
function useToolbarTheme(theme: ToolbarTheme) {/* ... */}
['large', 'small'].forEach(size => (
useToolbarTheme({ size } as ToolbarTheme)
));
The script ~/.bash_profile
is run on login.
I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload
instruction was immediately evaluated, and then the $
usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).
So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.
var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
console.log("script loaded :)");
onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
For my needs, it works fine now. Hope this can help others :)
//for update
(from x in dataBase.Customers
where x.Name == "Test"
select x).ToList().ForEach(xx => xx.Name="New Name");
//for delete
dataBase.Customers.RemoveAll(x=>x.Name=="Name");
When you install the android studio just by downloading from https://developer.android.com/studio/install.html sometimes sdk folder will not get appear in C:\Users\home\AppData\Local\Android Location..
But to set the android studio we need to set the path for android on this location.
So simply
1) start the android setup.
2) follow the instruction and android studio will automatically download the sdk folder by itself. (it will show the window like "Downloading Components").
After completing that installation check the above path again.
sdk folder will get appear now.
If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"
<DataGrid IsReadOnly="True" CanUserAddRows="False" />
Further more you can set IsReadOnly on individual columns to disable editing.
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
Use the GetDirectories
and GetFiles
methods to get the folders and files.
Use the SearchOption
AllDirectories
to get the folders and files in the subfolders also.
In command prompt type below
set PATH=%PATH%;C:\path\to\php
Where C:\path\to\php is the folder where your php.exe
file is located. After this run
C:\>php -v
than you will see something like
PHP 7.3.6 (cli) (built: May 29 2019 12:11:00)
UPDATE:
If you find that when you restart your computer, this solution will not work anymore:
Set the Path like as following:
Step 1 - Click on the
Windows
icon
Step 2 - Click on the
Settings
icon
Step 3 - Click on
System
Step 4 - Click on
About
Step 5 - Click on
System info
Step 6 - Click on
Advanced system settings
Step 7 - Click on
Environment variables...
Step 8 - Select
Path
row and then clickEdit
Step 9 - Click
New
and then clickBrowse
, then in the next panel which will open you need to select the folder you want in thePath
. For the initial premise of this guide i will add the folderC:\Users\NewFolderInPath
?Note: Replace your PHP installed path(e.g:
C:\Program Files\php
) with the above path ?.
Step 10 - Click
OK
and click everyOK
button you will encounter to close every previous windows.
So the way I would solve this problem is to make sure the two datetimes are in the right timezone.
I can see that you are using datetime.now()
which will return the systems current time, with no tzinfo set.
tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()
seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.
Take a look at Delorean, it makes dealing with this sort of thing much easier.
This is a little old but should get you started:
//******************************************************************************
// Automated platform detection
//******************************************************************************
// _WIN32 is used by
// Visual C++
#ifdef _WIN32
#define __NT__
#endif
// Define __MAC__ platform indicator
#ifdef macintosh
#define __MAC__
#endif
// Define __OSX__ platform indicator
#ifdef __APPLE__
#define __OSX__
#endif
// Define __WIN16__ platform indicator
#ifdef _Windows_
#ifndef __NT__
#define __WIN16__
#endif
#endif
// Define Windows CE platform indicator
#ifdef WIN32_PLATFORM_HPCPRO
#define __WINCE__
#endif
#if (_WIN32_WCE == 300) // for Pocket PC
#define __POCKETPC__
#define __WINCE__
//#if (_WIN32_WCE == 211) // for Palm-size PC 2.11 (Wyvern)
//#if (_WIN32_WCE == 201) // for Palm-size PC 2.01 (Gryphon)
//#ifdef WIN32_PLATFORM_HPC2000 // for H/PC 2000 (Galileo)
#endif
Step 1, to update margin
The basic idea is to get margin out and then update it. The update will be applies automatically and you do not need to set it back. To get the layout parameters, simply call this method:
LayoutParams layoutParams = (LayoutParams) yourView.findViewById(R.id.THE_ID).getLayoutParams();
The LayoutParams
comes from the layout of your view. If the view is from a linear layout, you need to import LinearLayout.LayoutParams
. If you use relative layout, import LinearLayout.LayoutParams
, etc.
Now, if you set the margin using Layout_marginLeft
, Right
, etc, you need to update margin in this way
layoutParams.setMargins(left, top, right, bottom);
If you set margin using the new layout_marginStart
, you need to update margin in this way
layoutParams.setMarginStart(start);
layoutParams.setMarginEnd(end);
Step 2, to update margin in dp
All two ways of updating margin above are updating in pixels. You need to do a translation of dp to pixels.
float dpRatio = context.getResources().getDisplayMetrics().density;
int pixelForDp = (int)dpValue * dpRatio;
Now put the calculated value to the above margin update functions and you should be all set
Code::Blocks: add '-static' in settings->compiler->Linker settings->Other linker options.
See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0);
rather than just 0,0
Or better still with the C++ interface:
cv::Mat M;
cout << "M = " << endl << " " << M << endl << endl;
Use a BigDecimal
instead of float
/double
. There are a lot of numbers which can't be represented as binary floating point (for example, 0.1
). So you either must always round the result to a known precision or use BigDecimal
.
See http://en.wikipedia.org/wiki/Floating_point for more information.
I will add my experience using saga in production system in addition to the library author's rather thorough answer.
Pro (using saga):
Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.
redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.
Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.
Con:
Generator syntax.
Lots of concepts to learn.
API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.
0 */2 * * *
The answer is from https://crontab.guru/every-2-hours. It is interesting.
this is an another way:
<html>
<head>
<title>Echo</title>
<style type="text/css">
#result{
border: 1px solid #000000;
min-height: 250px;
max-height: 100%;
padding: 5px;
font-family: sans-serif;
font-size: 12px;
}
</style>
<script type="text/javascript" lang="ja">
function start(){
function echo(text){
lastResultAreaText = document.getElementById('result').innerHTML;
resultArea = document.getElementById('result');
if(lastResultAreaText==""){
resultArea.innerHTML=text;
}
else{
resultArea.innerHTML=lastResultAreaText+"</br>"+text;
}
}
echo("Hello World!");
}
</script>
</head>
<body onload="start()">
<pre id="result"></pre>
</body>
class a(object):
def my_hello(self):
print "hello ravi"
class b(a):
def my_hello(self):
super(b,self).my_hello()
print "hi"
obj = b()
obj.my_hello()
Right, I'm not sure if it will work for others but worked for me.
I changed proxyPort
to 8080 and used jcenter instead of Maven. But I had to apply expeption to use HTTP instead of HTTPS. This is what I have in my build.gradle for build script and allprojects
buildscript {
repositories {
jcenter {
url "http://jcenter.bintray.com/"
}
}
}
allprojects {
repositories {
jcenter {
url "http://jcenter.bintray.com/"
}
}
}
UPDATE: 06/08
I have recently updated Gradle and plugin version and had some problems. It was complaining about plugin com.android.application
I did some digging around and changed
jcenter {
url "http://jcenter.bintray.com/"
}
to
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
Mindprod points out that this is not a straightforward question to answer:
A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.
For example, the JVM or native compiler might decide to store aboolean[]
in 64-bit long chunks like aBitSet
. It does not have to tell you, so long as the program gives the same answers.
- It might allocate some temporary Objects on the stack.
- It may optimize some variables or method calls totally out of existence replacing them with constants.
- It might version methods or loops, i.e. compile two versions of a method, each optimized for a certain situation, then decide up front which one to call.
Then of course the hardware and OS have multilayer caches, on chip-cache, SRAM cache, DRAM cache, ordinary RAM working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption.
You can use Instrumentation.getObjectSize()
to obtain an estimate of the storage consumed by an object.
To visualize the actual object layout, footprint, and references, you can use the JOL (Java Object Layout) tool.
In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. (From Dmitry Spikhalskiy's answer, Jayen's answer, and JavaWorld.)
Typically, references are 4 bytes on 32bit platforms or on 64bit platforms up to -Xmx32G
; and 8 bytes above 32Gb (-Xmx32G
). (See compressed object references.)
As a result, a 64-bit JVM would typically require 30-50% more heap space. (Should I use a 32- or a 64-bit JVM?, 2012, JDK 1.7)
Boxed wrappers have overhead compared to primitive types (from JavaWorld):
Integer
: The 16-byte result is a little worse than I expected because anint
value can fit into just 4 extra bytes. Using anInteger
costs me a 300 percent memory overhead compared to when I can store the value as a primitive type
Long
: 16 bytes also: Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like aLong
is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast,Integer
had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary.
Other containers are costly too:
Multidimensional arrays: it offers another surprise.
Developers commonly employ constructs likeint[dim1][dim2]
in numerical and scientific computing.In an
int[dim1][dim2]
array instance, every nestedint[dim2]
array is anObject
in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ.For example, a
int[128][2]
instance takes 3,600 bytes. Compared to the 1,040 bytes anint[256]
instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case ofbyte[256][1]
, the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead.
String
: aString
's memory growth tracks its internal char array's growth. However, theString
class adds another 24 bytes of overhead.For a nonempty
String
of size 10 characters or less, the added overhead cost relative to useful payload (2 bytes for each char plus 4 bytes for the length), ranges from 100 to 400 percent.
Consider this example object:
class X { // 8 bytes for reference to the class definition
int a; // 4 bytes
byte b; // 1 byte
Integer c = new Integer(); // 4 bytes for a reference
}
A naïve sum would suggest that an instance of X
would use 17 bytes. However, due to alignment (also called padding), the JVM allocates the memory in multiples of 8 bytes, so instead of 17 bytes it would allocate 24 bytes.
You would be able to launch your spring boot appication with the external properties file path as follows:
java -jar {jar-file-name}.jar
--spring.config.location=file:///C:/{file-path}/{file-name}.properties
input[type='text'], input[type='password']
{
// my css
}
That is the correct way to do it. Sadly CSS is not a programming language.
I suggest using one of the exchange
methods that accepts an HttpEntity
for which you can also set the HttpHeaders
. (You can also specify the HTTP method you want to use.)
For example,
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
I prefer this solution because it's strongly typed, ie. exchange
expects an HttpEntity
.
However, you can also pass that HttpEntity
as a request
argument to postForObject
.
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class);
This is mentioned in the RestTemplate#postForObject
Javadoc.
The
request
parameter can be aHttpEntity
in order to add additional HTTP headers to the request.