You probably are looking for AddReference dialog accessible from Project Context Menu (right click..)
From there you can reference dll's, after which you can reference namespaces that you need in your code.
Mustache pros:
Mustache cons:
Handlebars pros:
Handlebars cons:
Source: The client-side templating throwdown: mustache, handlebars, dust.js, and more
In my case @Ilya Dyoshin's solution didn't work: The mediatype "*" was not allowed. I fix this error by adding a new converter to the restTemplate this way during initialization of the MockRestServiceServer:
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =
new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(
Arrays.asList(
MediaType.APPLICATION_JSON,
MediaType.APPLICATION_OCTET_STREAM));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
mockServer = MockRestServiceServer.createServer(restTemplate);
(Based on the solution proposed by Yashwant Chavan on the blog named technicalkeeda)
JN Gerbaux
First consider if you really need to iterate over rows in a DataFrame. See this answer for alternatives.
If you still need to iterate over rows, you can use methods below. Note some important caveats which are not mentioned in any of the other answers.
for index, row in df.iterrows():
print(row["c1"], row["c2"])
for row in df.itertuples(index=True, name='Pandas'):
print(row.c1, row.c2)
itertuples()
is supposed to be faster than iterrows()
But be aware, according to the docs (pandas 0.24.2 at the moment):
iterrows: dtype
might not match from row to row
Because iterrows returns a Series for each row, it does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames). To preserve dtypes while iterating over the rows, it is better to use itertuples() which returns namedtuples of the values and which is generally much faster than iterrows()
iterrows: Do not modify rows
You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect.
Use DataFrame.apply() instead:
new_df = df.apply(lambda x: x * 2)
itertuples:
The column names will be renamed to positional names if they are invalid Python identifiers, repeated, or start with an underscore. With a large number of columns (>255), regular tuples are returned.
See pandas docs on iteration for more details.
I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date
constructor, but others will not. For example, Chrome 18 gives
> new Date("66")
Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)
This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11")
is greater than new Date("66")
and this is obviously the opposite of the desired effect).
Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().
In the end, the code becomes:
$.validator.addMethod(
"greaterThan",
function(value, element, params) {
var target = $(params).val();
var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
if (isValueNumeric && isTargetNumeric) {
return Number(value) > Number(target);
}
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date(target);
}
return false;
},
'Must be greater than {0}.');
For windows:
import pip
help(pip)
shows the version at the end of the help file.
A simple solution is to set an option with a blank value ""
I found this eliminates the extra undefined option.
Try this
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custom_actionbar, menu);
menu.setGroupVisible(...);
}
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
Swift 2.0:
Add this method to VC or to Extension of UIColor.
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
return UIColor.grayColor()
}
let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
Usage :
loginButton.tintColor = self.colorWithHexString("#be1337")
OR
let hexColor = self.colorWithHexString("#be1337")
See Python's document on sharing global variables across modules:
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).
config.py:
x = 0 # Default value of the 'x' configuration setting
Import the config module in all modules of your application; the module then becomes available as a global name.
main.py:
import config print (config.x)
or
from config import x print (x)
In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/14/2012 10:31:48";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
DateTime date11 = new DateTime(d1);
DateTime date22 = new DateTime(d2);
int days = Days.daysBetween(date11.withTimeAtStartOfDay(), date22.withTimeAtStartOfDay()).getDays();
int hours = Hours.hoursBetween(date11, date22).getHours() % 24;
int minutes = Minutes.minutesBetween(date11, date22).getMinutes() % 60;
int seconds = Seconds.secondsBetween(date11, date22).getSeconds() % 60;
if (hours > 0 || minutes > 0 || seconds > 0) {
days = days + 1;
}
System.out.println(days);
} catch (Exception e) {
e.printStackTrace();
}
}
This will give date diff for the same day as well
You can also use tables to accomplish this, like:
.pdf {
display: table;
}
.pdf:before {
display: table-cell;
vertical-align: middle;
}
Here is an example: https://jsfiddle.net/ar9fadd0/2/
EDIT: You can also use flex to accomplish this:
.pdf {
display: flex;
}
.pdf:before {
display: flex;
align-items: center;
}
Here is an example: https://jsfiddle.net/ctqk0xq1/1/
The only way I was able to get autoplay to work was to use the iframe player api.
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '480',
width: '853',
videoId: 'JW5meKfy3fY',
playerVars: {
'autoplay': 1,
'showinfo': 0,
'controls': 0
}
});
}
</script>
Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html
One way to handle this is to create a dynamic javascript file with the URLs embedded in it. Here are the steps (if you are using Spring MVC)
@RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public String dynamicJS(HttpServletRequest request) {
return "Your javascript code....";
}
Symptoms
You install an application that uses Microsoft Virtual WiFi technology on a computer that is running Windows 7 or Windows Server 2008 R2. However, the application does not work after the computer restarts. Additionally, you receive an error message that resembles the following:The hosted network couldn't be started. The group or resource is not in the correct state to perform the requested operation.
Cause
This issue occurs because the Virtual Wi-Fi filter driver does not create the Virtual Wi-Fi Adapter correctly when a PNP resource rebalance occurs during the startup process.Notes
1.This issue may occur when a Plug and Play (PNP) resource rebalance occurs during the startup process. The PNP resource rebalance is usually triggered by a change to the hardware configuration.
2.If you open Device Manager when this issue occurs, you notice that the Virtual WiFi Adapter is not created.
If you can't restart your hostednetwork after rebooting the OS ,just Try this hotfix .It fixed my problem. Or try to figure it out by yourself according to the Symptoms and Cause mentioned at the start of my answer.
if os.path.exists(filePath):
#the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
#the file does not exists but write privileges are given
else:
#can not write there
Note that path.exists
can fail for more reasons than just the file is not there
so you might have to do finer tests like testing if the containing directory exists and so on.
After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.
Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.
You can use the comparison operators to compare strings. A strcmp
function could be defined like this:
function strcmp(a, b) {
if (a.toString() < b.toString()) return -1;
if (a.toString() > b.toString()) return 1;
return 0;
}
Edit Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:
function strcmp(a, b) {
a = a.toString(), b = b.toString();
for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
if (i === n) return 0;
return a.charAt(i) > b.charAt(i) ? -1 : 1;
}
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"}
is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
I always have to use the brackets when I use the ALTER SCHEMA
query in SQL, or I get an error message.
Swift 4.2 / 5
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground),
name: Notification.Name.UIApplicationWillEnterForeground,
object: nil)
}
@objc func willEnterForeground() {
// do what's needed
}
C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:
Supported Types
You can declare a property for any Objective-C class, Core Foundation data type, or “plain old data” (POD) type (see C++ Language Note: POD Types). For constraints on using Core Foundation types, however, see “Core Foundation.”
POD does not include C arrays. See http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html
If you need an array, you should use NSArray or NSData.
The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.
in every version of bootstrap,you can do it manually
this do most things that you want for rtl
Note (2015): Both question and the answer below apply to the old, deprecated version 2.x of Twitter Bootstrap.
This feature of making and element "sticky" is built into the Twitter's Bootstrap and it is called Affix. All you have to do is to add:
<div data-spy="affix" data-offset-top="121">
... your navbar ...
</div>
around your tag and do not forget to load the Bootstrap's JS files as described in the manual. Data attribute offset-top
tells how many pixels the page is scrolled (from the top) to fix you menu component. Usually it is just the space to the top of the page.
Note: You will have to take care of the missing space when the menu will be fixed. Fixing means cutting it off out of your page layer and pasting in different layer that does not scroll. I am doing the following:
<div style="height: 77px;">
<div data-spy="affix" data-offset-top="121">
<div style="position: relative; height: 0; width: 100%;">
<div style="position: absolute; top: 0; left: 0;">
... my menu ...
</div>
</div>
</div>
</div>
where 77px
is the height of my affixed component.
Just for fun I took Siddharth's suggestion of separate textboxes and did comboboxes. If anybody's interested, add a userform with three comboboxes named cboDay, cboMonth and cboYear and arrange them left to right. Then paste the code below into the UserForm's code module. The required combobox properties are set in UserFormInitialization, so no additional prep should be required.
The tricky part is changing the day when it becomes invalid because of a change in year or month. This code just resets it to 01 when that happens and highlights cboDay.
I haven't coded anything like this in a while. Hopefully it will be of interest to somebody, someday. If not it was fun!
Dim Initializing As Boolean
Private Sub UserForm_Initialize()
Dim i As Long
Dim ctl As MSForms.Control
Dim cbo As MSForms.ComboBox
Initializing = True
With Me
With .cboMonth
' .AddItem "month"
For i = 1 To 12
.AddItem Format(i, "00")
Next i
.Tag = "DateControl"
End With
With .cboDay
' .AddItem "day"
For i = 1 To 31
.AddItem Format(i, "00")
Next i
.Tag = "DateControl"
End With
With .cboYear
' .AddItem "year"
For i = Year(Now()) To Year(Now()) + 12
.AddItem i
Next i
.Tag = "DateControl"
End With
DoEvents
For Each ctl In Me.Controls
If ctl.Tag = "DateControl" Then
Set cbo = ctl
With cbo
.ListIndex = 0
.MatchRequired = True
.MatchEntry = fmMatchEntryComplete
.Style = fmStyleDropDownList
End With
End If
Next ctl
End With
Initializing = False
End Sub
Private Sub cboDay_Change()
If Not Initializing Then
If Not IsValidDate Then
ResetMonth
End If
End If
End Sub
Private Sub cboMonth_Change()
If Not Initializing Then
ResetDayList
If Not IsValidDate Then
ResetMonth
End If
End If
End Sub
Private Sub cboYear_Change()
If Not Initializing Then
ResetDayList
If Not IsValidDate Then
ResetMonth
End If
End If
End Sub
Function IsValidDate() As Boolean
With Me
IsValidDate = IsDate(.cboMonth & "/" & .cboDay & "/" & .cboYear)
End With
End Function
Sub ResetDayList()
Dim i As Long
Dim StartDay As String
With Me.cboDay
StartDay = .Text
For i = 31 To 29 Step -1
On Error Resume Next
.RemoveItem i - 1
On Error GoTo 0
Next i
For i = 29 To 31
If IsDate(Me.cboMonth & "/" & i & "/" & Me.cboYear) Then
.AddItem Format(i, "0")
End If
Next i
On Error Resume Next
.Text = StartDay
If Err.Number <> 0 Then
.SetFocus
.ListIndex = 0
End If
End With
End Sub
Sub ResetMonth()
Me.cboDay.ListIndex = 0
End Sub
Short of using a video camera, no.
Many youtube videos for demonstrating iPhone applications are made with a screen grabber application (such as iShowU, ScreenFlow, or Snapz Pro) and the simulator. Be aware that the speed of response in the simulator can be dramatically different than a device - so it's possible to get effects (and miss) with the simulator you'll never see on a device. In particular, default animations can flash by in the simulator, where they just look quick on a device.
Adegoke A, Amit
I guess one crucial point you people are missing is difference between data and pointers as explained in this section.
Pointer : pointer to other nodes.
Data :- In context of database indexes, data is just another pointer to real data (row) which reside somewhere else.
Hence in case of B tree each node has three information keys, pointers to data associated with the keys and pointer to child nodes.
In B+ tree internal node keep keys and pointers to child node while leaf node keep keys and pointers to associated data. This allows more number of key for a given size of node. Size of node is determined mainly by block size.
Advantage of having more key per node is explained well above so I will save my typing effort.
Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.
Save it as a .ps1 file and then execute
powershell -file "path\to your\start stop nation service command file.ps1"
Below gives me opposite of what you have. (Notice Group column)
SELECT
*
FROM
myTable
GROUP BY
Group_value,
ID
ORDER BY
count(Group_value)
Let me know if this is fine with you...
I am trying to get what you want too...
This code should work for you
$("#intro").owlCarousel ({
slideSpeed : 800,
autoPlay: 6000,
items : 1,
stopOnHover : true,
itemsDesktop : [1199,1],
itemsDesktopSmall : [979,1],
itemsTablet : [768,1],
});
We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).
My fingers have memorized our process:
git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>
A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.
I encountered the same issue. You have to use ActiveX or Flash (or Java). The good thing is that it doesn't have to be invasive. I have a simple ActiveX method that will return the size of the to-be-uploaded file.
If you go with Flash, you can even do some fancy js/css to cusomize the uploading experience--only using Flash (as a 1x1 "movie") to access it's file uploading features.
Or, rather than having an extra event handler to prevent another handler, you can use the Event Object argument passed to your click event handler to determine whether a child was clicked. target
will be the clicked element and currentTarget
will be the .header div:
$(".header").click(function(e){
//Do nothing if .header was not directly clicked
if(e.target !== e.currentTarget) return;
$(this).children(".children").toggle();
});
Click on the WAMP server icon and from the menu under Config Files select
httpd.conf
. A long text file will open up in notepad. In this file scroll
down to the line that reads Port 80
and change this to read Port 8080
,
Save the file and close notepad. Once again click on the wamp server icon and
select restart all services. One more change needs to be made before we are
done. In Windows Explorer find the location where WAMP server was installed
which is by Default C:\Wamp
.
Update : On a newer version of WAMP, click the WAMP server icon > Apache > httpd.conf
, then change the line Listen 80
to Listen 8080
or any port you want.
Update: On 3.1.6 version of WAMP , right click on the wamp server icon in the taskbar ,select "tools"-> "Port used by Apache:80" -> "use a port other than 80", an input box will pop up , input a new port in it,click confirm button , then restart wamp .
I've been using Python for a few years and I've never run in to a case where I've needed lambda. Really, as the tutorial states, it's just for syntactic sugar.
Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:
InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );
Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.
Do the following:
<html>
)This is a hacky way, but it's the easiest way to do this.
Update your IDE with the latest PDT version for better code formatting. On the main menu click Help -> Install New Software and then add the following URL in the Work with field:
http://download.eclipse.org/tools/pdt/updates/4.0.1
When asked for the name, give it PDT4.0.1
and then move along with the update or install.
It will see if the appropriate PDT is already installed or if it is a lower version, which then would be updated.
After restarting or applying the changes go to Windows -> Preferences on the side bar and expand PHP -> Code Style. Here you will see an item named Formatter. Select it and choose the active profile for the code formating. Thats it.
The next time you format it, it will choose a format according to the chosen active profile.
Hope it helps.
Use struct.pack
to convert the integer values into binary bytes, then write the bytes. E.g.
newFile.write(struct.pack('5B', *newFileBytes))
However I would never give a binary file a .txt
extension.
The benefit of this method is that it works for other types as well, for example if any of the values were greater than 255 you could use '5i'
for the format instead to get full 32-bit integers.
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
Support for single character marker labels was added to Google Maps in version 3.21 (Aug 2015). See the new marker label API.
You can now create your label marker like this:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.latitude, result.longitude),
icon: markerIcon,
label: {
text: 'A'
}
});
If you would like to see the 1 character restriction removed, please vote for this issue.
Update October 2016:
This issue was fixed and as of version 3.26.10, Google Maps natively supports multiple character labels in combination with custom icons using MarkerLabels.
Try adding window
before location
(i.e. window.location
).
As you can see in the code of angular-JS ( https://github.com/angular/angular.js/blob/master/src/ng/filter/orderBy.js ) ng-repeat does not work with objects. Here is a hack with sortFunction.
http://jsfiddle.net/sunnycpp/qaK56/33/
<div ng-app='myApp'>
<div ng-controller="controller">
<ul>
<li ng-repeat="test in testData | orderBy:sortMe()">
Order = {{test.value.order}} -> Key={{test.key}} Name=:{{test.value.name}}
</li>
</ul>
</div>
</div>
myApp.controller('controller', ['$scope', function ($scope) {
var testData = {
a:{name:"CData", order: 2},
b:{name:"AData", order: 3},
c:{name:"BData", order: 1}
};
$scope.testData = _.map(testData, function(vValue, vKey) {
return { key:vKey, value:vValue };
}) ;
$scope.sortMe = function() {
return function(object) {
return object.value.order;
}
}
}]);
The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).
As RFC 5280 says:
The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.
X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.
The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".
In the context of the article you're linking to, the subject would be the user/owner of the cert.
Try this:
input[type="radio"] {
margin-top: -1px;
vertical-align: middle;
}
You can run the application file of project in simulator - not .ipa file.
You can get it from:
Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->
then u can see many files like 0CD04F....
find out your application file through open it.
You can copy the file to your system(which system simulator u need run ) location Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->
Then open the simulator 4.3 (its your simulator version where you pasted). You can see the application installed there.
Getting from other people:
Please tell them to find out Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->
then you can see many files like 0CD04F....
from their system and receive that file from them.
After they have got the file, please copy and paste the file in to your system `Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->(paste the file here).
Then you can see the app is installed in your system simulator and you can run it after clicking the file.
Please install http://asepsis.binaryage.com/ and then reboot your mac.
ASEPSIS redirect all .DS_Store on your mac to /usr/local/.dscage
After that, You could delete recursively all .DS_Store from your mac.
find ~ -name ".DS_Store" -delete
or
find <your path> -name ".DS_Store" -delete
You should repeat procedure after each Mac major update.
May be?
result.map(&:attributes)
If you need symbols keys:
result.map { |r| r.attributes.symbolize_keys }
Once when I was interviewing for Microsoft in college, the guy asked me how to detect a cycle in a linked list.
Having discussed in class the prior week the optimal solution to the problem, I started to tell him.
He told me, "No, no, everybody gives me that solution. Give me a different one."
I argued that my solution was optimal. He said, "I know it's optimal. Give me a sub-optimal one."
At the same time, it's a pretty good problem.
To make the browser downloads a file you need to make the request like that:
function downloadFile(urlToSend) {
var req = new XMLHttpRequest();
req.open("GET", urlToSend, true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=fileName;
link.click();
};
req.send();
}
What I can do to fix this (other than installing a real SSL certificate).
You can't.
On an https webpage you can only make AJAX request to https webpage (With a certificate trusted by the browser, if you use a self-signed one, it will not work for your visitors)
JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.
NamedParameterJDBCTemplate supports named parameters, you can use them like that:
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("name", name);
paramSource.addValue("city", city);
jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
Netbeans has great C and C++ support. Some people complain that it's bloated and slow, but I've been using it almost exclusively for personal projects and love it. The code assistance feature is one of the best I've seen.
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.
Below code has been tested and does exactly what is requested in the original question.
Parameters: %30s Column of 30 char and text right align. %10d integer notation, %10s will also work. Added clarification included on code comments.
stringarray[0]="a very long string.........."
# 28Char (max length for this column)
numberarray[0]=1122324333
# 10digits (max length for this column)
anotherfield[0]="anotherfield"
# 12Char (max length for this column)
stringarray[1]="a smaller string....."
numberarray[1]=123124343
anotherfield[1]="anotherfield"
printf "%30s %10d %13s" "${stringarray[0]}" ${numberarray[0]} "${anotherfield[0]}"
printf "\n"
printf "%30s %10d %13s" "${stringarray[1]}" ${numberarray[1]} "${anotherfield[1]}"
# a var string with spaces has to be quoted
printf "\n Next line will fail \n"
printf "%30s %10d %13s" ${stringarray[0]} ${numberarray[0]} "${anotherfield[0]}"
a very long string.......... 1122324333 anotherfield
a smaller string..... 123124343 anotherfield
http uses port 80, and understandably, your internet browser will automatically use that port when you type in an address - unless you specify another port. Now, when running a web server on your computer, you need to access that server somehow - and since port 80 is already busy, you need to use a different port to successfully connect to it. Although any open port is fair game, usually such a server is configured to use port 8080, hence when accessing your server you type in:
http:// (protocol) localhost (your computer) :8080 (port 8080) / (path pointing to the root of the public folder of your server)
Taken from http://en.wikipedia.org/wiki/Deadlock:
In concurrent computing, a deadlock is a state in which each member of a group of actions, is waiting for some other member to release a lock
A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.
A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.
Livelock is a risk with some algorithms that detect and recover from deadlock. If more than one process takes action, the deadlock detection algorithm can be repeatedly triggered. This can be avoided by ensuring that only one process (chosen randomly or by priority) takes action.
As mentioned by few users, below code can help find all the fields in a given class.
TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
String name=method.getName();
if(name.startsWith("get"))
{
System.out.println(name.substring(3));
}else if(name.startsWith("is"))
{
System.out.println(name.substring(2));
}
}
However a more interesting approach is below:
With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)
TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();
Map<String,Object> props = m.convertValue(testObject, Map.class);
for(Map.Entry<String, Object> entry : props.entrySet()){
if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
}
In case of the error:
"Internal compiler error: java.lang.OutOfMemoryError: GC overhead limit exceeded at java.lang.AbstractStringBuilder"
increase the java heap space to 2GB i.e., -Xmx2g.
I appreciate this wasn't the OP's issue, but I ran into this issue recently with a different cause. For reference, I was using the Liquibase Maven plugin (liquibase-maven-plugin:3.1.1) with SQL Server.
Anyway, I'd erroneously copied and pasted a SQL Server "use" statement into one of my scripts that switches databases, so liquibase was running and updating the DATABASECHANGELOGLOCK
, acquiring the lock in the correct database, but then switching databases to apply the changes. Not only could I NOT see my changes or liquibase audit in the correct database, but of course, when I ran liquibase again, it couldn't acquire the lock, as the lock had been released in the "wrong" database, and so was still locked in the "correct" database. I'd have expected liquibase to check the lock was still applied before releasing it, and maybe that is a bug in liquibase (I haven't checked yet), but it may well be addressed in later versions! That said, I suppose it could be considered a feature!
Quite a bit of a schoolboy error, I know, but I raise it here in case anyone runs into the same problem!
Another alternative is String.format()
. We are using it in jcabi-log (static utility wrapper around slf4j).
Logger.debug(this, "some variable = %s", value);
It's much more maintainable and extendable. Besides, it's easy to translate.
start MYSQL in safe mode
mysqld_safe --skip-grant-tables &
Connect to MYSQL server
mysql -u root
run SQL commands to reset password:
use mysql;
SET GLOBAL default_password_lifetime = 0;
SET PASSWORD = PASSWORD('new_password');
Last step, restart your mysql service
This is always cool, because when you get exported lists from, say Oracle, then you get records spanning several lines, which in turn can be interesting for, say, cvs files, so beware.
Anyhow, Rob's answer is good, but I would advise using something else than @, try a few more, like §§@@§§ or something, so it will have a chance for some uniqueness. (But still, remember the length of the varchar
/nvarchar
field you are inserting into..)
If you're looking for a shortcut for writing out all of your selectors, then a CSS Preprocessor (Sass, LESS, Stylus, etc.) can do what you're looking for. However, the generated styles must be valid CSS.
Sass:
#applyCSS {
.ui-bar-a {
color: blue;
}
.ui-bar-a .ui-link-inherit {
color: orange;
}
background: #CCC;
}
Generated CSS:
#applyCSS {
background: #CCC;
}
#applyCSS .ui-bar-a {
color: blue;
}
#applyCSS .ui-bar-a .ui-link-inherit {
color: orange;
}
Rather than use "d", why not "p". I am not sure if the "p *" will work. I didn't try that. You can; however use the following script"
#!/bin/bash
#
MAIL_INDEX=$(printf 'h a\nq\n' | mail | egrep -o '[0-9]* unread' | awk '{print $1}')
markAllRead=
for (( i=1; i<=$MAIL_INDEX; i++ ))
do
markAllRead=$markAllRead"p $i\n"
done
markAllRead=$markAllRead"q\n"
printf "$markAllRead" | mail
I think you want to test
your RegExp in TypeScript, so you have to do like this:
var trigger = "2",
regexp = new RegExp('^[1-9]\d{0,2}$'),
test = regexp.test(trigger);
alert(test + ""); // will display true
You should read MDN Reference - RegExp, the RegExp
object accepts two parameters pattern
and flags
which is nullable(can be omitted/undefined). To test your regex you have to use the .test()
method, not passing the string you want to test inside the declaration of your RegExp!
Why test + ""
?
Because alert()
in TS accepts a string as argument, it is better to write it this way. You can try the full code here.
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
name_only=file_name[:filename.index(".")
That will give you the file name up to the first ".", which would be the most common.
.h1 {
width: -moz-fit-content;
width: fit-content;
// workaround for IE11
display: table;
}
All modern browsers support width: fit-content
for that.
For IE11 we could emulate this behavior with display: table
which doesn't break margin collapse like display: inline-block
or float: left
.
I think I have a solution to the password problem. This single argument is truly amazing. It asks for the password once, and than never asks for it again. Even if you put it onto another program, it will not ask for the password. Here it is:
runas /user:Administrator /savecred Example1Server.exe
For Angular 9+ You can add headers and params directly without the key-value notion:
const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params});
There is more than one type of UUID, so "how safe" depends on which type (which the UUID specifications call "version") you are using.
Version 1 is the time based plus MAC address UUID. The 128-bits contains 48-bits for the network card's MAC address (which is uniquely assigned by the manufacturer) and a 60-bit clock with a resolution of 100 nanoseconds. That clock wraps in 3603 A.D. so these UUIDs are safe at least until then (unless you need more than 10 million new UUIDs per second or someone clones your network card). I say "at least" because the clock starts at 15 October 1582, so you have about 400 years after the clock wraps before there is even a small possibility of duplications.
Version 4 is the random number UUID. There's six fixed bits and the rest of the UUID is 122-bits of randomness. See Wikipedia or other analysis that describe how very unlikely a duplicate is.
Version 3 is uses MD5 and Version 5 uses SHA-1 to create those 122-bits, instead of a random or pseudo-random number generator. So in terms of safety it is like Version 4 being a statistical issue (as long as you make sure what the digest algorithm is processing is always unique).
Version 2 is similar to Version 1, but with a smaller clock so it is going to wrap around much sooner. But since Version 2 UUIDs are for DCE, you shouldn't be using these.
So for all practical problems they are safe. If you are uncomfortable with leaving it up to probabilities (e.g. your are the type of person worried about the earth getting destroyed by a large asteroid in your lifetime), just make sure you use a Version 1 UUID and it is guaranteed to be unique (in your lifetime, unless you plan to live past 3603 A.D.).
So why doesn't everyone simply use Version 1 UUIDs? That is because Version 1 UUIDs reveal the MAC address of the machine it was generated on and they can be predictable -- two things which might have security implications for the application using those UUIDs.
This error will also occur if you call .ps1
file from a .bat
file and file path has spaces.
The fix is to make sure there are no spaces in the path of .ps1
file.
user6779899's answer is neat and more generic However, based on the request by Imad El Hitti, a light weight solution is proposed here. This can be used when a child component is tightly connected to one parent only.
Parent.component.ts
export class Notifier {
valueChanged: (data: number) => void = (d: number) => { };
}
export class Parent {
notifyObj = new Notifier();
tellChild(newValue: number) {
this.notifyObj.valueChanged(newValue); // inform child
}
}
Parent.component.html
<my-child-comp [notify]="notifyObj"></my-child-comp>
Child.component.ts
export class ChildComp implements OnInit{
@Input() notify = new Notifier(); // create object to satisfy typescript
ngOnInit(){
this.notify.valueChanged = (d: number) => {
console.log(`Parent has notified changes to ${d}`);
// do something with the new value
};
}
}
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Here is a solution for reading - not writing - the extended properties based on what I found on this page and at help with shell32 objects.
To be clear this is a hack. It looks like this code will still run on Windows 10 but will hit on some empty properties. Previous version of Windows should use:
var i = 0;
while (true)
{
...
if (String.IsNullOrEmpty(header)) break;
...
i++;
On Windows 10 we assume that there are about 320 properties to read and simply skip the empty entries:
private Dictionary<string, string> GetExtendedProperties(string filePath)
{
var directory = Path.GetDirectoryName(filePath);
var shell = new Shell32.Shell();
var shellFolder = shell.NameSpace(directory);
var fileName = Path.GetFileName(filePath);
var folderitem = shellFolder.ParseName(fileName);
var dictionary = new Dictionary<string, string>();
var i = -1;
while (++i < 320)
{
var header = shellFolder.GetDetailsOf(null, i);
if (String.IsNullOrEmpty(header)) continue;
var value = shellFolder.GetDetailsOf(folderitem, i);
if (!dictionary.ContainsKey(header)) dictionary.Add(header, value);
Console.WriteLine(header +": " + value);
}
Marshal.ReleaseComObject(shell);
Marshal.ReleaseComObject(shellFolder);
return dictionary;
}
As mentioned you need to reference the Com assembly Interop.Shell32.
If you get an STA related exception, you will find the solution here:
Exception when using Shell32 to get File extended properties
I have no idea what those properties names would be like on a foreign system and couldn't find information about which localizable constants to use in order to access the dictionary. I also found that not all the properties from the Properties dialog were present in the dictionary returned.
BTW this is terribly slow and - at least on Windows 10 - parsing dates in the string retrieved would be a challenge so using this seems to be a bad idea to start with.
On Windows 10 you should definitely use the Windows.Storage library which contains the SystemPhotoProperties, SystemMusicProperties etc. https://docs.microsoft.com/en-us/windows/uwp/files/quickstart-getting-file-properties
And finally, I posted a much better solution that uses WindowsAPICodePack there
RUN
and ENTRYPOINT
are two different ways to execute a script.
RUN
means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won't be run after that: your final image is supposed to reflect the result of that script.
ENTRYPOINT
means your image (which has not executed the script yet) will create a container, and runs that script.
In both cases, the script needs to be added, and a RUN chmod +x /bootstrap.sh
is a good idea.
It should also start with a shebang (like #!/bin/sh
)
Considering your script (bootstrap.sh
: a couple of git config --global
commands), it would be best to RUN
that script once in your Dockerfile
, but making sure to use the right user (the global git config
file is %HOME%/.gitconfig
, which by default is the /root
one)
Add to your Dockerfile:
RUN /bootstrap.sh
Then, when running a container, check the content of /root/.gitconfig
to confirm the script was run.
You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.
Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.
To read up on this, check out this thread (from my very first Stackoverflow post no less)!
Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate
You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.
Try using the exact, or absolute, path.
Just to make concrete emory's answer, the executable code is the following :
Map<String,Callable<USer>> map = new HashMap<String,Callable<User>>();
map.put( "test" , new Callable<User> () { public User call (){ return fillUser("test" ); }} ) ;
map.put( "admin" , new Callable<Utente> () { public Utente call (){ return fillUser("admin" ); }} ) ;
where user is a POJO, and then
User user = map.get(USERNAME).call();
finally the called method is somewhere :
private User fillUser(String x){
User user = new User();
// set something in User
return user;
}
It's not a big issue i faced. Just clean the project and restart your xcode!! Hope it will be working for you! It's working for me. :)
Or First of all clean the project by holding Shift(?)+Command(?)+K or Select Product > Clean
Then
Go to XCode Menu> Preference
Select Account > Team > View Details
Select any Provisioning profile from Provisioning Profiles list
Right click > Select Show in Finder. Then you will see all lists of provisioning profiles
Select all provisionaling list from the folder and move it to trash
Download All provisioning profiles by clicking Download All below Provisioning Profile lists.
Now, Run again and it should Work!
I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.
Basically the solution is to use CSS to hide the <input>
element and style a <label>
around it to look like a button. Click the 'Run code snippet' button to see the results.
I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.
label.cameraButton {_x000D_
display: inline-block;_x000D_
margin: 1em 0;_x000D_
_x000D_
/* Styles to make it look like a button */_x000D_
padding: 0.5em;_x000D_
border: 2px solid #666;_x000D_
border-color: #EEE #CCC #CCC #EEE;_x000D_
background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<label class="cameraButton">Take a picture_x000D_
<input type="file" accept="image/*;capture=camera">_x000D_
</label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Add an id attribute to a html tag
<ul class="nav nav-tabs">
<li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
<li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
<li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
<div class="tab-pane" id="aaa">...Content...</div>
<div class="tab-pane" id="bbb">...Content...</div>
<div class="tab-pane" id="ccc">...Content...</div>
</div>
Then using JQuery
$("#tab_aaa").tab('show');
If you are using the MySql Workbench you can set this by opening up the administrator view and select the Advanced tab. The top section is "Localization" and the first check box should be "default-time-zone". Check that box and then enter your desired time zone, restart the server and you should be good to go.
I like Ruby Warrior. It is still somewhat under development, but it is a great game with a clever interface.
There is no default for Boolean
. Boolean
must be constructed with a boolean
or a String
. If the object is unintialized, it would point to null
.
The default value of primitive boolean
is false
.
http://download.oracle.com/javase/6/docs/api/java/lang/Boolean.html
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
This is pretty old, but I found following worth noting:
PS N:\> (measure-command {Get-WmiObject -Class Win32_LogicalDisk|select -property deviceid|%{$_.deviceid}|out-host}).totalmilliseconds
...
928.7403
PS N:\> (measure-command {gdr -psprovider 'filesystem'|%{$_.name}|out-host}).totalmilliseconds
...
169.474
Without filtering properties, on my test system, 4319.4196ms to 1777.7237ms. Unless I need a PS-Drive object returned, I'll stick with WMI.
EDIT: I think we have a winner: PS N:> (measure-command {[System.IO.DriveInfo]::getdrives()|%{$_.name}|out-host}).to??talmilliseconds 110.9819
(Following is the text of the linked section of the Wikipedia entry.)
A typical URL containing a query string is as follows:
http://server/path/program?query_string
When a server receives a request for such a page, it runs a program (if configured to do so), passing the query_string unchanged to the program. The question mark is used as a separator and is not part of the query string.
A link in a web page may have a URL that contains a query string, however, HTML defines three ways a web browser can generate the query string:
The main use of query strings is to contain the content of an HTML form, also known as web form. In particular, when a form containing the fields field1, field2, field3 is submitted, the content of the fields is encoded as a query string as follows:
field1=value1&field2=value2&field3=value3...
field1=value1&field1=value2&field1=value3...
For each field of the form, the query string contains a pair field=value. Web forms may include fields that are not visible to the user; these fields are included in the query string when the form is submitted
This convention is a W3C recommendation. W3C recommends that all web servers support semicolon separators in addition to ampersand separators[6] to allow application/x-www-form-urlencoded query strings in URLs within HTML documents without having to entity escape ampersands.
Technically, the form content is only encoded as a query string when the form submission method is GET. The same encoding is used by default when the submission method is POST, but the result is not sent as a query string, that is, is not added to the action URL of the form. Rather, the string is sent as the body of the HTTP request.
Here's a lazy version of @stephen's answer
import html.parser
import itertools
import urllib.request
class LinkParser(html.parser.HTMLParser):
def reset(self):
super().reset()
self.links = iter([])
def handle_starttag(self, tag, attrs):
if tag == 'a':
for (name, value) in attrs:
if name == 'href':
self.links = itertools.chain(self.links, [value])
def gen_links(stream, parser):
encoding = stream.headers.get_content_charset() or 'UTF-8'
for line in stream:
parser.feed(line.decode(encoding))
yield from parser.links
Use it like so:
>>> parser = LinkParser()
>>> stream = urllib.request.urlopen('http://stackoverflow.com/questions/3075550')
>>> links = gen_links(stream, parser)
>>> next(links)
'//stackoverflow.com'
Add the marker to the map like this
Marker markerName = map.addMarker(new MarkerOptions().position(latLng).title("Title"));
Then you'll be able to use the remove method, it will remove only that marker
markerName.remove();
You can use vertical-align and floating.
In most cases you want to vertical-align: middle, the image.
Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align
vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;
For middle, the definition is: The element is placed in the middle of the parent element.
So you might want to apply that to all elements within the element.
I think what you need is the below prototype
$(element).on('input',function(){code})
When you have to reload the file, you can erase the value of input. Next time you add a file, 'on change' event will trigger.
document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick
I had a component declared without the styleUrls property, like this:
@Component({
selector: 'app-server',
templateUrl: './server.component.html'
})
instead of:
@Component({
selector: 'app-server',
templateUrl: './server.component.html',
styleUrls: ['./server.component.css']
})
Adding in the styleUrls property solved the issue.
Potatoswatter's answer is all right, but I prefer to use find
or lower_bound
instead. lower_bound
is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.
map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) { // not found
// ...
my_map.insert(iter, make_pair(key, value)); // hinted insertion
} else {
// ... use iter->second here
}
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
You can use OpenLayers (js API for maps).
There's an example on their page showing how to embed OSM tiles.
Edit: New Link to OpenLayers examples
>>> numpy.array([[1, 2], [3, 4]])
array([[1, 2], [3, 4]])
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php
,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />
. You can reference that field with this jQuery: $("#field1").val()
.
Here's a complete example with the HTML. If we're assuming your fields are called field1
and field2
, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value
attribute.
A dictionary is something like an array that's accessed by keys (e.g. strings,...) rather than just plain sequential numbers. It contains key/value pairs, you can look up values using a key like using a phone book: key=name, number=value.
For defining such a dictionary, you use this syntax using curly braces, see also: http://wiki.python.org/moin/SimplePrograms
#!/bin/bash
# functiontest.sh a sample to call the function in the shell script
choice="true"
function process_install
{
commands...
}
function process_exit
{
commands...
}
function main
{
if [[ "$choice" == "true" ]]; then
process_install
elif [[ "$choice" == "false" ]]; then
process_exit
fi
}
main "$@"
it will start from the main function
I would put each element that you want inline inside a separate col-md-* div within your row. Or force your elements to display inline. The form-control class displays block because that's the way bootstrap thinks it should be done.
I'm using Batik for this. The complete Delphi code:
procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
StartInfo : TStartupInfo;
ProcInfo : TProcessInformation;
CreateOK : Boolean;
begin
FillChar(StartInfo, SizeOf(TStartupInfo), #0);
FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
StartInfo.cb := SizeOf(TStartupInfo);
CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
nil, nil, StartInfo, ProcInfo);
if CreateOK then begin
//may or may not be needed. Usually wait for child processes
if Wait then
WaitForSingleObject(ProcInfo.hProcess, INFINITE);
end else
ShowMessage('Unable to run ' + ProgramName);
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
procedure ConvertSVGtoPNG(aFilename: String);
const
ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
ExecNewProcess(ExecLine + aFilename, True);
end;
Allow only Alphabets in EditText android:
InputFilter letterFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String filtered = "";
for (int i = start; i < end; i++) {
char character = source.charAt(i);
if (!Character.isWhitespace(character)&&Character.isLetter(character)) {
filtered += character;
}
}
return filtered;
}
};
editText.setFilters(new InputFilter[]{letterFilter});
Here documents with the <<-HERE
terminator work well for indented multi-line text strings. It will remove any leading tabs from the here document. (Line terminators will still remain, though.)
cat <<-____HERE
continuation
lines
____HERE
See also http://ss64.com/bash/syntax-here.html
If you need to preserve some, but not all, leading whitespace, you might use something like
sed 's/^ //' <<____HERE
This has four leading spaces.
Two of them will be removed by sed.
____HERE
or maybe use tr
to get rid of newlines:
tr -d '\012' <<-____
continuation
lines
____
(The second line has a tab and a space up front; the tab will be removed by the dash operator before the heredoc terminator, whereas the space will be preserved.)
For wrapping long complex strings over many lines, I like printf
:
printf '%s' \
"This will all be printed on a " \
"single line (because the format string " \
"doesn't specify any newline)"
It also works well in contexts where you want to embed nontrivial pieces of shell script in another language where the host language's syntax won't let you use a here document, such as in a Makefile
or Dockerfile
.
printf '%s\n' >./myscript \
'#!/bin/sh` \
"echo \"G'day, World\"" \
'date +%F\ %T' && \
chmod a+x ./myscript && \
./myscript
The recommended naming and capitalization convention is to use PascalCasing for constants (Microsoft has a tool named StyleCop that documents all the preferred conventions and can check your source for compliance - though it is a little bit too anally retentive for many people's tastes). e.g.
private const int TheAnswer = 42;
The Pascal capitalization convention is also documented in Microsoft's Framework Design Guidelines.
I like using the ggplot2
for this sort of thing:
df$Date <- as.Date( df$Date, '%m/%d/%Y')
require(ggplot2)
ggplot( data = df, aes( Date, Visits )) + geom_line()
And if you want to search and replace based on the value of another field you could do a CONCAT:
update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));
Just to have this one here so that others will find it at once.
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
Please refer to List and Keys - React
Even simpler just do this:
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.90);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.90);
alertDialog.getWindow().setLayout(width, height);
replace code in onClick() method with this:
Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);
Here you can find a very small function that generates uuids https://gist.github.com/jed/982883
One of the final versions is:
function b(
a // placeholder
){
var cryptoObj = window.crypto || window.msCrypto; // for IE 11
return a // if the placeholder was passed, return
? ( // a random number from 0 to 15
a ^ // unless b is 8,
cryptoObj.getRandomValues(new Uint8Array(1))[0] // in which case
% 16 // a random number from
>> a/4 // 8 to 11
).toString(16) // in hexadecimal
: ( // or otherwise a concatenated string:
[1e7] + // 10000000 +
-1e3 + // -1000 +
-4e3 + // -4000 +
-8e3 + // -80000000 +
-1e11 // -100000000000,
).replace( // replacing
/[018]/g, // zeroes, ones, and eights with
b // random hex digits
)
}
Typically you'd define this toward the top of a class:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
Of course, use the appropriate member visibility (public
/private
/protected
) based on where you use this constant.
Don't use the ['type']
parameter to validate uploads. That field is user-provided, and can be trivially forged, allowing ANY type of file to be uploaded. The same goes for the ['name']
parameter - that's the name of the file as provided by the user. It is also trivial to forge, so the user's sending nastyvirus.exe
and calling it cutekittens.jpg
.
The proper method for validating uploads is to use server-side mime-type determination, e.g. via fileinfo, plus having proper upload success checking, which you do not:
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
case 'image/jpeg':
case 'application/pdf'
case etc....
$ok = true;
default:
die("Unknown/not permitted file type");
}
move_uploaded_file(...);
You are also using the user-provided filename as part of the final destination of the move_uploaded_files. it is also trivial to embed path data into that filename, which you then blindly use. That means a malicious remote user can scribble on ANY file on your server that they know the path for, plus plant new files.
I had similar issue when I had to install from github repo, but did not want to install git , etc.
The simple way to do it is using zip archive of the package. Add /zipball/master
to the repo URL:
$ pip install https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading/unpacking https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Downloading master
Running setup.py egg_info for package from https://github.com/hmarr/django-debug-toolbar-mongo/zipball/master
Installing collected packages: django-debug-toolbar-mongo
Running setup.py install for django-debug-toolbar-mongo
Successfully installed django-debug-toolbar-mongo
Cleaning up...
This way you will make pip work with github source repositories.
Self-contained example
Same technique as in this answer but:
Source:
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = new Button(this);
button.setText("click me");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Notification notification = new Notification.Builder(Main.this)
/* Make app open when you click on the notification. */
.setContentIntent(PendingIntent.getActivity(
Main.this,
Main.this.i,
new Intent(Main.this, Main.class),
PendingIntent.FLAG_CANCEL_CURRENT))
.setContentTitle("title")
.setAutoCancel(true)
.setContentText(String.format("id = %d", Main.this.i))
// Starting on Android 5, only the alpha channel of the image matters.
// https://stackoverflow.com/a/35278871/895245
// `android.R.drawable` resources all seem suitable.
.setSmallIcon(android.R.drawable.star_on)
// Color of the background on which the alpha image wil drawn white.
.setColor(Color.RED)
.build();
final NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Main.this.i, notification);
// If the same ID were used twice, the second notification would replace the first one.
//notificationManager.notify(0, notification);
Main.this.i++;
}
});
this.setContentView(button);
}
}
Tested in Android 22.
Same problem, and fixed it on my centos 6.5 using the following command.
yum install openssl-devel
For emacs there is also gitsum
Unfortunately, this doesn't work if there are other, non-related directories already in the same dir. Looking for a solution. The error message is: "fatal: destination path '.' already exists...".
The solution in this case is:
git init
git remote add origin [email protected]:me/name.git
git pull origin master
This recipe works even if there are other directories in the one you want to checkout in.
... or MyEnum.values() ? Or am I missing something?
I improved Salselvaprabu's answer in several ways:
Call it like this:
Test-Port example.com 999
Test-Port 192.168.0.1 80
function Test-Port($hostname, $port)
{
# This works no matter in which form we get $host - hostname or ip address
try {
$ip = [System.Net.Dns]::GetHostAddresses($hostname) |
select-object IPAddressToString -expandproperty IPAddressToString
if($ip.GetType().Name -eq "Object[]")
{
#If we have several ip's for that address, let's take first one
$ip = $ip[0]
}
} catch {
Write-Host "Possibly $hostname is wrong hostname or IP"
return
}
$t = New-Object Net.Sockets.TcpClient
# We use Try\Catch to remove exception info from console if we can't connect
try
{
$t.Connect($ip,$port)
} catch {}
if($t.Connected)
{
$t.Close()
$msg = "Port $port is operational"
}
else
{
$msg = "Port $port on $ip is closed, "
$msg += "You may need to contact your IT team to open it. "
}
Write-Host $msg
}
For i=1 To 10
Do
'Do everything in here and
If I_Dont_Want_Finish_This_Loop Then
Exit Do
End If
'Of course, if I do want to finish it,
'I put more stuff here, and then...
Loop While False 'quit after one loop
Next i
SELECT @variable1 = col1, @variable2 = col2
FROM table1
I'm late to the party, here is an Excel VBA script I wrote years ago for Australia. It can be easily modified to support other Countries. I've made a GitHub repository of the C# code here. I've hosted it on my site and you can download it here: http://jeremythompson.net/rocks/ParseAddress.xlsm
For any country with a PostCode that's numeric or can be matched with a RegEx my strategy works very well:
First we detect the First and Surname which are assumed to be the top line. Its easy to skip the name and start with the address by unticking the checkbox (called 'Name is top row' as shown below).
Next its safe to expect the Address consisting of the Street and Number come before the Suburb and the St, Pde, Ave, Av, Rd, Cres, loop, etc is a separator.
Detecting the Suburb vs the State and even Country can trick the most sophisticated parsers as there can be conflicts. To overcome this I use a PostCode look up based on the fact that after stripping Street and Apartment/Unit numbers as well as the PoBox,Ph,Fax,Mobile etc, only the PostCode number will remain. This is easy to match with a regEx to then look up the suburb(s) and country.
Your National Post Office Service will provide a list of post codes with Suburbs and States free of charge that you can store in an excel sheet, db table, text/json/xml file, etc.
DISCLAIMER, I know this code is not perfect, or even written well however its very easy to convert to any programming language and run in any type of application.The strategy is the answer depending on your country and rules, take this code as an example:
Option Explicit
Private Const TopRow As Integer = 0
Public Sub ParseAddress()
Dim strArr() As String
Dim sigRow() As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim Stat As String
Dim SpaceInName As Integer
Dim Temp As String
Dim PhExt As String
On Error Resume Next
Temp = ActiveSheet.Range("Address")
'Split info into array
strArr = Split(Temp, vbLf)
'Trim the array
For i = 0 To UBound(strArr)
strArr(i) = VBA.Trim(strArr(i))
Next i
'Remove empty items/rows
ReDim sigRow(LBound(strArr) To UBound(strArr))
For i = LBound(strArr) To UBound(strArr)
If Trim(strArr(i)) <> "" Then
sigRow(j) = strArr(i)
j = j + 1
End If
Next i
ReDim Preserve sigRow(LBound(strArr) To j)
'Find the name (MUST BE ON THE FIRST ROW UNLESS CHECKBOX UNTICKED)
i = TopRow
If ActiveSheet.Shapes("chkFirst").ControlFormat.Value = 1 Then
SpaceInName = InStr(1, sigRow(i), " ", vbTextCompare) - 1
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
Else
If MsgBox("First Name: " & VBA.Mid$(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("FirstName") = VBA.Left(sigRow(i), SpaceInName)
End If
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
Else
If MsgBox("Surame: " & VBA.Mid(sigRow(i), SpaceInName + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Surname") = VBA.Mid(sigRow(i), SpaceInName + 2)
End If
sigRow(i) = ""
End If
'Find the Street by looking for a "St, Pde, Ave, Av, Rd, Cres, loop, etc"
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
For j = 0 To 8
If InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) > 0 Then
'Find the position of the street in order to get the suburb
SpaceInName = InStr(1, VBA.UCase(sigRow(i)), Street(j), vbTextCompare) + Len(Street(j)) - 1
'If its a po box then add 5 chars
If VBA.Right(Street(j), 3) = "BOX" Then SpaceInName = SpaceInName + 5
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
Else
If MsgBox("Street Address: " & VBA.Mid(sigRow(i), 1, SpaceInName), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Street") = VBA.Mid(sigRow(i), 1, SpaceInName)
End If
'Trim the Street, Number leaving the Suburb if its exists on the same line
sigRow(i) = VBA.Mid(sigRow(i), SpaceInName) + 2
sigRow(i) = Replace(sigRow(i), VBA.Mid(sigRow(i), 1, SpaceInName), "")
GoTo PastAddress:
End If
Next j
End If
Next i
PastAddress:
'Mobile
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
For j = 0 To 3
Temp = Mb(j)
If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
Else
If MsgBox("Mobile: " & VBA.Mid(sigRow(i), Len(Temp) + 2), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Mobile") = VBA.Mid(sigRow(i), Len(Temp) + 2)
End If
sigRow(i) = ""
GoTo PastMobile:
End If
Next j
End If
Next i
PastMobile:
'Phone
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
For j = 0 To 1
Temp = Ph(j)
If VBA.Left(VBA.UCase(sigRow(i)), Len(Temp)) = Temp Then
'TODO: Detect the intl or national extension here.. or if we can from the postcode.
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
Else
If MsgBox("Phone: " & VBA.Mid(sigRow(i), Len(Temp) + 3), vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Phone") = VBA.Mid(sigRow(i), Len(Temp) + 3)
End If
sigRow(i) = ""
GoTo PastPhone:
End If
Next j
End If
Next i
PastPhone:
'Email
For i = 1 To UBound(sigRow)
If Len(sigRow(i)) > 0 Then
'replace with regEx search
If InStr(1, sigRow(i), "@", vbTextCompare) And InStr(1, VBA.UCase(sigRow(i)), ".CO", vbTextCompare) Then
Dim email As String
email = sigRow(i)
email = Replace(VBA.UCase(email), "EMAIL:", "")
email = Replace(VBA.UCase(email), "E-MAIL:", "")
email = Replace(VBA.UCase(email), "E:", "")
email = Replace(VBA.UCase(Trim(email)), "E ", "")
email = VBA.LCase(email)
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("Email") = email
Else
If MsgBox("Email: " & email, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("Email") = email
End If
sigRow(i) = ""
Exit For
End If
End If
Next i
'Now the only remaining items will be the postcode, suburb, country
'there shouldn't be any numbers (eg. from PoBox,Ph,Fax,Mobile) except for the Post Code
'Join the string and filter out the Post Code
Temp = Join(sigRow, vbCrLf)
Temp = Trim(Temp)
For i = 1 To Len(Temp)
Dim postCode As String
postCode = VBA.Mid(Temp, i, 4)
'In Australia PostCodes are 4 digits
If VBA.Mid(Temp, i, 1) <> " " And IsNumeric(postCode) Then
If ActiveSheet.Shapes("chkConfirm").ControlFormat.Value = 0 Then
ActiveSheet.Range("PostCode") = postCode
Else
If MsgBox("Post Code: " & postCode, vbQuestion + vbYesNo, "Confirm Details") = vbYes Then ActiveSheet.Range("PostCode") = postCode
End If
'Lookup the Suburb and State based on the PostCode, the PostCode sheet has the lookup
Dim mySuburbArray As Range
Set mySuburbArray = Sheets("PostCodes").Range("A2:B16670")
Dim suburbs As String
For j = 1 To mySuburbArray.Columns(1).Cells.Count
If mySuburbArray.Cells(j, 1) = postCode Then
'Check if the suburb is listed in the address
If InStr(1, UCase(Temp), mySuburbArray.Cells(j, 2), vbTextCompare) > 0 Then
'Set the Suburb and State
ActiveSheet.Range("Suburb") = mySuburbArray.Cells(j, 2)
Stat = mySuburbArray.Cells(j, 3)
ActiveSheet.Range("State") = Stat
'Knowing the State - for Australia we can get the telephone Ext
PhExt = PhExtension(VBA.UCase(Stat))
ActiveSheet.Range("PhExt") = PhExt
'remove the phone extension from the number
Dim prePhone As String
prePhone = ActiveSheet.Range("Phone")
prePhone = Replace(prePhone, PhExt & " ", "")
prePhone = Replace(prePhone, "(" & PhExt & ") ", "")
prePhone = Replace(prePhone, "(" & PhExt & ")", "")
ActiveSheet.Range("Phone") = prePhone
Exit For
End If
End If
Next j
Exit For
End If
Next i
End Sub
Private Function PhExtension(ByVal State As String) As String
Select Case State
Case Is = "NSW"
PhExtension = "02"
Case Is = "QLD"
PhExtension = "07"
Case Is = "VIC"
PhExtension = "03"
Case Is = "NT"
PhExtension = "04"
Case Is = "WA"
PhExtension = "05"
Case Is = "SA"
PhExtension = "07"
Case Is = "TAS"
PhExtension = "06"
End Select
End Function
Private Function Ph(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Ph = "PH"
Case Is = 1
Ph = "PHONE"
'Case Is = 2
'Ph = "P"
End Select
End Function
Private Function Mb(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Mb = "MB"
Case Is = 1
Mb = "MOB"
Case Is = 2
Mb = "CELL"
Case Is = 3
Mb = "MOBILE"
'Case Is = 4
'Mb = "M"
End Select
End Function
Private Function Fax(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Fax = "FAX"
Case Is = 1
Fax = "FACSIMILE"
'Case Is = 2
'Fax = "F"
End Select
End Function
Private Function State(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
State = "NSW"
Case Is = 1
State = "QLD"
Case Is = 2
State = "VIC"
Case Is = 3
State = "NT"
Case Is = 4
State = "WA"
Case Is = 5
State = "SA"
Case Is = 6
State = "TAS"
End Select
End Function
Private Function Street(ByVal Num As Integer) As String
Select Case Num
Case Is = 0
Street = " ST"
Case Is = 1
Street = " RD"
Case Is = 2
Street = " AVE"
Case Is = 3
Street = " AV"
Case Is = 4
Street = " CRES"
Case Is = 5
Street = " LOOP"
Case Is = 6
Street = "PO BOX"
Case Is = 7
Street = " STREET"
Case Is = 8
Street = " ROAD"
Case Is = 9
Street = " AVENUE"
Case Is = 10
Street = " CRESENT"
Case Is = 11
Street = " PARADE"
Case Is = 12
Street = " PDE"
Case Is = 13
Street = " LANE"
Case Is = 14
Street = " COURT"
Case Is = 15
Street = " BLVD"
Case Is = 16
Street = "P.O. BOX"
Case Is = 17
Street = "P.O BOX"
Case Is = 18
Street = "PO BOX"
Case Is = 19
Street = "POBOX"
End Select
End Function
According to Froyo source code, the Intent.EXTRA_INSTALLER_PACKAGE_NAME extra key is queried for the installer package name in the PackageInstallerActivity.
If you want to write a script to automate creation of jobs using the Jenkins API, you can use one of the API clients to do that. A ruby client for Jenkins is available at https://github.com/arangamani/jenkins_api_client
gem install jenkins_api_client
require "rubygems"
require "jenkins_api_client"
# Initialize the client by passing in the server information
# and credentials to communicate with the server
client = JenkinsApi::Client.new(
:server_ip => "127.0.0.1",
:username => "awesomeuser",
:password => "awesomepassword"
)
# The following block will create 10 jobs in Jenkins
# test_job_0, test_job_1, test_job_2, ...
10.times do |num|
client.job.create_freestyle(:name => "test_job_#{num}")
end
# The jobs in Jenkins can be listed using
client.job.list_all
The API client can be used to perform a lot of operations.
You'd need to be careful as onBlur
has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).
There is, however, no way to use onFocusOut
in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.
If somebody experiences problems with ExifInterface
on Android 4.4 (KitKat) for getting the orientation, it might be because of wrong path got from the URI. See a solution for propoer getPath
in Stack Overflow question Get real path from URI, Android KitKat new storage access framework
just use like this to make anything to center
android:layout_gravity="center"
android:gravity="center"
updated :
android:layout_gravity="center|right"
android:gravity="center|right"
Updated : Just remove MarginBottom from your textview.. Do like this.. for your textView
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" >
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center|right"
android:text="hello"
android:textSize="20dp" />
</LinearLayout>
You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.
However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.
If you are using Linux File is a command that will do a similar task.
The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db
file.
maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
Try putting your text in another div inside your span:
i.e.
<span><div>some text</div></span>
This worked for me:
& 'D:\Server\PSTools\PsExec.exe' @('\\1.1.1.1', '-accepteula', '-d', '-i', $id, '-h', '-u', 'domain\user', '-p', 'password', '-w', 'C:\path\to\the\app', 'java', '-jar', 'app.jar')
Just put paths or connection strings in one array item and split the other things in one array item each.
There are a lot of other options here: https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx
Microsoft should make this way simpler and compatible with command prompt syntax.
Use the str.isspace()
method:
Return
True
if there are only whitespace characters in the string and there is at least one character,False
otherwise.A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.
Combine that with a special case for handling the empty string.
Alternatively, you could use str.strip()
and check if the result is empty.
I have similar requirement where I need a MySQL client but not server (running in a virtual machine and don't want any additional overhead) and for me the easiest thing was to install MySQL community server taking typical installation options but NOT configure the server, so it never starts, never runs. Added C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin to system path environment variable and I'm able to use the MySQL command line client mssql.exe and mysqladmin.exe programs.
Try this
Replace
<Directory /usr/share/phpMyAdmin/>
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
Require ip 127.0.0.1
Require ip ::1
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
With this:
<Directory "/usr/share/phpMyAdmin/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
</Directory>
Add the following line for ease of access:
Alias /phpmyadmin /usr/share/phpMyAdmin
The MSDN documentation for C++'s GetTempFileName discusses your concern and answers it:
GetTempFileName is not able to guarantee that the file name is unique.
Only the lower 16 bits of the uUnique parameter are used. This limits GetTempFileName to a maximum of 65,535 unique file names if the lpPathName and lpPrefixString parameters remain the same.
Due to the algorithm used to generate file names, GetTempFileName can perform poorly when creating a large number of files with the same prefix. In such cases, it is recommended that you construct unique file names based on GUIDs.
You basically need to run the installation again to rebuild the master
database with the new collation. You cannot change the entire server's collation any other way.
See:
Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:
SELECT name, collation_name
FROM sys.databases
WHERE name = 'test2' -- put your database name here
This will yield a value something like:
Latin1_General_CI_AS
The _CI
means "case insensitive" - if you want case-sensitive, use _CS
in its place:
Latin1_General_CS_AS
So your T-SQL command would be:
ALTER DATABASE test2 -- put your database name here
COLLATE Latin1_General_CS_AS -- replace with whatever collation you need
You can get a list of all available collations on the server using:
SELECT * FROM ::fn_helpcollations()
You can see the server's current collation using:
SELECT SERVERPROPERTY ('Collation')
It's usually describes as for optional add-on software packages
source, or anything that isn't part of the base system. Only some distributions use it, others simply use /usr/local
.
Extract your file with Tar archiving tool. you can use it in this way:
tar xf example.sql.gz
Just create a Pair<TFirst, TSecond>
type and use that as your value.
I have an example of one in my C# in Depth source code. Reproduced here for simplicity:
using System;
using System.Collections.Generic;
public sealed class Pair<TFirst, TSecond>
: IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
}
public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}
...
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:local="urn:local" extension-element-prefixes="msxsl">
<msxsl:script language="CSharp" implements-prefix="local">
public string dateTimeNow()
{
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
</msxsl:script>
...
<xsl:value-of select="local:dateTimeNow()"/>
I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using set
literal syntax which has been backported to Python 2.7):
all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
# or
{'a', 'b'}.issubset({'a', 'b', 'c'})
I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.
So try to download other versions of PostgreSQL and get all the components
All of these answers ignore the easiest and quickest way to do this (as long as you have Bash 4):
if [ "${var1,,}" = "${var2,,}" ]; then
echo ":)"
fi
All you're doing there is converting both strings to lowercase and comparing the results.
Try setting the variable CMAKE_CXX_FLAGS
instead of CMAKE_C_FLAGS
:
set (CMAKE_CXX_FLAGS "-fexceptions")
The variable CMAKE_C_FLAGS
only affects the C compiler, but you are compiling C++ code.
Adding the flag to CMAKE_EXE_LINKER_FLAGS
is redundant.
The a == b
expression invokes A.__eq__
, since it exists. Its code includes self.value == other
. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__
to see if it knows how to compare itself to an int.
If you amend your code to show what values are being compared:
class A(object):
def __eq__(self, other):
print("A __eq__ called: %r == %r ?" % (self, other))
return self.value == other
class B(object):
def __eq__(self, other):
print("B __eq__ called: %r == %r ?" % (self, other))
return self.value == other
a = A()
a.value = 3
b = B()
b.value = 4
a == b
it will print:
A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
callback from adapter to activity can be done using registering listener in form of interface: Make an interface:
public MyInterface{
public void yourmethod(//incase needs parameters );
}
In Adapter Let's Say MyAdapter:
public MyAdapter extends BaseAdapter{
private MyInterface listener;
MyAdapter(Context context){
try {
this. listener = (( MyInterface ) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement MyInterface");
}
//do this where u need to fire listener l
try {
listener . yourmethod ();
} catch (ClassCastException exception) {
// do something
}
In Activity Implement your method:
MyActivity extends AppCompatActivity implements MyInterface{
yourmethod(){
//do whatever you want
}
}
Verify your component is properly imported in app-routing.module.ts. In my case that was the reason
The print
statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:
a = str(tag.getArtist())
Manually wrapping in BytesIO is no longer needed since PIL >= 2.8.0. Just use Image.open(response.raw)
Adding on top of Vinícius's comment:
You should pass stream=True
as noted https://requests.readthedocs.io/en/master/user/quickstart/#raw-response-content
So
img = Image.open(requests.get(url, stream=True).raw)
See comment in: https://github.com/Microsoft/TypeScript/issues/3069#issuecomment-99964139
TypeScript does not come with built in pollyfills. it is up to you to decide which pollyfill to use, if any. you can use something like es6Collection, es6-shims, corejs..etc. All the Typescript compiler needs is a declaration for the ES6 constructs you want to use. you can find them all in this lib file.
here is the relevant portion:
interface Map<K, V> { clear(): void; delete(key: K): boolean; entries(): IterableIterator<[K, V]>; forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void; get(key: K): V; has(key: K): boolean; keys(): IterableIterator<K>; set(key: K, value?: V): Map<K, V>; size: number; values(): IterableIterator<V>; [Symbol.iterator]():IterableIterator<[K,V]>; [Symbol.toStringTag]: string; } interface MapConstructor { new <K, V>(): Map<K, V>; new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>; prototype: Map<any, any>; } declare var Map: MapConstructor;
use
Date date = new Date();
String strDate = sdf.format(date);
intead Of
Calendar cal = Calendar.getInstance();
String strDate = sdf.format(cal.getTime());
I arrived at this post after hitting on another post that has been closed as a duplicate of this - titled 'how to store an array in localstorage?'. Which is fine except neither thread actually provides a full answer as to how you can maintain an array in localStorage - however I have managed to craft a solution based on information contained in both threads.
So if anyone else is wanting to be able to push/pop/shift items within an array, and they want that array stored in localStorage or indeed sessionStorage, here you go:
Storage.prototype.getArray = function(arrayName) {
var thisArray = [];
var fetchArrayObject = this.getItem(arrayName);
if (typeof fetchArrayObject !== 'undefined') {
if (fetchArrayObject !== null) { thisArray = JSON.parse(fetchArrayObject); }
}
return thisArray;
}
Storage.prototype.pushArrayItem = function(arrayName,arrayItem) {
var existingArray = this.getArray(arrayName);
existingArray.push(arrayItem);
this.setItem(arrayName,JSON.stringify(existingArray));
}
Storage.prototype.popArrayItem = function(arrayName) {
var arrayItem = {};
var existingArray = this.getArray(arrayName);
if (existingArray.length > 0) {
arrayItem = existingArray.pop();
this.setItem(arrayName,JSON.stringify(existingArray));
}
return arrayItem;
}
Storage.prototype.shiftArrayItem = function(arrayName) {
var arrayItem = {};
var existingArray = this.getArray(arrayName);
if (existingArray.length > 0) {
arrayItem = existingArray.shift();
this.setItem(arrayName,JSON.stringify(existingArray));
}
return arrayItem;
}
Storage.prototype.unshiftArrayItem = function(arrayName,arrayItem) {
var existingArray = this.getArray(arrayName);
existingArray.unshift(arrayItem);
this.setItem(arrayName,JSON.stringify(existingArray));
}
Storage.prototype.deleteArray = function(arrayName) {
this.removeItem(arrayName);
}
example usage - storing simple strings in localStorage array:
localStorage.pushArrayItem('myArray','item one');
localStorage.pushArrayItem('myArray','item two');
example usage - storing objects in sessionStorage array:
var item1 = {}; item1.name = 'fred'; item1.age = 48;
sessionStorage.pushArrayItem('myArray',item1);
var item2 = {}; item2.name = 'dave'; item2.age = 22;
sessionStorage.pushArrayItem('myArray',item2);
common methods to manipulate arrays:
.pushArrayItem(arrayName,arrayItem); -> adds an element onto end of named array
.unshiftArrayItem(arrayName,arrayItem); -> adds an element onto front of named array
.popArrayItem(arrayName); -> removes & returns last array element
.shiftArrayItem(arrayName); -> removes & returns first array element
.getArray(arrayName); -> returns entire array
.deleteArray(arrayName); -> removes entire array from storage
Setting session timeout through the deployment descriptor should work - it sets the default session timeout for the web app. Calling session.setMaxInactiveInterval() sets the timeout for the particular session it is called on, and overrides the default. Be aware of the unit difference, too - the deployment descriptor version uses minutes, and session.setMaxInactiveInterval() uses seconds.
So
<session-config>
<session-timeout>60</session-timeout>
</session-config>
sets the default session timeout to 60 minutes.
And
session.setMaxInactiveInterval(600);
sets the session timeout to 600 seconds - 10 minutes - for the specific session it's called on.
This should work in Tomcat or Glassfish or any other Java web server - it's part of the spec.
SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL
Q: What is happening here?
A: Conceptually, we select all rows from table1
and for each row we attempt to find a row in table2
with the same value for the name
column. If there is no such row, we just leave the table2
portion of our result empty for that row. Then we constrain our selection by picking only those rows in the result where the matching row does not exist. Finally, We ignore all fields from our result except for the name
column (the one we are sure that exists, from table1
).
While it may not be the most performant method possible in all cases, it should work in basically every database engine ever that attempts to implement ANSI 92 SQL
I think, better way is use HttpPostedFileBase in your controller or API. After this you can simple detect size, type etc.
File properties you can find here:
MVC3 How to check if HttpPostedFileBase is an image
For example ImageApi:
[HttpPost]
[Route("api/image")]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Images"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "Your message for success";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "Please select file";
}
return View();
}
Hope it help.
We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!
The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
Deploy the sample script as a Google Spreadsheet APP Script: google-script-just-email.js
remember to set the
TO_ADDRESS
in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.
action
to the App URLUsing the sample html
file:
index.html
create a basic form.
remember to paste your APP URL into the form
action
in the HTML form.
Open the HTML Form in your Browser, Input some data & submit it!
Submit the form. You should see a confirmation that it was sent:
Open the inbox for the email address you set (above)
Everything about this is customisable, you can easily style/theme the form with your favourite CSS Library and Store the submitted data in a Google Spreadsheet for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
Current version: Help
| Change Memory Settings
:
Since IntelliJ IDEA 15.0.4 you can also use: Help
| Edit Custom VM Options...
:
This will automatically create a copy of the .vmoptions
file in the config folder and open a dialog to edit it.
Older versions:
IntelliJ IDEA 12 is a signed application, therefore changing options in Info.plist
is no longer recommended, as the signature will not match and you will get issues depending on your system security settings (app will either not run, or firewall will complain on every start, or the app will not be able to use the system keystore to save passwords).
As a result of addressing IDEA-94050 a new way to supply JVM options was introduced in IDEA 12:
Now it can take VM options from
~/Library/Preferences/<appFolder>/idea.vmoptions
and system properties from~/Library/Preferences/<appFolder>/idea.properties
.
For example, to use -Xmx2048m option you should copy the original .vmoptions
file from /Applications/IntelliJ IDEA.app/bin/idea.vmoptions
to ~/Library/Preferences/IntelliJIdea12/idea.vmoptions
, then modify the -Xmx
setting.
The final file should look like:
-Xms128m
-Xmx2048m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops
Copying the original file is important, as options are not added, they are replaced.
This way your custom options will be preserved between updates and application files will remain unmodified making signature checker happy.
Community Edition: ~/Library/Preferences/IdeaIC12/idea.vmoptions
file is used instead.
On my machine (Windows7, 64bit) I could fix this by setting my execution environment to a 32bit variant of the jdk (I used 1.6.0_23). And I tried a lot of things before...
Although not usually a concern, from a security perspective, it is better to use synchronized on a private object, rather than putting it on a method.
Putting it on the method means you are using the lock of the object itself to provide thread safety. With this kind of mechanism, it is possible for a malicious user of your code to also obtain the lock on your object, and hold it forever, effectively blocking other threads. A non-malicious user can effectively do the same thing inadvertently.
If you use the lock of a private data member, you can prevent this, since it is impossible for a malicious user to obtain the lock on your private object.
private final Object lockObject = new Object();
public void getCount() {
synchronized( lockObject ) {
...
}
}
This technique is mentioned in Bloch's Effective Java (2nd Ed), Item #70
In the case of integers that are included at the string, if you want to avoid casting them to int
individually you can do:
mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
It is called list comprehension, and it is based on set builder notation.
ex:
>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]
I think you can change your
img {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
into a
img {
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
user-drag: none;
}
Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.
You might be using a ConsoleHandler
(I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO
. You will have to configure this handler, to publish log records of level Level.FINER
and higher, for the desired outcome.
I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.
Editing the handler level
1. Using the Configuration file
The java.util.logging properties file (by default, this is the logging.properties
file in JRE_HOME/lib
) can be modified to change the default level of the ConsoleHandler:
java.util.logging.ConsoleHandler.level = FINER
2. Creating handlers at runtime
This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.
Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);
Use:
$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 1)}
New-Item $newName -ItemType Directory
Just pass your Oracle path variables before you run any scripts:
Like for perl you can do add below in beginning of your script:
BEGIN {
my $ORACLE_HOME = "/usr/lib/oracle/11.2/client64";
my $LD_LIBRARY_PATH = "$ORACLE_HOME/lib";
if ($ENV{ORACLE_HOME} ne $ORACLE_HOME
|| $ENV{LD_LIBRARY_PATH} ne $LD_LIBRARY_PATH
) {
$ENV{ORACLE_HOME} = "/usr/lib/oracle/11.2/client64";
$ENV{LD_LIBRARY_PATH} = "$ORACLE_HOME/lib";
exec { $^X } $^X, $0, @ARGV;
}
}
looks like SimpleDateFormat is not checking the pattern strictly even after setLenient(false); method is applied on it, so i have used below method to validate if the date inputted is valid date or not as per supplied pattern.
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public boolean isValidFormat(String dateString, String pattern) {
boolean valid = true;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
try {
formatter.parse(dateString);
} catch (DateTimeParseException e) {
valid = false;
}
return valid;
}
there are 6 ways to do this in React,
number 1 and 2 and 3 are the best:
1-config CORS in the Server-Side
2-set headers manually like this:
resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
3-config NGINX for proxy_pass which is explained here.
4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)
5-bypass the cross-origin-policy with URL bellow(only for development)
"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
6-use proxy
in your package.json
file:(only for development)
if this is your API: http://45.456.200.5:7000/api/profile/
add this part in your package.json
file:
"proxy": "http://45.456.200.5:7000/",
and then make your request with the next parts of the api:
React.useEffect(() => {
axios
.get('api/profile/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
Different file name which posted as "recfile" at <input type="file" name='recfile' placeholder="Select file"/>
and received as "file" at upload.single('file')
Solution : make sure both sent and received file are similar upload.single('recfile')
var result = string.Join(",", arr);
This uses the following overload of string.Join
:
public static string Join<T>(string separator, IEnumerable<T> values);
try use CMAKE_GENERATOR_PLATFORM
e.g.
// x86
cmake -DCMAKE_GENERATOR_PLATFORM=x86 .
// x64
cmake -DCMAKE_GENERATOR_PLATFORM=x64 .
in my case I was using below dependency
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.42</version>
</dependency>
and getting the same exception of Auth fail, but updated dependency to below version and problem get resolved.
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
In python 2.7 you can use NumPy's numpy.std()
gives the population standard deviation.
In Python 3.4 statistics.stdev()
returns the sample standard deviation. The pstdv()
function is the same as numpy.std()
.
If you want timestamps that correspond to actual real times BUT also want them to be unique (for a given application instance), you can use the following code:
public class HiResDateTime
{
private static long lastTimeStamp = DateTime.UtcNow.Ticks;
public static long UtcNowTicks
{
get
{
long orig, newval;
do
{
orig = lastTimeStamp;
long now = DateTime.UtcNow.Ticks;
newval = Math.Max(now, orig + 1);
} while (Interlocked.CompareExchange
(ref lastTimeStamp, newval, orig) != orig);
return newval;
}
}
}
It's something they've built themselves - it's called Bigtable.
http://en.wikipedia.org/wiki/BigTable
There is a paper by Google on the database:
If you are writing this code as a script file then you will have to write it like this:
df = df.sort(['c1','c2'], ascending=[False,True])
Yes, you can set the screen orientation programatically anytime you want using:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.
And this is how you can get the current screen orientation and set it adequatly depending on its current state:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation();
// OR: orientation = getRequestedOrientation(); // inside an Activity
// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
});
Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/
EDIT
Also, you can get the screen orientation using the Configuration
:
Activity.getResources().getConfiguration().orientation
x = "xx yy 11 22 33"
gsub(" ", "", x)
> [1] "xxyy112233"
Arrays.asList(myArray).contains(false)
var minRows = 5;
var maxRows = 26;
function ResizeTextarea(id) {
var t = document.getElementById(id);
if (t.scrollTop == 0) t.scrollTop=1;
while (t.scrollTop == 0) {
if (t.rows > minRows)
t.rows--; else
break;
t.scrollTop = 1;
if (t.rows < maxRows)
t.style.overflowY = "hidden";
if (t.scrollTop > 0) {
t.rows++;
break;
}
}
while(t.scrollTop > 0) {
if (t.rows < maxRows) {
t.rows++;
if (t.scrollTop == 0) t.scrollTop=1;
} else {
t.style.overflowY = "auto";
break;
}
}
}
if you want to change default:
for bootstrap 3.x:
$.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';
$.fn.modal.prototype.constructor.Constructor.DEFAULTS.keyboard = false;
for bootstrap 4.x:
$.fn.modal.prototype.constructor.Constructor.Default.backdrop = 'static';
$.fn.modal.prototype.constructor.Constructor.Default.keyboard = false;
The variable name you're looking for is ansible_ssh_private_key_file
.
You should set it at 'vars' level:
in the inventory file:
myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
in the host_vars
:
# hosts_vars/myHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
# hosts_vars/myOtherHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
in a group_vars
file if you use the same key for a group of hosts
in the vars
section of your play:
- hosts: myHost
remote_user: ubuntu
vars_files:
- vars.yml
vars:
ansible_ssh_private_key_file: "{{ key1 }}"
tasks:
- name: Echo a hello message
command: echo hello
Service style: (probably the simplest one) returns the actual function: Useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference.
A service in AngularJS is a singleton JavaScript object which contains a set of functions
var myModule = angular.module("myModule", []);
myModule.value ("myValue" , "12345");
function MyService(myValue) {
this.doIt = function() {
console.log("done: " + myValue;
}
}
myModule.service("myService", MyService);
myModule.controller("MyController", function($scope, myService) {
myService.doIt();
});
Factory style: (more involved but more sophisticated) returns the function's return value: instantiate an object like new Object() in java.
Factory is a function that creates values. When a service, controller etc. needs a value injected from a factory, the factory creates the value on demand. Once created, the value is reused for all services, controllers etc. which need it injected.
var myModule = angular.module("myModule", []);
myModule.value("numberValue", 999);
myModule.factory("myFactory", function(numberValue) {
return "a value: " + numberValue;
})
myModule.controller("MyController", function($scope, myFactory) {
console.log(myFactory);
});
Provider style: (full blown, configurable version) returns the output of the function's $get function: Configurable.
Providers in AngularJS is the most flexible form of factory you can create. You register a provider with a module just like you do with a service or factory, except you use the provider() function instead.
var myModule = angular.module("myModule", []);
myModule.provider("mySecondService", function() {
var provider = {};
var config = { configParam : "default" };
provider.doConfig = function(configParam) {
config.configParam = configParam;
}
provider.$get = function() {
var service = {};
service.doService = function() {
console.log("mySecondService: " + config.configParam);
}
return service;
}
return provider;
});
myModule.config( function( mySecondServiceProvider ) {
mySecondServiceProvider.doConfig("new config param");
});
myModule.controller("MyController", function($scope, mySecondService) {
$scope.whenButtonClicked = function() {
mySecondService.doIt();
}
});
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
<head>_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>_x000D_
<meta charset=utf-8 />_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body ng-controller="MyCtrl">_x000D_
{{serviceOutput}}_x000D_
<br/><br/>_x000D_
{{factoryOutput}}_x000D_
<br/><br/>_x000D_
{{providerOutput}}_x000D_
_x000D_
<script>_x000D_
_x000D_
var app = angular.module( 'app', [] );_x000D_
_x000D_
var MyFunc = function() {_x000D_
_x000D_
this.name = "default name";_x000D_
_x000D_
this.$get = function() {_x000D_
this.name = "new name"_x000D_
return "Hello from MyFunc.$get(). this.name = " + this.name;_x000D_
};_x000D_
_x000D_
return "Hello from MyFunc(). this.name = " + this.name;_x000D_
};_x000D_
_x000D_
// returns the actual function_x000D_
app.service( 'myService', MyFunc );_x000D_
_x000D_
// returns the function's return value_x000D_
app.factory( 'myFactory', MyFunc );_x000D_
_x000D_
// returns the output of the function's $get function_x000D_
app.provider( 'myProv', MyFunc );_x000D_
_x000D_
function MyCtrl( $scope, myService, myFactory, myProv ) {_x000D_
_x000D_
$scope.serviceOutput = "myService = " + myService;_x000D_
$scope.factoryOutput = "myFactory = " + myFactory;_x000D_
$scope.providerOutput = "myProvider = " + myProv;_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myApp">_x000D_
<head>_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>_x000D_
<meta charset=utf-8 />_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div ng-controller="MyCtrl">_x000D_
{{hellos}}_x000D_
</div>_x000D_
<script>_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
//service style, probably the simplest one_x000D_
myApp.service('helloWorldFromService', function() {_x000D_
this.sayHello = function() {_x000D_
return "Hello, World!"_x000D_
};_x000D_
});_x000D_
_x000D_
//factory style, more involved but more sophisticated_x000D_
myApp.factory('helloWorldFromFactory', function() {_x000D_
return {_x000D_
sayHello: function() {_x000D_
return "Hello, World!"_x000D_
}_x000D_
};_x000D_
});_x000D_
_x000D_
//provider style, full blown, configurable version _x000D_
myApp.provider('helloWorld', function() {_x000D_
_x000D_
this.name = 'Default';_x000D_
_x000D_
this.$get = function() {_x000D_
var name = this.name;_x000D_
return {_x000D_
sayHello: function() {_x000D_
return "Hello, " + name + "!"_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
this.setName = function(name) {_x000D_
this.name = name;_x000D_
};_x000D_
});_x000D_
_x000D_
//hey, we can configure a provider! _x000D_
myApp.config(function(helloWorldProvider){_x000D_
helloWorldProvider.setName('World');_x000D_
});_x000D_
_x000D_
_x000D_
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {_x000D_
_x000D_
$scope.hellos = [_x000D_
helloWorld.sayHello(),_x000D_
helloWorldFromFactory.sayHello(),_x000D_
helloWorldFromService.sayHello()];_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
You might not have the ability to install Expect on the target server. This is often the case when one writes, say, a Jenkins job.
If so, I would consider something like the answer to the following on askubuntu.com:
https://askubuntu.com/questions/338857/automatically-enter-input-in-command-line
printf 'y\nyes\nno\nmaybe\n' | ./script_that_needs_user_input
Note that in some rare cases the command does not require the user to press enter after the character. in that case leave the newlines out:
printf 'yyy' | ./script_that_needs_user_input
For sake of completeness you can also use a here document:
./script_that_needs_user_input << EOF
y
y
y
EOF
Or if your shell supports it a here string:
./script <<< "y
y
y
"
Or you can create a file with one input per line:
./script < inputfile
Again, all credit for this answer goes to the author of the answer on askubuntu.com, lesmana.
Assuming HTTP authentication (WWW-Authenticate and Authorization headers) is in use, if authenticating as another user would grant access to the requested resource, then 401 Unauthorized should be returned.
403 Forbidden is used when access to the resource is forbidden to everyone or restricted to a given network or allowed only over SSL, whatever as long as it is no related to HTTP authentication.
If HTTP authentication is not in use and the service a cookie-based authentication scheme as is the norm nowadays, then a 403 or a 404 should be returned.
Regarding 401, this is from RFC 7235 (Hypertext Transfer Protocol (HTTP/1.1): Authentication):
3.1. 401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The origin server MUST send a WWW-Authenticate header field (Section 4.4) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The client MAY repeat the request with a new or replaced Authorization header field (Section 4.1). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.
The semantics of 403 (and 404) have changed over time. This is from 1999 (RFC 2616):
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
If the request method was not HEAD and the server wishes to make
public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404
(Not Found) can be used instead.
In 2014 RFC 7231 (Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content) changed the meaning of 403:
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the
server considers them insufficient to grant access. The client
SHOULD NOT automatically repeat the request with the same
credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons
unrelated to the credentials.An origin server that wishes to "hide" the current existence of a
forbidden target resource MAY instead respond with a status code of
404 (Not Found).
Thus, a 403 (or a 404) might now mean about anything. Providing new credentials might help... or it might not.
I believe the reason why this has changed is RFC 2616 assumed HTTP authentication would be used when in practice today's Web apps build custom authentication schemes using for example forms and cookies.
You need to clone in ssh not in https.
For that you need to set your ssh keys. I have prepared this little script that automates this:
#!/usr/bin/env bash
email="$1"
hostname="$2"
hostalias="$hostname"
keypath="$HOME/.ssh/${hostname}_rsa"
ssh-keygen -t rsa -C $email -f $keypath
if [ $? -eq 0 ]; then
cat >> ~/.ssh/config <<EOF
Host $hostalias
Hostname $hostname *.$hostname
User git
IdentitiesOnly yes
IdentityFile $keypath
EOF
fi
and run it like
bash script.sh [email protected] github.com
Change your remote url
git remote set-url origin [email protected]:user/foo.git
Add content of ~/.ssh/github.com_rsa.pub
to your ssh keys on github.com
Check connection
ssh -T [email protected]
It is not strange for me that none of the solutions above came up, but I saw how the igd installation removed the new version and installed the old one, for the solution I downloaded this archive:https://pypi.org/project/igd/#files
and changed the recommended version of the new version: 'lxml==4.3.0' in setup.py It works!
Not exactly the same problem for me, because I was running the last java version 1.8.0_92, IE v11 and windows 7.
My situation was also that I had Chrome as the default browser.
So what for me fixed it, was to set IExplorer as the default browser again, uninstall Java, go to Java.com using the IExplorer, and from the IExplorer download and install Java again to the last version.
'entityManager.unwrap(Session.class)' is used to get session from EntityManager.
@Repository
@Transactional
public class EmployeeRepository {
@PersistenceContext
private EntityManager entityManager;
public Session getSession() {
Session session = entityManager.unwrap(Session.class);
return session;
}
......
......
}
Demo Application link.
Have a look at this
for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.
For me the solution was one of the methods had to be void, I had it as Boolean.
This should work:
$(document).ready(function() {
$("someTableSelector").find("tr:gt(0)").remove();
});
To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook
However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.
Put these two lines before you import anything else from matplotlib:
import matplotlib
matplotlib.use('GTKAgg')
Of course, there are various options to use instead of GTKAgg
, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.