This was an issue for me years ago and I'd previously fixed it in Eclipse by excluding 1.7 from my projects, but it became an issue again for IntelliJ, which I recently installed. I fixed it by:
Uninstalling the JDK:
cd /Library/Java/JavaVirtualMachines
sudo rm -rf jdk1.8.0_45.jdk
(I had jdk1.8.0_45.jdk
installed; obviously you should uninstall whichever java version is listed in that folder. The offending files are located in that folder and should be deleted.)
Note that the next time you create a new project, or open an existing project, you will need to set the project SDK to point to the new JDK install. You also may still see this bug or have it creep back if you have JDK 1.7 installed in your JavaVirtualMachines folder (which is what I believe happened to me).
The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..
E.g.
a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}
An elegant way to implement this would be to make an extension method, like this:
public static class Extensions
{
public static List<string> GetSelectedItems(this CheckBoxList cbl)
{
var result = new List<string>();
foreach (ListItem item in cbl.Items)
if (item.Selected)
result.Add(item.Value);
return result;
}
}
I can then use something like this to compose a string will all values separated by ';':
string.Join(";", cbl.GetSelectedItems());
Have you tried mode 'a+'?
with open(filename, 'a+') as f:
f.write(...)
Note however that f.tell()
will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
I resolved this issue after deleting folder where I was trying to add the file in Visual Studio. Deleted folder from window explorer also. After doing all this, successfully able to add folder and file.
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
You can do it as below.
$(this).prev('input').val("hello world");
The default is: no prompt.
You can enable it with -Confirm
or disable it with -Confirm:$false
However, it will still prompt, when the target:
-Recurse
parameter is not specified.-Force
is required to also remove hidden and read-only items etc.
To sum it up:
Remove-Item -Recurse -Force -Confirm:$false
...should cover all scenarios.
I will answer your question using a math analogy:
In this instance, the number 0 will represent no value. If you pick a random number, say 15, how many times can 0 be subtracted from 15? Infinite times because 0 has no value, thus you are taking nothing out of 15. Do you have difficulty accepting that 15 - 0 = 15 instead of ERROR? So if we switch this analogy back to Java coding, the String "" represents no value. Pick a random string, say "hello world", how many times can "" be subtracted from "hello world"?
If min value in array, you can try like:
>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44
Here is a better solution from
Mac OS X wants to use system keychain when compiling the project
- Open Keychain Access.
- In the top-left corner, unlock the keychain (if it is locked).
- Choose the System keychain from the top-left corner.
- Find your distribution certificate and click the disclosure triangle.
- Double-click ‘Private key’ under your distribution certificate.
- In the popup, go to the Access Control tab.
- Select ‘Allow all applications to access this item’.
- Save the changes.
- Close all windows.
- Run the application.
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
We can use query instead of queryForObject, major difference between query and queryForObject is that query return list of Object(based on Row mapper return type) and that list can be empty if no data is received from database while queryForObject always expect only single object be fetched from db neither null nor multiple rows and in case if result is empty then queryForObject throws EmptyResultDataAccessException, I had written one code using query that will overcome the problem of EmptyResultDataAccessException in case of null result.
---------- public UserInfo getUserInfo(String username, String password) { String sql = "SELECT firstname, lastname,address,city FROM users WHERE id=? and pass=?"; List<UserInfo> userInfoList = jdbcTemplate.query(sql, new Object[] { username, password }, new RowMapper<UserInfo>() { public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException { UserInfo user = new UserInfo(); user.setFirstName(rs.getString("firstname")); user.setLastName(rs.getString("lastname")); user.setAddress(rs.getString("address")); user.setCity(rs.getString("city")); return user; } }); if (userInfoList.isEmpty()) { return null; } else { return userInfoList.get(0); } }
If the variable is same, then
: "${VARIABLE:=DEFAULT_VALUE}"
assigns DEFAULT_VALUE
to VARIABLE
if not defined. The double quotes prevent globbing and word splitting.
Also see Section 3.5.3, Shell Parameter Expansion, in the Bash manual.
Diffrence between Foreach & map :
Map() : If you use map then map can return new array by iterating main array.
Foreach() : If you use Foreach then it can not return anything for each can iterating main array.
useFul link : use this link for understanding diffrence
The = way is 2-way binding, which lets you to have live changes inside your directive. When someone changes that variable out of directive, you will have that changed data inside your directive, but @ way is not two-ways binding. It works like Text. You bind once, and you will have only its value.
To get it more clearly, you can use this great article:
I didn't create my virtualenv using sudo. So Sebastian's answer didn't apply to me. My project is called utils
. I checked utils
directory and saw this:
-rw-r--r-- 1 macuser staff 983 6 Jan 15:17 README.md
drwxr-xr-x 6 root staff 204 6 Jan 14:36 utils.egg-info
-rw-r--r-- 1 macuser staff 31 6 Jan 15:09 requirements.txt
As you can see, utils.egg-info
is owned by root
not macuser
. That is why it was giving me permission denied
error. I also had to remove /Users/macuser/.virtualenvs/armoury/lib/python2.7/site-packages/utils.egg-link
as it was created by root
as well. I did pip install -e .
again after removing those, and it worked.
If l
is your list and X
is your value:
for i in range(len(l) + 1):
print l[:i] + [X] + l[i:]
i will provide mine because @muni s solution was a bit overkill for me
note: if you want to add custom definitions for several resolutions together, say something like this:
//mobile generally
@media screen and (max-width: 1199) {
.irns-desktop{
display: none;
}
.irns-mobile{
display: initial;
}
}
Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')
//here all definitions to apply globally
//desktop
@media only screen
and (min-width : 1200) {
}
//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px) {
} // end media query
//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px) {
}//end media definition
//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px) {
}//end media query
//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {
}
//end media query
At least on Debian the nginx startup script has a reload function which does:
reload)
log_daemon_msg "Reloading $DESC configuration" "$NAME"
test_nginx_config
start-stop-daemon --stop --signal HUP --quiet --pidfile $PID \
--oknodo --exec $DAEMON
log_end_msg $?
;;
Seems like all you'd need to do is call service nginx reload
instead of restart
since it calls test_nginx_config
.
To run Anaconda Prompt using icon, I made an icon and put
%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
The file location would be different in each computer.
at icon -> right click -> Property -> Shortcut -> Target
I see %HOMEPATH%
at icon -> right click -> Property -> Start in
OS: Windows 10, Library: Anaconda 10 (64 bit)
It means something like this:
std::vector<Movie *> movies;
Then you add to the vector as you read lines:
movies.push_back(new Movie(...));
Remember to delete all of the Movie*
objects once you are done with the vector.
There is a special identifier that one can use in a formula to mean all the variables, it is the .
identifier.
y <- c(1,4,6)
d <- data.frame(y = y, x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
mod <- lm(y ~ ., data = d)
You can also do things like this, to use all variables but one (in this case x3 is excluded):
mod <- lm(y ~ . - x3, data = d)
Technically, .
means all variables not already mentioned in the formula. For example
lm(y ~ x1 * x2 + ., data = d)
where .
would only reference x3
as x1
and x2
are already in the formula.
In [95]: import scipy
In [96]: scipy.__version__
Out[96]: '0.12.0'
In [104]: scipy.version.*version?
scipy.version.full_version
scipy.version.short_version
scipy.version.version
In [105]: scipy.version.full_version
Out[105]: '0.12.0'
In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b74f3ea66eb'
In [107]: scipy.version.release
Out[107]: True
In [108]: scipy.version.short_version
Out[108]: '0.12.0'
In [109]: scipy.version.version
Out[109]: '0.12.0'
See SciPy doveloper documentation for reference.
The name
attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different id
attributes, but the same name
. When submitted, there is just the one value in the response - the radio button you selected.
Of course, there's more to it than that, but it will definitely get you thinking in the right direction.
I have Alter this function to auto uncheck previous
var limit = 3;_x000D_
$('.compare_items').on('click', function(evt) {_x000D_
index = $(this).parent('td').parent('tr').index();_x000D_
if ($('.compare_items:checked').length >= limit) {_x000D_
$('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');_x000D_
//this.checked = false;_x000D_
}_x000D_
localStorage.setItem('last-checked-item', index);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="checkbox" class="compare_items">1_x000D_
<input type="checkbox" class="compare_items">2_x000D_
<input type="checkbox" class="compare_items">3_x000D_
<input type="checkbox" class="compare_items">4_x000D_
<input type="checkbox" class="compare_items">5_x000D_
<input type="checkbox" class="compare_items">6_x000D_
<input type="checkbox" class="compare_items">7_x000D_
<input type="checkbox" class="compare_items">8_x000D_
<input type="checkbox" class="compare_items">9_x000D_
<input type="checkbox" class="compare_items">10
_x000D_
There is a significant problem with some of the answers posted so far: unicode()
decodes from the default encoding, which is often ASCII; in fact, unicode()
tries to make "sense" of the bytes it is given by converting them into characters. Thus, the following code, which is essentially what is recommended by previous answers, fails on my machine:
# -*- coding: utf-8 -*-
author = 'éric'
print '{0}'.format(unicode(author))
gives:
Traceback (most recent call last):
File "test.py", line 3, in <module>
print '{0}'.format(unicode(author))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
The failure comes from the fact that author
does not contain only ASCII bytes (i.e. with values in [0; 127]), and unicode()
decodes from ASCII by default (on many machines).
A robust solution is to explicitly give the encoding used in your fields; taking UTF-8 as an example:
u'{0} in {1}'.format(unicode(self.author, 'utf-8'), unicode(self.publication, 'utf-8'))
(or without the initial u
, depending on whether you want a Unicode result or a byte string).
At this point, one might want to consider having the author
and publication
fields be Unicode strings, instead of decoding them during formatting.
RemoteEndPoint is a property, its type is System.Net.EndPoint which inherits from System.Net.IPEndPoint.
If you take a look at IPEndPoint's members, you'll see that there's an Address
property.
Never recommended to mutate the state directly.
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
Push string to end of the array
this.setState(prevState => ({
myArray: [...prevState.myArray, "new value"]
}))
Push string to beginning of the array
this.setState(prevState => ({
myArray: ["new value", ...prevState.myArray]
}))
Push object to end of the array
this.setState(prevState => ({
myArray: [...prevState.myArray, {"name": "object"}]
}))
Push object to beginning of the array
this.setState(prevState => ({
myArray: [ {"name": "object"}, ...prevState.myArray]
}))
Right click on your project, then left click Properties, and select the Web tab. Debuggers > ASP.NET
KEYPRESS (enter key)
Click inside the snippet and press Enter key.
Vanilla
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
alert('hi.');
}
});
_x000D_
Vanilla shorthand (ES6)
this.addEventListener('keypress', event => {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
jQuery
$(this).on('keypress', function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
jQuery classic
$(this).keypress(function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
jQuery shorthand (ES6)
$(this).keypress((e) => {
if (e.keyCode == 13)
alert('hi.')
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Even shorter (ES6)
$(this).keypress(e=>
e.which==13?
alert`hi.`:null
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Due some requests, here an explanation:
I rewrote this answer as things have become deprecated over time so I updated it.
I used this
to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.
Deprecated:
The .which
and .keyCode
methods are actually considered deprecated so I would recommend .code
but I personally still use keyCode as the performance is much faster and only that counts for me.
The jQuery classic version .keypress()
is not officially deprecated as some people say but they are no more preferred like .on('keypress')
as it has a lot more functionality(live state, multiple handlers, etc.).
The 'keypress'
event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown today. (Note: It has nothing to do with jQuery's events, they are called the same but execute differently.)
All examples above are no biggies regarding deprecated or not. Consoles or any browser should be able to notify you with that if this happens. And if this ever does in future, just fix it.
Readablity:
Despite the ease making it too short and snippy isn't always good either. If you work in a team, your code must be readable and detailed. I recommend the jQuery version .on('keypress')
, this is the way to go and understandable by most people.
Performance:
I always follow my phrase Performance over Effectiveness as anything can be more effective if there is the option but it just should function and execute only what I want, the faster the better. This is why I prefer .keyCode
even if it's considered deprecated(in most cases). It's all up to you though.
If you are looking for Uniformly distributed pseudorandom integers use:
randi([13, 20])
Similar answer to caligari's answer, but we can tidy it up by just specifying the full column range:
=INDEX(G2:G, COUNT(G2:G))
This worked for me. The Container provides the height and FractionallySizedBox provides the width for the RaisedButton.
Container(
height: 50.0, //Provides height for the RaisedButton
child: FractionallySizedBox(
widthFactor: 0.7, ////Provides 70% width for the RaisedButton
child: RaisedButton(
onPressed: () {},
),
),
),
As gradle built-in tasks is deprecated in 4.8, try below
wrapper {
gradleVersion = '2.0' //version required
}
and run
gradle wrapper
Use media queries. Your CSS code would be:
@media screen and (max-width: 1024px) {
.yourClass {
display: none !important;
}
}
How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016
Step 1: Right button mouse > Select "Edit Top 200 Rows"
Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)
Step 3: Modify the query
Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)
Use @@ROWCOUNT:
SELECT * FROM service s WHERE s.service_id = ?;
IF @@ROWCOUNT > 0
-- do stuff here.....
According to SQL Server Books Online:
Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.
make folder and name it foe example download open note pad and insert this code
only change http://www.google.com/aa.zip to your file and save it to m.php for example
chamod the php file to 666 and the folder download to 777
<?php
define('BUFSIZ', 4095);
$url = 'http://www.google.com/aa.zip';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>
finally from your browser enter to these URL http://www.example.com/download/m.php
you will see in download folder the file download from other server
thanks
Using Glide library:
Glide.with(context)
.load(new File(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
Option 1
http://jquery.malsup.com/corner/
Option 2
http://code.google.com/p/curved-corner/downloads/detail?name=border-radius-demo.zip
Option 3
Option 4
http://www.netzgesta.de/corner/
Option 5
EDIT: Option 6
NOTE: The below solution no longer works on iOS 13+ devices - it will return garbage data.
Please use following code instead:
+ (NSString *)hexadecimalStringFromData:(NSData *)data
{
NSUInteger dataLength = data.length;
if (dataLength == 0) {
return nil;
}
const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02x", dataBuffer[i]];
}
return [hexString copy];
}
Solution that worked prior to iOS 13:
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"this will return '32 bytes' in iOS 13+ rather than the token", token);
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("this will return '32 bytes' in iOS 13+ rather than the token \(tokenString)")
}
you can find Java compiler version from .class files using a Hex Editor.
Step 1: Extract .class files from jar file using a zip extractor
step 2: open .class file with a hex editor.(I have used notepad++ hex editor plugin. This plugin reads file as binary and shows it in hex) You can see below.
Index 6 and 7 gives major version number of the class file format being used. https://en.wikipedia.org/wiki/Java_class_file
Java SE 11 = 55 (0x37 hex)
Java SE 10 = 54 (0x36 hex)
Java SE 9 = 53 (0x35 hex)
Java SE 8 = 52 (0x34 hex),
Java SE 7 = 51 (0x33 hex),
Java SE 6.0 = 50 (0x32 hex),
Java SE 5.0 = 49 (0x31 hex),
JDK 1.4 = 48 (0x30 hex),
JDK 1.3 = 47 (0x2F hex),
JDK 1.2 = 46 (0x2E hex),
JDK 1.1 = 45 (0x2D hex).
in iterm2
fn + leftArraw or fn + rightArrow
this worked for me
Use a for
loop:
keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
myDictionary.get(key)
or a list comprehension:
[myDictionary.get(key) for key in keys]
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');
while($row = mysql_fetch_array($sql_results))
{
$subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database.
$subArray[x]=$row['x'];
$subArray[y]=$row['y'];
$array[] = $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
I wrote a little category on UIView
that manages temporarily scrolling things around without needing to wrap the whole thing into a UIScrollView
. My use of the verb "scroll" here is perhaps not ideal, because it might make you think there's a scroll view involved, and there's not--we're just animating the position of a UIView
(or UIView
subclass).
There are a bunch of magic numbers embedded in this that are appropriate to my form and layout that might not be appropriate to yours, so I encourage tweaking this to fit your specific needs.
UIView+FormScroll.h:
#import <Foundation/Foundation.h>
@interface UIView (FormScroll)
-(void)scrollToY:(float)y;
-(void)scrollToView:(UIView *)view;
-(void)scrollElement:(UIView *)view toPoint:(float)y;
@end
UIView+FormScroll.m:
#import "UIView+FormScroll.h"
@implementation UIView (FormScroll)
-(void)scrollToY:(float)y
{
[UIView beginAnimations:@"registerScroll" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.4];
self.transform = CGAffineTransformMakeTranslation(0, y);
[UIView commitAnimations];
}
-(void)scrollToView:(UIView *)view
{
CGRect theFrame = view.frame;
float y = theFrame.origin.y - 15;
y -= (y/1.7);
[self scrollToY:-y];
}
-(void)scrollElement:(UIView *)view toPoint:(float)y
{
CGRect theFrame = view.frame;
float orig_y = theFrame.origin.y;
float diff = y - orig_y;
if (diff < 0) {
[self scrollToY:diff];
}
else {
[self scrollToY:0];
}
}
@end
Import that into your UIViewController, and then you can do
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self.view scrollToView:textField];
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
[self.view scrollToY:0];
[textField resignFirstResponder];
}
...or whatever. That category gives you three pretty good ways to adjust the position of a view.
As suggested above the inclusion of
/usr/lib/openmpi/include
in the include path takes care of this (in my case)
First you will need to install node definitions for Typescript. You can find the definitions file here:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts
Once you've got file, just add the reference to your .ts
file like this:
/// <reference path="path/to/node.d.ts" />
Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts
can look like this:
/// <reference path="path/to/node.d.ts" />
class MyClass {
// Here we import the File System module of node
private fs = require('fs');
constructor() { }
createFile() {
this.fs.writeFile('file.txt', 'I am cool!', function(err) {
if (err) {
return console.error(err);
}
console.log("File created!");
});
}
showFile() {
this.fs.readFile('file.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
}
}
// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();
Once you transpile your .ts
file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:
> node myClass.js
Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.
$('.clickHere').click(function(){
// this is flat click. this event will be attatched
//to element if element is available in
//dom at the time when JS loaded.
// do your stuff
});
$('.clickHere').on('click', function(){
// same as first one
// do your stuff
})
$(document).on('click', '.clickHere', function(){
// this is diffrent type
// of click. The click will be registered on document when JS
// loaded and will delegate to the '.clickHere ' element. This is
// called event delegation
// do your stuff
});
$('body').on('click', '.clickHere', function(){
// This is same as 3rd
// point. Here we used body instead of document/
// do your stuff
});
$('.clickHere').off().on('click', function(){ //
// deregister event listener if any and register the event again. This
// prevents the duplicate event resistration on same element.
// do your stuff
})
I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.
There are a few different ways you can achieve what you are asking for.
1.) Extend the application class and instantiate your controller and model objects there.
public class FavoriteColorsApplication extends Application {
private static FavoriteColorsApplication application;
private FavoriteColorsService service;
public FavoriteColorsApplication getInstance() {
return application;
}
@Override
public void onCreate() {
super.onCreate();
application = this;
application.initialize();
}
private void initialize() {
service = new FavoriteColorsService();
}
public FavoriteColorsService getService() {
return service;
}
}
Then you can call the your singleton from your custom Application object at any time:
public class FavoriteColorsActivity extends Activity {
private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_colors);
service = ((FavoriteColorsApplication) getApplication()).getService();
favoriteColors = service.findAllColors();
ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
favoriteColors);
lv.setAdapter(adapter);
}
2.) You can have your controller just create a singleton instance of itself:
public class Controller {
private static final String TAG = "Controller";
private static sController sController;
private Dao mDao;
private Controller() {
mDao = new Dao();
}
public static Controller create() {
if (sController == null) {
sController = new Controller();
}
return sController;
}
}
Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.
3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.
I hope I gave enough detail in regards to how you can do what you are hoping for.
map(float, mylist)
should do it.
(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need list(map(float, mylist)
- or use SilentGhost's answer which arguably is more pythonic.)
In case you want to train CNN's with the theano backend like the Keras mnist_cnn.py example:
You better use theano bleeding edge version. Otherwise there may occur assertion errors.
pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
pip install git+git://github.com/fchollet/keras.git
Use a backslash as such
"From time to \"time\"";
Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this
'From time to "time"';
The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such
$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"
As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:
$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;
I use this simple code:
fun getConnectionInfo(): ConnectionInfo {
val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (cm.activeNetwork == null) {
ConnectionInfo.NO_CONNECTION
} else {
if (cm.isActiveNetworkMetered) {
ConnectionInfo.MOBILE
} else {
ConnectionInfo.WI_FI
}
}
}
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.
When static variable is declared in a header file is its scope limited to .h file or across all units.
There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.
As such, a static variable declared in a header file is like a static variable in each individual source file.
Since declaring a variable static
this way means internal linkage, every translation unit #include
ing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.
I would like to know what is the difference between static variables in a header file vs declared in a class.
In a class declaration, static
means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static
(or "class") variable, it's the same value for all objects. You could think of it as a "class global".
Also generally static variable is initialized in .cpp file when declared in a class right ?
Yes, one (and only one) translation unit must initialize the class variable.
So that does mean static variable scope is limited to 2 compilation units ?
As I said:
static
means completely different things depending on context.Global static
limits scope to the translation unit. Class static
means global to all instances.
I hope this helps.
PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static
in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )
For Mysql8->
Query:
SELECT properties, properties->"$.price" FROM book where isbn='978-9730228236' and JSON_EXTRACT(properties, "$.price") > 400;
Data:
mysql> select * from book\G;
*************************** 1. row ***************************
id: 1
isbn: 978-9730228236
properties: {"price": 44.99, "title": "High-Performance Java Persistence", "author": "Vlad Mihalcea", "publisher": "Amazon"}
1 row in set (0.00 sec)
The free version of TightVnc viewer (I have TightVnc Viewer 1.5.4 8/3/2011) build does not support this. What you need is RealVNC but VNC Enterprise Edition 4.2 or the Personal Edition. Unfortunately this is not free and you have to pay for a license.
From the RealVNC website [releasenote] http://www.realvnc.com/products/enterprise/4.2/release-notes.html
VNC Viewer: Full-screen mode can span monitors on a multi-monitor system.
They are stored in the CGI fieldstorage object.
import cgi
form = cgi.FieldStorage()
print "The user entered %s" % form.getvalue("uservalue")
I implemented one similar to Brian's. Mine is different:
yield return
for producing an enumerator.DoSync
and GetSync
methods allowing sequential interactions that require exclusive access to the list.public class ConcurrentList<T> : IList<T>, IDisposable
{
private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
private int _count = 0;
public int Count
{
get
{
_lock.EnterReadLock();
try
{
return _count;
}
finally
{
_lock.ExitReadLock();
}
}
}
public int InternalArrayLength
{
get
{
_lock.EnterReadLock();
try
{
return _arr.Length;
}
finally
{
_lock.ExitReadLock();
}
}
}
private T[] _arr;
public ConcurrentList(int initialCapacity)
{
_arr = new T[initialCapacity];
}
public ConcurrentList():this(4)
{ }
public ConcurrentList(IEnumerable<T> items)
{
_arr = items.ToArray();
_count = _arr.Length;
}
public void Add(T item)
{
_lock.EnterWriteLock();
try
{
var newCount = _count + 1;
EnsureCapacity(newCount);
_arr[_count] = item;
_count = newCount;
}
finally
{
_lock.ExitWriteLock();
}
}
public void AddRange(IEnumerable<T> items)
{
if (items == null)
throw new ArgumentNullException("items");
_lock.EnterWriteLock();
try
{
var arr = items as T[] ?? items.ToArray();
var newCount = _count + arr.Length;
EnsureCapacity(newCount);
Array.Copy(arr, 0, _arr, _count, arr.Length);
_count = newCount;
}
finally
{
_lock.ExitWriteLock();
}
}
private void EnsureCapacity(int capacity)
{
if (_arr.Length >= capacity)
return;
int doubled;
checked
{
try
{
doubled = _arr.Length * 2;
}
catch (OverflowException)
{
doubled = int.MaxValue;
}
}
var newLength = Math.Max(doubled, capacity);
Array.Resize(ref _arr, newLength);
}
public bool Remove(T item)
{
_lock.EnterUpgradeableReadLock();
try
{
var i = IndexOfInternal(item);
if (i == -1)
return false;
_lock.EnterWriteLock();
try
{
RemoveAtInternal(i);
return true;
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
public IEnumerator<T> GetEnumerator()
{
_lock.EnterReadLock();
try
{
for (int i = 0; i < _count; i++)
// deadlocking potential mitigated by lock recursion enforcement
yield return _arr[i];
}
finally
{
_lock.ExitReadLock();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public int IndexOf(T item)
{
_lock.EnterReadLock();
try
{
return IndexOfInternal(item);
}
finally
{
_lock.ExitReadLock();
}
}
private int IndexOfInternal(T item)
{
return Array.FindIndex(_arr, 0, _count, x => x.Equals(item));
}
public void Insert(int index, T item)
{
_lock.EnterUpgradeableReadLock();
try
{
if (index > _count)
throw new ArgumentOutOfRangeException("index");
_lock.EnterWriteLock();
try
{
var newCount = _count + 1;
EnsureCapacity(newCount);
// shift everything right by one, starting at index
Array.Copy(_arr, index, _arr, index + 1, _count - index);
// insert
_arr[index] = item;
_count = newCount;
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
public void RemoveAt(int index)
{
_lock.EnterUpgradeableReadLock();
try
{
if (index >= _count)
throw new ArgumentOutOfRangeException("index");
_lock.EnterWriteLock();
try
{
RemoveAtInternal(index);
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
private void RemoveAtInternal(int index)
{
Array.Copy(_arr, index + 1, _arr, index, _count - index-1);
_count--;
// release last element
Array.Clear(_arr, _count, 1);
}
public void Clear()
{
_lock.EnterWriteLock();
try
{
Array.Clear(_arr, 0, _count);
_count = 0;
}
finally
{
_lock.ExitWriteLock();
}
}
public bool Contains(T item)
{
_lock.EnterReadLock();
try
{
return IndexOfInternal(item) != -1;
}
finally
{
_lock.ExitReadLock();
}
}
public void CopyTo(T[] array, int arrayIndex)
{
_lock.EnterReadLock();
try
{
if(_count > array.Length - arrayIndex)
throw new ArgumentException("Destination array was not long enough.");
Array.Copy(_arr, 0, array, arrayIndex, _count);
}
finally
{
_lock.ExitReadLock();
}
}
public bool IsReadOnly
{
get { return false; }
}
public T this[int index]
{
get
{
_lock.EnterReadLock();
try
{
if (index >= _count)
throw new ArgumentOutOfRangeException("index");
return _arr[index];
}
finally
{
_lock.ExitReadLock();
}
}
set
{
_lock.EnterUpgradeableReadLock();
try
{
if (index >= _count)
throw new ArgumentOutOfRangeException("index");
_lock.EnterWriteLock();
try
{
_arr[index] = value;
}
finally
{
_lock.ExitWriteLock();
}
}
finally
{
_lock.ExitUpgradeableReadLock();
}
}
}
public void DoSync(Action<ConcurrentList<T>> action)
{
GetSync(l =>
{
action(l);
return 0;
});
}
public TResult GetSync<TResult>(Func<ConcurrentList<T>,TResult> func)
{
_lock.EnterWriteLock();
try
{
return func(this);
}
finally
{
_lock.ExitWriteLock();
}
}
public void Dispose()
{
_lock.Dispose();
}
}
You could just use a HashSet<String>
to maintain a collection of unique objects. If the Integer
values in your map are important, then you can instead use the containsKey
method of maps to test whether your key is already in the map.
Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.
As an example on an SSL certificate for a web site the subject would be the domain name of the web site.
If you came here (just like me) to find the solution for integer value, here is the answer:
CAST(9/2 AS UNSIGNED)
returns 5
here's my refactored version which accepts multiline/single as an option
public string ShowDialog(string text, string caption, bool isMultiline = false, int formWidth = 300, int formHeight = 200)
{
var prompt = new Form
{
Width = formWidth,
Height = isMultiline ? formHeight : formHeight - 70,
FormBorderStyle = isMultiline ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
MaximizeBox = isMultiline
};
var textLabel = new Label
{
Left = 10,
Padding = new Padding(0, 3, 0, 0),
Text = text,
Dock = DockStyle.Top
};
var textBox = new TextBox
{
Left = isMultiline ? 50 : 4,
Top = isMultiline ? 50 : textLabel.Height + 4,
Multiline = isMultiline,
Dock = isMultiline ? DockStyle.Fill : DockStyle.None,
Width = prompt.Width - 24,
Anchor = isMultiline ? AnchorStyles.Left | AnchorStyles.Top : AnchorStyles.Left | AnchorStyles.Right
};
var confirmationButton = new Button
{
Text = @"OK",
Cursor = Cursors.Hand,
DialogResult = DialogResult.OK,
Dock = DockStyle.Bottom,
};
confirmationButton.Click += (sender, e) =>
{
prompt.Close();
};
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmationButton);
prompt.Controls.Add(textLabel);
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
}
onResume() for the fragment works fine...
public class listBook extends Fragment {
private String listbook_last_subtitle;
...
@Override
public void onCreate(Bundle savedInstanceState) {
String thisFragSubtitle = (String) getActivity().getActionBar().getSubtitle();
listbook_last_subtitle = thisFragSubtitle;
}
...
@Override
public void onResume(){
super.onResume();
getActivity().getActionBar().setSubtitle(listbook_last_subtitle);
}
...
REAL
is what you are looking for. Documentation of SQLite datatypes
There are two variants of CASE
, and you're not using the one that you think you are.
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE
Each condition is loosely equivalent to a if (case_value == when_value)
(pseudo-code).
However, you've put an entire condition as when_value
, leading to something like:
if (case_value == (case_value > 100))
Now, (case_value > 100)
evaluates to FALSE
, and is the only one of your conditions to do so. So, now you have:
if (case_value == FALSE)
FALSE
converts to 0
and, through the resulting full expression if (case_value == 0)
you can now see why the third condition fires.
Drop the first course_enrollment_settings
so that there's no case_value
, causing MySQL to know that you intend to use the second variant of CASE
:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE
Now you can provide your full conditionals as search_condition
.
Also, please read the documentation for features that you use.
the core functions are getBytes(String charset)
and new String(byte[] data)
. you can use these functions to do UTF-8 decoding.
UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String()
is the byte array, which calling is equal to new String(bytes, "UTF-8")
Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.
The decoding sentence should be
String decoded = new String(encoded.getBytes("ISO-8859-1"));
Use this code where str is your JSON string:
NSError *err = nil;
NSArray *arr =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
// do something using dictionary
}
yes,the sorting proceed differently. in first scenario, orders based on column1 and in addition to that process further by sorting colmun2 based on column1 .. in second scenario ,it orders completely based on column 1 only... please proceed with a simple example...u will get quickly..
Try using pip -V
(notice capital V)
If you are running the virtual env. it'll show the path to the env.'s location.
On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:
html {
margin: 0px;
height: 100%;
width: 100%;
}
body {
margin: 0px;
min-height: 100%;
width: 100%;
}
height
for the html
and min-height
for the body
.
You can check checkbox in the commit dialog.
You can use settings to automatically optimize imports since 11.1 and above.
scrollHeight
is a regular javascript property so you don't need jQuery.
var test = document.getElementById("foo").scrollHeight;
In Java 7, you can use Objects.requireNonNull()
.
Add an import of Objects
class from java.util
.
public class FooClass {
//...
public void acceptFoo(Foo obj) {
//If obj is null, NPE is thrown
Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
}
//...
}
iPhoney is designed specifically for Mac users
you can read about it and download it here
Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary
// fordictionary
var x = (from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() })
.ToDictionary( t => t.type, t => t.count);
//for stringbuilder not sure for this
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
StringBuilder MyStringBuilder = new StringBuilder();
foreach (var res in x)
{
//: is separator between to object
MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
}
Console.WriteLine(MyStringBuilder.ToString());
This is what I would use:
a. Make sure to use double quotes, for example:
$row['message'] = "This is a Text \n and so on \t Text text.";
b. To remove extra whitespace, use:
$ro = preg_replace('/\s+/', ' ', $row['message']);
echo $ro;
It may not be the fastest solution, but I think it will require the least code, and it should work. I've never used mysql, though, so I may be wrong.
Why not use properly formulated geospatial queries???
Here is the SQL server reference page on the STContains geospatial function:
or if you do not waant to use box and radian conversion , you cna always use the distance function to find the points that you need:
DECLARE @CurrentLocation geography;
SET @CurrentLocation = geography::Point(12.822222, 80.222222, 4326)
SELECT * , Round (GeoLocation.STDistance(@CurrentLocation ),0) AS Distance FROM [Landmark]
WHERE GeoLocation.STDistance(@CurrentLocation )<= 2000 -- 2 Km
There should be similar functionality for almost any database out there.
If you have implemented geospatial indexing correctly your searches would be way faster than the approach you are using
Leaving this here for myself,
If I get this error, I probably used const char*
when I should be using char* const
.
This makes the pointer constant, and not the contents of the string.
const char* const
makes it so the value and the pointer is constant also.
One more solution to the problem
(children are welcome to vote)
bool isEven(unsigned int x)
{
unsigned int half1 = 0, half2 = 0;
while (x)
{
if (x) { half1++; x--; }
if (x) { half2++; x--; }
}
return half1 == half2;
}
Already there are lots of answers to your question, You can do it like this also. You can give your table an alias name and use that in the select query like this:
SELECT a.id, b.id, name, section
FROM tbl_names as a
LEFT JOIN tbl_section as b ON a.id = b.id;
You must write onActivityResult() in your FirstActivity.Java as follows
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
This will trigger onActivityResult method of fragments on FirstActivity.java
php -d memory_limit=5G composer.phar update
A nice way to achieve this "if you have an office 365 account" is to use Office 365 outlook connector integrated with Azure Logic App,
Hope this helps someone!
I search a way to map a many-to-many association table with extra column(s) with hibernate in xml files configuration.
Assuming with have two table 'a' & 'c' with a many to many association with a column named 'extra'. Cause I didn't find any complete example, here is my code. Hope it will help :).
First here is the Java objects.
public class A implements Serializable{
protected int id;
// put some others fields if needed ...
private Set<AC> ac = new HashSet<AC>();
public A(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<AC> getAC() {
return ac;
}
public void setAC(Set<AC> ac) {
this.ac = ac;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 97;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof A))
return false;
final A other = (A) obj;
if (id != other.getId())
return false;
return true;
}
}
public class C implements Serializable{
protected int id;
// put some others fields if needed ...
public C(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 98;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof C))
return false;
final C other = (C) obj;
if (id != other.getId())
return false;
return true;
}
}
Now, we have to create the association table. The first step is to create an object representing a complex primary key (a.id, c.id).
public class ACId implements Serializable{
private A a;
private C c;
public ACId() {
super();
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result
+ ((c == null) ? 0 : c.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ACId other = (ACId) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (c == null) {
if (other.c != null)
return false;
} else if (!c.equals(other.c))
return false;
return true;
}
}
Now let's create the association object itself.
public class AC implements java.io.Serializable{
private ACId id = new ACId();
private String extra;
public AC(){
}
public ACId getId() {
return id;
}
public void setId(ACId id) {
this.id = id;
}
public A getA(){
return getId().getA();
}
public C getC(){
return getId().getC();
}
public void setC(C C){
getId().setC(C);
}
public void setA(A A){
getId().setA(A);
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AC that = (AC) o;
if (getId() != null ? !getId().equals(that.getId())
: that.getId() != null)
return false;
return true;
}
public int hashCode() {
return (getId() != null ? getId().hashCode() : 0);
}
}
At this point, it's time to map all our classes with hibernate xml configuration.
A.hbm.xml and C.hxml.xml (quiete the same).
<class name="A" table="a">
<id name="id" column="id_a" unsaved-value="0">
<generator class="identity">
<param name="sequence">a_id_seq</param>
</generator>
</id>
<!-- here you should map all others table columns -->
<!-- <property name="otherprop" column="otherprop" type="string" access="field" /> -->
<set name="ac" table="a_c" lazy="true" access="field" fetch="select" cascade="all">
<key>
<column name="id_a" not-null="true" />
</key>
<one-to-many class="AC" />
</set>
</class>
<class name="C" table="c">
<id name="id" column="id_c" unsaved-value="0">
<generator class="identity">
<param name="sequence">c_id_seq</param>
</generator>
</id>
</class>
And then association mapping file, a_c.hbm.xml.
<class name="AC" table="a_c">
<composite-id name="id" class="ACId">
<key-many-to-one name="a" class="A" column="id_a" />
<key-many-to-one name="c" class="C" column="id_c" />
</composite-id>
<property name="extra" type="string" column="extra" />
</class>
Here is the code sample to test.
A = ADao.get(1);
C = CDao.get(1);
if(A != null && C != null){
boolean exists = false;
// just check if it's updated or not
for(AC a : a.getAC()){
if(a.getC().equals(c)){
// update field
a.setExtra("extra updated");
exists = true;
break;
}
}
// add
if(!exists){
ACId idAC = new ACId();
idAC.setA(a);
idAC.setC(c);
AC AC = new AC();
AC.setId(idAC);
AC.setExtra("extra added");
a.getAC().add(AC);
}
ADao.save(A);
}
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
As for the question which event you should use for this: use the input
event, and fall back to keyup
/keydown
in older browsers.
Here’s an example, DOM0-style:
someElement.oninput = function() {
this.onkeydown = null;
// Your code goes here
};
someElement.onkeydown = function() {
// Your code goes here
};
The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The string.length
answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1
, as you’d expect.
However, for supplementary (non-BMP) symbols, things are a bit different. For example, ''.length == 2
, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.
Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and Unicode code points for this:
// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('').length; // 1 (note that `''.length == 2`!)
P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering , and you’ll see that it (incorrectly) counts as two characters.
The main problem is that serializing an entity model which has relation with other entity model(Foreign key relationship). This relation causes self referencing this will throw exception while serialization to json or xml. There are lots of options. Without serializing entity models by using custom models.Values or data from entity model data mapped to custom models(object mapping) using Automapper or Valueinjector then return request and it will serialize without any other issues. Or you can serialize entity model so first disable proxies in entity model
public class LabEntities : DbContext
{
public LabEntities()
{
Configuration.ProxyCreationEnabled = false;
}
To preserve object references in XML, you have two options. The simpler option is to add [DataContract(IsReference=true)] to your model class. The IsReference parameter enables oibject references. Remember that DataContract makes serialization opt-in, so you will also need to add DataMember attributes to the properties:
[DataContract(IsReference=true)]
public partial class Employee
{
[DataMember]
string dfsd{get;set;}
[DataMember]
string dfsd{get;set;}
//exclude the relation without giving datamember tag
List<Department> Departments{get;set;}
}
In Json format in global.asax
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
in xml format
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
var dcs = new DataContractSerializer(typeof(Employee), null, int.MaxValue,
false, /* preserveObjectReferences: */ true, null);
xml.SetSerializer<Employee>(dcs);
I did a simple test with a formula, X-(X+1)=-1, and the largest value of X I can get to work on Safari, Opera and Firefox (tested on OS X) is 9e15. Here is the code I used for testing:
javascript: alert(9e15-(9e15+1));
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.
The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.
kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.
There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin
to your paths. [Or you can install it on Win10/Bash]
Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:
data['vm']['synced_folder'].each do |i, folder|
if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
config.vm.synced_folder "#{folder['source']}", "#{folder['target']}",
id: "#{folder['id']}",
type: "rsync",
rsync__auto: "true",
rsync__exclude: ".hg/"
end
end
Once you're all set up, try vagrant up
. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto
in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!
If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.
One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.
The problem that I hit was that Write-Output actually linebreaks the output when using using PowerShell v2, at least to stdout. I was trying to write an XML text to stdout without success, because it would be hard wrapped at character 80.
The workaround was to use
[Console]::Out.Write($myVeryLongXMLTextBlobLine)
This was not an issue in PowerShell v3. Write-Output seems to be working properly there.
Depending on how the PowerShell script is invoked, you may need to use
[Console]::BufferWidth =< length of string, e.g. 10000)
before you write to stdout.
demo
branch into master
git fetch --all
demo
branch on localgit pull origin demo
master
branch. This branch will be completely changed with the code on demo
branchgit checkout master
master
branch and run this command.git reset --hard origin/demo
reset
means you will be resetting current branch
--hard
is a flag that means it will be reset without raising any merge conflict
origin/demo
will be the branch that will be considered to be the code that will forcefully overwrite current master
branch
The output of the above command will show you your last commit message on origin/demo
or demo
branch
Then, in the end, force push the code on the master
branch to your remote repo.
git push --force
Ideally you should use a transparent PNG with the circle in white and the background of the image transparent. Then you can set the background-color
of the .fb-icon
to blue on hover. So you're CSS would be:
fb-icon{
background:none;
}
fb-icon:hover{
background:#0000ff;
}
Additionally, if you don't want to use PNG's you can also use a sprite and alter the background position. A sprite is one large image with a collection of smaller images which can be used as a background image by changing the background position. So for eg, if your original circle image with the white background is 100px X 100px, you can increase the height of the image to 100px X 200px, so that the top half is the original image with the white background, while the lower half is the new image with the blue background. Then you set setup your CSS as:
fb-icon{
background:url('path/to/image/image.png') no-repeat 0 0;
}
fb-icon:hover{
background:url('path/to/image/image.png') no-repeat 0 -100px;
}
1) Maybe oveflow: hidden; will do the trick?
2) You need to set the size of each div with the text and button so that each of these divs have the same height. Then for your button:
button {
position: absolute;
bottom: 0;
}
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]
index=spell_list.index("Annual")
print(index)
The folder containing your Anaconda installation contains a subfolder called conda-meta
with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json
.
My file is called anaconda-5.0.1-py27hdb50712_1.json
, and at the bottom is more info about the version:
"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe",
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" },
"name": "anaconda",
"platform": "win",
"subdir": "win-64",
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2",
"version": "5.0.1"
(Slightly edited for brevity.)
The output from conda -V
is the conda version.
Put your JavaScript into separate .js file and use bundling & minification to obscure the code.
You can subclass UINavigationController
and override popViewController(animated: Bool)
. Beside being able to execute some code there you can also prevent the user from going back altogether, for instance to prompt to save or discard his current work.
Sample implementation where you can set a popHandler
that gets set/cleared by pushed controllers.
class NavigationController: UINavigationController
{
var popHandler: (() -> Bool)?
override func popViewController(animated: Bool) -> UIViewController?
{
guard self.popHandler?() != false else
{
return nil
}
self.popHandler = nil
return super.popViewController(animated: animated)
}
}
And sample usage from a pushed controller that tracks unsaved work.
let hasUnsavedWork: Bool = // ...
(self.navigationController as! NavigationController).popHandler = hasUnsavedWork ?
{
// Prompt saving work here with an alert
return false // Prevent pop until as user choses to save or discard
} : nil // No unsaved work, we clear popHandler to let it pop normally
As a nice touch, this will also get called by interactivePopGestureRecognizer
when the user tries to go back using a swipe gesture.
First, a short description of $on()
, $broadcast()
and $emit()
:
.$on(name, listener)
- Listens for a specific event by a given name
.$broadcast(name, args)
- Broadcast an event down through the $scope
of all children.$emit(name, args)
- Emit an event up the $scope
hierarchy to all parents, including the $rootScope
Based on the following HTML (see full example here):
<div ng-controller="Controller1">
<button ng-click="broadcast()">Broadcast 1</button>
<button ng-click="emit()">Emit 1</button>
</div>
<div ng-controller="Controller2">
<button ng-click="broadcast()">Broadcast 2</button>
<button ng-click="emit()">Emit 2</button>
<div ng-controller="Controller3">
<button ng-click="broadcast()">Broadcast 3</button>
<button ng-click="emit()">Emit 3</button>
<br>
<button ng-click="broadcastRoot()">Broadcast Root</button>
<button ng-click="emitRoot()">Emit Root</button>
</div>
</div>
The fired events will traverse the $scopes
as follows:
$scope
$scope
then $rootScope
$scope
then Controller 3 $scope
$scope
then $rootScope
$scope
$scope
, Controller 2 $scope
then $rootScope
$rootScope
and $scope
of all the Controllers (1, 2 then 3) $rootScope
JavaScript to trigger events (again, you can see a working example here):
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.broadcastAndEmit = function(){
// This will be seen by Controller 1 $scope and all children $scopes
$scope.$broadcast('eventX', {data: '$scope.broadcast'});
// Because this event is fired as an emit (goes up) on the $rootScope,
// only the $rootScope will see it
$rootScope.$emit('eventX', {data: '$rootScope.emit'});
};
$scope.emit = function(){
// Controller 1 $scope, and all parent $scopes (including $rootScope)
// will see this event
$scope.$emit('eventX', {data: '$scope.emit'});
};
$scope.$on('eventX', function(ev, args){
console.log('eventX found on Controller1 $scope');
});
$rootScope.$on('eventX', function(ev, args){
console.log('eventX found on $rootScope');
});
}]);
My approach, i think coming more from an development than an operations point of view, is:
Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.
Now, Set your values and then press Go under the Table Options Box.
You can play here with different types and check the output,
export class ParentCmp {
myVar:stirng="micronyks";
myVal:any;
myArray:Array[]=[1,2,3];
myArr:Array[];
constructor() {
if(this.myVar){
console.log('has value') // answer
}
else{
console.log('no value');
}
if(this.myVal){
console.log('has value')
}
else{
console.log('no value'); //answer
}
if(this.myArray){
console.log('has value') //answer
}
else{
console.log('no value');
}
if(this.myArr){
console.log('has value')
}
else{
console.log('no value'); //answer
}
}
}
This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:
When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.
$(document).ready(function() { $("input[id$='btnAwesome']").click(function() { // Do client side button click stuff here. }); });
The id$= is doing a regex match for an id ENDING with btnAwesome.
Edit:
Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.
The gist of it is you create a static method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.
$.ajax({ type: "POST", url: "PageName.aspx/MethodName", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Do something interesting here. } });
I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.
Just an update for Mysqli users :
$base= mysqli_connect($dbhost, $dbuser, $dbpass, $dbbase);
if (mysqli_connect_errno())
die('Could not connect: ' . mysql_error());
$return_arr = array();
if ($result = mysqli_query( $base, $sql )){
while ($row = mysqli_fetch_assoc($result)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
}
mysqli_close($base);
echo json_encode($return_arr);
You asked:
wouldn't it be easier to just accept JSON object through normal $_POST and then respond in JSON as well
From the Wikipedia on REST:
RESTful applications maximize the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimize the addition of new application-specific features on top of it
From what (little) I've seen, I believe this is usually accomplished by maximizing the use of existing HTTP verbs, and designing a URL scheme for your service that is as powerful and self-evident as possible.
Custom data protocols (even if they are built on top of standard ones, such as SOAP or JSON) are discouraged, and should be minimized to best conform to the REST ideology.
SOAP RPC over HTTP, on the other hand, encourages each application designer to define a new and arbitrary vocabulary of nouns and verbs (for example getUsers(), savePurchaseOrder(...)), usually overlaid onto the HTTP 'POST' verb. This disregards many of HTTP's existing capabilities such as authentication, caching and content type negotiation, and may leave the application designer re-inventing many of these features within the new vocabulary.
The actual objects you are working with can be in any format. The idea is to reuse as much of HTTP as possible to expose your operations the user wants to perform on those resource (queries, state management/mutation, deletion).
You asked:
Am I missing something?
There is a lot more to know about REST and the URI syntax/HTTP verbs themselves. For example, some of the verbs are idempotent, others aren't. I didn't see anything about this in your question, so I didn't bother trying to dive into it. The other answers and Wikipedia both have a lot of good information.
Also, there is a lot to learn about the various network technologies built on top of HTTP that you can take advantage of if you're using a truly restful API. I'd start with authentication.
If you have double-encoded UTF8 characters (various smart quotes, dashes, apostrophe ’, quotation mark “, etc), in mysql you can dump the data, then read it back in to fix the broken encoding.
Like this:
mysqldump -h DB_HOST -u DB_USER -p DB_PASSWORD --opt --quote-names \
--skip-set-charset --default-character-set=latin1 DB_NAME > DB_NAME-dump.sql
mysql -h DB_HOST -u DB_USER -p DB_PASSWORD \
--default-character-set=utf8 DB_NAME < DB_NAME-dump.sql
This was a 100% fix for my double encoded UTF-8.
Source: http://blog.hno3.org/2010/04/22/fixing-double-encoded-utf-8-data-in-mysql/
There is a great implementation of NavigationDrawer
that follows the Google Material Design Guidelines (and compatible down to API 10) - The MaterialDrawer library (link to GitHub). As of time of writing, May 2017, it's actively supported.
It's available in Maven Central repo. Gradle dependency setup:
compile 'com.mikepenz:materialdrawer:5.9.1'
Maven dependency setup:
<dependency>
<groupId>com.mikepenz</groupId>
<artifactId>materialdrawer</artifactId>
<version>5.9.1</version>
</dependency>
For a super succinct with jQuery approach try:
<div onclick="$(this).toggleClass('newclass')">click me</div>
Or pure JS:
<div onclick="this.classList.toggle('newclass');">click me</div>
USE style="max-width:90%;"
<select name=countries style="max-width:90%;">
<option value=af>Afghanistan</option>
<option value=ax>Åland Islands</option>
...
<option value=gs>South Georgia and the South Sandwich Islands</option>
...
</select>
Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.
To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source
Add a file to your repository like this:
mvn install:install-file \
-Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID
-DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
-Dpackaging=jar \
-DlocalRepositoryPath=/var/www/html/mavenRepository
If your domain is example.com
and the root directory of the web server is located at /var/www/html/
, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>
.
The API Guide has it all wrong (really Google?). With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map.
The actual documentation that Google provides gives you your answer. You just need to
// map is a GoogleMap object
map.isMyLocationEnabled = true
// map is a GoogleMap object
map.setMyLocationEnabled(true);
and watch the magic happen.
Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above
Try /E
To get a full list of options: xcopy /?
Always have a check before reading row.
if (SqlCommand.ExecuteScalar() == null)
{
}
Singleton beans in Spring and classes based on Singleton design pattern are quite different.
Singleton pattern ensures that one and only one instance of a particular class will ever be created per classloader where as the scope of a Spring singleton bean is described as 'per container per bean'. Singleton scope in Spring means that this bean will be instantiated only once by Spring. Spring container merely returns the same instance again and again for subsequent calls to get the bean.
Virtual classes are not the same as virtual inheritance. Virtual classes you cannot instantiate, virtual inheritance is something else entirely.
Wikipedia describes it better than I can. http://en.wikipedia.org/wiki/Virtual_inheritance
A CASE
statement is an expression, just like a boolean comparison. That means the 'AND' needs to go before the 'CASE' statement, not within it.:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND -- Added the "AND" here
CASE WHEN @day = 'Monday' THEN (Monday = 1) -- Removed "AND"
WHEN @day = 'Tuesday' THEN (Tuesday = 1) -- Removed "AND"
ELSE AND (Wednesday = 1)
END
Here is I would check the date format:
public static boolean checkFormat(String dateTimeString) {
return dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}") || dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}")
|| dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}") || dateTimeString
.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z") ||
dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}Z");
}
Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in
/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf
(its called Catalina Base and is often hidden) instead of the Apache installation directory.
open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.
<user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>
restart the server . That's all
I followed these steps (for Mac).
In /etc/ssh/sshd_config
change
#ChallengeResponseAuthentication yes
#PasswordAuthentication yes
to
ChallengeResponseAuthentication no
PasswordAuthentication no
Now generate the RSA key:
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
(For me an RSA key worked. A DSA key did not work.)
A private key will be generated in ~/.ssh/id_rsa
along with ~/.ssh/id_rsa.pub
(public key).
Now move to the .ssh folder: cd ~/.ssh
Enter rm -rf authorized_keys
(sometimes multiple keys lead to an error).
Enter vi authorized_keys
Enter :wq
to save this empty file
Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Restart the SSH:
sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd
I've worked on something similar.
Had to convert canvas Base64-encoded image to Uint8Array Blob
.
function b64ToUint8Array(b64Image) {
var img = atob(b64Image.split(',')[1]);
var img_buffer = [];
var i = 0;
while (i < img.length) {
img_buffer.push(img.charCodeAt(i));
i++;
}
return new Uint8Array(img_buffer);
}
var b64Image = canvas.toDataURL('image/jpeg');
var u8Image = b64ToUint8Array(b64Image);
var formData = new FormData();
formData.append("image", new Blob([ u8Image ], {type: "image/jpg"}));
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload", true);
xhr.send(formData);
Try this, it works for me:
var storage = null;
setLocalStorage();
function setLocalStorage() {
storage = (localStorage ? localStorage : (window.content.localStorage ? window.content.localStorage : null));
try {
storage.setItem('test_key', 'test_value');//verify if posible saving in the current storage
}
catch (e) {
if (e.name == "NS_ERROR_FILE_CORRUPTED") {
storage = sessionStorage ? sessionStorage : null;//set the new storage if fails
}
}
}
An int
array without elements is not necessarily null
. It will only be null
if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
Note: if you need to use sudo, do this:
sudo bash -c 'cat file2 >> file1'
The usual method of simply prepending sudo
to the command will fail, since the privilege escalation doesn't carry over into the output redirection.
I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:
pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-version}</version>
</dependency>
web.xml - Add multipart filter and mapping
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/springrest/*</url-pattern>
</filter-mapping>
app-context.xml - Add multipart resolver
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize">
<beans:value>10000000</beans:value>
</beans:property>
</beans:bean>
Your Controller
@RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
public @ResponseBody boolean saveStationImage(
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType,
@RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
// Do something with file
// Return results
}
Your client
public static Boolean updateStationImage(StationImage stationImage) {
if(stationImage == null) {
Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
return null;
}
Log.d(TAG, "Uploading: " + stationImage.getImageUri());
try {
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName("UTF8"));
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());
return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
Log.e(TAG + ":addStationImage", sw.toString());
}
return false;
}
That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.
I just added headers to my lambda function response and it worked like a charm
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: JSON.stringify('Hey it works'),
headers:{ 'Access-Control-Allow-Origin' : '*' }
};
return response;
};
i think the safest way would be :
private int getActionBarHeight() {
int actionBarHeight = getSupportActionBar().getHeight();
if (actionBarHeight != 0)
return actionBarHeight;
final TypedValue tv = new TypedValue();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
} else if (getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
return actionBarHeight;
}
Try this also, that is remove new { } and replace it with string.
<%: Html.TextBoxFor(x => x.Age,"0") %>
@echo off
setlocal enableextensions disabledelayedexpansion
set "search=%1"
set "replace=%2"
set "textFile=Input.txt"
for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
set "line=%%i"
setlocal enabledelayedexpansion
>>"%textFile%" echo(!line:%search%=%replace%!
endlocal
)
for /f
will read all the data (generated by the type
comamnd) before starting to process it. In the subprocess started to execute the type
, we include a redirection overwritting the file (so it is emptied). Once the do
clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.
Recoll is a fantastic full-text GUI search application for Unix/Linux that supports dozens of different formats, including PDF. It can even pass the exact page number and search term of a query to the document viewer and thus allows you to jump to the result right from its GUI.
Recoll also comes with a viable command-line interface and a web-browser interface.
You can use below code to find out principal (user email who logged in)
org.opensaml.saml2.core.impl.NameIDImpl principal =
(NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String email = principal.getValue();
This code is written on top of SAML.
None of the above worked.. but installing a new version of MySQL did the trick.
Check out Rx, Reactive Extensions for .NET. They point out that with IEnumerable you are basically 'pulling' from a stream. Linq queries over IQueryable/IEnumerable are set operations that 'suck' the results out of a set. But with the same operators over IObservable you can write Linq queries that 'react'.
For example, you could write a Linq query like (from m in MyObservableSetOfMouseMovements where m.X<100 and m.Y<100 select new Point(m.X,m.Y)).
and with the Rx extensions, that's it: You have UI code that reacts to the incoming stream of mouse movements and draws whenever you're in the 100,100 box...
Google has this to say on transferring data between accounts.
http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304
It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.
It's conveniently titled: "Moving Product Data"
http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582
As an alternative to 'save & quit', you can use git-commit's function git-commit-commit
, by default bound to C-c C-c. It will save the file and close it. Afterwards, you still have to close emacs with C-x C-c, as mentioned before. I am currently trying to find out how to make emacs quit automatically.
To show the div while selecting one value and hide while selecting another value from dropdown box: -
$('#yourselectorid').bind('change', function(event) {
var i= $('#yourselectorid').val();
if(i=="sometext") // equal to a selection option
{
$('#divid').show();
}
elseif(i=="othertext")
{
$('#divid').hide(); // hide the first one
$('#divid2').show(); // show the other one
}
});
x
is Unsigned hexadecimal integer ( 32 Bit )
p
is Pointer address
See printf on the C++ Reference. Even if both of them would write the same, I would use %p
to print a pointer.
Three possible solutions to iterate through the words of the string:
Version 1:
@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
for %%a in (%s%) do echo %%a
Version 2:
@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
set t=%s%
:loop
for /f "tokens=1*" %%a in ("%t%") do (
echo %%a
set t=%%b
)
if defined t goto :loop
Version 3:
@echo off & setlocal
set s=AAA BBB CCC DDD EEE FFF
call :sub1 %s%
exit /b
:sub1
if "%1"=="" exit /b
echo %1
shift
goto :sub1
Version 1 does not work when the string contains wildcard characters like '*' or '?'.
Versions 1 and 3 treat characters like '=', ';' or ',' as word separators. These characters have the same effect as the space character.
There is also another possibilty. I load OpenGl shaders from resources like this:
static private String vertexShaderCode;
static private String fragmentShaderCode;
static {
vertexShaderCode = readResourceAsString("/res/raw/vertex_shader.glsl");
fragmentShaderCode = readResourceAsString("/res/raw/fragment_shader.glsl");
}
private static String readResourceAsString(String path) {
Exception innerException;
Class<? extends FloorPlanRenderer> aClass = FloorPlanRenderer.class;
InputStream inputStream = aClass.getResourceAsStream(path);
byte[] bytes;
try {
bytes = new byte[inputStream.available()];
inputStream.read(bytes);
return new String(bytes);
} catch (IOException e) {
e.printStackTrace();
innerException = e;
}
throw new RuntimeException("Cannot load shader code from resources.", innerException);
}
As you can see, you can access any resource in path /res/...
Change aClass
to your class. This also how I load resources in tests (androidTests)
Static inner class is used in the builder pattern. Static inner class can instantiate it's outer class which has only private constructor. You can not do the same with the inner class as you need to have object of the outer class created prior to accessing the inner class.
class OuterClass {
private OuterClass(int x) {
System.out.println("x: " + x);
}
static class InnerClass {
public static void test() {
OuterClass outer = new OuterClass(1);
}
}
}
public class Test {
public static void main(String[] args) {
OuterClass.InnerClass.test();
// OuterClass outer = new OuterClass(1); // It is not possible to create outer instance from outside.
}
}
This will output x: 1
We need to define what is a web service before telling what are the difference between the SOAP and WSDL where the two (SOAP and WSDL) are components of a web service
Most applications are developed to interact with users, the user enters or searches for data through an interface and the application then responds to the user's input.
A Web service does more or less the same thing except that a Web service application communicates only from machine to machine or application to application. There is often no direct user interaction.
A Web service basically is a collection of open protocols that is used to exchange data between applications. The use of open protocols enables Web services to be platform independent. Software that are written in different programming languages and that run on different platforms can use Web services to exchange data over computer networks such as the Internet. In other words, Windows applications can talk to PHP, Java and Perl applications and many others, which in normal circumstances would not be possible.
How Do Web Services Work?
Because different applications are written in different programming languages, they often cannot communicate with each other. A Web service enables this communication by using a combination of open protocols and standards, chiefly XML, SOAP and WSDL. A Web service uses XML to tag data, SOAP to transfer a message and finally WSDL to describe the availability of services. Let's take a look at these three main components of a Web service application.
The Simple Object Access Protocol or SOAP is a protocol for sending and receiving messages between applications without confronting interoperability issues (interoperability meaning the platform that a Web service is running on becomes irrelevant). Another protocol that has a similar function is HTTP. It is used to access Web pages or to surf the Net. HTTP ensures that you do not have to worry about what kind of Web server -- whether Apache or IIS or any other -- serves you the pages you are viewing or whether the pages you view were created in ASP.NET or HTML.
Below is an example of a SOAP request and response message
SOAP Request:
POST /InStock HTTP/1.1
Host: www.bookshop.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.bookshop.org/prices">
<m:GetBookPrice>
<m:BookName>The Fleamarket</m:BookName>
</m:GetBookPrice>
</soap:Body>
</soap:Envelope>
SOAP Response:
POST /InStock HTTP/1.1
Host: www.bookshop.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.bookshop.org/prices">
<m:GetBookPriceResponse>
<m: Price>10.95</m: Price>
</m:GetBookPriceResponse>
</soap:Body>
</soap:Envelope>
Although both messages look the same, they carry out different methods. For instance looking at the above examples you can see that the requesting message uses the GetBookPrice
method to get the book price. The response is carried out by the GetBookPriceResponse
method, which is going to be the message that you as the "requestor" will see. You can also see that the messages are composed using XML.
WSDL is a document that describes a Web service and also tells you how to access and use its methods.
Take a look at a sample WSDL file:
<?xml version="1.0" encoding="UTF-8"?>
<definitions name ="DayOfWeek"
targetNamespace="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl"
xmlns:tns="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/wsdl/">
<message name="DayOfWeekInput">
<part name="date" type="xsd:date"/>
</message>
<message name="DayOfWeekResponse">
<part name="dayOfWeek" type="xsd:string"/>
</message>
<portType name="DayOfWeekPortType">
<operation name="GetDayOfWeek">
<input message="tns:DayOfWeekInput"/>
<output message="tns:DayOfWeekResponse"/>
</operation>
</portType>
<binding name="DayOfWeekBinding" type="tns:DayOfWeekPortType">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetDayOfWeek">
<soap:operation soapAction="getdayofweek"/>
<input>
<soap:body use="encoded"
namespace="http://www.roguewave.com/soapworx/examples"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded"
namespace="http://www.roguewave.com/soapworx/examples"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
</binding>
<service name="DayOfWeekService" >
<documentation>
Returns the day-of-week name for a given date
</documentation>
<port name="DayOfWeekPort" binding="tns:DayOfWeekBinding">
<soap:address location="http://localhost:8090/dayofweek/DayOfWeek"/>
</port>
</service>
</definitions>
The main things to remember about a WSDL file are that it provides you with:
Angular now supports min/max validators by default.
Angular provides the following validators by default. Adding the list here so that new comers can easily get to know what are the current supported default validators and google it further as per their interest.
you will get the complete list Angular validators
How to use min/max validator: From the documentation of Angular -
static min(min: number): ValidatorFn
static max(max: number): ValidatorFn
min()/max() is a static function that accepts a number parameter and returns A validator function that returns an error map with the min/max property if the validation check fails, otherwise null.
use min validator in formControl, (for further info, click here)
const control = new FormControl(9, Validators.min(10));
use max validator in formControl, (for further info, click here)
const control = new FormControl(11, Validators.max(10));
sometimes we need to add validator dynamically. setValidators() is the saviour. you can use it like the following -
const control = new FormControl(10);
control.setValidators([Validators.min(9), Validators.max(11)]);
Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).
This library files should be under cygwin\usr\include
Regards.
You can set the calendar to use only AM or PM using
calendar.set(Calendar.AM_PM, int);
0 = AM
1 = PM
Hope this helps
I installed GitHubDesktop
on Windows 10 and git.exe
is located there:
C:\Users\john\AppData\Local\GitHubDesktop\app-0.7.2\resources\app\git\cmd\git.exe
Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.
Best way is to have a contextual action bar with listview on multiselect, You can make listview as multiselect using the following code
listview.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
And now set multichoice listener for Listview ,You can see the complete implementation of multiselect listview at Android multi select listview
You never want to call thread.sleep()
on the UI
thread as it sounds like you have figured out. This freezes the UI
and is always a bad thing to do. You can use a separate Thread
and postDelayed
This SO answer shows how to do that as well as several other options
You can look at these and see which will work best for your particular situation
Make the 1 a float and float division will be used
public static void main(String d[]){
double g=1f/3;
System.out.printf("%.2f",g);
}
In my case, I added only butterknife library and forget to add annotationProcessor. By adding below line to build.gradle (App module), solved my problem.
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
To those that are incline to use GUI:
Click Right mouse button on procecdure name then select Test
Then in new window you will see script generated just add the parameters and click on Start Debugger
or F9
Hope this saves you some time.
You have to add
<script>jQuery.noConflict();</script>
after
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
The following property can be used: {{alignItems: 'center'}}
<View style={{alignItems: 'center'}}>
<Text> Hello i'm centered text</Text>
</View>
Just use two forms.
In the first form action attribute will have name of the second jdp page and your 1st button. In the second form there will be 2nd button with action attribute thats giving the name of your 3rd jsp page.
It will be like this :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="main1" method="get" action="2nd.jsp">
<input type="submit" name="ter" value="LOGOUT" >
</form>
<DIV ALIGN="left"><form name="main0" action="3rd.jsp" method="get">
<input type="submit" value="FEEDBACK">
</form></DIV>
</body>
</html>
As per Pylint documentation, the easiest is to use this chart:
So one can use:
pylint -j 0 --disable=I,E,R,W,C,F YOUR_FILES_LOC
Here's something to gather all the GET
variables in a global object, a routine optimized over several years. Since the rise of jQuery, it now seems appropriate to store them in jQuery itself, am checking with John on a potential core implementation.
jQuery.extend({
'Q' : window.location.search.length <= 1 ? {}
: function(a){
var i = a.length,
r = /%25/g, // Ensure '%' is properly represented
h = {}; // (Safari auto-encodes '%', Firefox 1.5 does not)
while(i--) {
var p = a[i].split('=');
h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
}
return h;
}(window.location.search.substr(1).split('&'))
});
Example usage:
switch ($.Q.event) {
case 'new' :
// http://www.site.com/?event=new
$('#NewItemButton').trigger('click');
break;
default :
}
Hope this helps. ;)
LocalDateTime
is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime
doesn't have such information. That's why the error occured.
If you want time-zone information, you should use ZonedDateTime
.
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"
This question still seems relevant, and the answer seems to be a moving target.
On my debian system (buster):
> update-java-alternatives -l
java-1.11.0-openjdk-amd64 1111 /usr/lib/jvm/java-1.11.0-openjdk-amd64
However, if you actually go look there, you'll see there are multiple directories and symbolic links placed there by the package system to simplify future maintenance.
The actual directory is java-11-openjdk-amd64
, with another symlink of default-java
. There is also an openjdk-11
directory, but it appears to only contain a source.zip file.
Given this, for Debian ONLY, I would guess the best value to use is /usr/lib/jvm/default-java
, as this should always be valid, even if you decide to install a totally different version of java, or even switch vendors.
The normal reason to want to know the path is because some application wants it, and you probably don't want that app to break because you did an upgrade that changed version numbers.
Use the View for your efforts in altering the position of the column: CREATE VIEW CORRECTED_POSITION AS SELECT co1_1, col_3, col_2 FROM UNORDERDED_POSITION should help.
This requests are made so some reports get produced where it is using SELECT * FROM [table_name]. Or, some business has a hierarchy approach of placing the information in order for better readability from the back end.
Thanks Dilip
Try the following lines in Dockerfile
:
RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1001 ubuntu
USER ubuntu
WORKDIR /home/ubuntu
useradd
options (see: man useradd
):
-r
, --system
Create a system account. see: Implications creating system accounts-m
, --create-home
Create the user's home directory.-d
, --home-dir HOME_DIR
Home directory of the new account.-s
, --shell SHELL
Login shell of the new account.-g
, --gid GROUP
Name or ID of the primary group.-G
, --groups GROUPS
List of supplementary groups.-u
, --uid UID
Specify user ID. see: Understanding how uid and gid work in Docker containers-p
, --password PASSWORD
Encrypted password of the new account (e.g. ubuntu
).To set the user password, add -p "$(openssl passwd -1 ubuntu)"
to useradd
command.
Alternatively add the following lines to your Dockerfile
:
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN echo 'ubuntu:ubuntu' | chpasswd
The first shell instruction is to make sure that -o pipefail
option is enabled before RUN
with a pipe in it. Read more: Hadolint: Linting your Dockerfile.
Removing .git hidden folder worked for me.
The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you’d like to return: public Object [ ] toArray(Object type[ ]).
public static void main(String[] args) {
List<String> l=new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
Object arr[]=l.toArray();
for(Object a:arr)
{
String str=(String)a;
System.out.println(str);
}
}
for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
Condensed version of @ChrisMcKenzie's answer:
var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
unable to verify the first certificate
The certificate chain is incomplete.
It means that the webserver you are connecting to is misconfigured and did not include the intermediate certificate in the certificate chain it sent to you.
It most likely looks as follows:
Intermediate certificate should be installed on the server, along with the server certificate.
Root certificates are embedded into the software applications, browsers and operating systems.
The application serving the certificate has to send the complete chain, this means the server certificate itself and all the intermediates. The root certificate is supposed to be known by the client.
Go to https://incomplete-chain.badssl.com using your browser.
It doesn't show any error (padlock in the address bar is green).
It's because browsers tend to complete the chain if it’s not sent from the server.
Now, connect to https://incomplete-chain.badssl.com using Node:
// index.js
const axios = require('axios');
axios.get('https://incomplete-chain.badssl.com')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Logs: "Error: unable to verify the first certificate".
You need to complete the certificate chain yourself.
To do that:
1: You need to get the missing intermediate certificate in .pem
format, then
2a: extend Node’s built-in certificate store using NODE_EXTRA_CA_CERTS
,
2b: or pass your own certificate bundle (intermediates and root) using ca
option.
Using openssl
(comes with Git for Windows).
Save the remote server's certificate details:
openssl s_client -connect incomplete-chain.badssl.com:443 -servername incomplete-chain.badssl.com | tee logcertfile
We're looking for the issuer (the intermediate certificate is the issuer / signer of the server certificate):
openssl x509 -in logcertfile -noout -text | grep -i "issuer"
It should give you URI of the signing certificate. Download it:
curl --output intermediate.crt http://cacerts.digicert.com/DigiCertSHA2SecureServerCA.crt
Finally, convert it to .pem
:
openssl x509 -inform DER -in intermediate.crt -out intermediate.pem -text
I'm using cross-env to set environment variables in package.json
file:
"start": "cross-env NODE_EXTRA_CA_CERTS=\"C:\\Users\\USERNAME\\Desktop\\ssl-connect\\intermediate.pem\" node index.js"
ca
optionThis option is going to overwrite the Node's built-in root CAs.
That's why we need to create our own root CA. Use ssl-root-cas.
Then, create a custom https
agent configured with our certificate bundle (root and intermediate). Pass this agent to axios
when making request.
// index.js
const axios = require('axios');
const path = require('path');
const https = require('https');
const rootCas = require('ssl-root-cas').create();
rootCas.addFile(path.resolve(__dirname, 'intermediate.pem'));
const httpsAgent = new https.Agent({ca: rootCas});
axios.get('https://incomplete-chain.badssl.com', { httpsAgent })
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Instead of creating a custom https
agent and passing it to axios
, you can place the certifcates on the https
global agent:
// Applies to ALL requests (whether using https directly or the request module)
https.globalAgent.options.ca = rootCas;
Another reason why you might get errors like "relation already exists" is if the DROP
command did not execute correctly.
One reason this can happen is if there are other sessions connected to the database which you need to close first.
I don't belive there's a way to do it within one query, but you can play tricks like this with a temporary variable:
declare @s varchar(max)
set @s = ''
select @s = @s + City + ',' from Locations
select @s
It's definitely less code than walking over a cursor, and probably more efficient.
Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
Assuming regular PCRE-style regex flavors:
If you want to check for it as a single, full word, it's \bTest\b
, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b
represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.
If you want to check for it as part of the word, it's just Test
, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.
You also need to handle exceptions from threads:
static void Main(string[] args) {
Application.ThreadException += MYThreadHandler;
}
private void MYThreadHandler(object sender, Threading.ThreadExceptionEventArgs e)
{
Console.WriteLine(e.Exception.StackTrace);
}
Whoop, sorry that was for winforms, for any threads you're using in a console application you will have to enclose in a try/catch block. Background threads that encounter unhandled exceptions do not cause the application to end.
Current Version 1.38.1
I had a problem with intending. The default Command+] is set to 4 and I wanted it to be 2. Installed "Indent 4-to-2" but it changed the entire file and not the selected text.
I changed the tab spacing in settings and it was simple.
Go to Settings
-> Text Editor
-> Tab Size
You can use the desc
command.
desc MY_TABLE
This will give you the column names, whether null is valid, and the datatype (and length if applicable)
You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):
using (new NetworkConnection(@"\\server\read", readCredentials))
using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
File.Copy(@"\\server\read\file", @"\\server2\write\file");
}
The last line should read
cbh.appendChild(document.createTextNode(cap));
Appending the text (label?) to the same container as the checkbox, not the checkbox itself
You can do it with:
NSNumber *myNumber = @15;
NSString *myNumberInString = [myNumber stringValue];
Double Click the Login Button in the NETBEANS or add the Event Listener on Click Event (ActionListener)
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
new FrmMain().setVisible(true); // Main Form to show after the Login Form..
}
});
I would suggest that a definition of 'transaction processing' would be more useful, as it covers transactions as a concept in computer science.
From wikipedia:
In computer science, transaction processing is information processing that is divided into individual, indivisible operations, called transactions. Each transaction must succeed or fail as a complete unit; it cannot remain in an intermediate state.
http://en.wikipedia.org/wiki/Transaction_processing#Implementations
Goto View -> Show Symbol Select as per screen-shot, you will get correct
Easiest way is to do this from your accounts with Xcode:
Head over Xcode -> Preferences -> Choose Accounts Tab -> View Details -> Hit refresh button on the bottom left -> Done.
Build again and it should work.
If you use a JSONB field, you must convert it to JSON with .to_json (ROR)
You can try it:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
Or in one line:
label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));
The execution time is much more faster than File and ImageIO.
I recommend you to compare the two solutions in a loop.
Nested classes are cool for hiding implementation details.
List:
class List
{
public:
List(): head(nullptr), tail(nullptr) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.
Look at std::list
or std::map
they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list
.
There is a way more convenient 'percent'-formatting option for the .format()
format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
I manage to find the answer for this solution, have to do javascript injection for this to install atob
const atob:any = require('atob');
asn1(pem: any){
asn1parser.Enc.base64ToBuf = function (b64:any) {
return asn1parser.Enc.binToBuf(atob(b64));
};
const dertest = asn1parser.PEM.parseBlock(pem).der;
var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
var buf = asn1parser.ASN1.parse(dertest);
var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );
The reason "sign" is not included is that if we included every useful one-liner in the list of built-in functions, Python wouldn't be easy and practical to work with anymore. If you use this function so often then why don't you do factor it out yourself? It's not like it's remotely hard or even tedious to do so.
Javascript has a FileSystem API. If you can deal with having the feature only work in Chrome, a good starting point would be: http://www.html5rocks.com/en/tutorials/file/filesystem/.
Make sure, that all of your class methods (updateVelocity
, updatePosition
, ...) take at least one positional argument, which is canonically named self
and refers to the current instance of the class.
When you call particle.updateVelocity()
, the called method implicitly gets an argument: the instance, here particle
as first parameter.
Use an array of valid dates format, check docs:
string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);
if(isValidFormat)
{
string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
// maybe throw an Exception
}
You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function
I don't think I saw anyone suggest this and the OP just said "script" so...
I needed to solve the same problem and my most comfortable language is Python.
I used the paramiko library. Furthermore, I also needed to issue commands for which I would need escalated permissions using sudo
. It turns out sudo can accept its password via stdin via the "-S" flag! See below:
import paramiko
ssh_client = paramiko.SSHClient()
# To avoid an "unknown hosts" error. Solve this differently if you must...
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# This mechanism uses a private key.
pkey = paramiko.RSAKey.from_private_key_file(PKEY_PATH)
# This mechanism uses a password.
# Get it from cli args or a file or hard code it, whatever works best for you
password = "password"
ssh_client.connect(hostname="my.host.name.com",
username="username",
# Uncomment one of the following...
# password=password
# pkey=pkey
)
# do something restricted
# If you don't need escalated permissions, omit everything before "mkdir"
command = "echo {} | sudo -S mkdir /var/log/test_dir 2>/dev/null".format(password)
# In order to inspect the exit code
# you need go under paramiko's hood a bit
# rather than just using "ssh_client.exec_command()"
chan = ssh_client.get_transport().open_session()
chan.exec_command(command)
exit_status = chan.recv_exit_status()
if exit_status != 0:
stderr = chan.recv_stderr(5000)
# Note that sudo's "-S" flag will send the password prompt to stderr
# so you will see that string here too, as well as the actual error.
# It was because of this behavior that we needed access to the exit code
# to assert success.
logger.error("Uh oh")
logger.error(stderr)
else:
logger.info("Successful!")
Hope this helps someone. My use case was creating directories, sending and untarring files and starting programs on ~300 servers as a time. As such, automation was paramount. I tried sshpass
, expect
, and then came up with this.
Generate your own API key here. Check out the documentation here.
You may need to set up a billing account when you try to enable the Google Cloud Translation API
in your account.
Below is a quick start example which translates two English
strings to Spanish
:
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;
public class QuickstartSample
{
public static void main(String[] arguments) throws IOException, GeneralSecurityException
{
Translate t = new Translate.Builder(
GoogleNetHttpTransport.newTrustedTransport()
, GsonFactory.getDefaultInstance(), null)
// Set your application name
.setApplicationName("Stackoverflow-Example")
.build();
Translate.Translations.List list = t.new Translations().list(
Arrays.asList(
// Pass in list of strings to be translated
"Hello World",
"How to use Google Translate from Java"),
// Target language
"ES");
// TODO: Set your API-Key from https://console.developers.google.com/
list.setKey("your-api-key");
TranslationsListResponse response = list.execute();
for (TranslationsResource translationsResource : response.getTranslations())
{
System.out.println(translationsResource.getTranslatedText());
}
}
}
Required maven dependencies for the code snippet:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-translate</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
<version>LATEST</version>
</dependency>
I also encountered a similar problem. I run Ubuntu 11.04 on VMware on a Windows 7 host OS. Virtual machines can't expose the physical wireless cards. All of that is using a virtualization layer.
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!