For when TypeScript is your preferred lang. of development
<template>
<span class="someClassName">
{{feesInLocale}}
</span>
</template>
@Prop({default: 0}) fees: any;
// computed are declared with get before a function
get feesInLocale() {
return this.fees;
}
and not
<template>
<span class="someClassName">
{{feesInLocale}}
</span>
</template>
@Prop() fees: any = 0;
get feesInLocale() {
return this.fees;
}
This error is occur,because the function is not defined. In my case i have called the datepicker function without including the datepicker js file that time I got this error.
ok so my solution for this was:
this.arrayWeNeed.DoWhatWeNeedWithThisArray();
const tempArray = [...arrayWeNeed];
this.arrayWeNeed = [];
this.arrayWeNeed = tempArray;
And this trigger me ngOnChanges
These toolz are great for this kind of simple yet repetitive logic.
http://toolz.readthedocs.org/en/latest/api.html#toolz.dicttoolz.valmap
Gets you right where you want to be.
import toolz
def f(x):
return x+1
toolz.valmap(f, my_list)
frame.setContentPane(newContents());
frame.revalidate(); // frame.pack() if you want to resize.
Remember, Java use 'copy reference by value' argument passing. So changing a variable wont change copies of the reference passed to other methods.
Also note JFrame
is very confusing in the name of usability. Adding a component or setting a layout (usually) performs the operation on the content pane. Oddly enough, getting the layout really does give you the frame's layout manager.
There is no single MVC pattern you could obey to. MVC just states more or less that you should not mingle data and view, so that e.g. views are responsible for holding data or classes which are processing data are directly affecting the view.
But nevertheless, the way Android deals with classes and resources, you're sometimes even forced to follow the MVC pattern. More complicated in my opinion are the activities which are responsible sometimes for the view, but nevertheless act as an controller in the same time.
If you define your views and layouts in the XML files, load your resources from the res folder, and if you avoid more or less to mingle these things in your code, then you're anyway following an MVC pattern.
$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value
I found a much simpler alternative way to generating soap message. Given a Person Object:
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String name;
private int age;
private String address; //setter and getters below
}
Below is a simple Soap Message Generator:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@Slf4j
public class SoapGenerator {
protected static final ObjectMapper XML_MAPPER = new XmlMapper()
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule());
private static final String SOAP_BODY_OPEN = "<soap:Body>";
private static final String SOAP_BODY_CLOSE = "</soap:Body>";
private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";
public static String soapWrap(String xml) {
return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
}
public static String soapUnwrap(String xml) {
return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
}
}
You can use by:
public static void main(String[] args) throws Exception{
Person p = new Person();
p.setName("Test");
p.setAge(12);
String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
log.info("Generated String");
log.info(xml);
}
There's a description of how to do this at Resize a column in a PostgreSQL table without changing data. You have to hack the database catalog data. The only way to do this officially is with ALTER TABLE, and as you've noted that change will lock and rewrite the entire table while it's running.
Make sure you read the Character Types section of the docs before changing this. All sorts of weird cases to be aware of here. The length check is done when values are stored into the rows. If you hack a lower limit in there, that will not reduce the size of existing values at all. You would be wise to do a scan over the whole table looking for rows where the length of the field is >40 characters after making the change. You'll need to figure out how to truncate those manually--so you're back some locks just on oversize ones--because if someone tries to update anything on that row it's going to reject it as too big now, at the point it goes to store the new version of the row. Hilarity ensues for the user.
VARCHAR is a terrible type that exists in PostgreSQL only to comply with its associated terrible part of the SQL standard. If you don't care about multi-database compatibility, consider storing your data as TEXT and add a constraint to limits its length. Constraints you can change around without this table lock/rewrite problem, and they can do more integrity checking than just the weak length check.
The function STR_TO_DATE(COLUMN, '%input_format') can do it, you only have to specify the input format. Example : to convert p052011
SELECT STR_TO_DATE('p052011','p%m%Y') FROM your_table;
The result : 2011-05-00
Here a solution for Swift 5.2
PlayerView.swift:
import AVFoundation
import UIKit
class PlayerView: UIView {
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
// Override UIView property
override static var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
VideoPlayer.swift
import AVFoundation
import Foundation
protocol VideoPlayerDelegate {
func downloadedProgress(progress:Double)
func readyToPlay()
func didUpdateProgress(progress:Double)
func didFinishPlayItem()
func didFailPlayToEnd()
}
let videoContext: UnsafeMutableRawPointer? = nil
class VideoPlayer : NSObject {
private var assetPlayer:AVPlayer?
private var playerItem:AVPlayerItem?
private var urlAsset:AVURLAsset?
private var videoOutput:AVPlayerItemVideoOutput?
private var assetDuration:Double = 0
private var playerView:PlayerView?
private var autoRepeatPlay:Bool = true
private var autoPlay:Bool = true
var delegate:VideoPlayerDelegate?
var playerRate:Float = 1 {
didSet {
if let player = assetPlayer {
player.rate = playerRate > 0 ? playerRate : 0.0
}
}
}
var volume:Float = 1.0 {
didSet {
if let player = assetPlayer {
player.volume = volume > 0 ? volume : 0.0
}
}
}
// MARK: - Init
convenience init(urlAsset:NSURL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
self.init()
playerView = view
autoPlay = startAutoPlay
autoRepeatPlay = repeatAfterEnd
if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
}
initialSetupWithURL(url: urlAsset)
prepareToPlay()
}
override init() {
super.init()
}
// MARK: - Public
func isPlaying() -> Bool {
if let player = assetPlayer {
return player.rate > 0
} else {
return false
}
}
func seekToPosition(seconds:Float64) {
if let player = assetPlayer {
pause()
if let timeScale = player.currentItem?.asset.duration.timescale {
player.seek(to: CMTimeMakeWithSeconds(seconds, preferredTimescale: timeScale), completionHandler: { (complete) in
self.play()
})
}
}
}
func pause() {
if let player = assetPlayer {
player.pause()
}
}
func play() {
if let player = assetPlayer {
if (player.currentItem?.status == .readyToPlay) {
player.play()
player.rate = playerRate
}
}
}
func cleanUp() {
if let item = playerItem {
item.removeObserver(self, forKeyPath: "status")
item.removeObserver(self, forKeyPath: "loadedTimeRanges")
}
NotificationCenter.default.removeObserver(self)
assetPlayer = nil
playerItem = nil
urlAsset = nil
}
// MARK: - Private
private func prepareToPlay() {
let keys = ["tracks"]
if let asset = urlAsset {
asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
DispatchQueue.main.async {
self.startLoading()
}
})
}
}
private func startLoading(){
var error:NSError?
guard let asset = urlAsset else {return}
let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: &error)
if status == AVKeyValueStatus.loaded {
assetDuration = CMTimeGetSeconds(asset.duration)
let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
playerItem = AVPlayerItem(asset: asset)
if let item = playerItem {
item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
if let output = videoOutput {
item.add(output)
item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed
assetPlayer = AVPlayer(playerItem: item)
if let player = assetPlayer {
player.rate = playerRate
}
addPeriodicalObserver()
if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
layer.player = assetPlayer
print("player created")
}
}
}
}
}
private func addPeriodicalObserver() {
let timeInterval = CMTimeMake(value: 1, timescale: 1)
if let player = assetPlayer {
player.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main, using: { (time) in
self.playerDidChangeTime(time: time)
})
}
}
private func playerDidChangeTime(time:CMTime) {
if let player = assetPlayer {
let timeNow = CMTimeGetSeconds(player.currentTime())
let progress = timeNow / assetDuration
delegate?.didUpdateProgress(progress: progress)
}
}
@objc private func playerItemDidReachEnd() {
delegate?.didFinishPlayItem()
if let player = assetPlayer {
player.seek(to: CMTime.zero)
if autoRepeatPlay == true {
play()
}
}
}
@objc private func didFailedToPlayToEnd() {
delegate?.didFailPlayToEnd()
}
private func playerDidChangeStatus(status:AVPlayer.Status) {
if status == .failed {
print("Failed to load video")
} else if status == .readyToPlay, let player = assetPlayer {
volume = player.volume
delegate?.readyToPlay()
if autoPlay == true && player.rate == 0.0 {
play()
}
}
}
private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
var maximum:TimeInterval = 0
for value in ranges {
let range:CMTimeRange = value.timeRangeValue
let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
if currentLoadedTimeRange > maximum {
maximum = currentLoadedTimeRange
}
}
let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration
delegate?.downloadedProgress(progress: progress)
}
deinit {
cleanUp()
}
private func initialSetupWithURL(url:NSURL) {
let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
urlAsset = AVURLAsset(url: url as URL, options: options)
}
// MARK: - Observations
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == videoContext {
if let key = keyPath {
if key == "status", let player = assetPlayer {
playerDidChangeStatus(status: player.status)
} else if key == "loadedTimeRanges", let item = playerItem {
moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
}
}
}
}
}
Usage:
private var playerView: PlayerView = PlayerView()
private var videoPlayer:VideoPlayer?
and inside viewDidLoad()
:
view.addSubview(playerView)
preparePlayer()
// set Constraints (if you do it purely in code)
playerView.translatesAutoresizingMaskIntoConstraints = false
playerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10.0).isActive = true
playerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10.0).isActive = true
playerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10.0).isActive = true
playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10.0).isActive = true
private func preparePlayer() {
if let filePath = Bundle.main.path(forResource: "my video", ofType: "mp4") {
let fileURL = NSURL(fileURLWithPath: filePath)
videoPlayer = VideoPlayer(urlAsset: fileURL, view: playerView)
if let player = videoPlayer {
player.playerRate = 0.67
}
}
}
If accessing/printing single element lists (e.g., sequentially or filtered):
my_list = [u'String'] # sample element
my_list = [str(my_list[0])]
If you aren't a fan of passing in a string, I prefer how @sesperanto has done it, except to make it even more concise, you could drop Float::INFINITY
in the date range and instead simply use created_at: p[:date]..
Note.where(
user_id: current_user.id,
notetype: p[:note_type],
created_at: p[:date]..
).order(:date, :created_at)
Take note that this will change the query to be >=
instead of >
. If that's a concern, you could always add a unit of time to the date by running something like p[:date] + 1.day..
Here's an option for resizing the font heights interactively, one point at a time:
;; font sizes
(global-set-key (kbd "s-=")
(lambda ()
(interactive)
(let ((old-face-attribute (face-attribute 'default :height)))
(set-face-attribute 'default nil :height (+ old-face-attribute 10)))))
(global-set-key (kbd "s--")
(lambda ()
(interactive)
(let ((old-face-attribute (face-attribute 'default :height)))
(set-face-attribute 'default nil :height (- old-face-attribute 10)))))
This is preferable when you want to resize text in all buffers. I don't like solutions using text-scale-increase
and text-scale-decrease
as line numbers in the gutter can get cut off afterwards.
I personally have this issue in Visual 2012 with x64 applications when I check the option "Managed C++ Compatibility Mode" of Debugging->General options of Tools->Options
menu.
=> Unchecking this option fixes the problem.
Have you looked at Delphi for PHP (<http://www.codegear.com/products/delphi/php>) ?
Joe Stagner of Microsoft really likes Delphi for PHP.
He says it here: "[Delphi for PHP] 2.0 is the REAL DEAL and I LOVE IT !"
//Calling close and then quit will kill the driver running process.
driver.close();
driver.quit();
Try this:
Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help +extension name Enable extension -extension name Disable extension
Application.DoEvents can create problems, if something other than graphics processing is put in the message queue.
It can be useful for updating progress bars and notifying the user of progress in something like MainForm construction and loading, if that takes a while.
In a recent application I've made, I used DoEvents to update some labels on a Loading Screen every time a block of code is executed in the constructor of my MainForm. The UI thread was, in this case, occupied with sending an email on a SMTP server that didn't support SendAsync() calls. I could probably have created a different thread with Begin() and End() methods and called a Send() from their, but that method is error-prone and I would prefer the Main Form of my application not throwing exceptions during construction.
Given some SVG:
<div id="main">
<svg id="octocat" xmlns="http://www.w3.org/2000/svg" width="400px" height="400px" viewBox="-60 0 420 330" style="fill:#fff;stroke: #000; stroke-opacity: 0.1">
<path id="puddle" d="m296.94 295.43c0 20.533-47.56 37.176-106.22 37.176-58.67 0-106.23-16.643-106.23-37.176s47.558-37.18 106.23-37.18c58.66 0 106.22 16.65 106.22 37.18z"/>
<path class="shadow-legs" d="m161.85 331.22v-26.5c0-3.422-.619-6.284-1.653-8.701 6.853 5.322 7.316 18.695 7.316 18.695v17.004c6.166.481 12.534.773 19.053.861l-.172-16.92c-.944-23.13-20.769-25.961-20.769-25.961-7.245-1.645-7.137 1.991-6.409 4.34-7.108-12.122-26.158-10.556-26.158-10.556-6.611 2.357-.475 6.607-.475 6.607 10.387 3.775 11.33 15.105 11.33 15.105v23.622c5.72.98 11.71 1.79 17.94 2.4z"/>
<path class="shadow-legs" d="m245.4 283.48s-19.053-1.566-26.16 10.559c.728-2.35.839-5.989-6.408-4.343 0 0-19.824 2.832-20.768 25.961l-.174 16.946c6.509-.025 12.876-.254 19.054-.671v-17.219s.465-13.373 7.316-18.695c-1.034 2.417-1.653 5.278-1.653 8.701v26.775c6.214-.544 12.211-1.279 17.937-2.188v-24.113s.944-11.33 11.33-15.105c0-.01 6.13-4.26-.48-6.62z"/>
<path id="cat" d="m378.18 141.32l.28-1.389c-31.162-6.231-63.141-6.294-82.487-5.49 3.178-11.451 4.134-24.627 4.134-39.32 0-21.073-7.917-37.931-20.77-50.759 2.246-7.25 5.246-23.351-2.996-43.963 0 0-14.541-4.617-47.431 17.396-12.884-3.22-26.596-4.81-40.328-4.81-15.109 0-30.376 1.924-44.615 5.83-33.94-23.154-48.923-18.411-48.923-18.411-9.78 24.457-3.733 42.566-1.896 47.063-11.495 12.406-18.513 28.243-18.513 47.659 0 14.658 1.669 27.808 5.745 39.237-19.511-.71-50.323-.437-80.373 5.572l.276 1.389c30.231-6.046 61.237-6.256 80.629-5.522.898 2.366 1.899 4.661 3.021 6.879-19.177.618-51.922 3.062-83.303 11.915l.387 1.36c31.629-8.918 64.658-11.301 83.649-11.882 11.458 21.358 34.048 35.152 74.236 39.484-5.704 3.833-11.523 10.349-13.881 21.374-7.773 3.718-32.379 12.793-47.142-12.599 0 0-8.264-15.109-24.082-16.292 0 0-15.344-.235-1.059 9.562 0 0 10.267 4.838 17.351 23.019 0 0 9.241 31.01 53.835 21.061v32.032s-.943 11.33-11.33 15.105c0 0-6.137 4.249.475 6.606 0 0 28.792 2.361 28.792-21.238v-34.929s-1.142-13.852 5.663-18.667v57.371s-.47 13.688-7.551 18.881c0 0-4.723 8.494 5.663 6.137 0 0 19.824-2.832 20.769-25.961l.449-58.06h4.765l.453 58.06c.943 23.129 20.768 25.961 20.768 25.961 10.383 2.357 5.663-6.137 5.663-6.137-7.08-5.193-7.551-18.881-7.551-18.881v-56.876c6.801 5.296 5.663 18.171 5.663 18.171v34.929c0 23.6 28.793 21.238 28.793 21.238 6.606-2.357.474-6.606.474-6.606-10.386-3.775-11.33-15.105-11.33-15.105v-45.786c0-17.854-7.518-27.309-14.87-32.3 42.859-4.25 63.426-18.089 72.903-39.591 18.773.516 52.557 2.803 84.873 11.919l.384-1.36c-32.131-9.063-65.692-11.408-84.655-11.96.898-2.172 1.682-4.431 2.378-6.755 19.25-.80 51.38-.79 82.66 5.46z"/>
<path id="face" d="m258.19 94.132c9.231 8.363 14.631 18.462 14.631 29.343 0 50.804-37.872 52.181-84.585 52.181-46.721 0-84.589-7.035-84.589-52.181 0-10.809 5.324-20.845 14.441-29.174 15.208-13.881 40.946-6.531 70.147-6.531 29.07-.004 54.72-7.429 69.95 6.357z"/>
<path id="eyes" d="m160.1 126.06 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z m94.43 0 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z"/>
<path id="pupils" d="m154.46 126.38 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z m94.42 0 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z"/>
<circle id="nose" cx="188.5" cy="148.56" r="4.401"/>
<path id="mouth" d="m178.23 159.69c-.26-.738.128-1.545.861-1.805.737-.26 1.546.128 1.805.861 1.134 3.198 4.167 5.346 7.551 5.346s6.417-2.147 7.551-5.346c.26-.738 1.067-1.121 1.805-.861s1.121 1.067.862 1.805c-1.529 4.324-5.639 7.229-10.218 7.229s-8.68-2.89-10.21-7.22z"/>
<path id="octo" d="m80.641 179.82 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m8.5 4.72 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.193 6.14 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m4.72 7.08 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.188 6.61 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m7.09 5.66 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.91 3.78 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.87 0 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m10.01 -1.64 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z"/>
<path id="drop" d="m69.369 186.12l-3.066 10.683s-.8 3.861 2.84 4.546c3.8-.074 3.486-3.627 3.223-4.781z"/>
</svg>
</div>
Using jQuery, for instance, you could do:
var _currentFill = "#f00"; // red
$svg = $("#octocat");
$("#face", $svg).attr('style', "fill:"+_currentFill); })
I provided a coloring book demo as an answer to another stackoverflow question: http://bl.ocks.org/4545199. Tested on Safari, Chrome, and Firefox.
As stated multiple times, inversion is achieved by the -v
option to grep
. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep
help text:
grep --help | grep invert
-v, --invert-match select non-matching lines
For me, the problem was trying to pass a filename in a url, with a dot. For example
"http://localhost:8080/something/asdf.jpg" //causes error because of '.jpg'
It could be solved by not passing the .jpg extension, or sending it all in a request body.
We don't have append function for Array in javascript, but we have push and unshift, imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
and we like append a value to this array, we can do, arr.push(6) and it will add 6 to the end of the array:
arr.push(6); // return [1, 2, 3, 4, 5, 6];
also we can use unshift, look at how we can apply this:
arr.unshift(0); //return [0, 1, 2, 3, 4, 5];
They are main functions to add or append new values to the arrays.
You are using |
(pipe) to direct the output of a command into another command. What you are looking for is &&
operator to execute the next command only if the previous one succeeded:
cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple
Or
cp /templates/apple /templates/used && mv /templates/apple /templates/inuse
To summarize (non-exhaustively) bash's command operators/separators:
|
pipes (pipelines) the standard output (stdout
) of one command into the standard input of another one. Note that stderr
still goes into its default destination, whatever that happen to be.|&
pipes both stdout
and stderr
of one command into the standard input of another one. Very useful, available in bash version 4 and above.&&
executes the right-hand command of &&
only if the previous one succeeded.||
executes the right-hand command of ||
only it the previous one failed.;
executes the right-hand command of ;
always regardless whether the previous command succeeded or failed. Unless set -e
was previously invoked, which causes bash
to fail on an error.Only tested in Chrome 44.
Example: http://codepen.io/hugovk/pen/OVqBoq
HTML:
<div>
<img src="http://lorempixel.com/1600/900/">
</div>
CSS:
<style type="text/css">
img {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
max-width: 100%;
max-height: 100%;
}
</style>
I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.
Now, it's exactly like the error message says: You can't capture stuff outside of the enclosing scope of the lambda.† grid
is not in the enclosing scope, but this
is (every access to grid
actually happens as this->grid
in member functions). For your usecase, capturing this
works, since you'll use it right away and you don't want to copy the grid
auto lambda = [this](){ std::cout << grid[0][0] << "\n"; }
If however, you want to store the grid and copy it for later access, where your puzzle
object might already be destroyed, you'll need to make an intermediate, local copy:
vector<vector<int> > tmp(grid);
auto lambda = [tmp](){}; // capture the local copy per copy
† I'm simplifying - Google for "reaching scope" or see §5.1.2 for all the gory details.
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
You need to wait for the emulator to full start - takes a few minutes. Once it is fully started (UI on the emulator will change), it should work.
You will need to restart the app after the emulator is running and choose the running emulator when prompted.
Just enable parsing of the autoexec.bat in the registry, using these instructions.
:: works only on windows vista and earlier
Run REGEDT32.EXE.
Modify the following value within HKEY_CURRENT_USER:
Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ParseAutoexec
1 = autoexec.bat is parsed
0 = autoexec.bat is not parsed
Only Files
Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}
Only Folders
Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}
Both
Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}
One liner as suggested here
How to determine one year from now in Javascript by JP DeVries
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
Or you can get the number of years from somewhere in a variable:
const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
Unfortunately the switch option to mount a volume is only found in the run
command.
docker run --help
-v, --volume list Bind mount a volume (default [])
There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.
docker container export -o ./myimage.docker mycontainer
docker import ./myimage.docker myimage
docker run -i -t -v /somedir --name mycontainer myimage /bin/bash
I found that I needed window = Tk()
and then window.mainloop()
Using of WildcardPattern
from System.Management.Automation
may be an option.
pattern = new WildcardPattern(patternString);
pattern.IsMatch(stringToMatch);
Visual Studio UI may not allow you to add System.Management.Automation
assembly to References of your project. Feel free to add it manually, as described here.
This answer aims to force an image pull in a situation where your node has already downloaded an image with the same name, therefore even though you push a new image to container registry, when you spin up some pods, your pod says "image already present".
For a case in Azure Container Registry (probably AWS and GCP also provides this):
You can look to your Azure Container Registry and by checking the manifest creation date you can identify what image is the most recent one.
Then, copy its digest hash (which has a format of sha256:xxx...xxx
).
You can scale down your current replica by running command below. Note that this will obviously stop your container and cause downtime.
kubectl scale --replicas=0 deployment <deployment-name> -n <namespace-name>
kubectl get deployments.apps <deployment-name> -o yaml > deployment.yaml
Then change the line with image field from <image-name>:<tag>
to <image-name>@sha256:xxx...xxx
, save the file.
Now you can scale up your replicas again. New image will be pulled with its unique digest.
Note: It is assumed that, imagePullPolicy: Always field is present in the container.
test -e
will test whether a file exists or not. The test command returns a zero value if the test succeeds or 1 otherwise.
Test can be written either as test -e
or using []
[ -e "$file_name" ] && grep "poet" $file_name
Unless you actually need the output of grep you can test the return value as grep will return 1 if there are no matches and zero if there are any.
In general terms you can test if a string is non-empty using [ "string" ]
which will return 0 if non-empty and 1 if empty
In my case, it was due to me calling the Makefile: MAKEFILE (all caps)
You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.
Public Sub SaveToDesktop()
ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
I'm not sure whether this would be a requirement, but may help!
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath())
doesn't work for all paths! The path is still URL-encoded!)
You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm
My own standard loop looks something like this:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
'Perform an edit
rs.Edit
rs!VendorYN = True
rs("VendorYN") = True 'The other way to refer to a field
rs.Update
'Save contact name into a variable
sContactName = rs!FirstName & " " & rs!LastName
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Finished looping through records."
rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
In .NET you don't find only C#. You can find Visual Basic for example. If a job requires .NET knowledge, probably it need a programmer who knows the entire set of languages provided by the .NET framework.
You can use something like this :
SELECT
Books.BookTitle,
Books.Edition,
Books.Year,
Books.Pages,
Books.Rating,
Categories.Category,
Publishers.Publisher,
Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.
For port 80 (which was the original question), Daniel is exactly right. I recently moved to https
and had to switch from iptables
to a light nginx proxy managing the SSL certs. I found a useful answer along with a gist by gabrielhpugliese on how to handle that. Basically I
Created an SSL Certificate Signing Request (CSR) via OpenSSL
openssl genrsa 2048 > private-key.pem
openssl req -new -key private-key.pem -out csr.pem
Changed the location
in /etc/nginx/conf.d/example_ssl.conf
to
location / {
proxy_pass http://localhost:3000;
proxy_set_header X-Real-IP $remote_addr;
}
Formatted the cert for nginx by cat
-ing the individual certs together and linked to it in my nginx example_ssl.conf
file (and uncommented stuff, got rid of 'example' in the name,...)
ssl_certificate /etc/nginx/ssl/cert_bundle.cert;
ssl_certificate_key /etc/nginx/ssl/private-key.pem;
Hopefully that can save someone else some headaches. I'm sure there's a pure-node way of doing this, but nginx was quick and it worked.
Forms in C# are classes that inherit the Form
base class.
You can show a popup by creating an instance of the class and calling ShowDialog()
.
For Me I use the input stage param:
When a user launch a pipeline, this one will be waiting him to choose on the list choice.
pipeline{
agent any
stages{
stage('checkout scm') {
steps {
script{
git credentialsId: '8bd8-419d-8af0-30960441fcd7', url: 'ssh://[email protected]:/usr/company/repositories/repo.git'
sh 'git branch -r | awk \'{print $1}\' ORS=\'\\n\' >>branch.txt'
}
}
}
stage('get build Params User Input') {
steps{
script{
liste = readFile 'branch.txt'
echo "please click on the link here to chose the branch to build"
env.BRANCH_SCOPE = input message: 'Please choose the branch to build ', ok: 'Validate!',
parameters: [choice(name: 'BRANCH_NAME', choices: "${liste}", description: 'Branch to build?')]
}
}
}
stage("checkout the branch"){
steps{
echo "${env.BRANCH_SCOPE}"
git credentialsId: 'ea346a50-8bd8-419d-8af0-30960441fcd7', url: 'ssh://[email protected]/usr/company/repositories/repo.git'
sh "git checkout -b build ${env.BRANCH_NAME}"
}
}
stage(" exec maven build"){
steps{
withMaven(maven: 'M3', mavenSettingsConfig: 'mvn-setting-xml') {
sh "mvn clean install "
}
}
}
stage("clean workwpace"){
steps{
cleanWs()
}
}
}
}
And then user will interact withim the build :
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
Outline is good, but only when you want the border all around.
Lets say if you want to make it only on bottom or top you can use
<style>
#border-top {
border-top: 1px solid #ccc;
box-shadow: inset 0 1px 0 #fff;
}
</style>
<p id="border-top">This is my content</p>
And for bottom:
<style>
#border-bottom {
border-top: 1px solid #ccc;
box-shadow: 0 1px 0 #fff;
}
</style>
<p id="border-bottom">This is my content</p>
Hope that this helps.
Using modern standards and compiler, no!
Some of the folks here have suggested that FORTRAN is faster because the compiler doesn't need to worry about aliasing (and hence can make more assumptions during optimisation). However, this has been dealt with in C since the C99 (I think) standard with the inclusion of the restrict keyword. Which basically tells the compiler, that within a give scope, the pointer is not aliased. Furthermore C enables proper pointer arithmetic, where things like aliasing can be very useful in terms of performance and resource allocation. Although I think more recent version of FORTRAN enable the use of "proper" pointers.
For modern implementations C general outperforms FORTRAN (although it is very fast too).
http://benchmarksgame.alioth.debian.org/u64q/fortran.html
EDIT:
A fair criticism of this seems to be that the benchmarking may be biased. Here is another source (relative to C) that puts result in more context:
http://julialang.org/benchmarks/
You can see that C typically outperforms Fortran in most instances (again see criticisms below that apply here too); as others have stated, benchmarking is an inexact science that can be easily loaded to favour one language over others. But it does put in context how Fortran and C have similar performance.
The standard SQL way is to use like:
where @stringVar like '%thisstring%'
That is in a query statement. You can also do this in TSQL:
if @stringVar like '%thisstring%'
Print service
import { Injectable } from '@angular/core';
@Injectable()
export class PrintingService {
public print(printEl: HTMLElement) {
let printContainer: HTMLElement = document.querySelector('#print-container');
if (!printContainer) {
printContainer = document.createElement('div');
printContainer.id = 'print-container';
}
printContainer.innerHTML = '';
let elementCopy = printEl.cloneNode(true);
printContainer.appendChild(elementCopy);
document.body.appendChild(printContainer);
window.print();
}
}
?omponent that I want to print
@Component({
selector: 'app-component',
templateUrl: './component.component.html',
styleUrls: ['./component.component.css'],
encapsulation: ViewEncapsulation.None
})
export class MyComponent {
@ViewChild('printEl') printEl: ElementRef;
constructor(private printingService: PrintingService) {}
public print(): void {
this.printingService.print(this.printEl.nativeElement);
}
}
Not the best choice, but works.
For me, in our work environment, we have Windows 7 64-bit with the machines locked down running McAfee with Host Intrusion turned on.
I turned off Host Intrusion and gradle would finally work, so definitely, it appears to be issues with certain Virus scanners.
UPDATE: Well I spoke too soon. Yes, I know longer get the "Unable to start the daemon process" message, but now I get the following:
Error:Could not list versions using M2 pattern 'http://jcenter.bintray.com/[organisation]/[module]/[revision]/[artifact]-revision.[ext]'.
I've used this in beamer
, but not for general documents, but it looks like that's what the original hint suggests
\newenvironment{changemargin}[2]{%
\begin{list}{}{%
\setlength{\topsep}{0pt}%
\setlength{\leftmargin}{#1}%
\setlength{\rightmargin}{#2}%
\setlength{\listparindent}{\parindent}%
\setlength{\itemindent}{\parindent}%
\setlength{\parsep}{\parskip}%
}%
\item[]}{\end{list}}
Then to use it
\begin{changemargin}{-1cm}{-1cm}
don't forget to
\end{changemargin}
at the end of the page
I got this from Changing margins “on the fly” in the TeX FAQ.
As long as method parameters (number (or) type) are different, yes they can. It is called overloading.
Overloaded methods are differentiated by the number and the type of the arguments passed into the method
public static void main(String[] args)
only main method with single String[]
(or) String...
as param will be considered as entry point for the program.
why not use the extension_loaded() function?
You can use Python-dateutil's relativedelta
to increment a datetime
object while remaining sensitive to things like leap years and month lengths. Python-dateutil comes packaged with matplotlib if you already have that. You can do the following:
from dateutil.relativedelta import relativedelta
new_date = old_date + relativedelta(years=1)
(This answer was given by @Max to a similar question).
But if your date is a string (i.e. not already a datetime
object) you can convert it using datetime:
from datetime import datetime
from dateutil.relativedelta import relativedelta
your_date_string = "April 1, 2012"
format_string = "%B %d, %Y"
datetime_object = datetime.strptime(your_date_string, format_string).date()
new_date = datetime_object + relativedelta(years=1)
new_date_string = datetime.strftime(new_date, format_string).replace(' 0', ' ')
new_date_string
will contain "April 1, 2013".
NB: Unfortunately, datetime
only outputs day values as "decimal numbers" - i.e. with leading zeros if they're single digit numbers. The .replace()
at the end is a workaround to deal with this issue copied from @Alex Martelli (see this question for his and other approaches to this problem).
I had the same issue on MySQL. I took the procedure from symcbean and adapted her to my needs.
Mine is only replacing textual values (or any type you put in the SELECT FROM information_schema) so if you have date fields, you will not have an error in execution.
Mind the collate in SET @stmt, it must match you database collation.
I used a template request in a variable with multiple replaces but if you have motivation, you could have done it with one CONCAT().
Anyway, if you have serialized data in your database, don't use this. It will not work unless you replace your string with a string with the same lenght.
Hope it helps someone.
DELIMITER $$
DROP PROCEDURE IF EXISTS replace_all_occurences_in_database$$
CREATE PROCEDURE replace_all_occurences_in_database (find_string varchar(255), replace_string varchar(255))
BEGIN
DECLARE loop_done integer DEFAULT 0;
DECLARE current_table varchar(255);
DECLARE current_column varchar(255);
DECLARE all_columns CURSOR FOR
SELECT
t.table_name,
c.column_name
FROM information_schema.tables t,
information_schema.columns c
WHERE t.table_schema = DATABASE()
AND c.table_schema = DATABASE()
AND t.table_name = c.table_name
AND c.DATA_TYPE IN('varchar', 'text', 'longtext');
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET loop_done = 1;
OPEN all_columns;
table_loop:
LOOP
FETCH all_columns INTO current_table, current_column;
IF (loop_done > 0) THEN
LEAVE table_loop;
END IF;
SET @stmt = 'UPDATE `|table|` SET `|column|` = REPLACE(`|column|`, "|find|", "|replace|") WHERE `|column|` LIKE "%|find|%"' COLLATE `utf8mb4_unicode_ci`;
SET @stmt = REPLACE(@stmt, '|table|', current_table);
SET @stmt = REPLACE(@stmt, '|column|', current_column);
SET @stmt = REPLACE(@stmt, '|find|', find_string);
SET @stmt = REPLACE(@stmt, '|replace|', replace_string);
PREPARE s1 FROM @stmt;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END LOOP;
END
$$
DELIMITER ;
This cheatsheet lists some common caveats related to UTF-8 handling in PHP: http://developer.loftdigital.com/blog/php-utf-8-cheatsheet
This function detecting multibyte characters in a string might also prove helpful (source):
function detectUTF8($string)
{
return preg_match('%(?:
[\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
|\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
|\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
|\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
|[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
|\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)+%xs',
$string);
}
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
With that in mind, the closest you could come is to use a PHP variable in your JS:
<?php
$a = 'foo'; // $a now holds PHP string foo
?>
<script>
var a = '<?php echo $a; ?>'; //outputting string foo in context of JS
//must wrap in quotes so that it is still string foo when JS does execute
//when this DOES execute in the browser, PHP will have already completed all processing and exited
</script>
<?php
//do something else with $a
//JS still hasn't executed at this point
?>
As I stated, in this scenario the PHP (ALL of it) executes FIRST at the server, causing:
$a
to be created as string 'foo'$a
to be outputted in context of some JavaScript (which is not currently executing)$a
As written, this results in the following being sent to the browser for execution (I removed the JS comments for clarity):
<script>
var a = 'foo';
</script>
Then, and only then, will the JS start executing with its own variable a
set to "foo" (at which point PHP is out of the picture).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.
IMPORTANT: You must start ssh-agent
You must start ssh-agent (if it is not running already) before using ssh-add as follows:
eval `ssh-agent -s` # start the agent
ssh-add id_rsa_2 # Where id_rsa_2 is your new private key file
Note that the eval command starts the agent on Git Bash on Windows. Other environments may use a variant to start the SSH agent.
I think error is not coming from the specified line but from the first 3 lines. Try this instead :
node {
stage("first") {
def foo = "foo"
sh "echo ${foo}"
}
}
I think you had some extra lines that are not valid...
From declaractive pipeline model documentation, it seems that you have to use an environment
declaration block to declare your variables, e.g.:
pipeline {
environment {
FOO = "foo"
}
agent none
stages {
stage("first") {
sh "echo ${FOO}"
}
}
}
They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.
Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.
Now... main (or little) differences you can see right now are:
SCAFFOLDING AND BOILERPLATE GENERATION
Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators
MODULARITY
Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...
BUILD SYSTEM
Mean.io has recently moved to gulp
Mean.js uses grunt
DEPLOYMENT
Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.
DOCUMENTATION
Mean.io has ok docs
Mean.js has AWESOME docs
COMMUNITY
Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth
On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.
MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:
You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..
Have fun!
This code does what your need:
<input type="checkbox" id="check" >check it</input>
$("#check").change( function(){
if( $(this).is(':checked') ) {
alert("checked");
}else{
alert("unchecked");
}
});
Also, you can check it on jsfiddle
Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do:
Run -> Run configurations...
Java Application
or by typing its name to filter box.Program arguments
box. Just in case it isn't clear, they're whitespace-separated so "a b c"
(without quotes) would mean you'd pass arguments a, b and c to your program.I do however recommend using JUnit/wrapper class just like Uri did say since that way you get a lot better control over the actual parameters than by doing this.
It seems like you can also use the patch command. Put the diff in the root of the repository and run patch
from the command line.
patch -i yourcoworkers.diff
or
patch -p0 -i yourcoworkers.diff
You may need to remove the leading folder structure if they created the diff without using --no-prefix
.
If so, then you can remove the parts of the folder that don't apply using:
patch -p1 -i yourcoworkers.diff
The -p(n) signifies how many parts of the folder structure to remove.
More information on creating and applying patches here.
You can also use
git apply yourcoworkers.diff --stat
to see if the diff by default will apply any changes. It may say 0 files affected if the patch is not applied correctly (different folder structure).
For that you neet to use the g flag of regex.... Like this :
var new_string=old_string.replace( / (regex) /g, replacement_text);
That sh
Usually, you would do something like this:
$post_data = json_encode(array('item' => $post_data));
But, as it seems you want the output to be with "{}
", you better make sure to force json_encode()
to encode as object, by passing the JSON_FORCE_OBJECT
constant.
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
"{}
" brackets specify an object and "[]
" are used for arrays according to JSON specification.
Something like this ought to do:
$url = preg_replace("|^.+?://|", "", $url);
Removes everything up to and including the ://
var hiddenFieldID = "input[id$=" + hiddenField + "]";
var requiredVal= $(hiddenFieldID).val();
To resolve such 403 during push error you have to go in .git directory config file and change the given line:
precomposeunicode = true
[remote "origin"]
http://[email protected]:abc/xyz.git
Change the line to this
precomposeunicode = true
[remote "origin"]
ssh://[email protected]/abc/xyz.git
This resolved my issue.
Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.
In other words, merging "main" into "current" in the following arrangement:
main
|
--feature
|
--current
I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.
Since SSRS utilizes VB, you can do the following:
=Today() 'returns date only
If you were to use:
=Now() 'returns date and current timestamp
I have run through this. My case was more involved. The project was packaged fine from maven command line.
Couple of things I made. 1. One class has many imports that confused eclipse. Cleaning them fixed part of the problem 2. One case was about a Setter, pressing F3 navigating to that Setter although eclipse complained it is not there. So I simply retyped it and it worked fine (even for all other Setters)
I am still struggling with Implicit super constructor Item() is undefined for default constructor. Must define an explicit constructor"
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
Here is a simple approach in up to 4 steps:
0 - Advise the team you are going to fix the repository
Connect with the team and let them know of the upcoming changes.
1 - Remove the last commit
Assuming your target branch is master
:
$ git checkout master # move to the target branch
$ git reset --hard HEAD^ # remove the last commit
$ git push -f # push to fix the remote
At this point you are done if you are working alone.
2 - Fix your teammate's local repositories
On your teammate's:
$ git checkout master # move to the target branch
$ git fetch # update the local references but do not merge
$ git reset --hard origin/master # match the newly fetched remote state
If your teammate had no new commits, you are done at this point and you should be in sync.
3 - Bringing back lost commits
Let's say a teammate had a new and unpublished commit that were lost in this process.
$ git reflog # find the new commit hash
$ git cherry-pick <commit_hash>
Do this for as many commits as necessary.
I have successfully used this approach many times. It requires a team effort to make sure everything is synchronized.
Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.
I've added IDs to html on the total price and on the buttons. Here is the jQuery.
$('#two').click(function(){
$('#count').val('2');
$('#total').text('Product price: $1000');
});
$('#four').click(function(){
$('#count').val('4');
$('#total').text('Product price: $2000');
});
You can use property dangerouslySetInnerHTML
, like this
const Component = React.createClass({_x000D_
iframe: function () {_x000D_
return {_x000D_
__html: this.props.iframe_x000D_
}_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe>
tag and pass it to new <iframe>
tag, like that
/**_x000D_
* getAttrs_x000D_
* returns all attributes from TAG string_x000D_
* @return Object_x000D_
*/_x000D_
const getAttrs = (iframeTag) => {_x000D_
var doc = document.createElement('div');_x000D_
doc.innerHTML = iframeTag;_x000D_
_x000D_
const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
return [].slice_x000D_
.call(iframe.attributes)_x000D_
.reduce((attrs, element) => {_x000D_
attrs[element.name] = element.value;_x000D_
return attrs;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<iframe {...getAttrs(this.props.iframe) } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
If you want a quick and dirty way of installing the build dependencies, use:
apt-get build-dep
This installs the dependencies. You need sources lines in your sources.list for this:
deb-src http://ftp.nl.debian.org/debian/ squeeze-updates main contrib non-free
If you are backporting packages from testing to stable, please be advised that the dependencies might have changed. The command apt-get build-deb installs dependencies for the source packages in your current repository.
But of course, dpkg-buildpackage -us -uc will show you any uninstalled dependencies.
If you want to compile more often, use cowbuilder.
apt-get install cowbuilder
Then create a build-area:
sudo DIST=squeeze ARCH=amd64 cowbuilder --create
Then compile a source package:
apt-get source cowsay
# do your magic editing
dpkg-source -b cowsay-3.03+dfsg1 # build the new source packages
cowbuilder --build cowsay_3.03+dfsg1-2.dsc # build the packages from source
Watch where cowbuilder puts the resulting package.
Good luck!
You should possibly make data
a keyword parameter with a default value of empty dictionary:
class DHT:
def __init__(self, data=dict()):
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
if __name__ == '__main__':
DHT().showData()
Here is what worked for me
Set editable to false
<EditText android:id="@+id/dob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Date of Birth"
android:inputType="none"
android:editable="false"
/>
Then add an event listener for OnFocusChange
private View.OnFocusChangeListener onFocusChangeDOB= new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus){
showDialog(DATE_DIALOG_ID);
}
}
};
Many answers provided for this question. Just wanted to add one more which uses bashism-
#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"
@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).
Ok, solved my problem, if anyone is passing by here is the answer:
Just had to add left: 0,
and top: 0,
to the styles, and yes, I'm tired.
position: 'absolute',
left: 0,
top: 0,
consider the following:
def gukan(count):
while count < 100:
print(count)
count=count+3;
gukan(0) #prints ..., 93, 96, 99
def gukan(count):
while count < 100:
print(count)
count=count+9;
gukan(0) # prints ..., 81, 90, 99
you should use count < 100
because count
will never reach the exact number 100 if you use 3 or 9 as the increment, thus creating an infinite loop.
Good luck!~ :)
http://www.asoft.be/prod_netver.html
Use this "good, lightweight, no-install-required program"
With the modification of a single line you could alter the fullcalendar.js script to allow a line break and put multiple information on the same line.
In FullCalendar.js on line ~3922 find htmlEscape(s) function and add .replace(/<br\s?/?>/g, '
') to the end of it.
function htmlEscape(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />')
.replace(/<br\s?\/?>/g, '<br />');
}
This will allow you to have multiple lines for the title, separating the information. Example replace the event.title with title: 'All Day Event' + '<br />' + 'Other Description'
This simple solution worked for me: file-upload.component.html
<div>
<input type="file" #fileInput placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>
</div>
And then do the upload in the component directly with XMLHttpRequest.
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent implements OnInit {
@ViewChild('fileInput') fileInput;
constructor() { }
ngOnInit() {
}
private upload() {
const fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
const formData = new FormData();
formData.append('files', fileBrowser.files[0]);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/Data/UploadFiles', true);
xhr.onload = function () {
if (this['status'] === 200) {
const responseText = this['responseText'];
const files = JSON.parse(responseText);
//todo: emit event
} else {
//todo: error handling
}
};
xhr.send(formData);
}
}
}
If you are using dotnet core, the parameter name must match the from field name. files in this case:
[HttpPost("[action]")]
public async Task<IList<FileDto>> UploadFiles(List<IFormFile> files)
{
return await _binaryService.UploadFilesAsync(files);
}
This answer is a plagiate of http://blog.teamtreehouse.com/uploading-files-ajax
Edit: After uploading, you have to clear the file-upload so that the user can select a new file. And instead of using XMLHttpRequest, maybe it is better to use fetch:
private addFileInput() {
const fileInputParentNative = this.fileInputParent.nativeElement;
const oldFileInput = fileInputParentNative.querySelector('input');
const newFileInput = document.createElement('input');
newFileInput.type = 'file';
newFileInput.multiple = true;
newFileInput.name = 'fileInput';
const uploadfiles = this.uploadFiles.bind(this);
newFileInput.onchange = uploadfiles;
oldFileInput.parentNode.replaceChild(newFileInput, oldFileInput);
}
private uploadFiles() {
this.onUploadStarted.emit();
const fileInputParentNative = this.fileInputParent.nativeElement;
const fileInput = fileInputParentNative.querySelector('input');
if (fileInput.files && fileInput.files.length > 0) {
const formData = new FormData();
for (let i = 0; i < fileInput.files.length; i++) {
formData.append('files', fileInput.files[i]);
}
const onUploaded = this.onUploaded;
const onError = this.onError;
const addFileInput = this.addFileInput.bind(this);
fetch('/api/Data/UploadFiles', {
credentials: 'include',
method: 'POST',
body: formData,
}).then((response: any) => {
if (response.status !== 200) {
const error = `An error occured. Status: ${response.status}`;
throw new Error(error);
}
return response.json();
}).then(files => {
onUploaded.emit(files);
addFileInput();
}).catch((error) => {
onError.emit(error);
});
}
Closure
A closure is not a function, and not an expression. It must be seen as a kind of 'snapshot' from the used variables outside the function scope and used inside the function. Grammatically, one should say: 'take the closure of the variables'.
Again, in other words: A closure is a copy of the relevant context of variables on which the function depends on.
Once more (naïf): A closure is having access to variables who are not being passed as parameter.
Bear in mind that these functional concepts strongly depend upon the programming language / environment you use. In JavaScript, the closure depends on lexical scoping (which is true in most C-languages).
So, returning a function is mostly returning an anonymous/unnamed function. When the function access variables, not passed as parameter, and within its (lexical) scope, a closure has been taken.
So, concerning your examples:
// 1
for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i); // closure, only when loop finishes within 1000 ms,
}, 1000); // i = 10 for all functions
}
// 2
for(var i = 0; i < 10; i++) {
(function(){
var i2 = i; // closure of i (lexical scope: for-loop)
setTimeout(function(){
console.log(i2); // closure of i2 (lexical scope:outer function)
}, 1000)
})();
}
// 3
for(var i = 0; i < 10; i++) {
setTimeout((function(i2){
return function() {
console.log(i2); // closure of i2 (outer scope)
}
})(i), 1000); // param access i (no closure)
}
All are using closures. Don't confuse the point of execution with closures. If the 'snapshot' of the closures is taken at the wrong moment, the values may be unexpected but certainly a closure is taken!
var test = "<div class='saved' >"+
"<div >test.test</div> <div class='remove'>[Remove]</div></div>";
You can add "\n" if you require line-break.
In my case it was the ErrorLog directive in httpd.conf. Just accidently noticed it already after I gave up. Decided to share the discovery ) Now I know where to find the 500-errors.
Windows 10 -
Based on the answer by Eduard Florinescu, but with newer code and the missing imports added:
$ cat work-auth.py
#!/usr/bin/python3
# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30) # Time to enter credentials
driver.quit()
$ cat work.py
#!/usr/bin/python3
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com') # Already authenticated
time.sleep(10)
driver.quit()
LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall
# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)
test: $(SRC)
gcc -o $@ $^ $(CFLAGS) $(LIBS)
You can use nested query for pagination as follow:
Paging from 4 Row to 8 Row where CustomerId is primary key.
SELECT Top 5 * FROM Customers
WHERE Country='Germany' AND CustomerId Not in (SELECT Top 3 CustomerID FROM Customers
WHERE Country='Germany' order by city)
order by city;
I just came up with a solution for sending stdout
to one command and stderr
to another, using named pipes.
Here goes.
mkfifo stdout-target
mkfifo stderr-target
cat < stdout-target | command-for-stdout &
cat < stderr-target | command-for-stderr &
main-command 1>stdout-target 2>stderr-target
It's probably a good idea to remove the named pipes afterward.
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
private void ResetAllProperties()
{
Type type = this.GetType();
PropertyInfo[] properties = (from c in type.GetProperties()
where c.Name.StartsWith("Doc")
select c).ToArray();
foreach (PropertyInfo item in properties)
{
if (item.PropertyType.FullName == "System.String")
item.SetValue(this, "", null);
}
}
I used the code block above to reset all string properties in my web user control object which names are started with "Doc".
There is also str_sub
from the stringr package
x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"
I can never remember all the parameters to Git commands, so I just put an alias in the ~/.gitconfig
file that makes more sense to me, so I can remember it, and it results in less typing:
[alias]
url = ls-remote --get-url
After reloading the terminal, you can then just type:
> git url
Here are a few more of my frequently used ones:
[alias]
cd = checkout
ls = branch
lsr = branch --remote
lst = describe --tags
I also highly recommend git-extras which has a git info
command which provides much more detailed information on the remote and local branches.
First you need to remember that in Unix and Linux, everything is a file, even directories. For a file to have the rights to be executed as a command, it needs to satisfy 3 conditions:
So this can be done simply with:
[ -f "${file}" ] && [ -r "${file}" ] && [ -x "${file}" ]
If your file is a symbolic link to a regular file, the test command will operate on the target and not the link-name. So the above command distinguishes if a file can be used as a command or not. So there is no need to pass the file first to realpath
or readlink
or any of those variants.
If the file can be executed on the current OS, that is a different question. Some answers above already pointed to some possibilities for that, so there is no need to repeat it here.
I just tested this- both CTE and non-CTE (where the query was typed out for every union instance) both took ~31 seconds. CTE made the code much more readable though- cut it down from 241 to 130 lines which is very nice. Temp table on the other hand cut it down to 132 lines, and took FIVE SECONDS to run. No joke. all of this testing was cached- the queries were all run multiple times before.
#!/usr/bin/env python
import tkinter as tk
class AppName(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.quitButton = tk.Button(self, text='Quit', command=self.quit)
self.quitButton.grid()
app = AppName()
app.master.title('Title here ...!')
app.master.iconbitmap('icon.ico')
app.mainloop()
it should work like this !
if your slug contain only A-Za-z0-9- then it is ok for you
function sanitize_slug($text)
{
$text = preg_replace('/[^A-Za-z0-9-]+/', '-', $text);
$text = trim($text, '-');
$text = preg_replace('~-+~', '-', $text);
return $text;
}
for the line you wrote
var g = $('<%=Label1.ClientID%>').val(); // Also I tried .text() and .html()
you missed adding #. it should be like this
var g = $('#<%=Label1.ClientID%>').text();
also I do not prefer using this method
that's because if you are calling a control in master or nested master page or if you are calling a control in page from master. Also controls in Repeater. regardless the MVC. this will cause problems.
you should ALWAYS call the ID of the control directly. like this
$('#ControlID')
this is simple and clear. but do not forget to set
ClientIDMode="Static"
in your controls to remain with same ID name after render. that's because ASP.net will modify the ID name in HTML rendered file in some contexts i.e. the page is for Master page the control name will be ConetentPlaceholderName_controlID
I hope it clears the question Good Luck
I am using Oracle SQL Developer,
In this tool, I had to enable DBMS output to view the results printed by dbms_output.put_line
You can find this option in the result pane where other query results are displayed. so, in the result pane, I have 7 tabs. 1st tab named as Results, next one is Script Output and so on. Out of this you can find a tab named as "DBMS Output" select this tab, then the 1st icon (looks like a dialogue icon) is Enable DBMS Output. Click this icon. Then you execute the PL/SQL, then select "DBMS Output tab, you should be able to see the results there.
Building on @rprog's answer, you can combine the various pieces of the suffix & filter step into one line using a negative regex:
dfNew = df.merge(df2, left_index=True, right_index=True,
how='outer', suffixes=('', '_DROP')).filter(regex='^(?!.*_DROP)')
Or using df.join
:
dfNew = df.join(df2, lsuffix="DROP").filter(regex="^(?!.*DROP)")
The regex here is keeping anything that does not end with the word "DROP", so just make sure to use a suffix that doesn't appear among the columns already.
As Brad Wilson states in his answer here:
ModelState.IsValid tells you if any model errors have been added to ModelState.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
Try using :-
if (!ModelState.IsValid)
{
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
// Breakpoint, Log or examine the list with Exceptions.
}
If it helps catching you the error. Courtesy this and this
In addition to the existing answer it is possible to set a default option as follows:
echo off
ECHO A current build of Test Harness exists.
set delBuild=n
set /p delBuild=Delete preexisting build [y/n] (default - %delBuild%)?:
This allows users to simply hit "Enter" if they want to enter the default.
Re the solution for SqlBulkCopy:
I used the StreamReader to convert and process the text file. The result was a list of my object.
I created a class than takes Datatable
or a List<T>
and a Buffer size (CommitBatchSize
). It will convert the list to a data table using an extension (in the second class).
It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.
Here is the class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class BulkUploadToSql<T>
{
public IList<T> InternalStore { get; set; }
public string TableName { get; set; }
public int CommitBatchSize { get; set; }=1000;
public string ConnectionString { get; set; }
public void Commit()
{
if (InternalStore.Count>0)
{
DataTable dt;
int numberOfPages = (InternalStore.Count / CommitBatchSize) + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
{
dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
BulkInsert(dt);
}
}
}
public void BulkInsert(DataTable dt)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = TableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dt);
connection.Close();
}
// reset
//this.dataTable.Clear();
}
}
public static class BulkUploadToSqlHelper
{
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
}
Here is an example when I want to insert a List of my custom object List<PuckDetection>
(ListDetections
):
var objBulk = new BulkUploadToSql<PuckDetection>()
{
InternalStore = ListDetections,
TableName= "PuckDetections",
CommitBatchSize=1000,
ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();
The BulkInsert
class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)
//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
loop { begin Bar.new rescue SystemExit p $! #: #<SystemExit: exit> end }
This will print #<SystemExit: exit>
in an infinite loop, without ever exiting.
If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr
function like this:
regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
// ...
}
Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.
In short, you add the selector after the URL. For example:
$('#result').load('ajax/test.html #container');
In our scenario we're storing the code on github/bitbucket and want to deploy to live servers. In this case the following combination works for us (that is a remix of the highly upvoted answers here):
.git
directory to your web servergit remote add live ssh://user@host:port/folder
git config receive.denyCurrentBranch ignore
On remote: nano .git/hooks/post-receive
and add this content:
#!/bin/sh
GIT_WORK_TREE=/var/www/vhosts/example.org git checkout -f
On remote: chmod +x .git/hooks/post-receive
git push live
If your .git
folder is within document root make sure you hide it from the outside by adding to .htaccess
(source):
RedirectMatch 404 /\..*$
This is a job for numpy
.
And here's a tutorial demonstrating how pincipal component analysis can be done using numpy
's built-in modules like mean,cov,double,cumsum,dot,linalg,array,rank
.
http://glowingpython.blogspot.sg/2011/07/principal-component-analysis-with-numpy.html
Notice that scipy
also has a long explanation here
- https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105
with the scikit-learn
library having more code examples -
https://github.com/scikit-learn/scikit-learn/blob/babe4a5d0637ca172d47e1dfdd2f6f3c3ecb28db/scikits/learn/utils/extmath.py#L105
There are many ways to create a Set and a List. HashSet and ArrayList are just two examples. It is also fairly common to use generics with collections these days. I suggest you have a look at what they are
This is a good introduction for java's builtin collections. http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html
My beautiful non-standard solution
HTML
<div style="background-color:#f5b405"></div>
jQuery
$(this).attr("style").replace("background-color:", "");
Result
#f5b405
Here is another way to do it.It is working fine for me .
N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]
for i in range(0,N):
sum.append(num1[i]+num2[i])
for element in sum:
print(element, end=" ")
print("")
The page to do this is at https://developers.facebook.com/tools/debug/ and has changed slightly since some of the other answers.
Paste your URL in there and hit "Debug". Then hit the "Fetch new scrape information" button under the URL text field and you should be all set. It'll pull the fresh meta tags from your page, but they'll still cache so keep in mind you'll need to do this whenever you change them. This is really critical if you are playing with the meta tags to get FB Shared URLs to format the way you want them to inside of facebook.
If you want to pass a method of a class as an argument but don't yet have the object on which you are going to call it, you can simply pass the object once you have it as the first argument (i.e. the "self" argument).
class FooBar:
def __init__(self, prefix):
self.prefix = prefix
def foo(self, name):
print "%s %s" % (self.prefix, name)
def bar(some_method):
foobar = FooBar("Hello")
some_method(foobar, "World")
bar(FooBar.foo)
This will print "Hello World"
I wrote a full replacement for sys.stderr
and just duplicated the code renaming stderr
to stdout
to make it also available to replace sys.stdout
.
To do this I create the same object type as the current stderr
and stdout
, and forward all methods to the original system stderr
and stdout
:
import os
import sys
import logging
class StdErrReplament(object):
"""
How to redirect stdout and stderr to logger in Python
https://stackoverflow.com/questions/19425736/how-to-redirect-stdout-and-stderr-to-logger-in-python
Set a Read-Only Attribute in Python?
https://stackoverflow.com/questions/24497316/set-a-read-only-attribute-in-python
"""
is_active = False
@classmethod
def lock(cls, logger):
"""
Attach this singleton logger to the `sys.stderr` permanently.
"""
global _stderr_singleton
global _stderr_default
global _stderr_default_class_type
# On Sublime Text, `sys.__stderr__` is set to None, because they already replaced `sys.stderr`
# by some `_LogWriter()` class, then just save the current one over there.
if not sys.__stderr__:
sys.__stderr__ = sys.stderr
try:
_stderr_default
_stderr_default_class_type
except NameError:
_stderr_default = sys.stderr
_stderr_default_class_type = type( _stderr_default )
# Recreate the sys.stderr logger when it was reset by `unlock()`
if not cls.is_active:
cls.is_active = True
_stderr_write = _stderr_default.write
logger_call = logger.debug
clean_formatter = logger.clean_formatter
global _sys_stderr_write
global _sys_stderr_write_hidden
if sys.version_info <= (3,2):
logger.file_handler.terminator = '\n'
# Always recreate/override the internal write function used by `_sys_stderr_write`
def _sys_stderr_write_hidden(*args, **kwargs):
"""
Suppress newline in Python logging module
https://stackoverflow.com/questions/7168790/suppress-newline-in-python-logging-module
"""
try:
_stderr_write( *args, **kwargs )
file_handler = logger.file_handler
formatter = file_handler.formatter
terminator = file_handler.terminator
file_handler.formatter = clean_formatter
file_handler.terminator = ""
kwargs['extra'] = {'_duplicated_from_file': True}
logger_call( *args, **kwargs )
file_handler.formatter = formatter
file_handler.terminator = terminator
except Exception:
logger.exception( "Could not write to the file_handler: %s(%s)", file_handler, logger )
cls.unlock()
# Only create one `_sys_stderr_write` function pointer ever
try:
_sys_stderr_write
except NameError:
def _sys_stderr_write(*args, **kwargs):
"""
Hides the actual function pointer. This allow the external function pointer to
be cached while the internal written can be exchanged between the standard
`sys.stderr.write` and our custom wrapper around it.
"""
_sys_stderr_write_hidden( *args, **kwargs )
try:
# Only create one singleton instance ever
_stderr_singleton
except NameError:
class StdErrReplamentHidden(_stderr_default_class_type):
"""
Which special methods bypasses __getattribute__ in Python?
https://stackoverflow.com/questions/12872695/which-special-methods-bypasses-getattribute-in-python
"""
if hasattr( _stderr_default, "__abstractmethods__" ):
__abstractmethods__ = _stderr_default.__abstractmethods__
if hasattr( _stderr_default, "__base__" ):
__base__ = _stderr_default.__base__
if hasattr( _stderr_default, "__bases__" ):
__bases__ = _stderr_default.__bases__
if hasattr( _stderr_default, "__basicsize__" ):
__basicsize__ = _stderr_default.__basicsize__
if hasattr( _stderr_default, "__call__" ):
__call__ = _stderr_default.__call__
if hasattr( _stderr_default, "__class__" ):
__class__ = _stderr_default.__class__
if hasattr( _stderr_default, "__delattr__" ):
__delattr__ = _stderr_default.__delattr__
if hasattr( _stderr_default, "__dict__" ):
__dict__ = _stderr_default.__dict__
if hasattr( _stderr_default, "__dictoffset__" ):
__dictoffset__ = _stderr_default.__dictoffset__
if hasattr( _stderr_default, "__dir__" ):
__dir__ = _stderr_default.__dir__
if hasattr( _stderr_default, "__doc__" ):
__doc__ = _stderr_default.__doc__
if hasattr( _stderr_default, "__eq__" ):
__eq__ = _stderr_default.__eq__
if hasattr( _stderr_default, "__flags__" ):
__flags__ = _stderr_default.__flags__
if hasattr( _stderr_default, "__format__" ):
__format__ = _stderr_default.__format__
if hasattr( _stderr_default, "__ge__" ):
__ge__ = _stderr_default.__ge__
if hasattr( _stderr_default, "__getattribute__" ):
__getattribute__ = _stderr_default.__getattribute__
if hasattr( _stderr_default, "__gt__" ):
__gt__ = _stderr_default.__gt__
if hasattr( _stderr_default, "__hash__" ):
__hash__ = _stderr_default.__hash__
if hasattr( _stderr_default, "__init__" ):
__init__ = _stderr_default.__init__
if hasattr( _stderr_default, "__init_subclass__" ):
__init_subclass__ = _stderr_default.__init_subclass__
if hasattr( _stderr_default, "__instancecheck__" ):
__instancecheck__ = _stderr_default.__instancecheck__
if hasattr( _stderr_default, "__itemsize__" ):
__itemsize__ = _stderr_default.__itemsize__
if hasattr( _stderr_default, "__le__" ):
__le__ = _stderr_default.__le__
if hasattr( _stderr_default, "__lt__" ):
__lt__ = _stderr_default.__lt__
if hasattr( _stderr_default, "__module__" ):
__module__ = _stderr_default.__module__
if hasattr( _stderr_default, "__mro__" ):
__mro__ = _stderr_default.__mro__
if hasattr( _stderr_default, "__name__" ):
__name__ = _stderr_default.__name__
if hasattr( _stderr_default, "__ne__" ):
__ne__ = _stderr_default.__ne__
if hasattr( _stderr_default, "__new__" ):
__new__ = _stderr_default.__new__
if hasattr( _stderr_default, "__prepare__" ):
__prepare__ = _stderr_default.__prepare__
if hasattr( _stderr_default, "__qualname__" ):
__qualname__ = _stderr_default.__qualname__
if hasattr( _stderr_default, "__reduce__" ):
__reduce__ = _stderr_default.__reduce__
if hasattr( _stderr_default, "__reduce_ex__" ):
__reduce_ex__ = _stderr_default.__reduce_ex__
if hasattr( _stderr_default, "__repr__" ):
__repr__ = _stderr_default.__repr__
if hasattr( _stderr_default, "__setattr__" ):
__setattr__ = _stderr_default.__setattr__
if hasattr( _stderr_default, "__sizeof__" ):
__sizeof__ = _stderr_default.__sizeof__
if hasattr( _stderr_default, "__str__" ):
__str__ = _stderr_default.__str__
if hasattr( _stderr_default, "__subclasscheck__" ):
__subclasscheck__ = _stderr_default.__subclasscheck__
if hasattr( _stderr_default, "__subclasses__" ):
__subclasses__ = _stderr_default.__subclasses__
if hasattr( _stderr_default, "__subclasshook__" ):
__subclasshook__ = _stderr_default.__subclasshook__
if hasattr( _stderr_default, "__text_signature__" ):
__text_signature__ = _stderr_default.__text_signature__
if hasattr( _stderr_default, "__weakrefoffset__" ):
__weakrefoffset__ = _stderr_default.__weakrefoffset__
if hasattr( _stderr_default, "mro" ):
mro = _stderr_default.mro
def __init__(self):
"""
Override any super class `type( _stderr_default )` constructor, so we can
instantiate any kind of `sys.stderr` replacement object, in case it was already
replaced by something else like on Sublime Text with `_LogWriter()`.
Assures all attributes were statically replaced just above. This should happen in case
some new attribute is added to the python language.
This also ignores the only two methods which are not equal, `__init__()` and `__getattribute__()`.
"""
different_methods = ("__init__", "__getattribute__")
attributes_to_check = set( dir( object ) + dir( type ) )
for attribute in attributes_to_check:
if attribute not in different_methods \
and hasattr( _stderr_default, attribute ):
base_class_attribute = super( _stderr_default_class_type, self ).__getattribute__( attribute )
target_class_attribute = _stderr_default.__getattribute__( attribute )
if base_class_attribute != target_class_attribute:
sys.stderr.write( " The base class attribute `%s` is different from the target class:\n%s\n%s\n\n" % (
attribute, base_class_attribute, target_class_attribute ) )
def __getattribute__(self, item):
if item == 'write':
return _sys_stderr_write
try:
return _stderr_default.__getattribute__( item )
except AttributeError:
return super( _stderr_default_class_type, _stderr_default ).__getattribute__( item )
_stderr_singleton = StdErrReplamentHidden()
sys.stderr = _stderr_singleton
return cls
@classmethod
def unlock(cls):
"""
Detach this `stderr` writer from `sys.stderr` and allow the next call to `lock()` create
a new writer for the stderr.
"""
if cls.is_active:
global _sys_stderr_write_hidden
cls.is_active = False
_sys_stderr_write_hidden = _stderr_default.write
class StdOutReplament(object):
"""
How to redirect stdout and stderr to logger in Python
https://stackoverflow.com/questions/19425736/how-to-redirect-stdout-and-stderr-to-logger-in-python
Set a Read-Only Attribute in Python?
https://stackoverflow.com/questions/24497316/set-a-read-only-attribute-in-python
"""
is_active = False
@classmethod
def lock(cls, logger):
"""
Attach this singleton logger to the `sys.stdout` permanently.
"""
global _stdout_singleton
global _stdout_default
global _stdout_default_class_type
# On Sublime Text, `sys.__stdout__` is set to None, because they already replaced `sys.stdout`
# by some `_LogWriter()` class, then just save the current one over there.
if not sys.__stdout__:
sys.__stdout__ = sys.stdout
try:
_stdout_default
_stdout_default_class_type
except NameError:
_stdout_default = sys.stdout
_stdout_default_class_type = type( _stdout_default )
# Recreate the sys.stdout logger when it was reset by `unlock()`
if not cls.is_active:
cls.is_active = True
_stdout_write = _stdout_default.write
logger_call = logger.debug
clean_formatter = logger.clean_formatter
global _sys_stdout_write
global _sys_stdout_write_hidden
if sys.version_info <= (3,2):
logger.file_handler.terminator = '\n'
# Always recreate/override the internal write function used by `_sys_stdout_write`
def _sys_stdout_write_hidden(*args, **kwargs):
"""
Suppress newline in Python logging module
https://stackoverflow.com/questions/7168790/suppress-newline-in-python-logging-module
"""
try:
_stdout_write( *args, **kwargs )
file_handler = logger.file_handler
formatter = file_handler.formatter
terminator = file_handler.terminator
file_handler.formatter = clean_formatter
file_handler.terminator = ""
kwargs['extra'] = {'_duplicated_from_file': True}
logger_call( *args, **kwargs )
file_handler.formatter = formatter
file_handler.terminator = terminator
except Exception:
logger.exception( "Could not write to the file_handler: %s(%s)", file_handler, logger )
cls.unlock()
# Only create one `_sys_stdout_write` function pointer ever
try:
_sys_stdout_write
except NameError:
def _sys_stdout_write(*args, **kwargs):
"""
Hides the actual function pointer. This allow the external function pointer to
be cached while the internal written can be exchanged between the standard
`sys.stdout.write` and our custom wrapper around it.
"""
_sys_stdout_write_hidden( *args, **kwargs )
try:
# Only create one singleton instance ever
_stdout_singleton
except NameError:
class StdOutReplamentHidden(_stdout_default_class_type):
"""
Which special methods bypasses __getattribute__ in Python?
https://stackoverflow.com/questions/12872695/which-special-methods-bypasses-getattribute-in-python
"""
if hasattr( _stdout_default, "__abstractmethods__" ):
__abstractmethods__ = _stdout_default.__abstractmethods__
if hasattr( _stdout_default, "__base__" ):
__base__ = _stdout_default.__base__
if hasattr( _stdout_default, "__bases__" ):
__bases__ = _stdout_default.__bases__
if hasattr( _stdout_default, "__basicsize__" ):
__basicsize__ = _stdout_default.__basicsize__
if hasattr( _stdout_default, "__call__" ):
__call__ = _stdout_default.__call__
if hasattr( _stdout_default, "__class__" ):
__class__ = _stdout_default.__class__
if hasattr( _stdout_default, "__delattr__" ):
__delattr__ = _stdout_default.__delattr__
if hasattr( _stdout_default, "__dict__" ):
__dict__ = _stdout_default.__dict__
if hasattr( _stdout_default, "__dictoffset__" ):
__dictoffset__ = _stdout_default.__dictoffset__
if hasattr( _stdout_default, "__dir__" ):
__dir__ = _stdout_default.__dir__
if hasattr( _stdout_default, "__doc__" ):
__doc__ = _stdout_default.__doc__
if hasattr( _stdout_default, "__eq__" ):
__eq__ = _stdout_default.__eq__
if hasattr( _stdout_default, "__flags__" ):
__flags__ = _stdout_default.__flags__
if hasattr( _stdout_default, "__format__" ):
__format__ = _stdout_default.__format__
if hasattr( _stdout_default, "__ge__" ):
__ge__ = _stdout_default.__ge__
if hasattr( _stdout_default, "__getattribute__" ):
__getattribute__ = _stdout_default.__getattribute__
if hasattr( _stdout_default, "__gt__" ):
__gt__ = _stdout_default.__gt__
if hasattr( _stdout_default, "__hash__" ):
__hash__ = _stdout_default.__hash__
if hasattr( _stdout_default, "__init__" ):
__init__ = _stdout_default.__init__
if hasattr( _stdout_default, "__init_subclass__" ):
__init_subclass__ = _stdout_default.__init_subclass__
if hasattr( _stdout_default, "__instancecheck__" ):
__instancecheck__ = _stdout_default.__instancecheck__
if hasattr( _stdout_default, "__itemsize__" ):
__itemsize__ = _stdout_default.__itemsize__
if hasattr( _stdout_default, "__le__" ):
__le__ = _stdout_default.__le__
if hasattr( _stdout_default, "__lt__" ):
__lt__ = _stdout_default.__lt__
if hasattr( _stdout_default, "__module__" ):
__module__ = _stdout_default.__module__
if hasattr( _stdout_default, "__mro__" ):
__mro__ = _stdout_default.__mro__
if hasattr( _stdout_default, "__name__" ):
__name__ = _stdout_default.__name__
if hasattr( _stdout_default, "__ne__" ):
__ne__ = _stdout_default.__ne__
if hasattr( _stdout_default, "__new__" ):
__new__ = _stdout_default.__new__
if hasattr( _stdout_default, "__prepare__" ):
__prepare__ = _stdout_default.__prepare__
if hasattr( _stdout_default, "__qualname__" ):
__qualname__ = _stdout_default.__qualname__
if hasattr( _stdout_default, "__reduce__" ):
__reduce__ = _stdout_default.__reduce__
if hasattr( _stdout_default, "__reduce_ex__" ):
__reduce_ex__ = _stdout_default.__reduce_ex__
if hasattr( _stdout_default, "__repr__" ):
__repr__ = _stdout_default.__repr__
if hasattr( _stdout_default, "__setattr__" ):
__setattr__ = _stdout_default.__setattr__
if hasattr( _stdout_default, "__sizeof__" ):
__sizeof__ = _stdout_default.__sizeof__
if hasattr( _stdout_default, "__str__" ):
__str__ = _stdout_default.__str__
if hasattr( _stdout_default, "__subclasscheck__" ):
__subclasscheck__ = _stdout_default.__subclasscheck__
if hasattr( _stdout_default, "__subclasses__" ):
__subclasses__ = _stdout_default.__subclasses__
if hasattr( _stdout_default, "__subclasshook__" ):
__subclasshook__ = _stdout_default.__subclasshook__
if hasattr( _stdout_default, "__text_signature__" ):
__text_signature__ = _stdout_default.__text_signature__
if hasattr( _stdout_default, "__weakrefoffset__" ):
__weakrefoffset__ = _stdout_default.__weakrefoffset__
if hasattr( _stdout_default, "mro" ):
mro = _stdout_default.mro
def __init__(self):
"""
Override any super class `type( _stdout_default )` constructor, so we can
instantiate any kind of `sys.stdout` replacement object, in case it was already
replaced by something else like on Sublime Text with `_LogWriter()`.
Assures all attributes were statically replaced just above. This should happen in case
some new attribute is added to the python language.
This also ignores the only two methods which are not equal, `__init__()` and `__getattribute__()`.
"""
different_methods = ("__init__", "__getattribute__")
attributes_to_check = set( dir( object ) + dir( type ) )
for attribute in attributes_to_check:
if attribute not in different_methods \
and hasattr( _stdout_default, attribute ):
base_class_attribute = super( _stdout_default_class_type, self ).__getattribute__( attribute )
target_class_attribute = _stdout_default.__getattribute__( attribute )
if base_class_attribute != target_class_attribute:
sys.stdout.write( " The base class attribute `%s` is different from the target class:\n%s\n%s\n\n" % (
attribute, base_class_attribute, target_class_attribute ) )
def __getattribute__(self, item):
if item == 'write':
return _sys_stdout_write
try:
return _stdout_default.__getattribute__( item )
except AttributeError:
return super( _stdout_default_class_type, _stdout_default ).__getattribute__( item )
_stdout_singleton = StdOutReplamentHidden()
sys.stdout = _stdout_singleton
return cls
@classmethod
def unlock(cls):
"""
Detach this `stdout` writer from `sys.stdout` and allow the next call to `lock()` create
a new writer for the stdout.
"""
if cls.is_active:
global _sys_stdout_write_hidden
cls.is_active = False
_sys_stdout_write_hidden = _stdout_default.write
To use this you can just call StdErrReplament::lock(logger)
and StdOutReplament::lock(logger)
passing the logger you want to use to send the output text. For example:
import os
import sys
import logging
current_folder = os.path.dirname( os.path.realpath( __file__ ) )
log_file_path = os.path.join( current_folder, "my_log_file.txt" )
file_handler = logging.FileHandler( log_file_path, 'a' )
file_handler.formatter = logging.Formatter( "%(asctime)s %(name)s %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S" )
log = logging.getLogger( __name__ )
log.setLevel( "DEBUG" )
log.addHandler( file_handler )
log.file_handler = file_handler
log.clean_formatter = logging.Formatter( "", "" )
StdOutReplament.lock( log )
StdErrReplament.lock( log )
log.debug( "I am doing usual logging debug..." )
sys.stderr.write( "Tests 1...\n" )
sys.stdout.write( "Tests 2...\n" )
Running this code, you will see on the screen:
And on the file contents:
If you would like to also see the contents of the log.debug
calls on the screen, you will need to add a stream handler to your logger. On this case it would be like this:
import os
import sys
import logging
class ContextFilter(logging.Filter):
""" This filter avoids duplicated information to be displayed to the StreamHandler log. """
def filter(self, record):
return not "_duplicated_from_file" in record.__dict__
current_folder = os.path.dirname( os.path.realpath( __file__ ) )
log_file_path = os.path.join( current_folder, "my_log_file.txt" )
stream_handler = logging.StreamHandler()
file_handler = logging.FileHandler( log_file_path, 'a' )
formatter = logging.Formatter( "%(asctime)s %(name)s %(levelname)s - %(message)s", "%Y-%m-%d %H:%M:%S" )
file_handler.formatter = formatter
stream_handler.formatter = formatter
stream_handler.addFilter( ContextFilter() )
log = logging.getLogger( __name__ )
log.setLevel( "DEBUG" )
log.addHandler( file_handler )
log.addHandler( stream_handler )
log.file_handler = file_handler
log.stream_handler = stream_handler
log.clean_formatter = logging.Formatter( "", "" )
StdOutReplament.lock( log )
StdErrReplament.lock( log )
log.debug( "I am doing usual logging debug..." )
sys.stderr.write( "Tests 1...\n" )
sys.stdout.write( "Tests 2...\n" )
Which would output like this when running:
While it would still saving this to the file my_log_file.txt
:
When disabling this with StdErrReplament:unlock()
, it will only restore the standard behavior of the stderr
stream, as the attached logger cannot be never detached because someone else can have a reference to its older version. This is why it is a global singleton which can never dies. Therefore, in case of reloading this module with imp
or something else, it will never recapture the current sys.stderr
as it was already injected on it and have it saved internally.
You can't target the last instance of the class name in your list without JS.
However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list
elements here: http://jsbin.com/vejixisudo/edit?html,css,output
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.
If you don't use jQuery
then the script would be something like this:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
See in action: http://jsfiddle.net/RJX5N/2/
I hope this answers your question.
-- IMPROVED VERSION--
This is a lot shorter and should do it as well:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
And a version with threshold
and mode
included:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
Yow can change the DropDownStyle in properties to DropDownList. This will not show the TextBox for filter.
(Screenshot provided by FUSION CHA0S.)
If you are running Linux, the following command is really useful for this:
trickle -s -d 50 -w 100 firefox
The -s
tells the command to run standalone, the -d 50
tells it to limit bandwidth to 50 KB/s, the -w 100
set the peak detection window size to 100 KB. firefox
tells the command to start firefox with all of this rate limiting applied to any sites it attempts to load.
Update
Chrome 38 is out now and includes throttling. To find it, bring up the Developer Tools: Ctrl+Shift+I does it on my machine, otherwise Menu->More Tools->Developer Tools will bring you there.
Then Toggle Device Mode by clicking the phone in the upper left of the Developer Tools Panel (see the tooltip below).
Then activate throttling like so.
If you find this a bit clunky, my suggestion above works for both Chrome and Firefox.
Being the author of the response that you highlight in your question, and admittedly coming to this one a bit late, I'd have to say that among the many reasons that have been listed, the productivity of a professional developer is one of the most highly-regarded skills.
By productivity, I mean the ability to do your job efficiently with the best-possible results. IDEs enable this on many levels. I'm not an Emacs expert, but I doubt that it lacks any of the features of the major IDEs.
Design, documentation, tracking, developing, building, analyzing, deploying, and maintenance, key stepping stones in an enterprise application, can all be done within an IDE.
Why you wouldn't use something so powerful if you have the choice?
As an experiment, commit yourself to use an IDE for, say, 30 days, and see how you feel. I would love to read your thoughts on the experience.
To easily understand the problem, imagine we wrote this code:
static void Main(string[] args)
{
string[] test = new string[3];
test[0]= "hello1";
test[1]= "hello2";
test[2]= "hello3";
for (int i = 0; i <= 3; i++)
{
Console.WriteLine(test[i].ToString());
}
}
Result will be:
hello1
hello2
hello3
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3).
So when it tries to access outside the bounds with (3) it throws the exception.
In case you don't know it already, Oracle has released ODP.NET which supports Entity Framework. It doesn't support code first yet though.
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
Here is the perfect coding which checks whether the Combo Box Item is Selected or not
if (string.IsNullOrEmpty(comboBox1.Text))
{
MessageBox.Show("No Item is Selected");
}
else
{
MessageBox.Show("Item Selected is:" + comboBox1.Text);
}
Mysql has this handy UPDATE INTO command ;)
edit Looks like they renamed it to REPLACE
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
Nowadays you can use lodash:
var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true
form.submit() doesn't work cause the HTML5 validation is performed before the form submition. When you click on a submit button, the HTML5 validation is trigerred and then the form is submited if validation was successfull.
if you using Generic Array List with Class instead of specific type like
EX:
private ArrayList<Model> aListModel = new ArrayList<Model>();
Here, Model = Class
Receiving Intent Like :
aListModel = (ArrayList<Model>) getIntent().getSerializableExtra(KEY);
MUST REMEMBER:
Here Model-class must be implemented like: ModelClass implements Serializable
Take a look at the Clay library:
It provides something similar to the ExpandoObject but with a bunch of extra features. Here is blog post explaining how to use it:
http://weblogs.asp.net/bleroy/archive/2010/08/18/clay-malleable-c-dynamic-objects-part-2.aspx
(be sure to read the IPerson interface example)
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
It is a reference to the current file name. In the file foo.rb
, __FILE__
would be interpreted as "foo.rb"
.
Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:
# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__
Running ruby test.rb
will output
test.rb
/full/path/to/dir2/test.rb
What that usually means is that you have lines ending with something other than a carriage return/line feed pair. It often happens when you copy and paste from a web page into the code editor.
Normalizing the line endings is just making sure that all of the line ending characters are consistent. It prevents one line from ending in \r\n
and another ending with \r
or \n
; the first is the Windows line end pair, while the others are typically used for Mac or Linux files.
Since you're developing in Visual Studio, you'll obviously want to choose "Windows" from the drop down. :-)
As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:
DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)
The original class came from this very useful article:
U wrote an unnecessary div, just leave it like this
<div id="texts" style="white-space:nowrap;">
<img src="tree.png" align="left"/>
A very long text(about 300 words)
</div>
_x000D_
What u are looking for is white-space:nowrap; this code will do the trick.
Add this to your viewcontroller. Works like a charm. Just adjust the values.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);
}
@objc func keyboardWillShow(sender: NSNotification) {
self.view.frame.origin.y -= 150
}
@objc func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y += 150
}
The correct solution is to store the ZIP Code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning.
A number is a thing you do arithmetic on. A ZIP Code is not that.
Just two steps to run the database after the Installation (Before that ensure your logged as postgres
user)
Installed-Dirs/bin/postmaster -D Installed-Dirs/pgsql/data
For an example:
[postgres@localhost bin]$ /usr/local/pgsql/bin/postmaster -D /usr/local/pgsql/data
Step-2 : Run psql from the Installed path (To check where you installed '#which postgres' will use to find out the installed location)
[postgres@localhost bin]$ psql
Comparator
is a functional interface, and Integer::max
complies with that interface (after autoboxing/unboxing is taken into consideration). It takes two int
values and returns an int
- just as you'd expect a Comparator<Integer>
to (again, squinting to ignore the Integer/int difference).
However, I wouldn't expect it to do the right thing, given that Integer.max
doesn't comply with the semantics of Comparator.compare
. And indeed it doesn't really work in general. For example, make one small change:
for (int i = 1; i <= 20; i++)
list.add(-i);
... and now the max
value is -20 and the min
value is -1.
Instead, both calls should use Integer::compare
:
System.out.println(list.stream().max(Integer::compare).get());
System.out.println(list.stream().min(Integer::compare).get());
To match the title of this question, the value of the id
attribute is:
var myId = $(this).attr('id');
alert( myId );
BUT, of course, the element must already have the id element defined, as:
<option id="opt7" class='select_continent' value='7'>Antarctica</option>
In the OP post, this was not the case.
Note that plain js is faster (in this case):
var myId = this.id
alert( myId );
That is, if you are just storing the returned text into a variable as in the above example. No need for jQuery's wonderfulness here.
Answer from 2020 year :
dependencies {
implementation "androidx.core:core-ktx:1.2.0"
}
and cal it simply in your code
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
setMargins(5)
}
$(this).find('option:selected').text();
Just use matrix
:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
You can do it without modifying the XML stream: Tell the XmlReader to not be so picky.
Setting the XmlReaderSettings.ConformanceLevel
to ConformanceLevel.Fragment
will let the parser ignore the fact that there is no root node.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create(tr,settings))
{
...
}
Now you can parse something like this (which is an real time XML stream, where it is impossible to wrap with a node).
<event>
<timeStamp>1354902435238</timeStamp>
<eventId>7073822</eventId>
</event>
<data>
<time>1354902435341</time>
<payload type='80'>7d1300786a0000000bf9458b0518000000000000000000000000000000000c0c030306001b</payload>
</data>
<data>
<time>1354902435345</time>
<payload type='80'>fd1260780912ff3028fea5ffc0387d640fa550f40fbdf7afffe001fff8200fff00f0bf0e000042201421100224ff40312300111400004f000000e0c0fbd1e0000f10e0fccc2ff0000f0fe00f00f0eed00f11e10d010021420401</payload>
</data>
<data>
<time>1354902435347</time>
<payload type='80'>fd126078ad11fc4015fefdf5b042ff1010223500000000000000003007ff00f20e0f01000e0000dc0f01000f000000000000004f000000f104ff001000210f000013010000c6da000000680ffa807800200000000d00c0f0</payload>
</data>
public function testAction()
{
$filter_a = array('like'=>'a%');
$filter_b = array('like'=>'b%');
echo(
(string)
Mage::getModel('catalog/product')
->getCollection()
->addFieldToFilter('sku',array($filter_a,$filter_b))
->getSelect()
);
}
Result:
WHERE (((e.sku like 'a%') or (e.sku like 'b%')))
I called ContextCompat.startForegroundService(this, intent)
to start the service then
In service onCreate
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
}
I used SOAP UI for functional and automated testing. SOAP UI allows you to run the tests on the click of a button. There is also a spring controllers testing page created by Ted Young. I used this article to create Rest unit tests in our application.
Sometimes it can make the assignment of a bool value easier to read at first glance:
// With
button.IsEnabled = someControl.HasError ? false : true;
// Without
button.IsEnabled = !someControl.HasError;
The problem is that /var/www
doesn't exist either, and mkdir
isn't recursive by default -- it expects the immediate parent directory to exist.
Use:
mkdir -p /var/www/app
...or install a package that creates a /var/www
prior to reaching this point in your Dockerfile.
To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.
Sub test_date_or_String()
Set c = ActiveCell
c.NumberFormat = "@"
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
c.NumberFormat = "m/d/yyyy"
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date
End Sub
Not numpy but scipy provides exactly the shift functionality you want,
import numpy as np
from scipy.ndimage.interpolation import shift
xs = np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
shift(xs, 3, cval=np.NaN)
where default is to bring in a constant value from outside the array with value cval
, set here to nan
. This gives the desired output,
array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])
and the negative shift works similarly,
shift(xs, -3, cval=np.NaN)
Provides output
array([ 3., 4., 5., 6., 7., 8., 9., nan, nan, nan])
Here is tiny function that left pad value with a given padding char You can specify how many characters to be padded to left..
Create function fsPadLeft(@var varchar(200),@padChar char(1)='0',@len int)
returns varchar(300)
as
Begin
return replicate(@PadChar,@len-Len(@var))+@var
end
To call :
declare @value int; set @value =2
select dbo.fsPadLeft(@value,'0',2)
I tried this and it works:
stage.getIcons().add(new Image(getClass().getResourceAsStream("../images/icon.png")));
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace WebserverInteractionClassLibrary
{
public class RequestManager
{
public string LastResponse { protected set; get; }
CookieContainer cookies = new CookieContainer();
internal string GetCookieValue(Uri SiteUri,string name)
{
Cookie cookie = cookies.GetCookies(SiteUri)[name];
return (cookie == null) ? null : cookie.Value;
}
public string GetResponseContent(HttpWebResponse response)
{
if (response == null)
{
throw new ArgumentNullException("response");
}
Stream dataStream = null;
StreamReader reader = null;
string responseFromServer = null;
try
{
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// Cleanup the streams and the response.
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
{
reader.Close();
}
if (dataStream != null)
{
dataStream.Close();
}
response.Close();
}
LastResponse = responseFromServer;
return responseFromServer;
}
public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
{
HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
return GetResponse(request);
}
public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
{
HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
return GetResponse(request);
}
public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
{
HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
return GetResponse(request);
}
public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
{
return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
}
public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
{
return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
}
internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
// Set the Method property of the request to POST.
request.Method = method;
// Set cookie container to maintain cookies
request.CookieContainer = cookies;
request.AllowAutoRedirect = allowAutoRedirect;
// If login is empty use defaul credentials
if (string.IsNullOrEmpty(login))
{
request.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else
{
request.Credentials = new NetworkCredential(login, password);
}
if (method == "POST")
{
// Convert POST data to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(content);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
return request;
}
internal HttpWebResponse GetResponse(HttpWebRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
cookies.Add(response.Cookies);
// Print the properties of each cookie.
Console.WriteLine("\nCookies: ");
foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
{
Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
}
}
catch (WebException ex)
{
Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return response;
}
}
}
On a 64-bit machine running in 64-bit mode:
echo %programfiles%
==> C:\Program Files
echo %programfiles(x86)%
==> C:\Program Files (x86)
On a 64-bit machine running in 32-bit (WOW64) mode:
echo %programfiles%
==> C:\Program Files (x86)
echo %programfiles(x86)%
==> C:\Program Files (x86)
On a 32-bit machine running in 32-bit mode:
echo %programfiles%
==> C:\Program Files
echo %programfiles(x86)%
==> %programfiles(x86)%
COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);
as described in the manual.
I faced the same problem, went through all the suggestions above, but nothing worked. Finally I deleted both .m2 and .ivy folder and it worked for me.
Go to Build Gradle (Module:app) Change the following. In my case, I choose 25.0.3
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.cesarhcq.viisolutions"
minSdkVersion 15
targetSdkVersion 25
After that, it works fine!
Just check whether the commons-logging.jar has been added to your libs and the classpath.. I had the same issue and that was because of this. dhammikas-
There is a statement you can issue at the module level:
Option Compare Text
This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":
Option Compare Text
Sub testCase()
If "UPPERcase" = "upperCASE" Then
MsgBox "this is true: option Compare Text has been set!"
End If
End Sub
See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match
function) but it will take care of all the if a=b
statements. As for Application.Match
- you may want to convert the arguments to either upper case or lower case using the LCase
function.
You can use commercial tools like Sisulizer. It will create satellite assembly for each language. Only thing you should pay attention is not to obfuscate form class names (if you use obfuscator).
If you want to make your own small function, this is a good starting point:
def eomday(year, month):
"""returns the number of days in a given month"""
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
d = days_per_month[month - 1]
if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
d = 29
return d
For this you have to know the rules for the leap years:
If you don't want to recompile (as Visual Leak Detector requires) I would recommend WinDbg, which is both powerful and fast (though it's not as easy to use as one could desire).
On the other hand, if you don't want to mess with WinDbg, you can take a look at UMDH, which is also developed by Microsoft and it's easier to learn.
Take a look at these links in order to learn more about WinDbg, memory leaks and memory management in general:
You can use the PHP function apc_clear_cache
.
Calling apc_clear_cache()
will clear the system cache and calling apc_clear_cache('user')
will clear the user cache.
Another option is to use the built-in Command Palette, which will walk you right through cloning a Git repository to a new directory.
From Using Version Control in VS Code:
You can clone a Git repository with the Git: Clone command in the Command Palette (Windows/Linux: Ctrl + Shift + P, Mac: Command + Shift + P). You will be asked for the URL of the remote repository and the parent directory under which to put the local repository.
At the bottom of Visual Studio Code you'll get status updates to the cloning. Once that's complete an information message will display near the top, allowing you to open the folder that was created.
Note that Visual Studio Code uses your machine's Git installation, and requires 2.0.0 or higher.
If you are using pdb, you can define aliases for shortcuts. I use these:
# Ned's .pdbrc
# Print a dictionary, sorted. %1 is the dict, %2 is the prefix for the names.
alias p_ for k in sorted(%1.keys()): print "%s%-15s= %-80.80s" % ("%2",k,repr(%1[k]))
# Print the instance variables of a thing.
alias pi p_ %1.__dict__ %1.
# Print the instance variables of self.
alias ps pi self
# Print the locals.
alias pl p_ locals() local:
# Next and list, and step and list.
alias nl n;;l
alias sl s;;l
# Short cuts for walking up and down the stack
alias uu u;;u
alias uuu u;;u;;u
alias uuuu u;;u;;u;;u
alias uuuuu u;;u;;u;;u;;u
alias dd d;;d
alias ddd d;;d;;d
alias dddd d;;d;;d;;d
alias ddddd d;;d;;d;;d;;d
In order to calculate the difference you have to put the +
operator,
that way typescript
converts the dates to numbers.
+new Date()- +new Date("2013-02-20T12:01:04.753Z")
From there you can make a formula to convert the difference to minutes
or hours
.
I think you should do:
Fragment currentFragment = fragmentManager.findFragmentByTag("fragmentTag");
The reason is because you set the tag "fragmentTag" to the last fragment you have added (when you called replace).
This :
mail.To = "[email protected]";
Should be:
mail.To.Add(new MailAddress("[email protected]"));
dbo is the default schema in SQL Server. You can create your own schemas to allow you to better manage your object namespace.
Ansible supports patterns which can be used for one/multiple hosts,groups and also can exclude/include groups. Here is the link for official document.
Absolutely it must be work!
chown -Rf www-data:www-data /var/www/html
You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array()
for this.
// Process all rows
while($row = mysql_fetch_array($result)) {
echo $row['column_name']; // Print a single column data
echo print_r($row); // Print the entire row data
}
Change your code to this :
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open)
ORDER BY idM1O LIMIT 1"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['fieldname'];
}
os.remove()
does not work on a directory, and os.rmdir()
will only work on an empty directory. And Python won't automatically expand "/home/me/test/*" like some shells do.
You can use shutil.rmtree()
on the directory to do this, however.
import shutil
shutil.rmtree('/home/me/test')
be careful as it removes the files and the sub-directories as well.
int i = 0;
bool b = Convert.ToBoolean(i);
This is straightforward, readable solution using a simple regex.
// Get specific char in string
const char = string.charAt(index);
const isLowerCaseLetter = (/[a-z]/.test(char));
const isUpperCaseLetter = (/[A-Z]/.test(char));
Short definition:
grep
: search for specific terms in a file
#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"
$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"
Now awk
and sed
are completly different than grep
.
awk
and sed
are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).
awk
is mostly used for data extraction and reporting. sed
is a stream editor
Each one of them has its own functionality and specialties.
Example
Sed
$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'
Awk
$ awk '{print $2}' file.txt
# this will print the second column of file.txt
Basic awk
usage:
Compute sum/average/max/min/etc. what ever you may need.
$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average: 30
I recommend that you read this book: Sed & Awk: 2nd Ed.
It will help you become a proficient sed/awk user on any unix-like environment.
git format-patch
also has the -B
flag.
The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).
This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.
An example:
git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch
I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.
Edit your_repo_dir/.git/config
(remember: .git
folder is hidden)
Change:
https://github.com/WEMP/project-slideshow.git
to:
https://*username*@github.com/WEMP/project-slideshow.git
Save the file. Do a git pull
to test it.
The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:
@Component
public class SpringContext implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext=applicationContext;
}
}
you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:
applicationContext.getBean(String serviceName,Interface.Class)
"SMTP = localhost",
"smtp_port = 25",
"; sendmail_path = ".
Credit: How to configure WAMP (localhost) to send email using Gmail?
It's 2017, and now you can use object-fit which has decent support. It works in the same way as a div's background-size
but on the element itself, and on any element including images.
.your-img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
If you don't want your code to depend on other packages, you can always just write these functions:
perm = function(n, x) {
factorial(n) / factorial(n-x)
}
comb = function(n, x) {
factorial(n) / factorial(n-x) / factorial(x)
}
The new cv2
interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:
import cv2 # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)
This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:
blank_image[:,0:width//2] = (255,0,0) # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)
If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2
interface rather than the older cv
one. I made the change recently and have never looked back. You can read more about cv2
at the OpenCV Change Logs.
I don't know if you managed to resolve this but I have recently experienced a similar problem where the For loop left one view each time. I found this was because the self.subviews was mutated (maybe) when the removeFromSuperview() was called.
To fix this I did:
let subViews: Array = self.subviews.copy()
for (var subview: NSView!) in subViews
{
subview.removeFromSuperview()
}
By doing .copy(), I could perform the removal of each subview while mutating the self.subviews array. This is because the copied array (subViews) contains all of the references to the objects and is not mutated.
EDIT: In your case I think you would use:
let theSubviews: Array = container_view.subviews.copy()
for (var view: NSView!) in theSubviews
{
view.removeFromSuperview()
}
Have you read this post?
http://eclipsewebmaster.blogspot.ch/search?q=wow-what-a-painful-release-this-was-is
Maybe it explains, why it was kinda difficult the last days.
The problem is that undefined compared to null using == gives true. The common check for undefined is therefore done like this:
typeof x == "undefined"
this ensures the type of the variable is really undefined.
The problem you have is that you're attempting to bind the "test" class to the event before there is anything with a "test" class in the DOM
. Although it may seem like this is all dynamic, what is really happening is JQuery
makes a pass over the DOM
and wires up the click event when the ready()
function fired, which happens before you created the "Click Me" in your button event.
By adding the "test" Click event to the "button" click handler it will wire it up after the correct element exists in the DOM
.
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("h2").html("<p class='test'>click me</p>")
$(".test").click(function(){
alert()
});
});
});
</script>
Using live()
(as others have pointed out) is another way to do this but I felt it was also a good idea to point out the minor error in your JS code. What you wrote wasn't wrong, it just needed to be correctly scoped. Grasping how the DOM
and JS works is one of the tricky things for many traditional developers to wrap their head around.
live()
is a cleaner way to handle this and in most cases is the correct way to go. It essentially is watching the DOM
and re-wiring things whenever the elements within it change.
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:
resources :articles do
resources :comments
end
You get paths like:
/articles/42
/articles/42/comments/99
routed to controllers at
app/controllers/articles_controller.rb
app/controllers/comments_controller.rb
just as it says at http://guides.rubyonrails.org/routing.html#nested-resources, with no special namespaces.
But partials and forms become tricky. Note the square brackets:
<%= form_for [@article, @comment] do |f| %>
Most important, if you want a URI, you may need something like this:
article_comment_path(@article, @comment)
Alternatively:
[@article, @comment]
as described at http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects
For example, inside a collections partial with comment_item
supplied for iteration,
<%= link_to "delete", article_comment_path(@article, comment_item),
:method => :delete, :confirm => "Really?" %>
What jamuraa says may work in the context of Article, but it did not work for me in various other ways.
There is a lot of discussion related to nested resources, e.g. http://weblog.jamisbuck.org/2007/2/5/nesting-resources
Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:
# POST /comments
post :create, :comment => {:article_id=>42, ...}
In order to test the route that they may prefer, they need to do it this way:
# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}
I learned this because my unit-tests started failing when I switched from this:
resources :comments
resources :articles do
resources :comments
end
to this:
resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:
resources :comments
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
Sorry for the long answer. Not many people are aware of the subtleties, I think.
Might benefit you to be aware of another option, word-wrap: break-word;
The difference here is that words that can completely fit on 1 line will do that, vs. being forced to break simply because there is no more real estate on the line the word starts on.
See the fiddle for an illustration http://jsfiddle.net/Jqkcp/
There are several "compilers" of PHP code. Most of them do not support all of PHP features, since these simply must be interpreted during run time.
We are using Phalanger - http://www.php-compiler.net/ - that is supporting even those dirty PHP dynamic features, and still is able to compile them as .NET assembly, that can be distributed as a standalone DLL.
We can check also in simple way as:
function isLetter(char){_x000D_
return ( (char >= 'A' && char <= 'Z') ||_x000D_
(char >= 'a' && char <= 'z') );_x000D_
}_x000D_
_x000D_
_x000D_
console.log(isLetter("a"));_x000D_
console.log(isLetter(3));_x000D_
console.log(isLetter("H"));
_x000D_
I used "hbase-1.3.0" and "hadoop-2.7.3" versions. Setting HADOOP_HOME environment variable and copying 'winutils.exe' file under HADOOP_HOME/bin folder solves the problem on a windows os. Attention to set HADOOP_HOME environment to the installation folder of hadoop(/bin folder is not necessary for these versions). Additionally I preferred using cross platform tool cygwin to settle linux os functionality (as possible as it can) because Hbase team recommend linux/unix env.
The code will look like this:
$(".data-cash").each(function (index) {
$(this).dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page",
"oPaginate": {
"sPrevious": "Prev",
"sNext": "Next"
}
},
"bSort": false,
"aaSorting": []
});
});
An alternative in Python 2.6 or above is to use collections.namedtuple()
-- it saves you writing any special methods:
from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
def __new__(cls, name, location, length):
obj = MyThingBase.__new__(cls, name, location)
obj.length = length
return obj
a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False
From a quick search, Oracle appears to use double quotes ("
, eg "table"
) and apparently requires the correct case—whereas, for anyone interested, MySQL defaults to using backticks (`) except when set to use double quotes for compatibility.