Error: the entity type requires a primary key
Your Id property needs to have a setter. However the setter can be private.
The [Key]
attribute is not necessary if the property is named "Id" as it will find it through the naming convention where it looks for a key with the name "Id".
public Guid Id { get; } // Will not work
public Guid Id { get; set; } // Will work
public Guid Id { get; private set; } // Will also work
How to set UICollectionViewCell Width and Height programmatically
in Swift3 and Swift4 you can change cell size by adding UICollectionViewDelegateFlowLayout and implementing it's like this :
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
or if create UICollectionView programmatically you can do it like this :
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal //this is for direction
layout.minimumInteritemSpacing = 0 // this is for spacing between cells
layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height) //this is for cell size
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
How to make a simple collection view with Swift
For swift 4.2
--
//MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1 //return number of sections in collection view
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 //return number of rows in section
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
configureCell(cell: cell, forItemAtIndexPath: indexPath)
return cell //return your cell
}
func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
cell.backgroundColor = UIColor.black
//Customise your cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
return view
}
//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// When user selects the cell
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
// When user deselects the cell
}
How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?
For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.width
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
layout.itemSize = CGSize(width: width / 2, height: width / 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
}
Place this code into viewDidLoad() function.
UICollectionView - dynamic cell height?
I just ran into this problem on a UICollectionView and the way that i solved it similar to the answer above but in a pure UICollectionView way.
Create a custom UICollectionViewCell that contains whatever you will be filling it with to make it dynamic. I created its own .xib for it as it seems like the easiest approach.
Add constraints in that .xib that allow for the cell to be calculated from top to bottom. The re-sizing won't work if you haven't accounted for all of the height. Say you have a view on top, then a label underneath it, and another label underneath that. You would need to connect constraints to the top of the cell to the top of that view, then the bottom of the view to the top of the first label, bottom of first label to the top of the second label, and bottom of second label to bottom of cell.
Load the .xib into the viewcontroller and register it with the collectionView on viewDidLoad
let nib = UINib(nibName: CustomCellName, bundle: nil)
self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "customCellID")`
Load a second copy of that xib into the class and store it as a property so you can use it to determine the size of what that cell should be
let sizingNibNew = NSBundle.mainBundle().loadNibNamed(CustomCellName, owner: CustomCellName.self, options: nil) as NSArray
self.sizingNibNew = (sizingNibNew.objectAtIndex(0) as? CustomViewCell)!
Implement the UICollectionViewFlowLayoutDelegate
in your view controller. The method that matters is called sizeForItemAtIndexPath
. Inside that method you will need to pull the data from the datasource that is associated with that cell from the indexPath. Then configure the sizingCell and call preferredLayoutSizeFittingSize
. The method returns a CGSize which will consist of the width minus the content insets and the height that is returned from self.sizingCell.preferredLayoutSizeFittingSize(targetSize)
.
override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
guard let data = datasourceArray?[indexPath.item] else {
return CGSizeZero
}
let sectionInset = self.collectionView?.collectionViewLayout.sectionInset
let widthToSubtract = sectionInset!.left + sectionInset!.right
let requiredWidth = collectionView.bounds.size.width
let targetSize = CGSize(width: requiredWidth, height: 0)
sizingNibNew.configureCell(data as! CustomCellData, delegate: self)
let adequateSize = self.sizingNibNew.preferredLayoutSizeFittingSize(targetSize)
return CGSize(width: (self.collectionView?.bounds.width)! - widthToSubtract, height: adequateSize.height)
}
In the class of the custom cell itself you will need to override awakeFromNib
and tell the contentView
that its size needs to be flexible
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight]
}
In the custom cell override layoutSubviews
override func layoutSubviews() {
self.layoutIfNeeded()
}
In the class of the custom cell implement preferredLayoutSizeFittingSize
. This is where you will need to do any trickery on the items that are being laid out. If its a label you will need to tell it what its preferredMaxWidth should be.
func preferredLayoutSizeFittingSize(_ targetSize: CGSize)-> CGSize {
let originalFrame = self.frame
let originalPreferredMaxLayoutWidth = self.label.preferredMaxLayoutWidth
var frame = self.frame
frame.size = targetSize
self.frame = frame
self.setNeedsLayout()
self.layoutIfNeeded()
self.label.preferredMaxLayoutWidth = self.questionLabel.bounds.size.width
// calling this tells the cell to figure out a size for it based on the current items set
let computedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
let newSize = CGSize(width:targetSize.width, height:computedSize.height)
self.frame = originalFrame
self.questionLabel.preferredMaxLayoutWidth = originalPreferredMaxLayoutWidth
return newSize
}
All those steps should give you the correct sizes. If your getting 0 or other funky numbers than you haven't set up your constraints properly.
Swift UIView background color opacity
The question is old, but it seems that there are people who have the same concerns.
What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?
The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed.
So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.
As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80),
In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.
self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)
extension is
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: alpha)
}
}
However, the actual view was
- 'View with background color specified in Interface Builder': R 0.09 G 0.09 B 0.09 alpha 0.8.
- 'View with background color by code': R 0.07 G 0.07 B 0.07 alpha 0.8
Calculating it,
- 0x12 = 18(decimal)
- 18/255 = 0.07058...
- 255 * 0.09 = 22.95
- 23(decimal) = 0x17
So, I was able to match the colors similarly by setting the UIColor values ??to 17, 17, 17 and alpha 0.8.
self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)
Or can anyone tell me what I'm missing?
UICollectionView Self Sizing Cells with Auto Layout
I tried using estimatedItemSize
but there were a bunch of bugs when inserting and deleting cells if the estimatedItemSize
was not exactly equal to the cell's height. i stopped setting estimatedItemSize
and implemented dynamic cell's by using a prototype cell. here's how that's done:
create this protocol:
protocol SizeableCollectionViewCell {
func fittedSize(forConstrainedSize size: CGSize)->CGSize
}
implement this protocol in your custom UICollectionViewCell
:
class YourCustomCollectionViewCell: UICollectionViewCell, SizeableCollectionViewCell {
@IBOutlet private var mTitle: UILabel!
@IBOutlet private var mDescription: UILabel!
@IBOutlet private var mContentView: UIView!
@IBOutlet private var mTitleTopConstraint: NSLayoutConstraint!
@IBOutlet private var mDesciptionBottomConstraint: NSLayoutConstraint!
func fittedSize(forConstrainedSize size: CGSize)->CGSize {
let fittedSize: CGSize!
//if height is greatest value, then it's dynamic, so it must be calculated
if size.height == CGFLoat.greatestFiniteMagnitude {
var height: CGFloat = 0
/*now here's where you want to add all the heights up of your views.
apple provides a method called sizeThatFits(size:), but it's not
implemented by default; except for some concrete subclasses such
as UILabel, UIButton, etc. search to see if the classes you use implement
it. here's how it would be used:
*/
height += mTitle.sizeThatFits(size).height
height += mDescription.sizeThatFits(size).height
height += mCustomView.sizeThatFits(size).height //you'll have to implement this in your custom view
//anything that takes up height in the cell has to be included, including top/bottom margin constraints
height += mTitleTopConstraint.constant
height += mDescriptionBottomConstraint.constant
fittedSize = CGSize(width: size.width, height: height)
}
//else width is greatest value, if not, you did something wrong
else {
//do the same thing that's done for height but with width, remember to include leading/trailing margins in calculations
}
return fittedSize
}
}
now make your controller conform to UICollectionViewDelegateFlowLayout
, and in it, have this field:
class YourViewController: UIViewController, UICollectionViewDelegateFlowLayout {
private var mCustomCellPrototype = UINib(nibName: <name of the nib file for your custom collectionviewcell>, bundle: nil).instantiate(withOwner: nil, options: nil).first as! SizeableCollectionViewCell
}
it will be used as a prototype cell to bind data to and then determine how that data affected the dimension that you want to be dynamic
finally, the UICollectionViewDelegateFlowLayout's
collectionView(:layout:sizeForItemAt:)
has to be implemented:
class YourViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
private var mDataSource: [CustomModel]
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)->CGSize {
//bind the prototype cell with the data that corresponds to this index path
mCustomCellPrototype.bind(model: mDataSource[indexPath.row]) //this is the same method you would use to reconfigure the cells that you dequeue in collectionView(:cellForItemAt:). i'm calling it bind
//define the dimension you want constrained
let width = UIScreen.main.bounds.size.width - 20 //the width you want your cells to be
let height = CGFloat.greatestFiniteMagnitude //height has the greatest finite magnitude, so in this code, that means it will be dynamic
let constrainedSize = CGSize(width: width, height: height)
//determine the size the cell will be given this data and return it
return mCustomCellPrototype.fittedSize(forConstrainedSize: constrainedSize)
}
}
and that's it. Returning the cell's size in collectionView(:layout:sizeForItemAt:)
in this way preventing me from having to use estimatedItemSize
, and inserting and deleting cells works perfectly.
Paging UICollectionView by cells, not screen
Here is my way to do it by using a UICollectionViewFlowLayout
to override the targetContentOffset
:
(Although in the end, I end up not using this and use UIPageViewController instead.)
/**
A UICollectionViewFlowLayout with...
- paged horizontal scrolling
- itemSize is the same as the collectionView bounds.size
*/
class PagedFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
self.scrollDirection = .horizontal
self.minimumLineSpacing = 8 // line spacing is the horizontal spacing in horizontal scrollDirection
self.minimumInteritemSpacing = 0
if #available(iOS 11.0, *) {
self.sectionInsetReference = .fromSafeArea // for iPhone X
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("not implemented")
}
// Note: Setting `minimumInteritemSpacing` here will be too late. Don't do it here.
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
collectionView.decelerationRate = UIScrollViewDecelerationRateFast // mostly you want it fast!
let insetedBounds = UIEdgeInsetsInsetRect(collectionView.bounds, self.sectionInset)
self.itemSize = insetedBounds.size
}
// Table: Possible cases of targetContentOffset calculation
// -------------------------
// start | |
// near | velocity | end
// page | | page
// -------------------------
// 0 | forward | 1
// 0 | still | 0
// 0 | backward | 0
// 1 | forward | 1
// 1 | still | 1
// 1 | backward | 0
// -------------------------
override func targetContentOffset( //swiftlint:disable:this cyclomatic_complexity
forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else { return proposedContentOffset }
let pageWidth = itemSize.width + minimumLineSpacing
let currentPage: CGFloat = collectionView.contentOffset.x / pageWidth
let nearestPage: CGFloat = round(currentPage)
let isNearPreviousPage = nearestPage < currentPage
var pageDiff: CGFloat = 0
let velocityThreshold: CGFloat = 0.5 // can customize this threshold
if isNearPreviousPage {
if velocity.x > velocityThreshold {
pageDiff = 1
}
} else {
if velocity.x < -velocityThreshold {
pageDiff = -1
}
}
let x = (nearestPage + pageDiff) * pageWidth
let cappedX = max(0, x) // cap to avoid targeting beyond content
//print("x:", x, "velocity:", velocity)
return CGPoint(x: cappedX, y: proposedContentOffset.y)
}
}
UICollectionView current visible cell index
converting @Anthony's answer to Swift 3.0 worked perfectly for me:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
var visibleRect = CGRect()
visibleRect.origin = yourCollectionView.contentOffset
visibleRect.size = yourCollectionView.bounds.size
let visiblePoint = CGPoint(x: CGFloat(visibleRect.midX), y: CGFloat(visibleRect.midY))
let visibleIndexPath: IndexPath? = yourCollectionView.indexPathForItem(at: visiblePoint)
print("Visible cell's index is : \(visibleIndexPath?.row)!")
}
Creating a UICollectionView programmatically
swift 4 code
//
// ViewController.swift
// coolectionView
//
import UIKit
class ViewController: UIViewController , UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
@IBOutlet weak var collectionView: UICollectionView!
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
if indexPath.row % 3 != 0
{
return CGSize(width:collectionView.frame.width/2 - 7.5 , height: 100)
}
else
{
return CGSize(width:collectionView.frame.width - 10 , height: 100 )
}
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell1234", for: indexPath as IndexPath) as! CollectionViewCell1234
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.lbl1.text = self.items[indexPath.item]
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
Cell spacing in UICollectionView
I know that the topic is old, but in case anyone still needs correct answer here what you need:
- Override standard flow layout.
Add implementation like that:
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *answer = [super layoutAttributesForElementsInRect:rect];
for(int i = 1; i < [answer count]; ++i) {
UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
NSInteger maximumSpacing = 4;
NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = origin + maximumSpacing;
currentLayoutAttributes.frame = frame;
}
}
return answer;
}
where maximumSpacing could be set to any value you prefer. This trick guarantees that the space between cells would be EXACTLY equal to maximumSpacing!!
UICollectionView cell selection and cell reuse
Only @stefanB solution worked for me on iOS 9.3
Here what I have to change for Swift 2
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//prepare your cell here..
//Add background view for normal cell
let backgroundView: UIView = UIView(frame: cell!.bounds)
backgroundView.backgroundColor = UIColor.lightGrayColor()
cell!.backgroundView = backgroundView
//Add background view for selected cell
let selectedBGView: UIView = UIView(frame: cell!.bounds)
selectedBGView.backgroundColor = UIColor.redColor()
cell!.selectedBackgroundView = selectedBGView
return cell!
}
func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
UICollectionView Set number of columns
Expanding on noob's answer:
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(numberOfItemsPerRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))
return CGSize(width: size, height: size)
}
This allows for any spacing between the cells. It assumes an Int
member variable called numberOfItemsPerRow
and also that all the cells are square and the same size. As noted in jhilgert00's answer we must also react to orientation changes, but now by using viewWillTransitionToSize
as willRotateToInterfaceOrientation
is depreciated.
UICollectionView spacing margins
Swift 4
let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
// If you create collectionView programmatically then just create this flow by UICollectionViewFlowLayout() and init a collectionView by this flow.
let itemSpacing: CGFloat = 3
let itemsInOneLine: CGFloat = 3
flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//collectionView.frame.width is the same as UIScreen.main.bounds.size.width here.
let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1)
flow.itemSize = CGSize(width: floor(width/itemsInOneLine), height: width/itemsInOneLine)
flow.minimumInteritemSpacing = 3
flow.minimumLineSpacing = itemSpacing
EDIT
If you want to change to scrollDirction
horizontally:
flow.scrollDirection = .horizontal
NOTE
If you set items in one lines isn't correctly, check if your collection view has paddings. That is:
let width = UIScreen.main.bounds.size.width - itemSpacing * CGFloat(itemsInOneLine - 1)
should be the collectionView width.
How to center align the cells of a UICollectionView?
The top solutions here did not work for me out-of-the-box, so I came up with this which should work for any horizontal scrolling collection view with flow layout and only one section:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
// Add inset to the collection view if there are not enough cells to fill the width.
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - (cellCount * cellWidth) - ((cellCount - 1)*cellSpacing)) * 0.5;
inset = MAX(inset, 0.0);
return UIEdgeInsetsMake(0.0, inset, 0.0, 0.0);
}
Access parent DataContext from DataTemplate
I was searching how to do something similar in WPF and I got this solution:
<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Content="{Binding}"
Command="{Binding Path=DataContext.CustomCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}} }"
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems
-which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate
is using a DataTemplate
, the DataContext
of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl
type.
ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)
This uses the above ideas but makes it a derived 'more sensitive' collection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections;
namespace somethingelse
{
public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
// this collection also reacts to changes in its components' properties
public ObservableCollectionEx() : base()
{
this.CollectionChanged +=new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ObservableCollectionEx_CollectionChanged);
}
void ObservableCollectionEx_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach(T item in e.OldItems)
{
//Removed items
item.PropertyChanged -= EntityViewModelPropertyChanged;
}
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach(T item in e.NewItems)
{
//Added items
item.PropertyChanged += EntityViewModelPropertyChanged;
}
}
}
public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
//This will get called when the property of an object inside the collection changes - note you must make it a 'reset' - I don't know, why
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(args);
}
}
}
Binding a WPF ComboBox to a custom list
I had a similar issue where the SelectedItem never got updated.
My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.
public override bool Equals(object obj)
{
return this.Id == (obj as MyCustomObject).Id;
}
ListBox vs. ListView - how to choose for data binding
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
Run java jar file on a server as background process
Systemd which now runs in the majority of distros
Step 1:
Find your user defined services mine was at /usr/lib/systemd/system/
Step 2:
Create a text file with your favorite text editor name it whatever_you_want.service
Step 3:
Put following
Template to the file whatever_you_want.service
[Unit]
Description=webserver Daemon
[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user
[Install]
WantedBy=multi-user.target
Step 4:
Run your service
as super user
$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service
How to update and delete a cookie?
http://www.quirksmode.org/js/cookies.html
update would just be resetting it using createCookie
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
var expires = "; expires=" + date.toGMTString();
} else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
How to get the android Path string to a file on Assets folder?
Have a look at the ReadAsset.java from API samples that come with the SDK.
try {
InputStream is = getAssets().open("read_asset.txt");
// We guarantee that the available method returns the total
// size of the asset... of course, this does mean that a single
// asset can't be more than 2 gigs.
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
// Finally stick the string into the text view.
TextView tv = (TextView)findViewById(R.id.text);
tv.setText(text);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
How to determine if one array contains all elements of another array
This can be achieved by doing
(a2 & a1) == a2
This creates the intersection of both arrays, returning all elements from a2
which are also in a1
. If the result is the same as a2
, you can be sure you have all elements included in a1
.
This approach only works if all elements in a2
are different from each other in the first place. If there are doubles, this approach fails. The one from Tempos still works then, so I wholeheartedly recommend his approach (also it's probably faster).
How to add subject alernative name to ssl certs?
Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS
entries for a host name and IP
entries for IP addresses).
To quote myself:
If you're using keytool
, as of Java 7, keytool has an option to
include a Subject Alternative Name (see the table in the documentation
for -ext): you could use -ext san=dns:www.example.com or -ext
san=ip:10.0.0.1
Note that you only need Java 7's keytool
to use this command. Once you've prepared your keystore, it should work with previous versions of Java.
(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)
How to render a DateTime object in a Twig template
Dont forget
@ORM\HasLifecycleCallbacks()
Entity :
/**
* Set gameDate
*
* @ORM\PrePersist
*/
public function setGameDate()
{
$this->dateCreated = new \DateTime();
return $this;
}
View:
{{ item.gameDate|date('Y-m-d H:i:s') }}
>> Output 2013-09-18 16:14:20
scrollIntoView Scrolls just too far
Based on the answer of Arseniy-II: I had the Use-Case where the scrolling entity was not window itself but a inner Template (in this case a div). In this scenario we need to set an ID for the scrolling container and get it via getElementById
to use its scrolling function:
<div class="scroll-container" id="app-content">
...
</div>
const yOffsetForScroll = -100
const y = document.getElementById(this.idToScroll).getBoundingClientRect().top;
const main = document.getElementById('app-content');
main.scrollTo({
top: y + main.scrollTop + yOffsetForScroll,
behavior: 'smooth'
});
Leaving it here in case someone faces a similar situation!
AngularJS - value attribute for select
You could modify you model to look like this:
$scope.options = {
"AL" : "Alabama",
"AK" : "Alaska",
"AS" : "American Samoa"
};
Then use
<select ng-options="k as v for (k,v) in options"></select>
HTML5 LocalStorage: Checking if a key exists
Update:
if (localStorage.hasOwnProperty("username")) {
//
}
Another way, relevant when value is not expected to be empty string, null or any other falsy value:
if (localStorage["username"]) {
//
}
Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working
Make sure:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
is the first <meta>
tag on your page, otherwise IE may not respect it.
Alternatively, the problem may be that IE is using Enterprise Mode for this website:
- Your question mentioned that the console shows:
HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.
- If so you may need to disable enterprise mode (or like this) or turn it off for that website from the Tools menu in IE.
- However Enterprise Mode should in theory be overridden by the X-UA-Compatible tag, but IE might have a bug...
Android: Unable to add window. Permission denied for this window type
Firstly you make sure you have add permission in manifest file.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Check if the application has draw over other apps permission or not?
This permission is by default available for API<23. But for API > 23 you have to ask for the permission in runtime.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1);
}
Use This code:
public class ChatHeadService extends Service {
private WindowManager mWindowManager;
private View mChatHeadView;
WindowManager.LayoutParams params;
public ChatHeadService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Language language = new Language();
//Inflate the chat head layout we created
mChatHeadView = LayoutInflater.from(this).inflate(R.layout.dialog_incoming_call, null);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mChatHeadView, params);
} else {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mChatHeadView, params);
}
TextView tvTitle=mChatHeadView.findViewById(R.id.tvTitle);
tvTitle.setText("Incoming Call");
//Set the close button.
Button btnReject = (Button) mChatHeadView.findViewById(R.id.btnReject);
btnReject.setText(language.getText(R.string.reject));
btnReject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//close the service and remove the chat head from the window
stopSelf();
}
});
//Drag and move chat head using user's touch action.
final Button btnAccept = (Button) mChatHeadView.findViewById(R.id.btnAccept);
btnAccept.setText(language.getText(R.string.accept));
LinearLayout linearLayoutMain=mChatHeadView.findViewById(R.id.linearLayoutMain);
linearLayoutMain.setOnTouchListener(new View.OnTouchListener() {
private int lastAction;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//remember the initial position.
initialX = params.x;
initialY = params.y;
//get the touch location
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_UP:
//As we implemented on touch listener with ACTION_MOVE,
//we have to check if the previous action was ACTION_DOWN
//to identify if the user clicked the view or not.
if (lastAction == MotionEvent.ACTION_DOWN) {
//Open the chat conversation click.
Intent intent = new Intent(ChatHeadService.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close the service and remove the chat heads
stopSelf();
}
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_MOVE:
//Calculate the X and Y coordinates of the view.
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
//Update the layout with new X & Y coordinate
mWindowManager.updateViewLayout(mChatHeadView, params);
lastAction = event.getAction();
return true;
}
return false;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
if (mChatHeadView != null) mWindowManager.removeView(mChatHeadView);
}
}
Changing width property of a :before css selector using JQuery
Pseudo elements are part of the shadow DOM and can not be modified (but can have their values queried).
However, sometimes you can get around that by using classes, for example.
jQuery
$('#element').addClass('some-class');
CSS
.some-class:before {
/* change your properties here */
}
This may not be suitable for your query, but it does demonstrate you can achieve this pattern sometimes.
To get a pseudo element's value, try some code like...
var pseudoElementContent = window.getComputedStyle($('#element')[0], ':before')
.getPropertyValue('content')
Gradle: Execution failed for task ':processDebugManifest'
I had the same problem and none of the other answers helped.
In my case, a comment in the manifest file was the culprit:
<manifest [...]
android:installLocation="auto">
<!-- change installLocation back to external after test -->
<uses-sdk [...]
(This might be a bug, seeing how comments in other areas of the manifest dont cause any problems.)
How to insert pandas dataframe via mysqldb into database?
Python 2 + 3
Prerequesites
- Pandas
- MySQL server
- sqlalchemy
- pymysql: pure python mysql client
Code
from pandas.io import sql
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user="root",
pw="your_password",
db="pandas"))
df.to_sql(con=engine, name='table_name', if_exists='replace')
What is "not assignable to parameter of type never" error in typescript?
This seems to be a recent regression or some strange behavior in typescript. If you have the code:
const result = []
Usually it would be treated as if you wrote:
const result:any[] = []
however, if you have both noImplicitAny
FALSE, AND strictNullChecks
TRUE in your tsconfig, it is treated as:
const result:never[] = []
This behavior defies all logic, IMHO. Turning on null checks changes the entry types of an array?? And then turning on noImplicitAny
actually restores the use of any
without any warnings??
When you truly have an array of any
, you shouldn't need to indicate it with extra code.
Place cursor at the end of text in EditText
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
editText.setSelection(editText.getText().length());
return false;
}
});
How can I verify if one list is a subset of another?
Since no one has considered comparing two strings, here's my proposal.
You may of course want to check if the pipe ("|") is not part of either lists and maybe chose automatically another char, but you got the idea.
Using an empty string as separator is not a solution since the numbers can have several digits ([12,3] != [1,23])
def issublist(l1,l2):
return '|'.join([str(i) for i in l1]) in '|'.join([str(i) for i in l2])
Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
In my case, this was caused by custom manifest entries added by the maven-jar-plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestEntries>
<git>${buildNumber}</git>
<build-time>${timestamp}</build-time>
</manifestEntries>
</archive>
</configuration>
</plugin>
Removing the following entries fixed the problem
<index>true</index>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
How to get rid of blank pages in PDF exported from SSRS
If the pages are blank coming from SSRS, you need to tweak your report layout. This will be far more efficient than running the output through and post process to repair the side effects of a layout problem.
SSRS is very finicky when it comes to pushing the boundaries of the margins. It is easy to accidentally widen/lengthen the report just by adjusting text box or other control on the report. Check the width and height property of the report surface carefully and squeeze them as much as possible. Watch out for large headers and footers.
Opencv - Grayscale mode Vs gray color conversion
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
How to find if a given key exists in a C++ std::map
Comparing the code of std::map::find and std::map::count, I'd say the first may yield some performance advantage:
const_iterator find(const key_type& _Keyval) const
{ // find an element in nonmutable sequence that matches _Keyval
const_iterator _Where = lower_bound(_Keyval); // Here one looks only for lower bound
return (_Where == end()
|| _DEBUG_LT_PRED(this->_Getcomp(),
_Keyval, this->_Key(_Where._Mynode()))
? end() : _Where);
}
size_type count(const key_type& _Keyval) const
{ // count all elements that match _Keyval
_Paircc _Ans = equal_range(_Keyval); // Here both lower and upper bounds are to be found, which is presumably slower.
size_type _Num = 0;
_Distance(_Ans.first, _Ans.second, _Num);
return (_Num);
}
MySQL Event Scheduler on a specific time everyday
This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:
CREATE EVENT event_name
ON SCHEDULE
EVERY 1 DAY
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
DO
# Your awesome query
Loading scripts after page load?
Here is a code I am using and which is working for me.
window.onload = function(){
setTimeout(function(){
var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = "vendor/js/jquery.min.js";
document.head.appendChild(scriptElement);
setTimeout(function() {
var scriptElement1=document.createElement('script');
scriptElement1.type = 'text/javascript';
scriptElement1.src = "gallery/js/lc_lightbox.lite.min.js";
document.head.appendChild(scriptElement1);
}, 100);
setTimeout(function() {
$(document).ready(function(e){
lc_lightbox('.elem', {
wrap_class: 'lcl_fade_oc',
gallery : true,
thumb_attr: 'data-lcl-thumb',
slideshow_time : 3000,
skin: 'minimal',
radius: 0,
padding : 0,
border_w: 0,
});
});
}, 200);
}, 150);
};
Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?
For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:
First, you need to link against QuickLook.framework
and #import
<QuickLook/QuickLook.h>;
Afterwards, in either viewDidLoad
or any of the lazy initialization methods:
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];
Javascript Get Values from Multiple Select Option Box
Here i am posting the answer just for reference which may become useful.
<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
var InvForm = document.forms.form;
var SelBranchVal = "";
var x = 0;
for (x=0;x<InvForm.kb.length;x++)
{
if(InvForm.kb[x].selected)
{
//alert(InvForm.kb[x].value);
SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
}
}
alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>
Flask - Calling python function on button OnClick event
index.html (index.html should be in templates folder)
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<h2>jQuery-AJAX in FLASK. Execute function on button click</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
function(data) { }); return false; }); }); </script>
</head>
<body>
<input type = "button" id = "mybutton" value = "Click Here" />
</body>
</html>
test.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/SomeFunction')
def SomeFunction():
print('In SomeFunction')
return "Nothing"
if __name__ == '__main__':
app.run()
How to Change Margin of TextView
TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);
I did this and it worked perfectly.
Maybe as you are giving the value in -ve, that's why your code is not working.
You just put this code where you are creating the reference of the view.
How to terminate a thread when main program ends?
Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt
. Such termination functions may (though inevitably in the main thread!) call any stop
function you require; together with the possibility of setting a thread as daemon
, that gives you the tools to properly design the system functionality you need.
How to extract table as text from the PDF using Python?
This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.
Here are the steps I found to work.
Use pdfimages
from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.
Use Tesseract to detect rotation and ImageMagick mogrify
to fix it.
Use OpenCV to find and extract tables.
Use OpenCV to find and extract each cell from the table.
Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.
Use Tesseract to OCR each cell.
Combine the extracted text of each cell into the format you need.
I wrote a python package with modules that can help with those steps.
Repo: https://github.com/eihli/image-table-ocr
Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html
Some of the steps don't require code, they take advantage of external tools like pdfimages
and tesseract
. I'll provide some brief examples for a couple of the steps that do require code.
- Finding tables:
This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/
import cv2
def find_tables(image):
BLUR_KERNEL_SIZE = (17, 17)
STD_DEV_X_DIRECTION = 0
STD_DEV_Y_DIRECTION = 0
blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
MAX_COLOR_VAL = 255
BLOCK_SIZE = 15
SUBTRACT_FROM_MEAN = -2
img_bin = cv2.adaptiveThreshold(
~blurred,
MAX_COLOR_VAL,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
BLOCK_SIZE,
SUBTRACT_FROM_MEAN,
)
vertical = horizontal = img_bin.copy()
SCALE = 5
image_width, image_height = horizontal.shape
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)
horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))
mask = horizontally_dilated + vertically_dilated
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
)
MIN_TABLE_AREA = 1e5
contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
epsilons = [0.1 * p for p in perimeter_lengths]
approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
bounding_rects = [cv2.boundingRect(a) for a in approx_polys]
# The link where a lot of this code was borrowed from recommends an
# additional step to check the number of "joints" inside this bounding rectangle.
# A table should have a lot of intersections. We might have a rectangular image
# here though which would only have 4 intersections, 1 at each corner.
# Leaving that step as a future TODO if it is ever necessary.
images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
return images
- Extract cells from table.
This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.
We want to identify the cells from left-to-right, top-to-bottom.
We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.
def cell_in_same_row(c1, c2):
c1_center = c1[1] + c1[3] - c1[3] / 2
c2_bottom = c2[1] + c2[3]
c2_top = c2[1]
return c2_top < c1_center < c2_bottom
orig_cells = [c for c in cells]
rows = []
while cells:
first = cells[0]
rest = cells[1:]
cells_in_same_row = sorted(
[
c for c in rest
if cell_in_same_row(c, first)
],
key=lambda c: c[0]
)
row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
rows.append(row_cells)
cells = [
c for c in rest
if not cell_in_same_row(c, first)
]
# Sort rows by average height of their center.
def avg_height_of_center(row):
centers = [y + h - h / 2 for x, y, w, h in row]
return sum(centers) / len(centers)
rows.sort(key=avg_height_of_center)
Datagridview full row selection but get single cell value
Just Use: dataGridView1.CurrentCell.Value.ToString()
private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
}
or
// dataGrid1.Rows[yourRowIndex ].Cells[yourColumnIndex].Value.ToString()
//Example1:yourRowIndex=dataGridView1.CurrentRow.Index (from selectedRow );
dataGrid1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString()
//Example2:yourRowIndex=3,yourColumnIndex=2 (select by programmatically )
dataGrid1.Rows[3].Cells[2].Value.ToString()
Iterate over object keys in node.js
What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.
The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.
You could try the following, however it will also load all the keys into memory
Object.keys(o).forEach(function(key) {
var val = o[key];
logic();
});
However since Object.keys
is a native method it may allow for better optimisation.
Benchmark
As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.
var async = {};
async.forEach = function(o, cb) {
var counter = 0,
keys = Object.keys(o),
len = keys.length;
var next = function() {
if (counter < len) cb(o[keys[counter++]], next);
};
next();
};
async.forEach(obj, function(val, next) {
// do things
setTimeout(next, 100);
});
What is the use of ByteBuffer in Java?
The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:
Absolute and relative get and put methods that read and write single bytes;
Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;
Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;
Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of
bytes in a particular byte order;
Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and
Methods for compacting, duplicating, and slicing a byte buffer.
Example code : Putting Bytes into a buffer.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Get the buffer's capacity
int capacity = bbuf.capacity(); // 10
// Use the absolute put(int, byte).
// This method does not affect the position.
bbuf.put(0, (byte)0xFF); // position=0
// Set the position
bbuf.position(5);
// Use the relative put(byte)
bbuf.put((byte)0xFF);
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
Converting ArrayList to HashMap
The general methodology would be to iterate through the ArrayList
, and insert the values into the HashMap
. An example is as follows:
HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
productMap.put(product.getProductCode(), product);
}
Callback function for JSONP with jQuery AJAX
This is what I do on mine
$(document).ready(function() {
if ($('#userForm').valid()) {
var formData = $("#userForm").serializeArray();
$.ajax({
url: 'http://www.example.com/user/' + $('#Id').val() + '?callback=?',
type: "GET",
data: formData,
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
});
function localJsonpCallback(json) {
if (!json.Error) {
$('#resultForm').submit();
} else {
$('#loading').hide();
$('#userForm').show();
alert(json.Message);
}
}
How to delete images from a private docker registry?
There is also a way you can remove some old images from repository just based on the date when it was created.
To do that enter your docker registry container and get the list of manifest's revisions for some specific repository:
ls -latr /var/lib/registry/docker/registry/v2/repositories/YOUR_REPO/_manifests/revisions/sha256/
The output then may be used within the request (with sha256 prefix):
curl -v --silent -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE http://DOCKER_REGISTRY_HOST:5000/v2/YOUR_REPO/manifests/sha256:OUTPUT_LINE
And of course do not forget to execute 'garbage-collect' command after that:
bin/registry garbage-collect /etc/docker/registry/config.yml
how to set start value as "0" in chartjs?
For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes
instead of yAxes
. Note that an array (and plural) is used for yAxes
(or xAxes
), because you may as well have multiple axes.
CronJob not running
For me, the solution was that the file cron was trying to run was in an encrypted directory, more specifcically a user diretory on /home/. Although the crontab was configured as root, because the script being run exisited in an encrypted user directory in /home/ cron could only read this directory when the user was actually logged in. To see if the directory is encrypted check if this directory exists:
/home/.ecryptfs/<yourusername>
if so then you have an encrypted home directory.
The fix for me was to move the script in to a non=encrypted directory and everythig worked fine.
Yii2 data provider default sorting
Try to this one
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$sort = $dataProvider->getSort();
$sort->defaultOrder = ['id' => SORT_ASC];
$dataProvider->setSort($sort);
How to initialize a vector with fixed length in R
?vector
X <- vector(mode="character", length=10)
This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default
displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.
> X[5] <- "character element in 5th position"
> X
[1] "" ""
[3] "" ""
[5] "character element in 5th position" ""
[7] "" ""
[9] "" ""
> nchar(X)
[1] 0 0 0 0 33 0 0 0 0 0
> length(X)
[1] 10
how do I insert a column at a specific column index in pandas?
df.insert(loc, column_name, value)
This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.
You can pass an optional parameter allow_duplicates
with True
value to create a new column with already existing column name.
Here is an example:
>>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
>>> df
b c
0 1 3
1 2 4
>>> df.insert(0, 'a', -1)
>>> df
a b c
0 -1 1 3
1 -1 2 4
>>> df.insert(0, 'a', -2)
Traceback (most recent call last):
File "", line 1, in
File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
raise ValueError(f"cannot insert {item}, already exists")
ValueError: cannot insert a, already exists
>>> df.insert(0, 'a', -2, allow_duplicates = True)
>>> df
a a b c
0 -2 -1 1 3
1 -2 -1 2 4
What does O(log n) mean exactly?
What's logb(n)?
It is the number of times you can cut a log of length n repeatedly into b equal parts before reaching a section of size 1.
How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/
I did this:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoDealer</title>
<style>
.container{
width: 860px;
height: 1074px;
margin-right: auto;
margin-left: auto;
border: 1px solid red;
}
.nav{
}
.wrapper{
display: block;
overflow: hidden;
border: 1px solid green;
}
.otherWrapper{
display: block;
overflow: hidden;
border: 1px solid green;
float:left;
}
.left{
width: 399px;
float: left;
background-color: pink;
}
.bottom{
clear: both;
width: 399px;
background-color: yellow;
}
.right{
height:350px;
width: 449px;
overflow: hidden;
background-color: blue;
overflow: hidden;
float:right;
}
</style>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="wrapper">
<div class="otherWrapper">
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
</div>
<div class="bottom">
<p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
</div>
<div class="right">
<p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
</div>
</div>
</div>
</body>
So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.
Enable Hibernate logging
I answer to myself. As suggested by Vadzim, I must consider the jboss-logging.xml file and insert these lines:
<logger category="org.hibernate">
<level name="TRACE"/>
</logger>
Instead of DEBUG level I wrote TRACE.
Now don't look only the console but open the server.log file (debug messages aren't sent to the console but you can configure this mode!).
Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
There are different ways we can pass the
Access-Control-Expose-Headers.
- As jgauffin has explained we can create a new attribute.
- As LaundroMatt has explained we can add in the web.config file.
Another way is we can add code as below in the webApiconfig.cs file.
config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });
Or we can add below code in the Global.Asax file.
protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
HttpContext.Current.Response.End();
}
}
I have written it for the options. Please modify the same as per your need.
Happy Coding !!
Is it possible to make an HTML anchor tag not clickable/linkable using CSS?
That isn't too easy to do with CSS, as it's not a behavioral language (ie JavaScript), the only easy way would be to use a JavaScript OnClick Event on your anchor and to return it as false, this is probably the shortest code you could use for that:
<a href="page.html" onclick="return false">page link</a>
jquery .on() method with load event
I'm not sure what you're going for here--by the time jQuery(document).ready()
has executed, it has already loaded, and thus document
's load event will already have been called. Attaching the load
event handler at this point will have no effect and it will never be called. If you're attempting to alert
"started" once the document has loaded, just put it right in the (document).ready()
call, like this:
jQuery(document).ready(function() {
var x = $('#initial').html();
$('#add').click(function() {
$('body').append(x);
});
alert('started');
});?
If, as your code also appears to insinuate, you want to fire the alert when .abc
has loaded, put it in an individual .load
handler:
jQuery(document).ready(function() {
var x = $('#initial').html();
$('#add').click(function() {
$('body').append(x);
});
$(".abc").on("load", function() {
alert('started');
}
});?
Finally, I see little point in using jQuery
in one place and $
in another. It's generally better to keep your code consistent, and either use jQuery
everywhere or $
everywhere, as the two are generally interchangeable.
How to validate white spaces/empty spaces? [Angular 2]
To avoid the form submition, just use required
attr in the input fields.
<input type="text" required>
Or, after submit
When the form is submited, you can use str.trim() to remove white spaces form start and end of an string. I did a submit function to show you:
submitFunction(formData){
if(!formData.foo){
// launch an alert to say the user the field cannot be empty
return false;
}
else
{
formData.foo = formData.foo.trim(); // removes white
// do your logic here
return true;
}
}
PDO error message?
Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:
$field1 = 'foo';
$field2 = 'bar';
$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);
$insert_QUERY->execute();
$databaseErrors = $insert_QUERY->errorInfo();
if( !empty($databaseErrors) ){
$errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
$errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...
/*
$errorLogMsg will return something like:
error info:
Array(
[0] => 42000
[1] => 1064
[2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table bogus(field1, field2) VALUES ('bar', NULL)' at line 1
)
*/
} else {
# no SQL errors.
}
How to detect scroll direction
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$(document).bind(mousewheelevt,
function(e)
{
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0)
{
scrollup();
}
else
{
scrolldown();
}
}
);
SQL Server: use CASE with LIKE
You can also do like this
select *
from table
where columnName like '%' + case when @varColumn is null then '' else @varColumn end + ' %'
Getting individual colors from a color map in matplotlib
I had precisely this problem, but I needed sequential plots to have highly contrasting color. I was also doing plots with a common sub-plot containing reference data, so I wanted the color sequence to be consistently repeatable.
I initially tried simply generating colors randomly, reseeding the RNG before each plot. This worked OK (commented-out in code below), but could generate nearly indistinguishable colors. I wanted highly contrasting colors, ideally sampled from a colormap containing all colors.
I could have as many as 31 data series in a single plot, so I chopped the colormap into that many steps. Then I walked the steps in an order that ensured I wouldn't return to the neighborhood of a given color very soon.
My data is in a highly irregular time series, so I wanted to see the points and the lines, with the point having the 'opposite' color of the line.
Given all the above, it was easiest to generate a dictionary with the relevant parameters for plotting the individual series, then expand it as part of the call.
Here's my code. Perhaps not pretty, but functional.
from matplotlib import cm
cmap = cm.get_cmap('gist_rainbow') #('hsv') #('nipy_spectral')
max_colors = 31 # Constant, max mumber of series in any plot. Ideally prime.
color_number = 0 # Variable, incremented for each series.
def restart_colors():
global color_number
color_number = 0
#np.random.seed(1)
def next_color():
global color_number
color_number += 1
#color = tuple(np.random.uniform(0.0, 0.5, 3))
color = cmap( ((5 * color_number) % max_colors) / max_colors )
return color
def plot_args(): # Invoked for each plot in a series as: '**(plot_args())'
mkr = next_color()
clr = (1 - mkr[0], 1 - mkr[1], 1 - mkr[2], mkr[3]) # Give line inverse of marker color
return {
"marker": "o",
"color": clr,
"mfc": mkr,
"mec": mkr,
"markersize": 0.5,
"linewidth": 1,
}
My context is JupyterLab and Pandas, so here's sample plot code:
restart_colors() # Repeatable color sequence for every plot
fig, axs = plt.subplots(figsize=(15, 8))
plt.title("%s + T-meter"%name)
# Plot reference temperatures:
axs.set_ylabel("°C", rotation=0)
for s in ["T1", "T2", "T3", "T4"]:
df_tmeter.plot(ax=axs, x="Timestamp", y=s, label="T-meter:%s" % s, **(plot_args()))
# Other series gets their own axis labels
ax2 = axs.twinx()
ax2.set_ylabel(units)
for c in df_uptime_sensors:
df_uptime[df_uptime["UUID"] == c].plot(
ax=ax2, x="Timestamp", y=units, label="%s - %s" % (units, c), **(plot_args())
)
fig.tight_layout()
plt.show()
The resulting plot may not be the best example, but it becomes more relevant when interactively zoomed in.
How to get names of enum entries?
In a nutshell
if your enums
is as below:
export enum Colors1 {
Red = 1,
Green = 2,
Blue = 3
}
to get specific text and value:
console.log(Colors1.Red); // 1
console.log(Colors1[Colors1.Red]); // Red
to get list of value and text:
public getTextAndValues(e: { [s: number]: string }) {
for (const enumMember in e) {
if (parseInt(enumMember, 10) >= 0) {
console.log(e[enumMember]) // Value, such as 1,2,3
console.log(parseInt(enumMember, 10)) // Text, such as Red,Green,Blue
}
}
}
thsi.getTextAndValues(Colors1)
if your enums
is as below:
export enum Colors2 {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
to get specific text and value:
console.log(Colors2.Red); // Red
console.log(Colors2["Red"]); // Red
to get list of value and text:
public getTextAndValues(e: { [s: string]: string }) {
for (const enumMember in e) {
console.log(e[enumMember]);// Value, such as Red,Green,Blue
console.log(enumMember); // Text, such as Red,Green,Blue
}
}
this.getTextAndValues(Colors2)
Play infinitely looping video on-load in HTML5
The loop attribute should do it:
<video width="320" height="240" autoplay loop>
<source src="movie.mp4" type="video/mp4" />
<source src="movie.ogg" type="video/ogg" />
Your browser does not support the video tag.
</video>
Should you have a problem with the loop attribute (as we had in the past), listen to the videoEnd
event and call the play()
method when it fires.
Note1: I'm not sure about the behavior on Apple's iPad/iPhone, because they have some restrictions against autoplay
.
Note2: loop="true"
and autoplay="autoplay"
are deprecated
Subtracting time.Duration from time in Go
In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
count := 10
then := now.Add(time.Duration(-count) * time.Minute)
// if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
// then := now.Add(-10 * time.Minute)
fmt.Println("10 minutes ago:", then)
}
Produces:
now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
Not to mention, you can also use time.Hour
or time.Second
instead of time.Minute
as per your needs.
Playground: https://play.golang.org/p/DzzH4SA3izp
Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect
statistics on the table with the ANALYZE statement or the DBMS_STATS
package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
Getting Chrome to accept self-signed localhost certificate
UPDATED Apr 23/2020
Recommended by the Chromium Team
https://www.chromium.org/Home/chromium-security/deprecating-powerful-features-on-insecure-origins#TOC-Testing-Powerful-Features
Quick Super-Easy Solution
There is a secret bypass phrase that can be typed into the error page to have Chrome proceed despite the security error: thisisunsafe (in earlier versions of Chrome, type badidea, and even earlier, danger). DO NOT USE THIS UNLESS YOU UNDERSTAND EXACTLY WHY YOU NEED IT!
Source:
https://chromium.googlesource.com/chromium/src/+/d8fc089b62cd4f8d907acff6fb3f5ff58f168697%5E%21/
(NOTE that window.atob('dGhpc2lzdW5zYWZl')
resolves to thisisunsafe
)
The latest version of the source is @ https://chromium.googlesource.com/chromium/src/+/refs/heads/master/components/security_interstitials/core/browser/resources/interstitial_large.js and the window.atob
function can be executed in a JS console.
For background about why the Chrome team changed the bypass phrase (the first time):
https://bugs.chromium.org/p/chromium/issues/detail?id=581189
If all else fails (Solution #1)
For quick one-offs if the "Proceed Anyway" option is not available, nor the bypass phrase is working, this hack works well:
Allow certificate errors from localhost
by enabling this flag (note Chrome needs a restart after changing the flag value):
chrome://flags/#allow-insecure-localhost
(and vote-up answer https://stackoverflow.com/a/31900210/430128 by @Chris)
If the site you want to connect to is localhost
, you're done. Otherwise, setup a TCP tunnel to listen on port 8090 locally and connect to broken-remote-site.com
on port 443, ensure you have socat
installed and run something like this in a terminal window:
socat tcp-listen:8090,reuseaddr,fork tcp:broken-remote-site.com:443
Go to https://localhost:8090 in your browser.
If all else fails (Solution #2)
Similar to "If all else fails (Solution #1)", here we configure a proxy to our local service using ngrok. Because you can either access ngrok http tunnels via TLS (in which case it is terminated by ngrok with a valid certificate), or via a non-TLS endpoint, the browser will not complain about invalid certificates.
Download and install ngrok and then expose it via ngrok.io
:
ngrok http https://localhost
ngrok will start up and provide you a host name which you can connect to, and all requests will be tunneled back to your local machine.
HTML Form Redirect After Submit
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
PHP MySQL Query Where x = $variable
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
CSS3 Transform Skew One Side
You try with the :before
was pretty close, the only thing you had to change was actually using skew instead of the borders: http://jsfiddle.net/Hfkk7/1101/
Edit: Your border approach would work too, the only thing you did wrong was having the before element on top of your div, so the transparent border wasnt showing. If you would have position the pseudo element to the left of your div, everything would have worked too: http://jsfiddle.net/Hfkk7/1102/
Spring @Transactional read-only propagation
By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.
Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.
How to destroy a JavaScript object?
You could put all of your code under one namespace like this:
var namespace = {};
namespace.someClassObj = {};
delete namespace.someClassObj;
Using the delete
keyword will delete the reference to the property, but on the low level the JavaScript garbage collector (GC) will get more information about which objects to be reclaimed.
You could also use Chrome Developer Tools to get a memory profile of your app, and which objects in your app are needing to be scaled down.
Default SecurityProtocol in .NET 4.5
An alternative to hard-coding ServicePointManager.SecurityProtocol
or the explicit SchUseStrongCrypto key as mentioned above:
You can tell .NET to use the default SCHANNEL settings with the SystemDefaultTlsVersions key,
e.g.:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319] "SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319] "SystemDefaultTlsVersions"=dword:00000001
How do I extract data from JSON with PHP?
The acepted Answer is very detailed and correct in most of the cases.
I just want to add that i was getting an error while attempting to load a JSON text file encoded with UTF8, i had a well formatted JSON but the 'json_decode' always returned me with NULL, it was due the BOM mark.
To solve it, i made this PHP function:
function load_utf8_file($filePath)
{
$response = null;
try
{
if (file_exists($filePath)) {
$text = file_get_contents($filePath);
$response = preg_replace("/^\xEF\xBB\xBF/", '', $text);
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
}
finally{ }
return $response;
}
Then i use it like this to load a JSON file and get a value from it:
$str = load_utf8_file('appconfig.json');
$json = json_decode($str, true);
//print_r($json);
echo $json['prod']['deploy']['hostname'];
Is there a way to override class variables in Java?
You can create a getter and then override that getter. It's particularly useful if the variable you are overriding is a sub-class of itself. Imagine your super class has an Object
member but in your sub-class this is now more defined to be an Integer
.
class Dad
{
private static final String me = "dad";
protected String getMe() {
return me;
}
public void printMe()
{
System.out.println(getMe());
}
}
class Son extends Dad
{
private static final String me = "son";
@Override
protected String getMe() {
return me;
}
}
public void doIt()
{
new Son().printMe(); //Prints "son"
}
open existing java project in eclipse
If this is a simple Java project, You essentially create a new project and give the location of the existing code. The project wizard will tell you that it will use existing sources.
Also, Eclipse 3.3.2 is ancient history, you guys should really upgrade. This is like using Visual Studio 5.
Min / Max Validator in Angular 2 Final
To apply min/max validation
on a number
you will need to create a Custom Validator
Validators class currently only have a few validators, namely
- required
- requiredTrue
- minlength
- maxlength
- pattern
- nullValidator
- compose
- composeAsync
Validator: Here is toned down version of my number Validator, you can improve it as you like
static number(prms = {}): ValidatorFn {
return (control: FormControl): {[key: string]: any} => {
if(isPresent(Validators.required(control))) {
return null;
}
let val: number = control.value;
if(isNaN(val) || /\D/.test(val.toString())) {
return {"number": true};
} else if(!isNaN(prms.min) && !isNaN(prms.max)) {
return val < prms.min || val > prms.max ? {"number": true} : null;
} else if(!isNaN(prms.min)) {
return val < prms.min ? {"number": true} : null;
} else if(!isNaN(prms.max)) {
return val > prms.max ? {"number": true} : null;
} else {
return null;
}
};
}
Usage:
// check for valid number
var numberControl = new FormControl("", [Validators.required, CustomValidators.number()])
// check for valid number and min value
var numberControl = new FormControl("", CustomValidators.number({min: 0}))
// check for valid number and max value
var numberControl = new FormControl("", CustomValidators.number({max: 20}))
// check for valid number and value range ie: [0-20]
var numberControl = new FormControl("", CustomValidators.number({min: 0, max: 20}))
What is :: (double colon) in Python when subscripting sequences?
TL;DR
This visual example will show you how to a neatly select elements in a NumPy Matrix (2 dimensional array) in a pretty entertaining way (I promise). Step 2 below illustrate the usage of that "double colons" ::
in question.
(Caution: this is a NumPy array specific example with the aim of illustrating the a use case of "double colons" ::
for jumping of elements in multiple axes. This example does not cover native Python data structures like List
).
One concrete example to rule them all...
Say we have a NumPy matrix that looks like this:
In [1]: import numpy as np
In [2]: X = np.arange(100).reshape(10,10)
In [3]: X
Out[3]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
Say for some reason, your boss wants you to select the following elements:
"But How???"... Read on! (We can do this in a 2-step approach)
Step 1 - Obtain subset
Specify the "start index" and "end index" in both row-wise and column-wise directions.
In code:
In [5]: X2 = X[2:9,3:8]
In [6]: X2
Out[6]:
array([[23, 24, 25, 26, 27],
[33, 34, 35, 36, 37],
[43, 44, 45, 46, 47],
[53, 54, 55, 56, 57],
[63, 64, 65, 66, 67],
[73, 74, 75, 76, 77],
[83, 84, 85, 86, 87]])
Notice now we've just obtained our subset, with the use of simple start and end indexing technique. Next up, how to do that "jumping"... (read on!)
Step 2 - Select elements (with the "jump step" argument)
We can now specify the "jump steps" in both row-wise and column-wise directions (to select elements in a "jumping" way) like this:
In code (note the double colons):
In [7]: X3 = X2[::3, ::2]
In [8]: X3
Out[8]:
array([[23, 25, 27],
[53, 55, 57],
[83, 85, 87]])
We have just selected all the elements as required! :)
Consolidate Step 1 (start and end) and Step 2 ("jumping")
Now we know the concept, we can easily combine step 1 and step 2 into one consolidated step - for compactness:
In [9]: X4 = X[2:9,3:8][::3,::2]
In [10]: X4
Out[10]:
array([[23, 25, 27],
[53, 55, 57],
[83, 85, 87]])
Done!
Checking if a folder exists using a .bat file
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
wildcard * in CSS for classes
If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes
How can I filter a date of a DateTimeField in Django?
There's a fantastic blogpost that covers this here: Comparing Dates and Datetimes in the Django ORM
The best solution posted for Django>1.7,<1.9 is to register a transform:
from django.db import models
class MySQLDatetimeDate(models.Transform):
"""
This implements a custom SQL lookup when using `__date` with datetimes.
To enable filtering on datetimes that fall on a given date, import
this transform and register it with the DateTimeField.
"""
lookup_name = 'date'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'DATE({})'.format(lhs), params
@property
def output_field(self):
return models.DateField()
Then you can use it in your filters like this:
Foo.objects.filter(created_on__date=date)
EDIT
This solution is definitely back end dependent. From the article:
Of course, this implementation relies on your particular flavor of SQL having a DATE() function. MySQL does. So does SQLite. On the other hand, I haven’t worked with PostgreSQL personally, but some googling leads me to believe that it does not have a DATE() function. So an implementation this simple seems like it will necessarily be somewhat backend-dependent.
Pie chart with jQuery
There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:
https://zoomcharts.com/
Example of charts:
Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/
What is cool about this lib:
- Others slice can be expanded
- Pie offers drill down for hierarchical structures (see example)
- write your own data source controller easily, or provide simple json file
- export high res images out of box
- full touch support, works smoothly on iPad, iPhone, android, etc.
Charts are free for non-commercial use, commercial licenses and technical support available as well.
Also interactive Time charts and Net Charts are there for you to use.
Charts come with extensive API and Settings, so you can control every aspect of the charts.
Fix columns in horizontal scrolling
Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/
HTML
<h2>TableHeadFixer Fix Left Column</h2>
<div id="parent">
<table id="fixTable" class="table">
<thead>
<tr>
<th>Ano</th>
<th>Jan</th>
<th>Fev</th>
<th>Mar</th>
<th>Abr</th>
<th>Maio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
</tbody>
</table>
</div>
JS
$(document).ready(function() {
$("#fixTable").tableHeadFixer({"head" : false, "right" : 1});
});
CSS
#parent {
height: 300px;
}
#fixTable {
width: 1800px !important;
}
https://jsfiddle.net/5gfuqqc4/
How to import cv2 in python3?
Make a virtual enviroment using python3
virtualenv env_name --python="python3"
and run the following command
pip3 install opencv-python
AttributeError: 'str' object has no attribute
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
How to change Status Bar text color in iOS
You dont need to do any code for this
You need to add "View controller-based status bar appearance" key in info.plist as follows:
& set its value type to Boolean & value to NO.
Then click on project settings,then click on General Tab & under Deployment Info set the preferred status bar style to .Light as follows:
Thats it.
Add A Year To Today's Date
Function
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
month = month + 1;
if (month < 10) {
month = "0" + month;
}
var day = date.getDate();
if (day < 10) {
day = "0" + day;
}
year = year + 1;
var FullDate = year + '/' + month + '/' + day;
what is the multicast doing on 224.0.0.251?
Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.
The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.
mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.
If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.
Django: Get list of model fields?
At least with Django 1.9.9 -- the version I'm currently using --, note that .get_fields()
actually also "considers" any foreign model as a field, which may be problematic. Say you have:
class Parent(models.Model):
id = UUIDField(primary_key=True)
class Child(models.Model):
parent = models.ForeignKey(Parent)
It follows that
>>> map(lambda field:field.name, Parent._model._meta.get_fields())
['id', 'child']
while, as shown by @Rockallite
>>> map(lambda field:field.name, Parent._model._meta.local_fields)
['id']
How to add multiple font files for the same font?
If you are using Google fonts I would suggest the following.
If you want the fonts to run from your localhost or server you need to download the files.
Instead of downloading the ttf packages in the download links, use the live link they provide, for example:
http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,300italic,400italic,600italic
Paste the URL in your browser and you should get a font-face declaration similar to the first answer.
Open the URLs provided, download and rename the files.
Stick the updated font-face declarations with relative paths to the woff files in your CSS, and you are done.
Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string
Can you open the 3rd party XML source in Firefox and see what it auto-detects as encoding? Maybe they are using plain old ISO-8859-1, UTF-16 or something else.
If they declare it to be UTF-8, though, and serve something else, their feed is clearly broken. Working around such a broken feed feels horrible to me (even though sometimes unavoidable, I know).
If it's a simple case like "UTF-8 versus ISO-8859-1", you can also try your luck with mb_detect_encoding().
How would I check a string for a certain letter in Python?
in
keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.
In this case string is nothing but a list of characters:
dog = "xdasds"
if "x" in dog:
print "Yes!"
You can check a substring too:
>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>>
>>>
>>> 'xa' in "xdasds"
False
Think collection:
>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>>
You can also test the set membership over user defined classes.
For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.
How to display a confirmation dialog when clicking an <a> link?
Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:
document.body.onclick = function( e ) {
// Cross-browser handling
var evt = e || window.event,
target = evt.target || evt.srcElement;
// If the element clicked is an anchor
if ( target.nodeName === 'A' ) {
// Add the confirm box
return confirm( 'Are you sure?' );
}
};
This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.
Spring-Security-Oauth2: Full authentication is required to access this resource
This is incredible but real.
csrf filter is enabled by default and it actually blocks any POST, PUT
or DELETE requests which do not include de csrf token.
Try using a GET instead of POST to confirm that this is it.
If this is so then allow any HTTP method:
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
/**
* Allow POST, PUT or DELETE request
*
* NOTE: csrf filter is enabled by default and it actually blocks any POST, PUT or DELETE requests
* which do not include de csrf token.
*/
http.csrf().disable()
}
If you are obtaining a 401 the most intuitive thing is to think that in the request you have No Auth or you are missing something in the headers regarding authorization.
But apparently there is an internal function that is filtering the HTTP methods that use POST and returns a 401. After fixing it I thought it was a cache issue with the status code but apparently not.
GL
Simplest way to serve static data from outside the application server in a Java web application
If you want to work with JAX-RS (e.g. RESTEasy) try this:
@Path("/pic")
public Response get(@QueryParam("url") final String url) {
String picUrl = URLDecoder.decode(url, "UTF-8");
return Response.ok(sendPicAsStream(picUrl))
.header(HttpHeaders.CONTENT_TYPE, "image/jpg")
.build();
}
private StreamingOutput sendPicAsStream(String picUrl) {
return output -> {
try (InputStream is = (new URL(picUrl)).openStream()) {
ByteStreams.copy(is, output);
}
};
}
using javax.ws.rs.core.Response
and com.google.common.io.ByteStreams
Creating a fixed sidebar alongside a centered Bootstrap 3 grid
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
JSFIDDLE
Getting text from td cells with jQuery
First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:
ID Selector:
$('#mytable td').each(function() {
var cellText = $(this).html();
});
Class Selector:
$('.myTableClass td').each(function() {
var cellText = $(this).html();
});
Additional Information:
Take a look at jQuery's selector docs.
Laravel csrf token mismatch for ajax POST Request
You should include a hidden CSRF (cross site request forgery) token field in the form so that the CSRF protection middleware can validate the request.
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.
So when doing ajax requests, you'll need to pass the csrf token via data parameter.
Here's the sample code.
var request = $.ajax({
url : "http://localhost/some/action",
method:"post",
data : {"_token":"{{ csrf_token() }}"} //pass the CSRF_TOKEN()
});
Converting NSString to NSDictionary / JSON
I believe you are misinterpreting the JSON format for key values. You should store your string as
NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now if you do following NSLog statement
NSLog(@"%@",[json objectForKey:@"ID"]);
Result would be another NSDictionary.
{
Content = 268;
type = text;
}
Hope this helps to get clear understanding.
What is the proper use of an EventEmitter?
There is no: nono and no: yesyes.
The truth is in the middle
And no reasons to be scared because of the next version of Angular.
From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.
I know..Maybe I'm a bit an old fashioned developer.
But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.
Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly.
You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.
Simple way to encode a string according to a password?
Assuming you are only looking for simple obfuscation that will obscure things from the very casual observer, and you aren't looking to use third party libraries. I'd recommend something like the Vigenere cipher. It is one of the strongest of the simple ancient ciphers.
Vigenère cipher
It's quick and easy to implement. Something like:
import base64
def encode(key, string):
encoded_chars = []
for i in xrange(len(string)):
key_c = key[i % len(key)]
encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
encoded_chars.append(encoded_c)
encoded_string = "".join(encoded_chars)
return base64.urlsafe_b64encode(encoded_string)
Decode is pretty much the same, except you subtract the key.
It is much harder to break if the strings you are encoding are short, and/or if it is hard to guess the length of the passphrase used.
If you are looking for something cryptographic, PyCrypto is probably your best bet, though previous answers overlook some details: ECB mode in PyCrypto requires your message to be a multiple of 16 characters in length. So, you must pad. Also, if you want to use them as URL parameters, use base64.urlsafe_b64_encode()
, rather than the standard one. This replaces a few of the characters in the base64 alphabet with URL-safe characters (as it's name suggests).
However, you should be ABSOLUTELY certain that this very thin layer of obfuscation suffices for your needs before using this. The Wikipedia article I linked to provides detailed instructions for breaking the cipher, so anyone with a moderate amount of determination could easily break it.
Best way to find if an item is in a JavaScript array?
A robust way to check if an object is an array in javascript is detailed here:
Here are two functions from the xa.js framework which I attach to a utils = {}
‘container’. These should help you properly detect arrays.
var utils = {};
/**
* utils.isArray
*
* Best guess if object is an array.
*/
utils.isArray = function(obj) {
// do an instanceof check first
if (obj instanceof Array) {
return true;
}
// then check for obvious falses
if (typeof obj !== 'object') {
return false;
}
if (utils.type(obj) === 'array') {
return true;
}
return false;
};
/**
* utils.type
*
* Attempt to ascertain actual object type.
*/
utils.type = function(obj) {
if (obj === null || typeof obj === 'undefined') {
return String (obj);
}
return Object.prototype.toString.call(obj)
.replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};
If you then want to check if an object is in an array, I would also include this code:
/**
* Adding hasOwnProperty method if needed.
*/
if (typeof Object.prototype.hasOwnProperty !== 'function') {
Object.prototype.hasOwnProperty = function (prop) {
var type = utils.type(this);
type = type.charAt(0).toUpperCase() + type.substr(1);
return this[prop] !== undefined
&& this[prop] !== window[type].prototype[prop];
};
}
And finally this in_array function:
function in_array (needle, haystack, strict) {
var key;
if (strict) {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] === needle) {
return true;
}
}
} else {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
When can I use a forward declaration?
I'm writing this as a separate answer rather than just a comment because I disagree with Luc Touraille's answer, not on the grounds of legality but for robust software and the danger of misinterpretation.
Specifically, I have an issue with the implied contract of what you expect users of your interface to have to know.
If you are returning or accepting reference types, then you are just saying they can pass through a pointer or reference which they may in turn have known only through a forward declaration.
When you are returning an incomplete type X f2();
then you are saying your caller must have the full type specification of X. They need it in order to create the LHS or temporary object at the call site.
Similarly, if you accept an incomplete type, the caller has to have constructed the object which is the parameter. Even if that object was returned as another incomplete type from a function, the call site needs the full declaration. i.e.:
class X; // forward for two legal declarations
X returnsX();
void XAcceptor(X);
XAcepptor( returnsX() ); // X declaration needs to be known here
I think there's an important principle that a header should supply enough information to use it without a dependency requiring other headers. That means header should be able to be included in a compilation unit without causing a compiler error when you use any functions it declares.
Except
If this external dependency is desired behaviour. Instead of using conditional compilation you could have a well-documented requirement for them to supply their own header declaring X. This is an alternative to using #ifdefs and can be a useful way to introduce mocks or other variants.
The important distinction being some template techniques where you are explicitly NOT expected to instantiate them, mentioned just so someone doesn't get snarky with me.
How to use a Java8 lambda to sort a stream in reverse order?
You can define your Comparator with your own logic like this;
private static final Comparator<UserResource> sortByLastLogin = (c1, c2) -> {
if (Objects.isNull(c1.getLastLoggedin())) {
return -1;
} else if (Objects.isNull(c2.getLastLoggedin())) {
return 1;
}
return c1.getLastLoggedin().compareTo(c2.getLastLoggedin());
};
And use it inside foreach as:
list.stream()
.sorted(sortCredentialsByLastLogin.reversed())
.collect(Collectors.toList());
How can I create an array/list of dictionaries in python?
Try this:
lst = []
##use append to add items to the list.
lst.append({'A':0,'C':0,'G':0,'T':0})
lst.append({'A':1,'C':1,'G':1,'T':1})
##if u need to add n no of items to the list, use range with append:
for i in range(n):
lst.append({'A':0,'C':0,'G':0,'T':0})
print lst
How can I move HEAD back to a previous location? (Detached head) & Undo commits
Before answering, let's add some background, explaining what this HEAD
is.
First of all what is HEAD?
HEAD
is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD
at any given time (excluding git worktree
).
The content of HEAD
is stored inside .git/HEAD
and it contains the 40 bytes SHA-1 of the current commit.
detached HEAD
If you are not on the latest commit - meaning that HEAD
is pointing to a prior commit in history it's called detached HEAD
.
On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD
is not pointing to the tip of the current branch:
A few options on how to recover from a detached HEAD:
git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits to go back
This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.
# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>
# Create a new branch forked to the given commit
git checkout -b <branch name>
You can always use the reflog
as well.
git reflog
will display any change which updated the HEAD
and checking out the desired reflog entry will set the HEAD
back to this commit.
Every time the HEAD is modified there will be a new entry in the reflog
git reflog
git checkout HEAD@{...}
This will get you back to your desired commit
"Move" your HEAD back to the desired commit.
# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32
# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
- Note: (Since Git 2.7) you can also use the
git rebase --no-autostash
as well.
"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.
# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>
This schema illustrates which command does what.
As you can see there, reset && checkout
modify the HEAD
.
How to set a radio button in Android
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
Getting the actual usedrange
This function returns the actual used range to the lower right limit. It returns "Nothing" if the sheet is empty.
'2020-01-26
Function fUsedRange() As Range
Dim lngLastRow As Long
Dim lngLastCol As Long
Dim rngLastCell As Range
On Error Resume Next
Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious)
If rngLastCell Is Nothing Then 'look for data backwards in rows
Set fUsedRange = Nothing
Exit Function
Else
lngLastRow = rngLastCell.Row
End If
Set rngLastCell = ActiveSheet.Cells.Find("*", searchorder:=xlByColumns, searchdirection:=xlPrevious)
If rngLastCell Is Nothing Then 'look for data backwards in columns
Set fUsedRange = Nothing
Exit Function
Else
lngLastCol = rngLastCell.Column
End If
Set fUsedRange = ActiveSheet.Range(Cells(1, 1), Cells(lngLastRow, lngLastCol)) 'set up range
End Function
How to install Python package from GitHub?
To install Python package from github, you need to clone that repository.
git clone https://github.com/jkbr/httpie.git
Then just run the setup.py file from that directory,
sudo python setup.py install
What are all the escape characters?
These are escape characters which are used to manipulate string.
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
Read more about them from here.
http://docs.oracle.com/javase/tutorial/java/data/characters.html
Load different application.yml in SpringBoot Test
This might be considered one of the options. now if you wanted to load a yml file ( which did not get loaded by default on applying the above annotations) the trick is to use
@ContextConfiguration(classes= {...}, initializers={ConfigFileApplicationContextInitializer.class})
Here is a sample code
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(classes= {DataSourceTestConfig.class}, initializers = {ConfigFileApplicationContextInitializer.class})
public class CustomDateDeserializerTest {
private ObjectMapper objMapper;
@Before
public void setUp() {
objMapper = new ObjectMapper();
}
@Test
public void test_dateDeserialization() {
}
}
Again make sure that the setup config java file - here DataSourceTestConfig.java
contains the following property values.
@Configuration
@ActiveProfiles("test")
@TestPropertySource(properties = { "spring.config.location=classpath:application-test.yml" })
public class DataSourceTestConfig implements EnvironmentAware {
private Environment env;
@Bean
@Profile("test")
public DataSource testDs() {
HikariDataSource ds = new HikariDataSource();
boolean isAutoCommitEnabled = env.getProperty("spring.datasource.hikari.auto-commit") != null ? Boolean.parseBoolean(env.getProperty("spring.datasource.hikari.auto-commit")):false;
ds.setAutoCommit(isAutoCommitEnabled);
// Connection test query is for legacy connections
//ds.setConnectionInitSql(env.getProperty("spring.datasource.hikari.connection-test-query"));
ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
long timeout = env.getProperty("spring.datasource.hikari.idleTimeout") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.idleTimeout")): 40000;
ds.setIdleTimeout(timeout);
long maxLifeTime = env.getProperty("spring.datasource.hikari.maxLifetime") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.maxLifetime")): 1800000 ;
ds.setMaxLifetime(maxLifeTime);
ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
ds.setUsername(env.getProperty("spring.datasource.username"));
ds.setPassword(env.getProperty("spring.datasource.password"));
int poolSize = env.getProperty("spring.datasource.hikari.maximum-pool-size") != null ? Integer.parseInt(env.getProperty("spring.datasource.hikari.maximum-pool-size")): 10;
ds.setMaximumPoolSize(poolSize);
return ds;
}
@Bean
@Profile("test")
public JdbcTemplate testJdbctemplate() {
return new JdbcTemplate(testDs());
}
@Bean
@Profile("test")
public NamedParameterJdbcTemplate testNamedTemplate() {
return new NamedParameterJdbcTemplate(testDs());
}
@Override
public void setEnvironment(Environment environment) {
// TODO Auto-generated method stub
this.env = environment;
}
}
maven compilation failure
It also matters the order of the dependencies. I've had the same issue. And basically I had to put first the scope test
and then scope compile
dependencies in the pom.xml
. If I put first the scope compile
and then the scope test
it will fail.
Can a foreign key be NULL and/or duplicate?
Yes foreign key can be null as told above by senior programmers... I would add another scenario where Foreign key will required to be null....
suppose we have tables comments, Pictures and Videos in an application which allows comments on pictures and videos. In comments table we can have two Foreign Keys PicturesId, and VideosId along with the primary Key CommentId. So when you comment on a video only VideosId would be required and pictureId would be null... and if you comment on a picture only PictureId would be required and VideosId would be null...
Open JQuery Datepicker by clicking on an image w/ no input field
The jQuery documentation says that the datePicker needs to be attached to a SPAN or a DIV when it is not associated with an input box. You could do something like this:
<img src='someimage.gif' id="datepickerImage" />
<div id="datepicker"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
})
.hide()
.click(function() {
$(this).hide();
});
$("#datepickerImage").click(function() {
$("#datepicker").show();
});
});
</script>
Two's Complement in Python
Two's complement subtracts off (1<<bits)
if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.
A function for two's complement of an int...
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is
Going from a binary string is particularly easy...
binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))
A bit more useful to me is going from hex values (32 bits in this example)...
hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)
Mac OS X and multiple Java versions
As found on this website
So Let’s begin by installing jEnv
Run this in the terminal
brew install https://raw.github.com/gcuisinier/jenv/homebrew/jenv.rb
Add jEnv to the bash profile
if which jenv > /dev/null; then eval "$(jenv init -)"; fi
When you first install jEnv will not have any JDK associated with it.
For example, I just installed JDK 8 but jEnv does not know about it. To check Java versions on jEnv
At the moment it only found Java version(jre) on the system. The *
shows the version currently selected. Unlike rvm and rbenv, jEnv cannot install JDK for you. You need to install JDK manually from Oracle website.
Install JDK 6 from Apple website. This will install Java in /System/Library/Java/JavaVirtualMachines/
. The reason we are installing Java 6 from Apple website is that SUN did not come up with JDK 6 for MAC, so Apple created/modified its own deployment version.
Similarly install JDK7 and JDK8.
Add JDKs to jEnv.
JDK 6:
JDK 7:
JDK 8:
Check the java versions installed using jenv
So now we have 3 versions of Java on our system. To set a default version use the command
jenv local <jenv version>
Ex – I wanted Jdk 1.6 to start IntelliJ
jenv local oracle64-1.6.0.65
check the java version
java -version
That’s it. We now have multiple versions of java and we can switch between them easily. jEnv also has some other features, such as wrappers for Gradle, Ant, Maven, etc, and the ability to set JVM options globally or locally. Check out the documentation for more information.
Configure Apache .conf for Alias
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
How can I scale an entire web page with CSS?
For Cross-Browser Compatibility :
Example Goes Below :
<html><body class="entire-webpage"></body></html>
.entire-webpage{
zoom: 2;
-moz-transform: scale(2);/* Firefox Property */
-moz-transform-origin: 0 0;
-o-transform: scale(2);/* Opera Property */
-o-transform-origin: 0 0;
-webkit-transform: scale(2);/* Safari Property */
-webkit-transform-origin: 0 0;
transform: scale(2); /* Standard Property */
transform-origin: 0 0; /* Standard Property */
}
Configure Log4net to write to multiple files
Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:
<root>
<level value="ALL" />
<appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
<level value="ALL" />
<appender-ref ref="File1Appender2" />
</logger>
This is how I have done it in the past. Then something like this for the other log:
private static readonly ILog otherLog = LogManager.GetLogger("SomeName");
And you can get your normal logger as follows:
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Read the loggers and appenders section of the documentation to understand how this works.
Display current path in terminal only
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
Where does Visual Studio look for C++ header files?
There exists a newer question what is hitting the problem better asking How do include paths work in Visual Studio?
There is getting revealed the way to do it in the newer versions of VisualStudio
- in the current project only (as the question is set here too) as well as
- for every new project as default
The second is the what the answer of Steve Wilkinson above explains, what is, as he supposed himself, not the what Microsoft would recommend.
To say it the shortway here: do it, but do it in the User-Directory at
C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0
in the XML-file
Microsoft.Cpp.Win32.user.props
and/or
Microsoft.Cpp.x64.user.props
and not in the C:\program files - directory, where the unmodified Factory-File of Microsoft is expected to reside.
Then you do it the way as VisualStudio is doing it too and everything is regular.
For more info why to do it alike, see my answer there.
Pass variables from servlet to jsp
You could set all the values into the response object before forwaring the request to the jsp. Or you can put your values into a session bean and access it in the jsp.
node.js string.replace doesn't work?
According to the Javascript standard, String.replace
isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.
You can always just set the string to the modified value:
variableABC = variableABC.replace('B', 'D')
Edit: The code given above is to only replace the first occurrence.
To replace all occurrences, you could do:
variableABC = variableABC.replace(/B/g, "D");
To replace all occurrences and ignore casing
variableABC = variableABC.replace(/B/gi, "D");
How to respond to clicks on a checkbox in an AngularJS directive?
Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.
Two important pieces that are needed are:
$scope.entities = [{
"title": "foo",
"id": 1
}, {
"title": "bar",
"id": 2
}, {
"title": "baz",
"id": 3
}];
$scope.selected = [];
How to display an error message in an ASP.NET Web Application
All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.
If occurs during a postback:
markup:
<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>
code:
try
{
do something
}
catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}
Fluid width with equally spaced DIVs
This worked for me with 5 images in diferent sizes.
- Create a container div
- An Unordered list for the images
- On css the unordened must be displayed vertically and without bullets
- Justify content of container div
This works because of justify-content:space-between, and it's on a list, displayed horizontally.
On CSS
#container {
display: flex;
justify-content: space-between;
}
#container ul li{ display:inline; list-style-type:none;
}
On html
<div id="container">
<ul>
<li><img src="box1.png"><li>
<li><img src="box2.png"><li>
<li><img src="box3.png"><li>
<li><img src="box4.png"><li>
<li><img src="box5.png"><li>
</ul>
</div>
How do I get a string format of the current date time, in python?
#python3
import datetime
print(
'1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
)
d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))
# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")
print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")
1: test-2018-02-14_16:40:52.txt
2a: March 04, 2018
2b: March 04, 2018
3: Today is 2018-11-11 yay
Description:
Using the new string format to inject value into a string at placeholder {}, value is the current time.
Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.
https://docs.python.org/3/library/string.html#formatexamples
Using jQuery how to get click coordinates on the target element
see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});
Ruby: Easiest Way to Filter Hash Keys?
If you want the remaining hash:
params.delete_if {|k, v| ! k.match(/choice[0-9]+/)}
or if you just want the keys:
params.keys.delete_if {|k| ! k.match(/choice[0-9]+/)}
Error ITMS-90717: "Invalid App Store Icon"
Alternative:(Using Sierra or High Sierra and Ionic)
- Copy and Paste the App Store icon to the desktop.
- Open the image. Click File Menu->Duplicate.
- Save it by unticking the Alpha channel.
- Replace the current App Store icon with this one.
- Validate and upload.
Set textarea width to 100% in bootstrap modal
After testing those suggestions here, I draw the conclusion that we have to apply two things.
Apply form-control
class to your textarea
element. This is among Bootstrap's built-in classes.
Extend this class by adding the following property:
.form-control {
max-width: 100%;
}
Hope this helps others who are looking for a solution to this issue.
How does Python manage int and long?
It manages them because int
and long
are sibling class definitions. They have appropriate methods for +, -, *, /, etc., that will produce results of the appropriate class.
For example
>>> a=1<<30
>>> type(a)
<type 'int'>
>>> b=a*2
>>> type(b)
<type 'long'>
In this case, the class int
has a __mul__
method (the one that implements *) which creates a long
result when required.
How to automatically import data from uploaded CSV or XLS file into Google Sheets
(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).
My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert()
changed names to create()
so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!
The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.
Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload
class. This snippet assumes your auth code works where your service endpoint is DRIVE
with a minimum auth scope of https://www.googleapis.com/auth/drive.file
.
# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'
# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))
Better yet, rather than uploading to My Drive
, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA
. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.
If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.
Compare a date string to datetime in SQL Server?
In sqlserver
DECLARE @p_date DATE
SELECT *
FROM table1
WHERE column_dateTime=@p_date
In C#
Pass the short string of date value using ToShortDateString() function.
sample:
DateVariable.ToShortDateString();
Asynchronous method call in Python?
You can implement a decorator to make your functions asynchronous, though that's a bit tricky. The multiprocessing
module is full of little quirks and seemingly arbitrary restrictions – all the more reason to encapsulate it behind a friendly interface, though.
from inspect import getmodule
from multiprocessing import Pool
def async(decorated):
r'''Wraps a top-level function around an asynchronous dispatcher.
when the decorated function is called, a task is submitted to a
process pool, and a future object is returned, providing access to an
eventual return value.
The future object has a blocking get() method to access the task
result: it will return immediately if the job is already done, or block
until it completes.
This decorator won't work on methods, due to limitations in Python's
pickling machinery (in principle methods could be made pickleable, but
good luck on that).
'''
# Keeps the original function visible from the module global namespace,
# under a name consistent to its __name__ attribute. This is necessary for
# the multiprocessing pickling machinery to work properly.
module = getmodule(decorated)
decorated.__name__ += '_original'
setattr(module, decorated.__name__, decorated)
def send(*args, **opts):
return async.pool.apply_async(decorated, args, opts)
return send
The code below illustrates usage of the decorator:
@async
def printsum(uid, values):
summed = 0
for value in values:
summed += value
print("Worker %i: sum value is %i" % (uid, summed))
return (uid, summed)
if __name__ == '__main__':
from random import sample
# The process pool must be created inside __main__.
async.pool = Pool(4)
p = range(0, 1000)
results = []
for i in range(4):
result = printsum(i, sample(p, 100))
results.append(result)
for result in results:
print("Worker %i: sum value is %i" % result.get())
In a real-world case I would ellaborate a bit more on the decorator, providing some way to turn it off for debugging (while keeping the future interface in place), or maybe a facility for dealing with exceptions; but I think this demonstrates the principle well enough.
Cannot hide status bar in iOS7
Many of the answers on this thread work, but it's my understanding if you're trying to do anything dynamic you'll eventually need to call:
[self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
gpg decryption fails with no secret key error
When migrating from one machine to another-
Check the gpg version and supported algorithms between the two systems.
gpg --version
Check the presence of keys on both systems.
gpg --list-keys
pub 4096R/62999779 2020-08-04
sub 4096R/0F799997 2020-08-04
gpg --list-secret-keys
sec 4096R/62999779 2020-08-04
ssb 4096R/0F799997 2020-08-04
Check for the presence of same pair of key ids on the other machine. For decrypting, only secret key(sec) and secret sub key(ssb) will be needed.
If the key is not present on the other machine, export the keys in a file from the machine on which keys are present, scp the file and import the keys on the machine where it is missing.
Do not recreate the keys on the new machine with the same passphrase, name, user details as the newly generated key will have new unique id and "No secret key" error will still appear if source is using previously generated public key for encryption. So, export and import, this will ensure that same key id is used for decryption and encryption.
gpg --output gpg_pub_key --export <Email address>
gpg --output gpg_sec_key --export-secret-keys <Email address>
gpg --output gpg_sec_sub_key --export-secret-subkeys <Email address>
gpg --import gpg_pub_key
gpg --import gpg_sec_key
gpg --import gpg_sec_sub_key
Regex to validate JSON
For "strings and numbers", I think that the partial regular expression for numbers:
-?(?:0|[1-9]\d*)(?:\.\d+)(?:[eE][+-]\d+)?
should be instead:
-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?
since the decimal part of the number is optional, and also it is probably safer to escape the -
symbol in [+-]
since it has a special meaning between brackets
Are HTTPS URLs encrypted?
You can not always count on privacy of the full URL either. For instance, as is sometimes the case on enterprise networks, supplied devices like your company PC are configured with an extra "trusted" root certificate so that your browser can quietly trust a proxy (man-in-the-middle) inspection of https traffic. This means that the full URL is exposed for inspection. This is usually saved to a log.
Furthermore, your passwords are also exposed and probably logged and this is another reason to use one time passwords or to change your passwords frequently.
Finally, the request and response content is also exposed if not otherwise encrypted.
One example of the inspection setup is described by Checkpoint here. An old style "internet café" using supplied PC's may also be set up this way.
Selecting a Linux I/O Scheduler
As documented in /usr/src/linux/Documentation/block/switching-sched.txt
, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.
# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq
Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:
noop
is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resources
deadline
is a lightweight scheduler which tries to put a hard limit on latency
cfq
tries to maintain system-wide fairness of I/O bandwidth
The default was anticipatory
for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq
became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory
has a long history of being tunable for best performance on these workloads, and deadline
very quickly passes all requests through to the underlying device.
PHP - define constant inside a class
This is a pretty old question, but perhaps this answer can still help someone else.
You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:
class Foo {
// This is a private constant
final public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
The final keyword on a method prevents an extending class from re-defining the method.
You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.
To get nearly exactly what Alex was looking for the following code can be used:
final class Constants {
public MYCONSTANT()
{
return 'MYCONSTANT_VALUE';
}
}
class Foo {
static public app()
{
return new Constants();
}
}
The emulated constant value would be accessible like this:
Foo::app()->MYCONSTANT();
Access-Control-Allow-Origin error sending a jQuery Post to Google API's
try my code
In JavaScript
var settings = {
"url": "https://myinboxhub.co.in/example",
"method": "GET",
"timeout": 0,
"headers": {},
};
$.ajax(settings).done(function (response) {
console.log(response);
if (response.auth) {
console.log('on success');
}
}).fail(function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 413) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 405) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
});;
In PHP
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
Android ImageView Animation
I have found out, that if you use the .getWidth/2 etc... that it won't work you need to get the number of pixels the image is and divide it by 2 yourself and then just type in the number for the last 2 arguments.
so say your image was a 120 pixel by 120 pixel square, ur x and y would equal 60 pixels.
so in your code, you would right:
RotateAnimation anim = new RotateAnimation(0f, 350f, 60f, 60f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
and now your image will pivot round its center.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Reverse a string in Java
Everybody proposes a way to reverse string here. If you, the reader of
the answer, are interested in, my way using \u202E
unicode is here.
public static String reverse(String s) {
return "\u202E" + s;
}
It can be tested from here.
It is just to print. If your aim is to pass a string in a reversed manner, you need to do it using loop or recursion.
Is it possible to define more than one function per file in MATLAB, and access them from outside that file?
I define multiple functions in one .m file with Octave and then use the command from within the .m file where I need to make use of the functions from that file:
source("mycode.m");
Not sure if this is available with Matlab.
octave:8> help source
'source' is a built-in function
-- Built-in Function: source (FILE)
Parse and execute the contents of FILE. This is equivalent to
executing commands from a script file, but without requiring the
file to be named `FILE.m'.
change cursor from block or rectangle to line?
If you happen to be using a mac keyboard on linux (ubuntu), Insert
is actually fn
+ return
. You can also click on the zero of the number pad to switch between the cursor types.
Took me a while to figure that out. :-P
How to pretty print nested dictionaries?
I took sth's answer and modified it slightly to fit my needs of a nested dictionaries and lists:
def pretty(d, indent=0):
if isinstance(d, dict):
for key, value in d.iteritems():
print '\t' * indent + str(key)
if isinstance(value, dict) or isinstance(value, list):
pretty(value, indent+1)
else:
print '\t' * (indent+1) + str(value)
elif isinstance(d, list):
for item in d:
if isinstance(item, dict) or isinstance(item, list):
pretty(item, indent+1)
else:
print '\t' * (indent+1) + str(item)
else:
pass
Which then gives me output like:
>>>
xs:schema
@xmlns:xs
http://www.w3.org/2001/XMLSchema
xs:redefine
@schemaLocation
base.xsd
xs:complexType
@name
Extension
xs:complexContent
xs:restriction
@base
Extension
xs:sequence
xs:element
@name
Policy
@minOccurs
1
xs:complexType
xs:sequence
xs:element
...
Rename MySQL database
First backup the old database called HRMS and edit the script file with replace the word HRMS to SUNHRM. After this step import the database file to the mysql
ASP.NET MVC Razor pass model to layout
Let's assume your model is a collection of objects (or maybe a single object). For each object in the model do the following.
1) Put the object you want to display in the ViewBag. For example:
ViewBag.YourObject = yourObject;
2) Add a using statement at the top of _Layout.cshtml that contains the class definition for your objects. For example:
@using YourApplication.YourClasses;
3) When you reference yourObject in _Layout cast it. You can apply the cast because of what you did in (2).
Can PHP cURL retrieve response headers AND body in a single request?
Curl has a built in option for this, called CURLOPT_HEADERFUNCTION. The value of this option must be the name of a callback function. Curl will pass the header (and the header only!) to this callback function, line-by-line (so the function will be called for each header line, starting from the top of the header section). Your callback function then can do anything with it (and must return the number of bytes of the given line). Here is a tested working code:
function HandleHeaderLine( $curl, $header_line ) {
echo "<br>YEAH: ".$header_line; // or do whatever
return strlen($header_line);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
$body = curl_exec($ch);
The above works with everything, different protocols and proxies too, and you dont need to worry about the header size, or set lots of different curl options.
P.S.: To handle the header lines with an object method, do this:
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$object, 'methodName'))