Programs & Examples On #Weak

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

Swift error : signal SIGABRT how to solve it

To solve the problem, first clean the project and then rebuild.

To clean the project, go to MenuBar: Product -> Clean

Then to rebuild the project, just click the Run button as usual.

Deep copy in ES6 using the spread syntax

No such functionality is built-in to ES6. I think you have a couple of options depending on what you want to do.

If you really want to deep copy:

  1. Use a library. For example, lodash has a cloneDeep method.
  2. Implement your own cloning function.

Alternative Solution To Your Specific Problem (No Deep Copy)

However, I think, if you're willing to change a couple things, you can save yourself some work. I'm assuming you control all call sites to your function.

  1. Specify that all callbacks passed to mapCopy must return new objects instead of mutating the existing object. For example:

    mapCopy(state, e => {
      if (e.id === action.id) {
        return Object.assign({}, e, {
          title: 'new item'
        });
      } else {  
        return e;
      }
    });
    

    This makes use of Object.assign to create a new object, sets properties of e on that new object, then sets a new title on that new object. This means you never mutate existing objects and only create new ones when necessary.

  2. mapCopy can be really simple now:

    export const mapCopy = (object, callback) => {
      return Object.keys(object).reduce(function (output, key) {
        output[key] = callback.call(this, object[key]);
        return output;
      }, {});
    }
    

Essentially, mapCopy is trusting its callers to do the right thing. This is why I said this assumes you control all call sites.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

How to make a UILabel clickable?

Good and convenient solution:

In your ViewController:

@IBOutlet weak var label: LabelButton!

override func viewDidLoad() {
    super.viewDidLoad()

    self.label.onClick = {
        // TODO
    }
}

You can place this in your ViewController or in another .swift file(e.g. CustomView.swift):

@IBDesignable class LabelButton: UILabel {
    var onClick: () -> Void = {}
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        onClick()
    }
}

In Storyboard select Label and on right pane in "Identity Inspector" in field class select LabelButton.

Don't forget to enable in Label Attribute Inspector "User Interaction Enabled"

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Recently I faced the issue while working on some legacy code. After googling I found that the issue is everywhere but without any concrete resolution. I worked on various parts of the exception message and analyzed below.

Analysis:

  1. SSLException: exception happened with the SSL (Secure Socket Layer), which is implemented in javax.net.ssl package of the JDK (openJDK/oracleJDK/AndroidSDK)
  2. Read error ssl=# I/O error during system call: Error occured while reading from the Secure socket. It happened while using the native system libraries/driver. Please note that all the platforms solaris, Windows etc. have their own socket libraries which is used by the SSL. Windows uses WINSOCK library.
  3. Connection reset by peer: This message is reported by the system library (Solaris reports ECONNRESET, Windows reports WSAECONNRESET), that the socket used in the data transfer is no longer usable because an existing connection was forcibly closed by the remote host. One needs to create a new secure path between the host and client

Reason:

Understanding the issue, I try finding the reason behind the connection reset and I came up with below reasons:

  • The peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close.
  • This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with Network dropped connection on reset(On Windows(WSAENETRESET)) and Subsequent operations fail withConnection reset by peer(On Windows(WSAECONNRESET)).
  • If the target server is protected by Firewall, which is true in most of the cases, the Time to live (TTL) or timeout associated with the port forcibly closes the idle connection at given timeout. this is something of our interest

Resolution:

  1. Events on the server side such as sudden service stop, rebooted, network interface disabled can not be handled by any means.
  2. On the server side, Configure firewall for the given port with the higher Time to Live (TTL) or timeout values such as 3600 secs.
  3. Clients can "try" keeping the network active to avoid or reduce the Connection reset by peer.
  4. Normally on going network traffic keeps the connection alive and problem/exception is not seen frequently. Strong Wifi has least chances of Connection reset by peer.
  5. With the mobile networks 2G, 3G and 4G where the packet data delivery is intermittent and dependent on the mobile network availability, it may not reset the TTL timer on the server side and results into the Connection reset by peer.

Here are the terms suggested to set on various forums to resolve the issue

  • ConnectionTimeout: Used only at the time out making the connection. If host takes time to connection higher value of this makes the client wait for the connection.
  • SoTimeout: Socket timeout-It says the maximum time within which the a data packet is received to consider the connection as active.If no data received within the given time, the connection is assumed as stalled/broken.
  • Linger: Upto what time the socket should not be closed when data is queued to be sent and the close socket function is called on the socket.
  • TcpNoDelay: Do you want to disable the buffer that holds and accumulates the TCP packets and send them once a threshold is reached? Setting this to true will skip the TCP buffering so that every request is sent immediately. Slowdowns in the network may be caused by an increase in network traffic due to smaller and more frequent packet transmission.

So none of the above parameter helps keeping the network alive and thus ineffective.

I found one setting that may help resolving the issue which is this functions

setKeepAlive(true)
setSoKeepalive(HttpParams params, enableKeepalive="true") 

How did I resolve my issue?

  • Set the HttpConnectionParams.setSoKeepAlive(params, true)
  • Catch the SSLException and check for the exception message for Connection reset by peer
  • If exception is found, store the download/read progress and create a new connection.
  • If possible resume the download/read else restart the download

I hope the details help. Happy Coding...

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I had the same problem. This issue worked for me. In storyboard select your table view and change it from static cells into dynamic cells.

How to set image in circle in swift

If you mean you want to make a UIImageView circular in Swift you can just use this code:

imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.clipsToBounds = true

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Just delete these lines from the root build.gradle

android {
compileSdkVersion 19
buildToolsVersion '19.1' }

Now trying and compile again. It should work.

How to set image for bar button with swift?

I have achieved that programatically with this code:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        //set image for button
        button.setImage(UIImage(named: "fb.png"), forState: UIControlState.Normal)
        //add function for button
        button.addTarget(self, action: "fbButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
        //set frame
        button.frame = CGRectMake(0, 0, 53, 31)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        println("Share to fb")
    }
}

And result will be:

enter image description here

Same way you can set button for left side too this way:

self.navigationItem.leftBarButtonItem = barButton

And result will be:

enter image description here

And if you want same transaction as navigation controller have when you go back with default back button then you can achieve that with custom back button with this code:

func backButtonPressed(sender:UIButton) {
    navigationController?.popViewControllerAnimated(true)
}

For swift 3.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton.init(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: UIControlState.normal)
        //add function for button
        button.addTarget(self, action: #selector(ViewController.fbButtonPressed), for: UIControlEvents.touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        print("Share to fb")
    }
}

For swift 4.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: .normal)
        //add function for button
        button.addTarget(self, action: #selector(fbButtonPressed), for: .touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    @objc func fbButtonPressed() {

        print("Share to fb")
    }
}

Adding a view controller as a subview in another view controller

Thanks to Rob. Adding detailed syntax for your second observation :

let controller:MyView = self.storyboard!.instantiateViewControllerWithIdentifier("MyView") as! MyView
controller.ANYPROPERTY=THEVALUE // If you want to pass value
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
self.addChildViewController(controller)
controller.didMoveToParentViewController(self)

And to remove the viewcontroller :

self.willMoveToParentViewController(nil)
self.view.removeFromSuperview()
self.removeFromParentViewController() 

Programmatically set image to UIImageView with Xcode 6.1/Swift

OK, got it working with this (creating the UIImageView programmatically):

var imageViewObject :UIImageView

imageViewObject = UIImageView(frame:CGRectMake(0, 0, 600, 600))

imageViewObject.image = UIImage(named:"afternoon")

self.view.addSubview(imageViewObject)

self.view.sendSubviewToBack(imageViewObject)

React.js inline style best practices

Comparing to writing your styles in a CSS file, React's style attribute has the following advantages:

  1. The ability to use the tools javascript as a programming language provides to control the style of your elements. This includes embedding variables, using conditions, and passing styles to a child component.
  2. A "component" approach. No more separation of HTML, JS, and CSS code wrote for the component. Component's code is consolidated and written in one place.

However, the React's style attribute comes with a few drawbacks - you can't

  1. Can't use media queries
  2. Can't use pseudo-selectors,
  3. less efficient compared to CSS classes.

Using CSS in JS, you can get all the advantages of a style tag, without those drawbacks. As of today, there are a few popular well-supported CSS in js-libraries, including Emotion, Styled-Components, and Radium. Those libraries are to CSS kind of what React is to HTML. They allow you to write your CSS and control your CSS in your JS code.

let's compare how our code will look for styling a simple element. We'll style a "hello world" div so it shows big on desktop and smaller on mobile.

Using the style attribute

return (
   <div style={{fontSize:24}} className="hello-world">
      Hello world
   </div>
)

Since media query is not possible in a style tag, we'll have to add a className to the element and add a css rule.

@media screen and (max-width: 700px){
   .hello-world {
      font-size: 16px; 
   }
}

Using Emotion's 10 CSS tag

return (
   <div
      css={{
         fontSize: 24, 
         [CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY]:{
            fontSize: 16 
         }
      }
   >
      Hello world
   </div>
)

Emotion also supports template strings as well as styled-components. So if you prefer you can write:

return (
   <Box>
      Hello world
   </Box>
)

const Box = styled.div`
   font-size: 24px; 
   ${CSS_CONSTS.MOBILE_MAX_MEDIA_QUERY}{
      font-size: 16px; 
   }
`

Behind the hoods "CSS in JS" uses CSS classes. Emotion specifically built with performance in mind and uses caching. Compared to React style attributes CSS in JS will provide better performance.

###Best Practices

Here are a few best practices I recommend:

  1. If you want to style your elements inline, or in your JS, use a CSS-in-js library, don't use a style attribute.

Should I be aiming to do all styling this way, and have no styles at all specified in my CSS file?

  1. If you use a css-in-js solution there is no need to write styles in CSS files. Writing your CSS in JS is superior as you can use all the tools a programming language as JS provides.

should I avoid inline styles completely?

  1. Structuring your style code in JS is pretty similar to structuring your code in general. For example:
  • recognize styles that repeat, and write them in one place. There are two ways to do this in Emotion:
// option 1 - Write common styles in CONSTANT variables
// styles.js
export const COMMON_STYLES = {
   BUTTON: css`
      background-color: blue; 
      color: white; 
      :hover {
         background-color: dark-blue; 
      }
   `
}

// SomeButton.js
const SomeButton = (props) => {
   ...
   return (
      <button
         css={COMMON_STYLES.BUTTON}
         ...
      >
         Click Me
      </button>
   )
}

// Option 2 - Write your common styles in a dedicated component 

const Button = styled.button`
   background-color: blue; 
   color: white; 
   :hover {
      background-color: dark-blue; 
   }   
`

const SomeButton = (props) => {
   ...
   return (
      <Button ...> 
         Click me
      </Button>
   )
}

  • React coding pattern is of encapsulated components - HTML and JS that controls a component is written in one file. That is where your css/style code to style that component belongs.

  • When necessary, add a styling prop to your component. This way you can reuse code and style written in a child component, and customize it to your specific needs by the parent component.

const Button = styled.button([COMMON_STYLES.BUTTON, props=>props.stl])

const SmallButton = (props)=>(
   <Button 
      ...
      stl={css`font-size: 12px`}
   >
      Click me if you can see me
   </Button>
)

const BigButton = (props) => (
   <Button
      ...
      stl={css`font-size: 30px;`}
   >
      Click me
   </Button>
)

How do I change UIView Size?

For a progress bar kind of thing, in Swift 4

I follow these steps:

  1. I create a UIView outlet : @IBOutlet var progressBar: UIView!
  2. Then a property to increase its width value after a user action var progressBarWidth: Int = your value
  3. Then for the increase/decrease of the progress progressBar.frame.size.width = CGFloat(progressBarWidth)
  4. And finally in the IBACtion method I add progressBarWidth += your value for auto increase the width every time user touches a button.

Command failed due to signal: Segmentation fault: 11

In my case, I was trying to extend a CoreData class with a helper method that could work on all of its subclasses:

extension ExampleCoreDataClass {
   static func insert() -> Self {
   ...

I got no warnings about this, but when I tried to compile it the segmentation fault appeared.

After struggling for a while I used a protocol extension instead and this resolved the error:

extension NSFetchRequestResult where Self: ExampleCoreDataClass {
   static func insert() -> Self {
   ...

How to modify WooCommerce cart, checkout pages (main theme portion)

Another way to totally override the cart.php is to copy:

woocommerce/templates/cart/cart.php to   
yourtheme/woocommerce/cart/cart.php

Then do whatever you need at the yourtheme/woocommerce/cart/cart.php

Custom UITableViewCell from nib in Swift

Another method that may work for you (it's how I do it) is registering a class.

Assume you create a custom tableView like the following:

class UICustomTableViewCell: UITableViewCell {...}

You can then register this cell in whatever UITableViewController you will be displaying it in with "registerClass":

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.registerClass(UICustomTableViewCell.self, forCellReuseIdentifier: "UICustomTableViewCellIdentifier")
}

And you can call it as you would expect in the cell for row method:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("UICustomTableViewCellIdentifier", forIndexPath: indexPath) as! UICustomTableViewCell
    return cell
}

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Show Current Location and Update Location in MKMapView in Swift

Hi Sometimes setting the showsUserLocation in code doesn't work for some weird reason.

So try a combination of the following.

In viewDidLoad()

  self.mapView.showsUserLocation = true

Go to your storyboard in Xcode, on the right panel's attribute inspector tick the User location check box, like in the attached image. run your app and you should be able to see the User location

enter image description here

How to Correctly handle Weak Self in Swift Blocks with Arguments

[Closure and strong reference cycles]

As you know Swift's closure can capture the instance. It means that you are able to use self inside a closure. Especially escaping closure[About] can create a strong reference cycle[About]. By the way you have to explicitly use self inside escaping closure.

Swift closure has Capture List feature which allows you to avoid such situation and break a reference cycle because do not have a strong reference to captured instance. Capture List element is a pair of weak/unowned and a reference to class or variable.

For example

class A {
    private var completionHandler: (() -> Void)!
    private var completionHandler2: ((String) -> Bool)!
    
    func nonescapingClosure(completionHandler: () -> Void) {
        print("Hello World")
    }
    
    func escapingClosure(completionHandler: @escaping () -> Void) {
        self.completionHandler = completionHandler
    }
    
    func escapingClosureWithPArameter(completionHandler: @escaping (String) -> Bool) {
        self.completionHandler2 = completionHandler
    }
}

class B {
    var variable = "Var"
    
    func foo() {
        let a = A()
        
        //nonescapingClosure
        a.nonescapingClosure {
            variable = "nonescapingClosure"
        }
        
        //escapingClosure
        //strong reference cycle
        a.escapingClosure {
            self.variable = "escapingClosure"
        }
        
        //Capture List - [weak self]
        a.escapingClosure {[weak self] in
            self?.variable = "escapingClosure"
        }
        
        //Capture List - [unowned self]
        a.escapingClosure {[unowned self] in
            self.variable = "escapingClosure"
        }
        
        //escapingClosureWithPArameter
        a.escapingClosureWithPArameter { [weak self] (str) -> Bool in
            self?.variable = "escapingClosureWithPArameter"
            return true
        }
    }
}
  • weak - more preferable, use it when it is possible
  • unowned - use it when you are sure that lifetime of instance owner is bigger than closure

[weak vs unowned]

How can I add the new "Floating Action Button" between two widgets/layouts

Keep it Simple Adding Floating Action Button using TextView by giving rounded xml background. - Add compile com.android.support:design:23.1.1 to gradle file

  • Use CoordinatorLayout as root view.
  • Before Ending the CoordinatorLayout introduce a textView.
  • Inside Drawable draw a circle.

Circle Xml is

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/colorPrimary"/>
    <size
        android:width="30dp"
        android:height="30dp"/>
</shape>

Layout xml is

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    >

    <RelativeLayout
        android:id="@+id/viewA"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1.6"
        android:background="@drawable/contact_bg"
        android:gravity="center_horizontal|center_vertical"
        >
        </RelativeLayout>

    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="3.4"
        android:orientation="vertical"
        android:padding="16dp"
        android:weightSum="10"
        >

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            >
            </LinearLayout>

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Name"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/name"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Ritesh Kumar Singh"
                android:singleLine="true"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Phone"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/number"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="8283001122"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Email"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="[email protected]"
                android:textSize="22dp"
                android:singleLine="true"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

        </LinearLayout>


        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="City"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Panchkula"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


    <TextView
        android:id="@+id/floating"
        android:transitionName="@string/transition_name_circle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="16dp"
        android:clickable="false"
        android:background="@drawable/circle"
        android:elevation="10dp"
        android:text="R"
        android:textSize="40dp"
        android:gravity="center"
        android:textColor="@android:color/black"
        app:layout_anchor="@id/viewA"
        app:layout_anchorGravity="bottom"/>

        </android.support.design.widget.CoordinatorLayout>

Click here to se how it Will look like

Shall we always use [unowned self] inside closure in Swift

According to Apple-doc

  • Weak references are always of an optional type, and automatically become nil when the instance they reference is deallocated.

  • If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference

Example -

    // if my response can nil use  [weak self]
      resource.request().onComplete { [weak self] response in
      guard let strongSelf = self else {
        return
      }
      let model = strongSelf.updateModel(response)
      strongSelf.updateUI(model)
     }

    // Only use [unowned self] unowned if guarantees that response never nil  
      resource.request().onComplete { [unowned self] response in
      let model = self.updateModel(response)
      self.updateUI(model)
     }

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Apple uses "NSObjectProtocol" instead of "class".

public protocol UIScrollViewDelegate : NSObjectProtocol {
   ...
}

This also works for me and removed the errors I was seeing when trying to implement my own delegate pattern.

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

python object() takes no parameters error

You must press twice on tap and (_) key each time, it must look like:

__init__

ES6 class variable alternatives

The way I solved this, which is another option (if you have jQuery available), was to Define the fields in an old-school object and then extend the class with that object. I also didn't want to pepper the constructor with assignments, this appeared to be a neat solution.

function MyClassFields(){
    this.createdAt = new Date();
}

MyClassFields.prototype = {
    id : '',
    type : '',
    title : '',
    createdAt : null,
};

class MyClass {
    constructor() {
        $.extend(this,new MyClassFields());
    }
};

-- Update Following Bergi's comment.

No JQuery Version:

class SavedSearch  {
    constructor() {
        Object.assign(this,{
            id : '',
            type : '',
            title : '',
            createdAt: new Date(),
        });

    }
}

You still do end up with 'fat' constructor, but at least its all in one class and assigned in one hit.

EDIT #2: I've now gone full circle and am now assigning values in the constructor, e.g.

class SavedSearch  {
    constructor() {
        this.id = '';
        this.type = '';
        this.title = '';
        this.createdAt = new Date();
    }
}

Why? Simple really, using the above plus some JSdoc comments, PHPStorm was able to perform code completion on the properties. Assigning all the vars in one hit was nice, but the inability to code complete the properties, imo, isn't worth the (almost certainly minuscule) performance benefit.

How to lowercase a pandas dataframe string column if it has missing values?

you can try this one also,

df= df.applymap(lambda s:s.lower() if type(s) == str else s)

How do I type a TAB character in PowerShell?

Test with [char]9, such as:

$Tab = [char]9
Write-Output "$Tab hello"

Output:

     hello

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Always pass weak reference of self into block in ARC?

Some explanation ignore a condition about the retain cycle [If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.] For more information, read the document

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

The second question is easier to answer: you basically can use PyPy as a drop-in replacement if all your code is pure Python. However, many widely used libraries (including some of the standard library) are written in C and compiled as Python extensions. Some of these can be made to work with PyPy, some can't. PyPy provides the same "forward-facing" tool as Python --- that is, it is Python --- but its innards are different, so tools that interface with those innards won't work.

As for the first question, I imagine it is sort of a Catch-22 with the first: PyPy has been evolving rapidly in an effort to improve speed and enhance interoperability with other code. This has made it more experimental than official.

I think it's possible that if PyPy gets into a stable state, it may start getting more widely used. I also think it would be great for Python to move away from its C underpinnings. But it won't happen for a while. PyPy hasn't yet reached the critical mass where it is almost useful enough on its own to do everything you'd want, which would motivate people to fill in the gaps.

How to position the Button exactly in CSS

It seems some what center of the screen. So I would like to do like this

body { 
     background: url('http://oi44.tinypic.com/33tjudk.jpg') no-repeat center center fixed;    
     background-size:cover; 
     text-align: 0 auto; // Make the play button horizontal center
}

#play_button {
    position:absolute;  // absolutely positioned
    transition: .5s ease;
    top: 50%;  // Makes vertical center
} 

Copy and Paste a set range in the next empty row

Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):

EDIT: edited for pasting values only based on comments below.

Private Sub CommandButton1_Click()
  Application.ScreenUpdating = False
  Dim copySheet As Worksheet
  Dim pasteSheet As Worksheet

  Set copySheet = Worksheets("Sheet1")
  Set pasteSheet = Worksheets("Sheet2")

  copySheet.Range("A3:E3").Copy
  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
  Application.CutCopyMode = False
  Application.ScreenUpdating = True
End Sub

using sql count in a case statement

Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.

For example, here's a simple table Grades:

| Letters |
|---------|
| A       |
| A       |
| B       |
| C       |

We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):

SELECT
    COUNT(CASE WHEN Letter = 'A' THEN 1 END)           AS [Count - End],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
    COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)    AS [Count - Else Zero],
    SUM(CASE WHEN Letter = 'A' THEN 1 END)             AS [Sum - End],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END)   AS [Sum - Else Null],
    SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END)      AS [Sum - Else Zero]
FROM Grades

And here are the results (unpivoted for readability):

|    Description    | Counts |
|-------------------|--------|
| Count - End       |    2   |
| Count - Else Null |    2   |
| Count - Else Zero |    4   | *Note: Will include count of zero values
| Sum - End         |    2   |
| Sum - Else Null   |    2   |
| Sum - Else Zero   |    2   |

Which lines up with the docs for Aggregate Functions in SQL

Docs for COUNT:

COUNT(*) - returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression) - evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression) - evaluates expression for each row in a group, and returns the number of unique, nonnull values.

Docs for SUM:

ALL - Applies the aggregate function to all values. ALL is the default.
DISTINCT - Specifies that SUM return the sum of unique values.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I haven't worked much with Appcelerator Titanium, but I'll put my understanding of it at the end.

I can speak a bit more to the differences between PhoneGap and Xamarin, as I work with these two 5 (or more) days a week.

If you are already familiar with C# and JavaScript, then the question I guess is, does the business logic lie in an area more suited to JavaScript or C#?

PhoneGap

PhoneGap is designed to allow you to write your applications using JavaScript and HTML, and much of the functionality that they do provide is designed to mimic the current proposed specifications for the functionality that will eventually be available with HTML5. The big benefit of PhoneGap in my opinion is that since you are doing the UI with HTML, it can easily be ported between platforms. The downside is, because you are porting the same UI between platforms, it won't feel quite as at home in any of them. Meaning that, without further tweaking, you can't have an application that feels fully at home in iOS and Android, meaning that it has the iOS and Android styling. The majority of your logic can be written using JavaScript, which means it too can be ported between platforms. If the current PhoneGap API does most of what you want, then it's pretty easy to get up and running. If however, there are things you need from the device that are not in the API, then you get into the fun of Plugin Development, which will be in the native device's development language of choice (with one caveat, but I'll get to that), which means you would likely need to get up to speed quickly in Objective-C, Java, etc. The good thing about this model, is you can usually adapt many different native libraries to serve your purpose, and many libraries already have PhoneGap Plugins. Although you might not have much experience with these languages, there will at least be a plethora of examples to work from.

Xamarin

Xamarin.iOS and Xamarin.Android (also known as MonoTouch and MonoDroid), are designed to allow you to have one library of business logic, and use this within your application, and hook it into your UI. Because it's based on .NET 4.5, you get some awesome lambda notations, LINQ, and a whole bunch of other C# awesomeness, which can make writing your business logic less painful. The downside here is that Xamarin expects that you want to make your applications truly feel native on the device, which means that you will likely end up rewriting your UI for each platform, before hooking it together with the business logic. I have heard about MvvmCross, which is designed to make this easier for you, but I haven't really had an opportunity to look into it yet. If you are familiar with the MVVM system in C#, you may want to have a look at this. When it comes to native libraries, MonoTouch becomes interesting. MonoTouch requires a Binding library to tell your C# code how to link into the underlying Objective-C and Java code. Some of these libraries will already have bindings, but if yours doesn't, creating one can be, interesting. Xamarin has made a tool called Objective Sharpie to help with this process, and for the most part, it will get you 95% of the way there. The remaining 5% will probably take 80% of your time attempting to bind a library.

Update

As noted in the comments below, Xamarin has released Xamarin Forms which is a cross platform abstraction around the platform specific UI components. Definitely worth the look.

PhoneGap / Xamarin Hybrid

Now because I said I would get to it, the caveat mentioned in PhoneGap above, is a Hybrid approach, where you can use PhoneGap for part, and Xamarin for part. I have quite a bit of experience with this, and I would caution you against it. Highly. The problem with this, is it is such a no mans' land that if you ever run into issues, almost no one will have come close to what you're doing, and will question what you're trying to do greatly. It is doable, but it's definitely not fun.

Appcelerator Titanium

As I mentioned before, I haven't worked much with Appcelerator Titanium, So for the differences between them, I will suggest you look at Comparing Titanium and Phonegap or Comparison between Corona, Phonegap, Titanium as it has a very thorough description of the differences. Basically, it appears that though they both use JavaScript, how that JavaScript is interpreted is slightly different. With Titanium, you will be writing your JavaScript to the Titanium SDK, whereas with PhoneGap, you will write your application using the PhoneGap API. As PhoneGap is very HTML5 and JavaScript standards compliant, you can use pretty much any JavaScript libraries you want, such as JQuery. With PhoneGap your user interface will be composed of HTML and CSS. With Titanium, you will benefit from their Cross-platform XML which appears to generate Native components. This means it will definitely have a better native look and feel.

What is the right way to treat argparse.Namespace() as a dictionary?

You can access the namespace's dictionary with vars():

>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}

You can modify the dictionary directly if you wish:

>>> d['baz'] = 'store me'
>>> args.baz
'store me'

Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.

"java.lang.OutOfMemoryError : unable to create new native Thread"

I encountered same issue during the load test, the reason is because of JVM is unable to create a new Java thread further. Below is the JVM source code

if (native_thread->osthread() == NULL) {    
// No one should hold a reference to the 'native_thread'.    
    delete native_thread;   
if (JvmtiExport::should_post_resource_exhausted()) {      
    JvmtiExport::post_resource_exhausted(        
        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 
        JVMTI_RESOURCE_EXHAUSTED_THREADS, 
        "unable to create new native thread");    
    } THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "unable to create new native thread");  
} Thread::start(native_thread);`

Root cause : JVM throws this exception when JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR (resources exhausted (means memory exhausted) ) or JVMTI_RESOURCE_EXHAUSTED_THREADS (Threads exhausted).

In my case Jboss is creating too many threads , to serve the request, but all the threads are blocked . Because of this, JVM is exhausted with threads as well with memory (each thread holds memory , which is not released , because each thread is blocked).

Analyzed the java thread dumps observed nearly 61K threads are blocked by one of our method, which is causing this issue . Below is the portion of Thread dump

"SimpleAsyncTaskExecutor-16562" #38070 prio=5 os_prio=0 tid=0x00007f9985440000 nid=0x2ca6 waiting for monitor entry [0x00007f9d58c2d000]
   java.lang.Thread.State: BLOCKED (on object monitor)

How to identify a strong vs weak relationship on ERD?

  1. Weak (Non-Identifying) Relationship

    • Entity is existence-independent of other enties

    • PK of Child doesn’t contain PK component of Parent Entity

  2. Strong (Identifying) Relationship

    • Child entity is existence-dependent on parent

    • PK of Child Entity contains PK component of Parent Entity

    • Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.

Regular expression to allow spaces between words

I find this one works well for a "FullName":

([a-z',.-]+( [a-z',.-]+)*){1,70}/

Multiple Cursors in Sublime Text 2 Windows

Try using Ctrl-click on the multiple places you want the cursors. Ctrl-D is for multiple incremental finds.

How to include "zero" / "0" results in COUNT aggregate?

The problem with a LEFT JOIN is that if there are no appointments, it will still return one row with a null, which when aggregated by COUNT will become 1, and it will appear that the person has one appointment when actually they have none. I think this will give the correct results:

SELECT person.person_id,
(SELECT COUNT(*) FROM appointment WHERE person.person_id = appointment.person_id) AS 'Appointments'
FROM person;

Binding ng-model inside ng-repeat loop in AngularJS

<h4>Order List</h4>
<ul>
    <li ng-repeat="val in filter_option.order">
        <span>
            <input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
            &nbsp;{{filter_option.order_name[$index]}}
        </span>
        <select title="" ng-model="filter_param[val]">
            <option value="asc">Asc</option>
            <option value="desc">Desc</option>
        </select>
    </li>
</ul>

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

This problem mainly happens when you are using connection pooling because when you close connection that connection go back to the connection pool and all cursor associated with that connection never get closed as the connection to database is still open. So one alternative is to decrease the idle connection time of connections in pool, so may whenever connection sits idle in connection for say 10 sec , connection to database will get closed and new connection created to put in pool.

When is std::weak_ptr useful?

A good example would be a cache.

For recently accessed objects, you want to keep them in memory, so you hold a strong pointer to them. Periodically, you scan the cache and decide which objects have not been accessed recently. You don't need to keep those in memory, so you get rid of the strong pointer.

But what if that object is in use and some other code holds a strong pointer to it? If the cache gets rid of its only pointer to the object, it can never find it again. So the cache keeps a weak pointer to objects that it needs to find if they happen to stay in memory.

This is exactly what a weak pointer does -- it allows you to locate an object if it's still around, but doesn't keep it around if nothing else needs it.

Parse large JSON file in Nodejs

To process a file line-by-line, you simply need to decouple the reading of the file and the code that acts upon that input. You can accomplish this by buffering your input until you hit a newline. Assuming we have one JSON object per line (basically, format B):

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var buf = '';

stream.on('data', function(d) {
    buf += d.toString(); // when data is read, stash it in a string buffer
    pump(); // then process the buffer
});

function pump() {
    var pos;

    while ((pos = buf.indexOf('\n')) >= 0) { // keep going while there's a newline somewhere in the buffer
        if (pos == 0) { // if there's more than one newline in a row, the buffer will now start with a newline
            buf = buf.slice(1); // discard it
            continue; // so that the next iteration will start with data
        }
        processLine(buf.slice(0,pos)); // hand off the line
        buf = buf.slice(pos+1); // and slice the processed data off the buffer
    }
}

function processLine(line) { // here's where we do something with a line

    if (line[line.length-1] == '\r') line=line.substr(0,line.length-1); // discard CR (0x0D)

    if (line.length > 0) { // ignore empty lines
        var obj = JSON.parse(line); // parse the JSON
        console.log(obj); // do something with the data here!
    }
}

Each time the file stream receives data from the file system, it's stashed in a buffer, and then pump is called.

If there's no newline in the buffer, pump simply returns without doing anything. More data (and potentially a newline) will be added to the buffer the next time the stream gets data, and then we'll have a complete object.

If there is a newline, pump slices off the buffer from the beginning to the newline and hands it off to process. It then checks again if there's another newline in the buffer (the while loop). In this way, we can process all of the lines that were read in the current chunk.

Finally, process is called once per input line. If present, it strips off the carriage return character (to avoid issues with line endings – LF vs CRLF), and then calls JSON.parse one the line. At this point, you can do whatever you need to with your object.

Note that JSON.parse is strict about what it accepts as input; you must quote your identifiers and string values with double quotes. In other words, {name:'thing1'} will throw an error; you must use {"name":"thing1"}.

Because no more than a chunk of data will ever be in memory at a time, this will be extremely memory efficient. It will also be extremely fast. A quick test showed I processed 10,000 rows in under 15ms.

Difference between scaling horizontally and vertically for databases

SQL databases like Oracle, db2 also support Horizontal scaling through Shared disk cluster. For example Oracle RAC, IBM DB2 purescale or Sybase ASE Cluster edition. New node can be added to Oracle RAC system or DB2 purescale system to achieve horizontal scaling.

But the approach is different from noSQL databases (like mongodb, CouchDB or IBM Cloudant) is that the data sharding is not part of Horizontal scaling. In noSQL databases data is shraded during horizontal scaling.

What are advantages of Artificial Neural Networks over Support Vector Machines?

One obvious advantage of artificial neural networks over support vector machines is that artificial neural networks may have any number of outputs, while support vector machines have only one. The most direct way to create an n-ary classifier with support vector machines is to create n support vector machines and train each of them one by one. On the other hand, an n-ary classifier with neural networks can be trained in one go. Additionally, the neural network will make more sense because it is one whole, whereas the support vector machines are isolated systems. This is especially useful if the outputs are inter-related.

For example, if the goal was to classify hand-written digits, ten support vector machines would do. Each support vector machine would recognize exactly one digit, and fail to recognize all others. Since each handwritten digit cannot be meant to hold more information than just its class, it makes no sense to try to solve this with an artificial neural network.

However, suppose the goal was to model a person's hormone balance (for several hormones) as a function of easily measured physiological factors such as time since last meal, heart rate, etc ... Since these factors are all inter-related, artificial neural network regression makes more sense than support vector machine regression.

Is Python strongly typed?

You are confusing 'strongly typed' with 'dynamically typed'.

I cannot change the type of 1 by adding the string '12', but I can choose what types I store in a variable and change that during the program's run time.

The opposite of dynamic typing is static typing; the declaration of variable types doesn't change during the lifetime of a program. The opposite of strong typing is weak typing; the type of values can change during the lifetime of a program.

Differences between strong and weak in Objective-C

It may be helpful to think about strong and weak references in terms of balloons.

A balloon will not fly away as long as at least one person is holding on to a string attached to it. The number of people holding strings is the retain count. When no one is holding on to a string, the ballon will fly away (dealloc). Many people can have strings to that same balloon. You can get/set properties and call methods on the referenced object with both strong and weak references.

A strong reference is like holding on to a string to that balloon. As long as you are holding on to a string attached to the balloon, it will not fly away.

A weak reference is like looking at the balloon. You can see it, access it's properties, call it's methods, but you have no string to that balloon. If everyone holding onto the string lets go, the balloon flies away, and you cannot access it anymore.

What is the difference between 'typedef' and 'using' in C++11?

I know the original poster has a great answer, but for anyone stumbling on this thread like I have there's an important note from the proposal that I think adds something of value to the discussion here, particularly to concerns in the comments about if the typedef keyword is going to be marked as deprecated in the future, or removed for being redundant/old:

It has been suggested to (re)use the keyword typedef ... to introduce template aliases:

template<class T>
  typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages [sic] among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector<•, MyAllocator<•> > – where the bullet is a placeholder for a type-name.Consequently we do not propose the “typedef” syntax.On the other hand the sentence

template<class T>
  using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

To me, this implies continued support for the typedef keyword in C++ because it can still make code more readable and understandable.

Updating the using keyword was specifically for templates, and (as was pointed out in the accepted answer) when you are working with non-templates using and typedef are mechanically identical, so the choice is totally up to the programmer on the grounds of readability and communication of intent.

What is the connection string for localdb for version 11

I had the same problem for a bit. I noticed that I had:

Data Source= (localdb)\v11.0"

Simply by adding one back-slash it solved the problem for me:

Data Source= (localdb)\\v11.0"

sizing div based on window width

Try absolute positioning:

<div style="position:relative;width:100%;">
    <div id="help" style="
    position:absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index:1;">
        <img src="/portfolio/space_1_header.png" border="0" style="width:100%;">
    </div>
</div>

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Great answers! One thing that I would like to clarify deeper is nonatomic/atomic. The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents. I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute. For example:

@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...

In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads. BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.

If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

I actually managed to work out what I was doing wrong (and it was my fault).

I'm used to using pre-jQuery Rails, so when I included the Bootstrap JS files I didn't think that including the version of jQuery bundled with them would cause any issues, however when I removed that one JS file everything started working perfectly.

Lesson learnt, triple check which JS files are loaded, see if there's any conflicts.

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

Objective-C ARC: strong vs retain and weak vs assign

To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.

 -(void)displayLocalVariable
  {
     NSString myName = @"ABC";
     NSLog(@"My name is = %@", myName);
  }

In above method scope of myName variable is limited to displayLocalVariable method, once the method gets finished myName variable which is holding the string "ABC" will get deallocated from the memory.

Now what if we want to hold the myName variable value throughout our view controller life cycle. For this we can create the property named as username which will have Strong reference to the variable myName(see self.username = myName; in below code), as below,

@interface LoginViewController ()

@property(nonatomic,strong) NSString* username;
@property(nonatomic,weak) NSString* dummyName;

- (void)displayLocalVariable;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated
{
     [self displayLocalVariable];
}

- (void)displayLocalVariable
{
   NSString myName = @"ABC";
   NSLog(@"My name is = %@", myName);
   self.username = myName;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end

Now in above code you can see myName has been assigned to self.username and self.username is having a strong reference(as we declared in interface using @property) to myName(indirectly it's having Strong reference to "ABC" string). Hence String myName will not get deallocated from memory till self.username is alive.

  • Weak reference

Now consider assigning myName to dummyName which is a Weak reference, self.dummyName = myName; Unlike Strong reference Weak will hold the myName only till there is Strong reference to myName. See below code to understand Weak reference,

-(void)displayLocalVariable
  {
     NSString myName = @"ABC";
     NSLog(@"My name is = %@", myName);
     self.dummyName = myName;
  }

In above code there is Weak reference to myName(i.e. self.dummyName is having Weak reference to myName) but there is no Strong reference to myName, hence self.dummyName will not be able to hold the myName value.

Now again consider the below code,

-(void)displayLocalVariable
      {
         NSString myName = @"ABC";
         NSLog(@"My name is = %@", myName);
         self.username = myName;
         self.dummyName = myName;
      } 

In above code self.username has a Strong reference to myName, hence self.dummyName will now have a value of myName even after method ends since myName has a Strong reference associated with it.

Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated retain count reaches to 0.

Hope this helps.

Force DOM redraw/refresh on Chrome/Mac

This is my solution that worked for disappearing content...

<script type = 'text/javascript'>
    var trash_div;

    setInterval(function()
    {
        if (document.body)
        {
            if (!trash_div)
                trash_div = document.createElement('div');

            document.body.appendChild(trash_div);
            document.body.removeChild(trash_div);
        }
    }, 1000 / 25); //25 fps...
</script>

Git merge without auto commit

When there is one commit only in the branch, I usually do

git merge branch_name --ff

Change name of folder when cloning from GitHub?

git clone <Repo> <DestinationDirectory>

Clone the repository located at Repo into the folder called DestinationDirectory on the local machine.

Increasing Google Chrome's max-connections-per-server limit to more than 6

BTW, HTTP 1/1 specification (RFC2616) suggests no more than 2 connections per server.

Clients that use persistent connections SHOULD limit the number of simultaneous connections that they maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy. A proxy SHOULD use up to 2*N connections to another server or proxy, where N is the number of simultaneously active users. These guidelines are intended to improve HTTP response times and avoid congestion.

Making Enter key on an HTML form submit instead of activating button

You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit", and the other buttons mark them with type="button". In your example:

<button type="button" onclick="return myFunc1()">Button 1</button>
<input type="submit" name="go" value="Submit"/>

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as

<class>com.yourCompanyName.WhateverEntityClass</class>

In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.

How to select different app.config for several build configurations

Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :

 <None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />

 <None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />

Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!

How can I find the number of years between two dates?

// int year =2000;  int month =9 ;    int day=30;

    public int getAge (int year, int month, int day) {

            GregorianCalendar cal = new GregorianCalendar();
            int y, m, d, noofyears;         

            y = cal.get(Calendar.YEAR);// current year ,
            m = cal.get(Calendar.MONTH);// current month 
            d = cal.get(Calendar.DAY_OF_MONTH);//current day
            cal.set(year, month, day);// here ur date 
            noofyears = y - cal.get(Calendar.YEAR);
            if ((m < cal.get(Calendar.MONTH))
                            || ((m == cal.get(Calendar.MONTH)) && (d < cal
                                            .get(Calendar.DAY_OF_MONTH)))) {
                    --noofyears;
            }
            if(noofyears < 0)
                    throw new IllegalArgumentException("age < 0");
             System.out.println(noofyears);
            return noofyears;

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

while doing performance testing, the measure i go by is RPS, that is how many requests per second can the server serve within acceptable latency.

theoretically one server can only run as many requests concurrently as number of cores on it..

It doesn't look like the problem is ASP.net's threading model, since it can potentially serve thousands of rps. It seems like the problem might be your application. Are you using any synchronization primitives ?

also whats the latency on your web services, are they very quick to respond (within microseconds), if not then you might want to consider asynchronous calls, so you dont end up blocking

If this doesnt yeild something, then you might want to profile your code using visual studio or redgate profiler

Should IBOutlets be strong or weak under ARC?

It looks like something has changed over the years and now Apple recommends to use strong in general. The evidence on their WWDC session is in session 407 - Implementing UI Designs in Interface Builder and starts at 32:30. My note from what he says is (almost, if not exactly, quoting him):

  • outlet connections in general should be strong especially if we connect a subview or constraint that is not always retained by the view hierarchy

  • weak outlet connection might be needed when creating custom views that has some reference to something back up in the view hierarchy and in general it is not recommended

In other wards it should be always strong now as long as some of our custom view doesn't create a retain cycle with some of the view up in the view hierarchy

EDIT :

Some may ask the question. Does keeping it with a strong reference doesn't create a retain cycle as the root view controller and the owning view keeps the reference to it? Or why that changed happened? I think the answer is earlier in this talk when they describe how the nibs are created from the xib. There is a separate nib created for a VC and for the view. I think this might be the reason why they change the recommendations. Still it would be nice to get a deeper explanation from Apple.

Set position / size of UI element as percentage of screen size

The above problem can also be solved using ConstraintLayout through Guidelines.

Below is the snippet.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.constraint.Guideline
    android:id="@+id/upperGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.68" />

<Gallery
    android:id="@+id/gallery"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/lowerGuideLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/upperGuideLine" />

<android.support.constraint.Guideline
    android:id="@+id/lowerGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.84" />

</android.support.constraint.ConstraintLayout>

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

My personal opinion: Go for Swing together with the NetBeans platform.

If you need advanced components (more than NetBeans offers) you can easily integrate SwingX without problems (or JGoodies) as the NetBeans platform is completely based on Swing.

I would not start a large desktop application (or one that is going to be large) without a good platform that is build upon the underlying UI framework.

The other option is SWT together with the Eclipse RCP, but it's harder (though not impossible) to integrate "pure" Swing components into such an application.

The learning curve is a bit steep for the NetBeans platform (although I guess that's true for Eclipse as well) but there are some good books around which I would highly recommend.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

Firefox Developer Edition (59.0b6) has Scratchpad (Shift +F4) where you can run javascript

php foreach with multidimensional array

Example with mysql_fetch_assoc():

while ($row = mysql_fetch_assoc($result))
{
    /* ... your stuff ...*/
}

In your case with foreach, with the $result array you get from select():

foreach ($result as $row)
{
    /* ... your stuff ...*/
}

It's much like the same, with proper iteration.

Why am I seeing "TypeError: string indices must be integers"?

item is most likely a string in your code; the string indices are the ones in the square brackets, e.g., gravatar_id. So I'd first check your data variable to see what you received there; I guess that data is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.

ActionBar text color

Ok, I've found a better way. I'm now able to only change the color of the title. You can also tweak the subtitle.

Here is my styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/MyTheme.ActionBarStyle</item>
  </style>

  <style name="MyTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
  </style>

  <style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">@color/red</item>
  </style>
</resources>

How do I check/uncheck all checkboxes with a button using jQuery?

 $(document).on('change', '.check-all', function () {
   if($(this).prop('checked')) {
      $('.check-box').prop('checked', true)
   }else {
      $('.check-box').prop('checked', false);
   }

Stretch horizontal ul to fit width of div

inelegant (but effective) way: use percentages

#horizontal-style {
    width: 100%;
}

li {
    width: 20%;
}

This only works with the 5 <li> example. For more or less, modify your percentage accordingly. If you have other <li>s on your page, you can always assign these particular ones a class of "menu-li" so that only they are affected.

MD5 hashing in Android

Please use SHA-512, MD5 is insecure

public static String getSHA512SecurePassword(String passwordToHash) {
    String generatedPassword = null;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update("everybreathyoutake".getBytes());
        byte[] bytes = md.digest(passwordToHash.getBytes());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        generatedPassword = sb.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return generatedPassword;
}

Example of a strong and weak entity types

A weak entity is one that can only exist when owned by another one. For example: a ROOM can only exist in a BUILDING. On the other hand, a TIRE might be considered as a strong entity because it also can exist without being attached to a CAR.

How do the major C# DI/IoC frameworks compare?

I came across another performance comparison(latest update 10 April 2014). It compares the following:

Here is a quick summary from the post:

Conclusion

Ninject is definitely the slowest container.

MEF, LinFu and Spring.NET are faster than Ninject, but still pretty slow. AutoFac, Catel and Windsor come next, followed by StructureMap, Unity and LightCore. A disadvantage of Spring.NET is, that can only be configured with XML.

SimpleInjector, Hiro, Funq, Munq and Dynamo offer the best performance, they are extremely fast. Give them a try!

Especially Simple Injector seems to be a good choice. It's very fast, has a good documentation and also supports advanced scenarios like interception and generic decorators.

You can also try using the Common Service Selector Library and hopefully try multiple options and see what works best for you.

Some informtion about Common Service Selector Library from the site:

The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references. The hope is that using this library, third-party applications and frameworks can begin to leverage IoC/Service Location without tying themselves down to a specific implementation.

Update

13.09.2011: Funq and Munq were added to the list of contestants. The charts were also updated, and Spring.NET was removed due to it's poor performance.

04.11.2011: "added Simple Injector, the performance is the best of all contestants".

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

An elegant way in Swift 3 and better to understand:

override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
    let leftMargin:CGFloat = 40
    let imgWidth:CGFloat = 24
    let imgHeight:CGFloat = 24
    return CGRect(x: leftMargin, y: (contentRect.size.height-imgHeight) * 0.5, width: imgWidth, height: imgHeight)
}

override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
    let leftMargin:CGFloat = 80
    let rightMargin:CGFloat = 80
    return CGRect(x: leftMargin, y: 0, width: contentRect.size.width-leftMargin-rightMargin, height: contentRect.size.height)
}
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
    let leftMargin:CGFloat = 10
    let rightMargin:CGFloat = 10
    let topMargin:CGFloat = 10
    let bottomMargin:CGFloat = 10
    return CGRect(x: leftMargin, y: topMargin, width: bounds.size.width-leftMargin-rightMargin, height: bounds.size.height-topMargin-bottomMargin)
}
override func contentRect(forBounds bounds: CGRect) -> CGRect {
    let leftMargin:CGFloat = 5
    let rightMargin:CGFloat = 5
    let topMargin:CGFloat = 5
    let bottomMargin:CGFloat = 5
    return CGRect(x: leftMargin, y: topMargin, width: bounds.size.width-leftMargin-rightMargin, height: bounds.size.height-topMargin-bottomMargin)
}

jQuery .get error response function?

$.get does not give you the opportunity to set an error handler. You will need to use the low-level $.ajax function instead:

$.ajax({
    url: 'http://example.com/page/2/',
    type: 'GET',
    success: function(data){ 
        $(data).find('#reviews .card').appendTo('#reviews');
    },
    error: function(data) {
        alert('woops!'); //or whatever
    }
});

Edit March '10

Note that with the new jqXHR object in jQuery 1.5, you can set an error handler after calling $.get:

$.get('http://example.com/page/2/', function(data){ 
    $(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
    alert('woops'); // or whatever
});

'this' is undefined in JavaScript class methods

In ES2015 a.k.a ES6, class is a syntactic sugar for functions.

If you want to force to set a context for this you can use bind() method. As @chetan pointed, on invocation you can set the context as well! Check the example below:

class Form extends React.Component {
constructor() {
    super();
  }
  handleChange(e) {
    switch (e.target.id) {
      case 'owner':
        this.setState({owner: e.target.value});
        break;
      default:
    }
  }
  render() {
    return (
      <form onSubmit={this.handleNewCodeBlock}>
        <p>Owner:</p> <input onChange={this.handleChange.bind(this)} />
      </form>
    );
  }
}

Here we forced the context inside handleChange() to Form.

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];

Java time-based map/cache with expiring keys

If anybody needs a simple thing, following is a simple key-expiring set. It might be converted to a map easily.

public class CacheSet<K> {
    public static final int TIME_OUT = 86400 * 1000;

    LinkedHashMap<K, Hit> linkedHashMap = new LinkedHashMap<K, Hit>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, Hit> eldest) {
            final long time = System.currentTimeMillis();
            if( time - eldest.getValue().time > TIME_OUT) {
                Iterator<Hit> i = values().iterator();

                i.next();
                do {
                    i.remove();
                } while( i.hasNext() && time - i.next().time > TIME_OUT );
            }
            return false;
        }
    };


    public boolean putIfNotExists(K key) {
        Hit value = linkedHashMap.get(key);
        if( value != null ) {
            return false;
        }

        linkedHashMap.put(key, new Hit());
        return true;
    }

    private static class Hit {
        final long time;


        Hit() {
            this.time = System.currentTimeMillis();
        }
    }
}

Peak detection in a 2D array

Just wanna tell you guys there is a nice option to find local maxima in images with python:

from skimage.feature import peak_local_max

or for skimage 0.8.0:

from skimage.feature.peak import peak_local_max

http://scikit-image.org/docs/0.8.0/api/skimage.feature.peak.html

Simple conversion between java.util.Date and XMLGregorianCalendar

From XMLGregorianCalendar to java.util.Date you can simply do:

java.util.Date dt = xmlGregorianCalendarInstance.toGregorianCalendar().getTime();  

Should I use past or present tense in git commit messages?

does it matter? people are generally smart enough to interpret messages correctly, if they aren't you probably shouldn't let them access your repository anyway!

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

If its IIS make sure That Under your common HTTP Features you have Static Content turned on

How can I get CMake to find my alternative Boost installation?

I had a similar issue, and I could use customized Boost libraries by adding the below lines to my CMakeLists.txt file:

set(Boost_NO_SYSTEM_PATHS TRUE)
if (Boost_NO_SYSTEM_PATHS)
  set(BOOST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../3p/boost")
  set(BOOST_INCLUDE_DIRS "${BOOST_ROOT}/include")
  set(BOOST_LIBRARY_DIRS "${BOOST_ROOT}/lib")
endif (Boost_NO_SYSTEM_PATHS)
find_package(Boost REQUIRED regex date_time system filesystem thread graph program_options)
include_directories(${BOOST_INCLUDE_DIRS})

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

This worked for me:

     // After logout redirect user to Loing Activity
    Intent i = new Intent(_context, MainActivity.class);
    // Closing all the Activities
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

    // Add new Flag to start new Activity
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Staring Login Activity
    _context.startActivity(i);

How to replace master branch in Git, entirely, from another branch?

What about using git branch -m to rename the master branch to another one, then rename seotweaks branch to master? Something like this:

git branch -m master old-master
git branch -m seotweaks master
git push -f origin master

This might remove commits in origin master, please check your origin master before running git push -f origin master.

How do I put a clear button inside my HTML text input box like the iPhone does?

@thebluefox has summarized the most of all. You're only also forced to use JavaScript to make that button to work anyway. Here's an SSCCE, you can copy'n'paste'n'run it:

_x000D_
_x000D_
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('input.deletable').wrap('<span class="deleteicon" />').after($('<span/>').click(function() {
                    $(this).prev('input').val('').trigger('change').focus();
                }));
            });
        </script>
        <style>
            span.deleteicon {
                position: relative;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                top: 5px;
                right: 0px;
                width: 16px;
                height: 16px;
                background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 16px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <input type="text" class="deletable">
    </body>
</html>
_x000D_
_x000D_
_x000D_

Source.

jQuery is by the way not necessary, it just nicely separates the logic needed for progressive enhancement from the source, you can of course also go ahead with plain HTML/CSS/JS:

_x000D_
_x000D_
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532, with "plain" HTML/CSS/JS</title>
        <style>
            span.deleteicon {
                position: relative;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                top: 5px;
                right: 0px;
                width: 16px;
                height: 16px;
                background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 16px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <span class="deleteicon">
            <input type="text">
            <span onclick="var input = this.previousSibling; input.value = ''; input.focus();"></span>
        </span>
    </body>
</html>
_x000D_
_x000D_
_x000D_

You only ends up with uglier HTML (and non-crossbrowser compatible JS ;) ).

Note that when the UI look'n'feel isn't your biggest concern, but the functionality is, then just use <input type="search"> instead of <input type="text">. It'll show the (browser-specific) clear button on HTML5 capable browsers.

"No such file or directory" error when executing a binary

readelf -a xxx

 INTERP         
  0x0000000000000238 0x0000000000400238 0x0000000000400238           
  0x000000000000001c 0x000000000000001c  R      1
  [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

If I recall correctly, there are some issues with adding SharePoint web services as a VS2K8 "Service Reference". You need to add it as an old-style "Web Reference" to work properly.

Warning as error - How to get rid of these

Each project in Visual Studio has a "treat warnings as errors" option. Go through each of your projects and change that setting:

  1. Right-click on your project, select "Properties".
  2. Click "Build".
  3. Switch "Treat warnings as errors" from "All" to "Specific warnings" or "None".

The location of this switch varies, depending on the type of project (class library vs. web application, for example).

How to debug PDO database queries?

Searching internet I found this as an acceptable solution. A different class is used instead of PDO and PDO functions are called through magic function calls. I am not sure this creates serious performance problems. But it can be used until a sensible logging feature is added to PDO.

So as per this thread, you can write a wrapper for your PDO connection which can log and throws an exception when you get a error.

Here is simple example:

class LoggedPDOSTatement extends PDOStatement    {

function execute ($array)    {
    parent::execute ($array);
    $errors = parent::errorInfo();
    if ($errors[0] != '00000'):
        throw new Exception ($errors[2]);
    endif;
  }

}

so you can use that class instead of PDOStatement:

$this->db->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('LoggedPDOStatement', array()));

Here a mentioned PDO decorator implementation:

class LoggedPDOStatement    {

function __construct ($stmt)    {
    $this->stmt = $stmt;
}

function execute ($params = null)    {
    $result = $this->stmt->execute ($params); 
    if ($this->stmt->errorCode() != PDO::ERR_NONE):
        $errors = $this->stmt->errorInfo();
        $this->paint ($errors[2]);
    endif;
    return $result;
}

function bindValue ($key, $value)    {
    $this->values[$key] = $value;    
    return $this->stmt->bindValue ($key, $value);
}

function paint ($message = false)    {
    echo '<pre>';
    echo '<table cellpadding="5px">';
    echo '<tr><td colspan="2">Message: ' . $message . '</td></tr>';
    echo '<tr><td colspan="2">Query: ' . $this->stmt->queryString . '</td></tr>';
    if (count ($this->values) > 0):
    foreach ($this->values as $key => $value):
    echo '<tr><th align="left" style="background-color: #ccc;">' . $key . '</th><td>' . $value . '</td></tr>';
    endforeach;
    endif;
    echo '</table>';
    echo '</pre>';
}

function __call ($method, $params)    {
    return call_user_func_array (array ($this->stmt, $method), $params); 
}

}

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

You should be aware of a few key factors...

First, there are two types of compression: Lossless and Lossy.

  • Lossless means that the image is made smaller, but at no detriment to the quality.
  • Lossy means the image is made (even) smaller, but at a detriment to the quality. If you saved an image in a Lossy format over and over, the image quality would get progressively worse and worse.

There are also different colour depths (palettes): Indexed color and Direct color.

  • Indexed means that the image can only store a limited number of colours (usually 256), controlled by the author, in something called a Color Map
  • Direct means that you can store many thousands of colours that have not been directly chosen by the author

BMP - Lossless / Indexed and Direct

This is an old format. It is Lossless (no image data is lost on save) but there's also little to no compression at all, meaning saving as BMP results in VERY large file sizes. It can have palettes of both Indexed and Direct, but that's a small consolation. The file sizes are so unnecessarily large that nobody ever really uses this format.

Good for: Nothing really. There isn't anything BMP excels at, or isn't done better by other formats.

BMP vs GIF


GIF - Lossless / Indexed only

GIF uses lossless compression, meaning that you can save the image over and over and never lose any data. The file sizes are much smaller than BMP, because good compression is actually used, but it can only store an Indexed palette. This means that for most use cases, there can only be a maximum of 256 different colours in the file. That sounds like quite a small amount, and it is.

GIF images can also be animated and have transparency.

Good for: Logos, line drawings, and other simple images that need to be small. Only really used for websites.

GIF vs JPEG


JPEG - Lossy / Direct

JPEGs images were designed to make detailed photographic images as small as possible by removing information that the human eye won't notice. As a result it's a Lossy format, and saving the same file over and over will result in more data being lost over time. It has a palette of thousands of colours and so is great for photographs, but the lossy compression means it's bad for logos and line drawings: Not only will they look fuzzy, but such images will also have a larger file-size compared to GIFs!

Good for: Photographs. Also, gradients.

JPEG vs GIF


PNG-8 - Lossless / Indexed

PNG is a newer format, and PNG-8 (the indexed version of PNG) is really a good replacement for GIFs. Sadly, however, it has a few drawbacks: Firstly it cannot support animation like GIF can (well it can, but only Firefox seems to support it, unlike GIF animation which is supported by every browser). Secondly it has some support issues with older browsers like IE6. Thirdly, important software like Photoshop have very poor implementation of the format. (Damn you, Adobe!) PNG-8 can only store 256 colours, like GIFs.

Good for: The main thing that PNG-8 does better than GIFs is having support for Alpha Transparency.

PNG-8 vs GIF


PNG-24 - Lossless / Direct

PNG-24 is a great format that combines Lossless encoding with Direct color (thousands of colours, just like JPEG). It's very much like BMP in that regard, except that PNG actually compresses images, so it results in much smaller files. Unfortunately PNG-24 files will still be bigger than JPEGs (for photos), and GIFs/PNG-8s (for logos and graphics), so you still need to consider if you really want to use one.

Even though PNG-24s allow thousands of colours while having compression, they are not intended to replace JPEG images. A photograph saved as a PNG-24 will likely be at least 5 times larger than a equivalent JPEG image, with very little improvement in visible quality. (Of course, this may be a desirable outcome if you're not concerned about filesize, and want to get the best quality image you can.)

Just like PNG-8, PNG-24 supports alpha-transparency, too.


SVG - Lossless / Vector

A filetype that is currently growing in popularity is SVG, which is different than all the above in that it's a vector file format (the above are all raster). This means that it's actually comprised of lines and curves instead of pixels. When you zoom in on a vector image, you still see a curve or a line. When you zoom in on a raster image, you will see pixels.

For example:

PNG vs SVG

SVG vs PNG

This means SVG is perfect for logos and icons you wish to retain sharpness on Retina screens or at different sizes. It also means a small SVG logo can be used at a much larger (bigger) size without degradation in image quality -- something that would require a separate larger (in terms of filesize) file with raster formats.

SVG file sizes are often tiny, even if they're visually very large, which is great. It's worth bearing in mind, however, that it does depend on the complexity of the shapes used. SVGs require more computing power than raster images because mathematical calculations are involved in drawing the curves and lines. If your logo is especially complicated it could slow down a user's computer, and even have a very large file size. It's important that you simplify your vector shapes as much as possible.

Additionally, SVG files are written in XML, and so can be opened and edited in a text editor(!). This means its values can be manipulated on the fly. For example, you could use JavaScript to change the colour of an SVG icon on a website, much like you would some text (ie. no need for a second image), or even animate them.

In all, they are best for simple flat shapes like logos or graphs.

I hope that helps!

Process to convert simple Python script into Windows executable

You can create executable from python script using NSIS (Nullsoft scriptable install system). Follow the below steps to convert your python files to executable.

  • Download and install NSIS in your system.

  • Compress the folder in the .zip file that you want to export into the executable.

  • Start NSIS and select Installer based on ZIP file. Find and provide a path to your compressed file.

  • Provide your Installer Name and Default Folder path and click on Generate to generate your exe file.

  • Once its done you can click on Test to test executable or Close to complete the process.

  • The executable generated can be installed on the system and can be distributed to use this application without even worrying about installing the required python and its packages.

For a video tutorial follow: How to Convert any Python File to .EXE

Improve INSERT-per-second performance of SQLite

After reading this tutorial, I tried to implement it to my program.

I have 4-5 files that contain addresses. Each file has approx 30 million records. I am using the same configuration that you are suggesting but my number of INSERTs per second is way low (~10.000 records per sec).

Here is where your suggestion fails. You use a single transaction for all the records and a single insert with no errors/fails. Let's say that you are splitting each record into multiple inserts on different tables. What happens if the record is broken?

The ON CONFLICT command does not apply, cause if you have 10 elements in a record and you need each element inserted to a different table, if element 5 gets a CONSTRAINT error, then all previous 4 inserts need to go too.

So here is where the rollback comes. The only issue with the rollback is that you lose all your inserts and start from the top. How can you solve this?

My solution was to use multiple transactions. I begin and end a transaction every 10.000 records (Don't ask why that number, it was the fastest one I tested). I created an array sized 10.000 and insert the successful records there. When the error occurs, I do a rollback, begin a transaction, insert the records from my array, commit and then begin a new transaction after the broken record.

This solution helped me bypass the issues I have when dealing with files containing bad/duplicate records (I had almost 4% bad records).

The algorithm I created helped me reduce my process by 2 hours. Final loading process of file 1hr 30m which is still slow but not compared to the 4hrs that it initially took. I managed to speed the inserts from 10.000/s to ~14.000/s

If anyone has any other ideas on how to speed it up, I am open to suggestions.

UPDATE:

In Addition to my answer above, you should keep in mind that inserts per second depending on the hard drive you are using too. I tested it on 3 different PCs with different hard drives and got massive differences in times. PC1 (1hr 30m), PC2 (6hrs) PC3 (14hrs), so I started wondering why would that be.

After two weeks of research and checking multiple resources: Hard Drive, Ram, Cache, I found out that some settings on your hard drive can affect the I/O rate. By clicking properties on your desired output drive you can see two options in the general tab. Opt1: Compress this drive, Opt2: Allow files of this drive to have contents indexed.

By disabling these two options all 3 PCs now take approximately the same time to finish (1hr and 20 to 40min). If you encounter slow inserts check whether your hard drive is configured with these options. It will save you lots of time and headaches trying to find the solution

iPhone UILabel text soft shadow

While it's impossible to set a blur radius directly on UILabel, you definitely could change it by manipulating CALayer.

Just set:

//Required properties
customLabel.layer.shadowRadius = 5.0 //set shadow radius to your desired value.
customLabel.layer.shadowOpacity = 1.0 //Choose an opacity. Make sure it's visible (default is 0.0)

//Other options
customLabel.layer.shadowOffset = CGSize(width: 10, height: 10)
customLabel.layer.shadowColor = UIColor.black.cgColor
customLabel.layer.masksToBounds = false

What I hope will help someone and other answers failed to clarify is that it will not work if you also set UILabel Shadow Color property directly on Interface Builder while trying to setup .layer.shadowRadius.

So if setting label.layer.shadowRadius didn't work, please verify Shadow Color for this UILabel on Interface Builder. It should be set to default. And then, please, if you want a shadow color other than black, set this color also through .layer property.

enter image description here

IBOutlet and IBAction

IBOutlet

  • It is a property.
  • When the nib(IB) file is loaded, it becomes part of encapsulated data which connects to an instance variable.
  • Each connection is unarchived and reestablished.

IBAction

  • Attribute indicates that the method is an action that you can connect to from your storyboard in Interface Builder.

@ - Dynamic pattern IB - Interface Builder

How to quickly edit values in table in SQL Server Management Studio?

Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.

Pushing value of Var into an Array

.val() does not return an array from a DOM element: $('#fruit') is going to find the element in the document with an ID of #fruit and get its value (if it has a value).

PNG transparency issue in IE8

I had the same thing happen to a PNG with transparency that was set as the background-image of an <A> element with opacity applied.

The fix was to set the background-color of the <A> element.

So, the following:

filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;

Turns into:

/* "Overwritten" by the background-image. However this fixes the IE7 and IE8 PNG-transparency-plus-opacity bug. */
background-color: #FFFFFF; 

filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;

Where's my JSON data in my incoming Django request?

Method 1

Client : Send as JSON

$.ajax({
    url: 'example.com/ajax/',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    processData: false,
    data: JSON.stringify({'name':'John', 'age': 42}),
    ...
});

//Sent as a JSON object {'name':'John', 'age': 42}

Server :

data = json.loads(request.body) # {'name':'John', 'age': 42}

Method 2

Client : Send as x-www-form-urlencoded
(Note: contentType & processData have changed, JSON.stringify is not needed)

$.ajax({
    url: 'example.com/ajax/',
    type: 'POST',    
    data: {'name':'John', 'age': 42},
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',  //Default
    processData: true,       
});

//Sent as a query string name=John&age=42

Server :

data = request.POST # will be <QueryDict: {u'name':u'John', u'age': 42}>

Changed in 1.5+ : https://docs.djangoproject.com/en/dev/releases/1.5/#non-form-data-in-http-requests

Non-form data in HTTP requests :
request.POST will no longer include data posted via HTTP requests with non form-specific content-types in the header. In prior versions, data posted with content-types other than multipart/form-data or application/x-www-form-urlencoded would still end up represented in the request.POST attribute. Developers wishing to access the raw POST data for these cases, should use the request.body attribute instead.

Probably related

Java Best Practices to Prevent Cross Site Scripting

My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.

Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:

// java-ish pseudocode
StringBuffer safestrbuf = new StringBuffer(string.length()*4);
foreach(char c : string.split() ){  
  if( Character.isAlphaNumeric(c) ) safestrbuf.append(c);
  else safestrbuf.append(""+(int)symbol);

You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

Convert your solution to x64. If you still face an issue, grant max length to everything that throws an exception like below :

 var jsSerializer = new JavaScriptSerializer();
 jsSerializer.MaxJsonLength = Int32.MaxValue;

How should I use Outlook to send code snippets?

If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.

With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.

Below is the summary of the style I have defined for emailing the code snippets.

Do not check spelling or grammar, Border:
Box: (Single solid line, Orange,  0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted

HTML table headers always visible at top of window when viewing a large table

Using display: fixed on the thead section should work, but for it only work on the current table in view, you will need the help of JavaScript. And it will be tricky because it will need to figure out scrolling places and location of elements relative to the viewport, which is one of the prime areas of browser incompatibility.

Have a look at the popular JavaScript frameworks (jQuery, MooTools, YUI, etc etc.) to see if they can either do what you want or make it easier to do what you want.

Get first 100 characters from string, respecting full words

This works fine for me, I use it in my script

<?PHP
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!";
$small = some_function($big);
echo $small;

function some_function($string){
     $string = substr($string,0,100);
     $string = substr($string,0,strrpos($string," "));
     return $string;
}
?>

good luck

How to dynamically add a style for text-align using jQuery

suppose below is the html paragraph tag:

<p style="background-color:#ff0000">This is a paragraph.</p>

and we want to change the paragraph color in jquery.

The client side code will be:

<script>
$(document).ready(function(){
    $("p").css("background-color", "yellow");
});
</script> 

Truncating long strings with CSS: feasible yet?

If you're OK with a JavaScript solution, there's a jQuery plug-in to do this in a cross-browser fashion - see http://azgtech.wordpress.com/2009/07/26/text-overflow-ellipsis-for-firefox-via-jquery/

JUnit: how to avoid "no runnable methods" in test utils classes

Be careful when using an IDE's code-completion to add the import for @Test.

It has to be import org.junit.Test and not import org.testng.annotations.Test, for example. If you do the latter, you'll get the "no runnable methods" error.

Getting a 'source: not found' error when using source in a bash script

In the POSIX standard, which /bin/sh is supposed to respect, the command is . (a single dot), not source. The source command is a csh-ism that has been pulled into bash.

Try

. $env_name/bin/activate

Or if you must have non-POSIX bash-isms in your code, use #!/bin/bash.

How to change the pop-up position of the jQuery DatePicker control

This puts the functionality into a method named function, allowing for your code to encapsulate it or for the method to be made a jquery extension. Just used on my code, works perfectly

var nOffsetTop  = /* whatever value, set from wherever */;
var nOffsetLeft = /* whatever value, set from wherever */;

$(input).datepicker
(
   beforeShow : function(oInput, oInst) 
   { 
      AlterPostion(oInput, oInst, nOffsetTop, nOffsetLeft); 
   }
);

/* can be converted to extension, or whatever*/
var AlterPosition = function(oInput, oItst, nOffsetTop, nOffsetLeft)
{
   var divContainer = oInst.dpDiv;
   var oElem        = $(this);
       oInput       = $(oInput);

   setTimeout(function() 
   { 
      divContainer.css
      ({ 
         top  : (nOffsetTop >= 0 ? "+=" + nOffsetTop : "-=" + (nOffsetTop * -1)), 
         left : (nOffsetTop >= 0 ? "+=" + nOffsetLeft : "-=" + (nOffsetLeft * -1))
      }); 
   }, 10);
}

Setting the selected value on a Django forms.ChoiceField

Both Tom and Burton's answers work for me eventually, but I had a little trouble figuring out how to apply them to a ModelChoiceField.

The only trick to it is that the choices are stored as tuples of (<model's ID>, <model's unicode repr>), so if you want to set the initial model selection, you pass the model's ID as the initial value, not the object itself or it's name or anything else. Then it's as simple as:

form = EmployeeForm(initial={'manager': manager_employee_id})

Alternatively the initial argument can be ignored in place of an extra line with:

form.fields['manager'].initial = manager_employee_id

How can you print a variable name in python?

You can't, as there are no variables in Python but only names.

For example:

> a = [1,2,3]
> b = a
> a is b
True

Which of those two is now the correct variable? There's no difference between a and b.

There's been a similar question before.

Requested registry access is not allowed

As a temporary fix, users can right click the utility and select "Run as administrator."

MS SQL Date Only Without Time

Here's a query that will return all results within a range of days.

DECLARE @startDate DATETIME
DECLARE @endDate DATETIME

SET @startDate = DATEADD(day, -30, GETDATE())
SET @endDate = GETDATE()

SELECT *
FROM table
WHERE dateColumn >= DATEADD(day, DATEDIFF(day, 0, @startDate), 0)
  AND dateColumn <  DATEADD(day, 1, DATEDIFF(day, 0, @endDate))

How to fix "Referenced assembly does not have a strong name" error?

For me, the problem was a NuGet package without a strong name. The solution was to install StrongNamer from NuGet, which automatically adds a strong name to all referenced assemblies. Just simply having it referenced in the project fixed my issue.

What's the difference between SoftReference and WeakReference in Java?

Weak references are collected eagerly. If GC finds that an object is weakly reachable (reachable only through weak references), it'll clear the weak references to that object immediately. As such, they're good for keeping a reference to an object for which your program also keeps (strongly referenced) "associated information" somewere, like cached reflection information about a class, or a wrapper for an object, etc. Anything that makes no sense to keep after the object it is associated with is GC-ed. When the weak reference gets cleared, it gets enqueued in a reference queue that your code polls somewhere, and it discards the associated objects as well. That is, you keep extra information about an object, but that information is not needed once the object it refers to goes away. Actually, in certain situations you can even subclass WeakReference and keep the associated extra information about the object in the fields of the WeakReference subclass. Another typical use of WeakReference is in conjunction with Maps for keeping canonical instances.

SoftReferences on the other hand are good for caching external, recreatable resources as the GC typically delays clearing them. It is guaranteed though that all SoftReferences will get cleared before OutOfMemoryError is thrown, so they theoretically can't cause an OOME[*].

Typical use case example is keeping a parsed form of a contents from a file. You'd implement a system where you'd load a file, parse it, and keep a SoftReference to the root object of the parsed representation. Next time you need the file, you'll try to retrieve it through the SoftReference. If you can retrieve it, you spared yourself another load/parse, and if the GC cleared it in the meantime, you reload it. That way, you utilize free memory for performance optimization, but don't risk an OOME.

Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If on the other hand you mistakenly use SoftReference for a task a WeakReference is meant to be used (namely, you keep information associated with an Object somehow strongly referenced, and discard it when the Reference object gets cleared), you can run into OOME as your code that polls the ReferenceQueue and discards the associated objects might happen to not run in a timely fashion.

So, the decision depends on usage - if you're caching information that is expensive to construct, but nonetheless reconstructible from other data, use soft references - if you're keeping a reference to a canonical instance of some data, or you want to have a reference to an object without "owning" it (thus preventing it from being GC'd), use a weak reference.

PHP removing a character in a string

While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).

$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
  if ($urlString[$i] === '?') {
    $urlString[$i+1] = '';
    break;
  }
}

Weird, I know.

Simple Random Samples from a Sql database

If you need exactly m rows, realistically you'll generate your subset of IDs outside of SQL. Most methods require at some point to select the "nth" entry, and SQL tables are really not arrays at all. The assumption that the keys are consecutive in order to just join random ints between 1 and the count is also difficult to satisfy — MySQL for example doesn't support it natively, and the lock conditions are... tricky.

Here's an O(max(n, m lg n))-time, O(n)-space solution assuming just plain BTREE keys:

  1. Fetch all values of the key column of the data table in any order into an array in your favorite scripting language in O(n)
  2. Perform a Fisher-Yates shuffle, stopping after m swaps, and extract the subarray [0:m-1] in ?(m)
  3. "Join" the subarray with the original dataset (e.g. SELECT ... WHERE id IN (<subarray>)) in O(m lg n)

Any method that generates the random subset outside of SQL must have at least this complexity. The join can't be any faster than O(m lg n) with BTREE (so O(m) claims are fantasy for most engines) and the shuffle is bounded below n and m lg n and doesn't affect the asymptotic behavior.

In Pythonic pseudocode:

ids = sql.query('SELECT id FROM t')
for i in range(m):
  r = int(random() * (len(ids) - i))
  ids[i], ids[i + r] = ids[i + r], ids[i]

results = sql.query('SELECT * FROM t WHERE id IN (%s)' % ', '.join(ids[0:m-1])

Is there a max array length limit in C++?

There are two limits, both not enforced by C++ but rather by the hardware.

The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_t can take. This data type is large enough to contain the size in bytes of any object

The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a vector<int> of a given size n typically takes multiple times as much memory as an array of type vector<char> (minus a small constant value), since int is usually bigger than char. Therefore, a vector<char> may contain more items than a vector<int> before memory is full. The same counts for raw C-style arrays like int[] and char[].

Additionally, this upper limit may be influenced by the type of allocator used to construct the vector because an allocator is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.

Apart from that, C++ doesn't enforce any limits.

ZIP Code (US Postal Code) validation

One way to check valid Canada postal code is-

function isValidCAPostal(pcVal) {
   return ^[A-Za-z][0-9][A-Za-z]\s{0,1}[0-9][A-Za-z][0-9]$/.test(pcVal);
}

Hope this will help someone.

How do I simulate a low bandwidth, high latency environment?

I guess tc could do the job on UNIX based platform.

tc is used to configure Traffic Control in the Linux kernel
http://lartc.org/manpages/tc.txt

Singleton: How should it be used

Singletons are handy when you've got a lot code being run when you initialize and object. For example, when you using iBatis when you setup a persistence object it has to read all the configs, parse the maps, make sure its all correct, etc.. before getting to your code.

If you did this every time, performance would be much degraded. Using it in a singleton, you take that hit once and then all subsequent calls don't have to do it.

Response.Redirect with POST instead of Get?

PostbackUrl can be set on your asp button to post to a different page.

if you need to do it in codebehind, try Server.Transfer.

Hidden Features of C#?

I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.

double? num1 = null; 
double num2 = num1 ?? -100;

Set a nullable double, num1, to null, then set a regular double, num2, to num1 or -100 if num1 was null.

http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx

one more thing about Nullable type:

DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();

it is return String.Empty. Check this link for more details

Graph visualization library in JavaScript

In a commercial scenario, a serious contestant for sure is yFiles for HTML:

It offers:

  • Easy import of custom data (this interactive online demo seems to pretty much do exactly what the OP was looking for)
  • Interactive editing for creating and manipulating the diagrams through user gestures (see the complete editor)
  • A huge programming API for customizing each and every aspect of the library
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Does not depend on a specfic UI toolkit but supports integration into almost any existing Javascript toolkit (see the "integration" demos)
  • Automatic layout (various styles, like "hierarchic", "organic", "orthogonal", "tree", "circular", "radial", and more)
  • Automatic sophisticated edge routing (orthogonal and organic edge routing with obstacle avoidance)
  • Incremental and partial layout (adding and removing elements and only slightly or not at all changing the rest of the diagram)
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Implementations of graph analysis algorithms (paths, centralities, network flows, etc.)
  • Uses HTML 5 technologies like SVG+CSS and Canvas and modern Javascript leveraging properties and other more ES5 and ES6 features (but for the same reason will not run in IE versions 8 and lower).
  • Uses a modular API that can be loaded on-demand using UMD loaders

Here is a sample rendering that shows most of the requested features:

Screenshot of a sample rendering created by the BPMN demo.

Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.

The ternary (conditional) operator in C

It's crucial for code obfuscation, like this:

Look->       See?!

No
:(
Oh, well
);

What order are the Junit @Before/@After called?

I think based on the documentation of the @Before and @After the right conclusion is to give the methods unique names. I use the following pattern in my tests:

public abstract class AbstractBaseTest {

  @Before
  public final void baseSetUp() { // or any other meaningful name
    System.out.println("AbstractBaseTest.setUp");
  }

  @After
  public final void baseTearDown() { // or any other meaningful name
    System.out.println("AbstractBaseTest.tearDown");
  }
}

and

public class Test extends AbstractBaseTest {

  @Before
  public void setUp() {
    System.out.println("Test.setUp");
  }

  @After
  public void tearDown() {
    System.out.println("Test.tearDown");
  }

  @Test
  public void test1() throws Exception {
    System.out.println("test1");
  }

  @Test
  public void test2() throws Exception {
    System.out.println("test2");
  }
}

give as a result

AbstractBaseTest.setUp
Test.setUp
test1
Test.tearDown
AbstractBaseTest.tearDown
AbstractBaseTest.setUp
Test.setUp
test2
Test.tearDown
AbstractBaseTest.tearDown

Advantage of this approach: Users of the AbstractBaseTest class cannot override the setUp/tearDown methods by accident. If they want to, they need to know the exact name and can do it.

(Minor) disadvantage of this approach: Users cannot see that there are things happening before or after their setUp/tearDown. They need to know that these things are provided by the abstract class. But I assume that's the reason why they use the abstract class

How to add a new schema to sql server 2008?

Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.

IF NOT EXISTS (SELECT schema_name 
    FROM information_schema.schemata 
    WHERE schema_name = 'newSchemaName' )
BEGIN
    EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END

Why is the Android emulator so slow? How can we speed up the Android emulator?

The current (May 2011) version of the emulator is slow particularly with Android 3.0 (Honeycomb) primarily because the emulator does not support hardware GL -- this means that the GL code gets translated into software (ARM software, in fact) which then gets emulated in software in QEMU. This is crazy-slow. They're working on this problem and have it partially solved, but not with any sort of release quality.

Check out the video Google I/O 2011: Android Development Tools to see it in action -- jump to about 44 minutes.

Taskkill /f doesn't kill a process

I was getting the following results with taskkill

>taskkill /im "MyApp.exe" /t /f
ERROR: The process with PID 32040 (child process of PID 54176) could not be terminated.
Reason: There is no running instance of the task.

>taskkill /pid 54176  /t /f
ERROR: The process "54176" not found.

What worked for me was sysinternal's pskill

>pskill.exe -t 32040

PsKill v1.15 - Terminates processes on local or remote systems
Copyright (C) 1999-2012  Mark Russinovich
Sysinternals - www.sysinternals.com

Process 32040 killed.

You can get pskill from the sysinternal's live site

Format of the initialization string does not conform to specification starting at index 0

In my case the problem was that on the server, a different appsettings.json file was used by the application.

How to search for rows containing a substring?

Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Even if WHERE textcolumn LIKE "%SUBSTRING%" is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).

If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")

How do I add my bot to a channel?

This is how I've added a bot to my channel and set up notifications:

  1. Make sure the channel is public (you can set it private later)
  2. Add administrators > Type the bot username and make it administrator
  3. Your bot will join your channel
  4. set a channel id by setting the channel url like

telegram.me/whateverIWantAndAvailable

the channel id will be @whateverIWantAndAvailable

Now set up your bot to send notifications by pusshing the messages here:

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test

the message which bot will notify is: Test

I strongly suggest an urlencode of the message like

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works

in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");

I hope it helps

TypeError: $(...).on is not a function

The problem may be if you are using older version of jQuery. Because older versions of jQuery have 'live' method instead of 'on'

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

In my case,

I was trying to update my model by making a foreign key required, but the database had "null" data in it already in some columns from previously entered data. So every time i run update-database...i got the error.

I SOLVED it by manually deleting from the database all rows that had null in the column i was making required.

Why am I getting a FileNotFoundError?

Is test.rtf located in the same directory you're in when you run this?

If not, you'll need to provide the full path to that file.

Suppose it's located in

/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data

In that case you'd enter

data/test.rtf

as your file name

Or it could be in

/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder

In that case you'd enter

../some_other_folder/test.rtf

How to read a string one letter at a time in python

Use 'index'.

def GetMorseCode(letter):
   index = letterList.index(letter)
   code = codeList[index]
   return code

Of course, you'll want to validate your input letter (convert its case as necessary, make sure it's in the list in the first place by checking that index != -1), but that should get you down the path.

Android and setting width and height programmatically in dp units

simplest way(and even works from api 1) that tested is:

getResources().getDimensionPixelSize(R.dimen.example_dimen);

From documentations:

Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.

How to pass a single object[] to a params object[]

new[] { (object) 0, (object) null, (object) false }

How to get MAC address of your machine using a C program?

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

int main()
{
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, "eth0");
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;
    for (i = 0; i < 6; ++i)
      printf(" %02x", (unsigned char) s.ifr_addr.sa_data[i]);
    puts("\n");
    return 0;
  }
  return 1;
}

How to shift a column in Pandas DataFrame

Trying to answer a personal problem and similar to yours I found on Pandas Doc what I think would answer this question:

DataFrame.shift(periods=1, freq=None, axis=0) Shift index by desired number of periods with an optional time freq

Notes

If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would like to extend the index when shifting and preserve the original data.

Hope to help future questions in this matter.

change cursor to finger pointer

I think the "best answer" above, albeit programmatically accurate, does not actually answer the question posed. the question asks how to change the pointer in the mouseover event. I see posts about how one may have an error somewhere is not answering the question. In the accepted answer, the mouseover event is blank (onmouseover="") and the style option, instead, is included. Baffling why this was done.

There may be nothing wrong with the inquirer's link. consider the following html:

<a id=test_link onclick="alert('kinda neat);">Click ME!</a>

When a user mouse's over this link, the pointer will not change to a hand...instead, the pointer will behave like it's hovering over normal text. One might not want this...and so, the mouse pointer needs to be told to change.

the answer being sought for is this (which was posted by another):

<a id=test_link onclick="alert('Nice!');"
       onmouseover="this.style.cursor='pointer';">Click ME!</a>

However, this is ... a nightmare if you have lots of these, or use this kind of thing all over the place and decide to make some kind of a change or run into a bug. better to make a CSS class for it:

a.lendhand {
  cursor: pointer;
}

then:

<a class=lendhand onclick="alert('hand is lent!');">Click ME!</a>

there are many other ways which would be, arguably, better than this method. DIVs, BUTTONs, IMGs, etc might prove more useful. I see no harm in using <a>...</a>, though.

jarett.

Case Insensitive String comp in C

static int ignoreCaseComp (const char *str1, const char *str2, int length)
{
    int k;
    for (k = 0; k < length; k++)
    {

        if ((str1[k] | 32) != (str2[k] | 32))
            break;
    }

    if (k != length)
        return 1;
    return 0;
}

Reference

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

I bumped into this problem lately with Windows 10 from another direction, and found the answer from @JonSkeet very helpful in solving my problem.

I also did som further research with a test form and found that when the the current culture was set to "no" or "nb-NO" at runtime (Thread.CurrentThread.CurrentCulture = new CultureInfo("no");), the ToString("yyyy-MM-dd HH:mm:ss") call responded differently in Windows 7 and Windows 10. It returned what I expected in Windows 7 and HH.mm.ss in Windows 10!

I think this is a bit scary! Since I believed that a culture was a culture in any Windows version at least.

Make more than one chart in same IPython Notebook cell

Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.

df.plot(subplots=True)

If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].

How to create Haar Cascade (.xml file) to use in OpenCV?

How to create CascadeClassifier :

  1. Open this link : https://github.com/opencv/opencv/tree/master/data/haarcascades
  2. Right click on where you find "haarcascade_frontalface_default.xml"
  3. Click on "Save link as"
  4. Save it into the same folder in which your file is.
  5. Include this line in your file face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

How to create a windows service from java app

Yet another answer is Yet Another Java Service Wrapper, this seems like a good alternative to Java Service Wrapper as has better licensing. It is also intended to be easy to move from JSW to YAJSW. Certainly for me, brand new to windows servers and trying to get a Java app running as a service, it was very easy to use.

Some others I found, but didn't end up using:

  • Java Service Launcher I didn't use this because it looked more complicated to get working than YAJSW. I don't think this is a wrapper.
  • JSmooth Creating Window's services isn't its primary goal, but can be done. I didn't use this because there's been no activity since 2007.

How do I import .sql files into SQLite 3?

Use sqlite3 database.sqlite3 < db.sql. You'll need to make sure that your files contain valid SQL for SQLite.

error LNK2005, already defined?

The linker tells you that you have the variable k defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k to use. In C++ you can have only one defintion of the same construct (variable, type, function).

To fix it, you will have to decide what your goal is

  • If you want to have two variables, both named k, you can use an anonymous namespace in both .cpp files, then refer to k as you are doing now:

.

namespace {
  int k;
}
  • You can rename one of the ks to something else, thus avoiding the duplicate defintion.
  • If you want to have only once definition of k and use that in both .cpp files, you need to declare in one as extern int k;, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern implies that the variable is defined in another compilation unit.

How to build and use Google TensorFlow C++ api

If you don't mind using CMake, there is also tensorflow_cc project that builds and installs TF C++ API for you, along with convenient CMake targets you can link against. The project README contains an example and Dockerfiles you can easily follow.

CSS root directory

In the CSS all you have to do is put url(logical path to the image file)

How do you add an SDK to Android Studio?

For those starting with an existing IDEA installation (IDEA 15 in my case) to which they're adding the Android SDK (and not starting formally speaking with Android Studio), ...

Download (just) the SDK to your filesystem (somewhere convenient to you; it doesn't matter where).

When creating your first project and you get to the Project SDK: bit (or adding the Android SDK ahead of time as you wish), navigate (New) to the root of what you exploded into the filesystem as suggested by some of the other answers here.

At that point you'll get a tiny dialog to confirm with:

Java SDK:     1.7            (e.g.)
Build target: Android 6.0    (e.g.)

You can click OK whereupon you'll see what you did as an option in the Project SDK: drop-down, e.g.:

Android API 23 Platform (java version "1.7.0_67")

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

accessing a docker container from another container

Using docker-compose, services are exposed to each other by name by default. Docs.
You could also specify an alias like;

version: '2.1'
services:
  mongo:
    image: mongo:3.2.11
  redis:
    image: redis:3.2.10
  api:
    image: some-image
    depends_on:
      - mongo
      - solr
    links:
      - "mongo:mongo.openconceptlab.org"
      - "solr:solr.openconceptlab.org"
      - "some-service:some-alias"

And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org for mongo in this case.

Cloning an Object in Node.js

Looking for a true clone option, I stumbled across ridcully's link to here:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:

Object.defineProperty(Object.prototype, 'clone', {
    enumerable: false,
    value: function() {
        var newObj = (this instanceof Array) ? [] : {};
        for (i in this) {
        if (i == 'clone') continue;
            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            } else newObj[i] = this[i]
        } return newObj;
    }
});

Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

use request.getContextPath() instead of ${pageContext.request.contextPath} in JSP expression language.

<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);

output: willPrintMyProjectcontextPath

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

I had trouble finding the applicationhost.config file. It was in c:\windows\System32\inetsrv\ (Server2008) or the c:\windows\System32\inetsrv\config\ (Server2008r2).

After I changed that setting, I also had to change the way IIS loads the aspnet_filter.dll. Open the IIS Manager, go under "Sites", "SharePoint - 80", in the "IIS" grouping, under the "ISAPI Filters", make sure that all of the "Executable" paths point to ...Microsoft.NET\Framework64\v#.#.####\aspnet_filter.dll. Some of mine were pointed to the \Framework\ (not 64).

You also need to restart the WWW service to reload the new settings.

How to log out user from web site using BASIC authentication?

This JavaScript must be working for all latest version browsers:

//Detect Browser
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
var Host = window.location.host;


//Clear Basic Realm Authentication
if(isIE){
//IE
    document.execCommand("ClearAuthenticationCache");
    window.location = '/';
}
else if(isSafari)
{//Safari. but this works mostly on all browser except chrome
    (function(safeLocation){
        var outcome, u, m = "You should be logged out now.";
        // IE has a simple solution for it - API:
        try { outcome = document.execCommand("ClearAuthenticationCache") }catch(e){}
        // Other browsers need a larger solution - AJAX call with special user name - 'logout'.
        if (!outcome) {
            // Let's create an xmlhttp object
            outcome = (function(x){
                if (x) {
                    // the reason we use "random" value for password is 
                    // that browsers cache requests. changing
                    // password effectively behaves like cache-busing.
                    x.open("HEAD", safeLocation || location.href, true, "logout", (new Date()).getTime().toString())
                    x.send("");
                    // x.abort()
                    return 1 // this is **speculative** "We are done." 
                } else {
                    return
                }
            })(window.XMLHttpRequest ? new window.XMLHttpRequest() : ( window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : u )) 
        }
        if (!outcome) {
            m = "Your browser is too old or too weird to support log out functionality. Close all windows and restart the browser."
        }
        alert(m);
        window.location = '/';
        // return !!outcome
    })(/*if present URI does not return 200 OK for GET, set some other 200 OK location here*/)
}
else{
//Firefox,Chrome
    window.location = 'http://log:out@'+Host+'/';
}

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

how to get the first and last days of a given month

You might want to look at the strtotime and date functions.

<?php

$query_date = '2010-02-04';

// First day of the month.
echo date('Y-m-01', strtotime($query_date));

// Last day of the month.
echo date('Y-m-t', strtotime($query_date));

Add custom message to thrown exception while maintaining stack trace in Java

Following code is a simple example that worked for me.Let me call the function main as parent function and divide as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

class Main {
    public static void main(String args[]) {
        try{
            long ans=divide(0);
            System.out.println("answer="+ans);
        }
        catch(Exception e){
            System.out.println("got exception:"+e.getMessage());

        }

    }
    public static long divide(int num) throws Exception{
        long x=-1;
        try {
            x=5/num;
        }
        catch (Exception e){
            throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
        }
        return x;
    }
}  

the last line return x will not run if error occurs somewhere in between.

A KeyValuePair in Java

The class AbstractMap.SimpleEntry is generic and can be useful.

Capturing mobile phone traffic on Wireshark

For iOS Devices:

? Open Terminal and simply write:

rvictl -s udid

it'll open an interface on Wireshark with a name, In my case its rvi0.

enter image description here

udid is iPhone's unique device id.

(How to find my iOS Device UDID)

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I was using jdk1.8.0_171 when I faced the same issue. I tried top 2 solutions here (adding a certificate using keytool and another solution which has a hack in it) but they didn't work for me.

I upgraded my JDK to 1.8.0_181 and it worked like a charm.

"Unknown class <MyClass> in Interface Builder file" error at runtime

Go to Build Phases-> Compile Sources and add your new .m files.

How do I make a checkbox required on an ASP.NET form?

If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control

public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
    private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
    protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
    {
        get
        {
            if (_ctrlToValidate == null)
                _ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;

            return _ctrlToValidate;
        }
    }

    protected override bool ControlPropertiesValid()
    {
        if (this.ControlToValidate.Length == 0)
            throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));

        if (this.CheckBoxToValidate == null)
            throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));

        return true;
    }

    protected override bool EvaluateIsValid()
    {
        return CheckBoxToValidate.Checked;
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (this.Visible && this.Enabled)
        {
            System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
            if (this.DetermineRenderUplevel() && this.EnableClientScript)
            {
                cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
            }
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
            {
                cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
            } 
        }
    }

    private string GetClientSideScript()
    {
        return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
    }
}

What is meant by Ems? (Android TextView)

em is the typography unit of font width. one em in a 16-point typeface is 16 points

Error in finding last used cell in Excel with VBA

Find Last Row in a Column OR a Table Column(ListObject) by range

Finding the last row requires:

  1. Specifying several parameters (table name, column inside table relative to first column, worksheet, range).
  2. May require switching between methods. e.g. if the range is a Table (List Object) or not. Using the wrong search type will return wrong results.

This proposed solution is more general, requires only the range ,less chance of typos and is short (just calling MyLastRow function).

Sub test()
Dim rng As Range
Dim Result As Long
Set rng = Worksheets(1).Range("D4")
Result = MyLastRow(rng)
End Sub
    Function MyLastRow(FirstRow As Range) As Long
    Dim WS As Worksheet
    Dim TableName As String
    Dim ColNumber As Long
    Dim LastRow As Long
    Dim FirstColumnTable As Long
    Dim ColNumberTable As Long
    Set WS = FirstRow.Worksheet
    TableName = GetTableName(FirstRow)
    ColNumber = FirstRow.Column
    
    ''If the table (ListObject) does not start in column "A" we need to calculate the 
    ''first Column table and how many Columns from its beginning the Column is located.
    If TableName <> vbNullString Then
     FirstColumnTable = WS.ListObjects(TableName).ListColumns(1).Range.Column
     ColNumberTable = ColNumber - FirstColumnTable + 1
    End If 

    If TableName = vbNullString Then
    LastRow = WS.Cells(WS.Rows.Count, ColNumber).End(xlUp).Row
    Else
    LastRow = WS.ListObjects(TableName).ListColumns(ColNumberTable).Range.Find( _
               What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
    MyLastRow = LastRow
    End Function
    
    ''Get Table Name by Cell Range
    Function GetTableName(CellRange As Range) As String
        If CellRange.ListObject Is Nothing Then
            GetTableName = vbNullString
        Else
            GetTableName = CellRange.ListObject.Name
        End If
    End Function

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

How to import image (.svg, .png ) in a React Component

There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config

_x000D_
_x000D_
{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
}
_x000D_
_x000D_
_x000D_

, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside

_x000D_
_x000D_
declare module '*.jpg';
declare module '*.png';
_x000D_
_x000D_
_x000D_

,then restart dev-server. After these steps we can import and use images like in code bellow

_x000D_
_x000D_
import React from 'react';
import image from './img1.png';
import './helloWorld.scss';

const HelloWorld = () => (
  <>
    <h1 className="main">React TypeScript Starter</h1>
        <img src={image} alt="some example image" />
  </>
);
export default HelloWorld;
_x000D_
_x000D_
_x000D_

Works in typescript and also in javacript,just change extension from .ts to .js

Cheers.

What is a plain English explanation of "Big O" notation?

Big O describes an upper limit on the growth behaviour of a function, for example the runtime of a program, when inputs become large.

Examples:

  • O(n): If I double the input size the runtime doubles

  • O(n2): If the input size doubles the runtime quadruples

  • O(log n): If the input size doubles the runtime increases by one

  • O(2n): If the input size increases by one, the runtime doubles

The input size is usually the space in bits needed to represent the input.

How do you automatically set the focus to a textbox when a web page loads?

IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:

$(document).ready(function() {
  $('input:text[value=""]:visible:enabled:first').focus();
});

Hope that helps...

Thanks...

How can I generate a list of files with their absolute path in Linux?

Use this for dirs (the / after ** is needed in bash to limit it to directories):

ls -d -1 "$PWD/"**/

this for files and directories directly under the current directory, whose names contain a .:

ls -d -1 "$PWD/"*.*

this for everything:

ls -d -1 "$PWD/"**/*

Taken from here http://www.zsh.org/mla/users/2002/msg00033.html

In bash, ** is recursive if you enable shopt -s globstar.

How to check if a specific key is present in a hash or not?

In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:

YourHash.has_key? :yourkey

getting the error: expected identifier or ‘(’ before ‘{’ token

you need to place the opening brace after main , not before it

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

Auto height div with overflow and scroll when needed

You can do this assignment easily by using jquery. In this way, you can define number of row limitation. Furthermore, you can regular breakpoints height that want adding vertical scrolling. I must say that more than 3 rows get modify class and also height is 76px.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var length = $(this).find('li').length;_x000D_
  if (length > 3) {_x000D_
    $(".parent").addClass('modify');_x000D_
  }_x000D_
})
_x000D_
/*for beauty*/_x000D_
_x000D_
ul {_x000D_
  margin: 0 auto;_x000D_
  width: 50%;_x000D_
  border: 1px solid #ccc;_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  padding: 3px;_x000D_
  background: #ccc;_x000D_
  margin: 2px 0;_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
/*main class*/_x000D_
_x000D_
.modify {_x000D_
  overflow-y: scroll;_x000D_
  height: 76px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul class="parent">_x000D_
  <li>item 1</li>_x000D_
  <li>item 2</li>_x000D_
  <li>item 3</li>_x000D_
  <li>item 4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Determine when a ViewPager changes pages

You can also use ViewPager.SimpleOnPageChangeListener instead of ViewPager.OnPageChangeListener and override only those methods you want to use.

viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

    // optional 
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

    // optional 
    @Override
    public void onPageSelected(int position) { }

    // optional 
    @Override
    public void onPageScrollStateChanged(int state) { }
});

Hope this help :)

Edit: As per android APIs, setOnPageChangeListener (ViewPager.OnPageChangeListener listener) is deprecated. Please check this url:- Android ViewPager API

HTML button to NOT submit form

By default, html buttons submit a form.

This is due to the fact that even buttons located outside of a form act as submitters (see the W3Schools website: http://www.w3schools.com/tags/att_button_form.asp)

In other words, the button type is "submit" by default

<button type="submit">Button Text</button>

Therefore an easy way to get around this is to use the button type.

<button type="button">Button Text</button>

Other options include returning false at the end of the onclick or any other handler for when the button is clicked, or to using an < input> tag instead

To find out more, check out the Mozilla Developer Network's information on buttons: https://developer.mozilla.org/en/docs/Web/HTML/Element/button

Module not found: Error: Can't resolve 'core-js/es6'

After Migrated to Angular8, core-js/es6 or core-js/es7 Will not work.

You have to simply replace import core-js/es/

For ex.

import 'core-js/es6/symbol'  

to

import 'core-js/es/symbol'

This will work properly.

Copy directory to another directory using ADD command

Indeed ADD go /usr/local/ will add content of go folder and not the folder itself, you can use Thomasleveil solution or if that did not work for some reason you can change WORKDIR to /usr/local/ then add your directory to it like:

WORKDIR /usr/local/
COPY go go/

or

WORKDIR /usr/local/go
COPY go ./

But if you want to add multiple folders, it will be annoying to add them like that, the only solution for now as I see it from my current issue is using COPY . . and exclude all unwanted directories and files in .dockerignore, let's say I got folders and files:

- src 
- tmp 
- dist 
- assets 
- go 
- justforfun 
- node_modules 
- scripts 
- .dockerignore 
- Dockerfile 
- headache.lock 
- package.json 

and I want to add src assets package.json justforfun go so:

in Dockerfile:

FROM galaxy:latest

WORKDIR /usr/local/
COPY . .

in .dockerignore file:

node_modules
headache.lock
tmp
dist

Or for more fun (or you like to confuse more people make them suffer as well :P) can be:

*
!src 
!assets 
!go 
!justforfun 
!scripts 
!package.json 

In this way you ignore everything, but excluding what you want to be copied or added only from "ignore list".

It is a late answer but adding more ways to do the same covering even more cases.

Label points in geom_point

The ggrepel package works great for repelling overlapping text labels away from each other. You can use either geom_label_repel() (draws rectangles around the text) or geom_text_repel() functions.

library(ggplot2)
library(ggrepel)

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv", sep = ",")

nbaplot <- ggplot(nba, aes(x= MIN, y = PTS)) + 
  geom_point(color = "blue", size = 3)

### geom_label_repel
nbaplot + 
  geom_label_repel(aes(label = Name),
                  box.padding   = 0.35, 
                  point.padding = 0.5,
                  segment.color = 'grey50') +
  theme_classic()

enter image description here

### geom_text_repel
# only label players with PTS > 25 or < 18
# align text vertically with nudge_y and allow the labels to 
# move horizontally with direction = "x"
ggplot(nba, aes(x= MIN, y = PTS, label = Name)) + 
  geom_point(color = dplyr::case_when(nba$PTS > 25 ~ "#1b9e77", 
                                      nba$PTS < 18 ~ "#d95f02",
                                      TRUE ~ "#7570b3"), 
             size = 3, alpha = 0.8) +
  geom_text_repel(data          = subset(nba, PTS > 25),
                  nudge_y       = 32 - subset(nba, PTS > 25)$PTS,
                  size          = 4,
                  box.padding   = 1.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  geom_label_repel(data         = subset(nba, PTS < 18),
                  nudge_y       = 16 - subset(nba, PTS < 18)$PTS,
                  size          = 4,
                  box.padding   = 0.5,
                  point.padding = 0.5,
                  force         = 100,
                  segment.size  = 0.2,
                  segment.color = "grey50",
                  direction     = "x") +
  scale_x_continuous(expand = expand_scale(mult = c(0.2, .2))) +
  scale_y_continuous(expand = expand_scale(mult = c(0.1, .1))) +
  theme_classic(base_size = 16)

Edit: To use ggrepel with lines, see this and this.

Created on 2019-05-01 by the reprex package (v0.2.0).

How to delete and update a record in Hive

Delete has been recently added in Hive version 0.14 Deletes can only be performed on tables that support ACID Below is the link from Apache .

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Delete

Anchor links in Angularjs?

You can also Navigate to HTML id from inside controller

$location.hash('id_in_html');

Node Sass couldn't find a binding for your current environment

This happens when in your workstation you run an update of Node.js and you are using node-sass globally.

So you should uninstall node-sass globally

npm uninstall -g node-sass

And then you have to install it globally, again

npm install -g node-sass

How to convert a normal Git repository to a bare one?

Here's what I think is safest and simplest. There is nothing here not stated above. I just want to see an answer that shows a safe step-by-step procedure. You start one folder up from the repository (repo) you want to make bare. I've adopted the convention implied above that bare repository folders have a .git extension.

(1) Backup, just in case.
    (a) > mkdir backup
    (b) > cd backup
    (c) > git clone ../repo
(2) Make it bare, then move it
    (a) > cd ../repo
    (b) > git config --bool core.bare true
    (c) > mv .git ../repo.git
(3) Confirm the bare repository works (optional, since we have a backup)
    (a) > cd ..
    (b) > mkdir test
    (c) > cd test
    (d) > git clone ../repo.git
(4) Clean up
    (a) > rm -Rf repo
    (b) (optional) > rm -Rf backup/repo
    (c) (optional) > rm -Rf test/repo

MySQL query String contains

Quite simple actually:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");

The % is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.

retrieve data from db and display it in table in php .. see this code whats wrong with it?

This is a very simple code I use and you manipulate it to change the colour and size of the table as you see fit.

First connect to the database:

<?php
$connect=mysql_connect('localhost', 'root', 'password');

mysql_select_db("name");
//here u select the data you want to retrieve from the db

$query="select * from tablename";

$result= mysql_query($query);

//here you check to see if any data has been found and you define the width of the table

If($result){

echo "<table width ='340' align='left'>
      <tr color ='#5D9951>";
$i=0;

    If(mysql_num_rows($result)>0)
    {
         //here you fetch the data from the database and print it in the respective columns   
        while($i<mysql_num_fields($result))
        {    
             echo "<th>".mysql_field_name($result, $i)."</th>";
             $i++;
        }
        echo "</tr>";

        $color=1;

        while($rows=mysql_fetch_array($result, MYSQL_ASSOC))
        {    
            If ($color==1){
                echo "<tr color='#'#cccccc'>";

                foreach ($rows as $data){
                    echo "<td align='center'>".$data. "</td>";
                }

                $color=2;
            }
            $color=1;
        }
     } else {
        echo"no results found";
        echo "</table>";
    } else {
        echo "error running query:".MYSQL_error();
}
?>

It's a very elementary piece of code but it helps if you are not used to using functions.

Which is faster: Stack allocation or Heap allocation

Aside from the orders-of-magnitude performance advantage over heap allocation, stack allocation is preferable for long running server applications. Even the best managed heaps eventually get so fragmented that application performance degrades.

Git Symlinks in Windows

For those using CygWin on Vista, Win7, or above, the native git command can create "proper" symlinks that are recognized by Windows apps such as Android Studio. You just need to set the CYGWIN environment variable to include winsymlinks:native or winsymlinks:nativestrict as such:

export CYGWIN="$CYGWIN winsymlinks:native"

The downside to this (and a significant one at that) is that the CygWin shell has to be "Run as Administrator" in order for it to have the OS permissions required to create those kind of symlinks. Once they're created, though, no special permissions are required to use them. As long they aren't changed in the repository by another developer, git thereafter runs fine with normal user permissions.

Personally, I use this only for symlinks that are navigated by Windows apps (i.e. non-CygWin) because of this added difficulty.

For more information on this option, see this SO question: How to make symbolic link with cygwin in Windows 7

Store mysql query output into a shell variable

Another example when the table name or database contains unsupported characters such as a space, or '-'

db='data-base'

db_d=''
db_d+='`'
db_d+=$db
db_d+='`'

myvariable=`mysql --user=$user --password=$password -e "SELECT A, B, C FROM $db_d.table_a;"`

How to clear or stop timeInterval in angularjs?

When you want to create interval store promise to variable:

var p = $interval(function() { ... },1000);

And when you want to stop / clear the interval simply use:

$interval.cancel(p);

How to open Atom editor from command line in OS X?

Iv'e noticed this recently with all new macs here at my office. Atom will be installed via an image for the developers but we found the Atom is never in the Application folder.

When doing a ls on the /usr/local/bin folder the path for atom will show something like "/private/var/folders/cs" . To resolve this, we just located atom.app and copied it into the application folder, then ran the system link commands provided by nwinkler which resoled the issue. Developers can now open atom from the command line with "atom" or open the current projects from their working director with "atom ."

bash: pip: command not found

The updated command for installing pip3 is :

sudo apt-get install python3-pip

How to get form values in Symfony2 controller

I got it working by this:

if ($request->getMethod() == 'POST') {
    $username = $request->request->get('username');
    $password = $request->request->get('password');

    // Do something with the post data
}

You need to have the Request $request as a parameter in the function too! Hope this helps.

Cannot open new Jupyter Notebook [Permission Denied]

change the ownership of the ~/.local/share/jupyter directory from root to user.

sudo chown -R user:user ~/.local/share/jupyter 

see here: https://github.com/ipython/ipython/issues/8997

The first user before the colon is your username, the second user after the colon is your group. If you get chown: [user]: illegal group name, find your group with groups, or specify no group with sudo chown user: ~/.local/share/jupyter.

EDIT: Added -R option in comments to the answer. You have to change ownership of all files inside this directory (or inside ~/.jupyter/, wherever it gives you PermissionError) to your user to make it work.

Tool to convert java to c# code

Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.

Better way to remove specific characters from a Perl string

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

Why I can't access remote Jupyter Notebook server?

Anyone who is still stuck - follow the instructions on this page.

Basically:

  1. Follow the steps as initially described by AWS.

    1. Open SSH as normal.
    2. source activate python3
    3. Jupyter Notebook
  2. Don't cut and paste anything. Instead open a new terminal window without closing the first one.

  3. In the new window enter enter the SSH command as described in the above link.

  4. Open a web browser and go to http://127.0.0.1:8157

Iterate over values of object

In case you want to deeply iterate into a complex (nested) object for each key & value, you can do so using Object.keys():

const iterate = (obj) => {
    Object.keys(obj).forEach(key => {

    console.log(`key: ${key}, value: ${obj[key]}`)

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
        }
    })
}

How can I check for NaN values?

here is an answer working with:

  • NaN implementations respecting IEEE 754 standard
    • ie: python's NaN: float('nan'), numpy.nan...
  • any other objects: string or whatever (does not raise exceptions if encountered)

A NaN implemented following the standard, is the only value for which the inequality comparison with itself should return True:

def is_nan(x):
    return (x != x)

And some examples:

import numpy as np
values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
    print(f"{repr(value):<8} : {is_nan(value)}")

Output:

nan      : True
nan      : True
55       : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False

How to check if a Unix .tar.gz file is a valid file without uncompressing?

I have tried the following command and they work well.

bzip2 -t file.bz2
gunzip -t file.gz

However, we can found these two command are time-consuming. Maybe we need some more quick way to determine the intact of the compress files.

Drop-down menu that opens up/upward with pure css

If we are use chosen dropdown list, then we can use below css(No JS/JQuery require)

<select chosen="{width: '100%'}" ng- 
   model="modelName" class="form-control input- 
   sm"
   ng- 
   options="persons.persons as 
   persons.persons for persons in 
   jsonData"
   ng- 
   change="anyFunction(anyParam)" 
   required>
   <option value=""> </option>
</select>
<style>   
.chosen-container .chosen-drop {
    border-bottom: 0;
    border-top: 1px solid #aaa;
    top: auto;
    bottom: 40px;
}

.chosen-container.chosen-with-drop .chosen-single {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px;

    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;

    background-image: none;
}

.chosen-container.chosen-with-drop .chosen-drop {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px;

    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    box-shadow: none;

    margin-bottom: -16px;
}
</style>

HttpListener Access Denied

As an alternative that doesn't require elevation or netsh you could also use TcpListener for instance.

The following is a modified excerpt of this sample: https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp

// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";

// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);

// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
    authorizationEndpoint,
    System.Uri.EscapeDataString(redirectURI),
    clientID,
    state,
    code_challenge,
    code_challenge_method);

// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);

// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();

// Read response.
var response = ReadString(client);

// Brings this app back to the foreground.
this.Activate();

// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
    client.Dispose();
    listener.Stop();

    Console.WriteLine("HTTP server stopped.");
});

// TODO: Check the response here to get the authorization code and verify the code challenge

The read and write methods being:

private string ReadString(TcpClient client)
{
    var readBuffer = new byte[client.ReceiveBufferSize];
    string fullServerReply = null;

    using (var inStream = new MemoryStream())
    {
        var stream = client.GetStream();

        while (stream.DataAvailable)
        {
            var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
            if (numberOfBytesRead <= 0)
                break;

            inStream.Write(readBuffer, 0, numberOfBytesRead);
        }

        fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
    }

    return fullServerReply;
}

private Task WriteStringAsync(TcpClient client, string str)
{
    return Task.Run(() =>
    {
        using (var writer = new StreamWriter(client.GetStream(), new UTF8Encoding(false)))
        {
            writer.Write("HTTP/1.0 200 OK");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Type: text/html; charset=UTF-8");
            writer.Write(Environment.NewLine);
            writer.Write("Content-Length: " + str.Length);
            writer.Write(Environment.NewLine);
            writer.Write(Environment.NewLine);
            writer.Write(str);
        }
    });
}

'ssh-keygen' is not recognized as an internal or external command

If you have installed Git, and is installed at C:\Program Files, follow as below

  1. Go to "C:\Program Files\Git"
  2. Run git-bash.exe, this opens a new window
  3. In the new bash window, run "ssh-keygen -t rsa -C""
  4. It prompts for file in which to save key, dont input any value - just press enter
  5. Same for passphrase (twice), just press enter
  6. id_rsa and id_rsa.pub will be generated in your home folder under .ssh

How to catch integer(0)?

Inspired by Andrie's answer, you could use identical and avoid any attribute problems by using the fact that it is the empty set of that class of object and combine it with an element of that class:

attr(a, "foo") <- "bar"

identical(1L, c(a, 1L))
#> [1] TRUE

Or more generally:

is.empty <- function(x, mode = NULL){
    if (is.null(mode)) mode <- class(x)
    identical(vector(mode, 1), c(x, vector(class(x), 1)))
}

b <- numeric(0)

is.empty(a)
#> [1] TRUE
is.empty(a,"numeric")
#> [1] FALSE
is.empty(b)
#> [1] TRUE
is.empty(b,"integer")
#> [1] FALSE

String replace method is not replacing characters

package com.tulu.ds;

public class EmailSecurity {
    public static void main(String[] args) {
        System.out.println(returnSecuredEmailID("[email protected]"));
    }
    private static String returnSecuredEmailID(String email){
        String str=email.substring(1, email.lastIndexOf("@")-1);
        return email.replaceAll(email.substring(1, email.lastIndexOf("@")-1),replacewith(str.length(),"*"));
    }
    private static String replacewith(int length,String replace) {
        String finalStr="";
        for(int i=0;i<length;i++){
            finalStr+=replace;
        }
        return finalStr;
    }   
}

CALL command vs. START with /WAIT option

Call

Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call. Call has no effect at the command-line when used outside of a script or batch file. https://technet.microsoft.com/en-us/library/bb490873.aspx

Start

Starts a separate Command Prompt window to run a specified program or command. Used without parameters, start opens a second command prompt window. https://technet.microsoft.com/en-us/library/bb491005.aspx

Java: Instanceof and Generics

The error message says it all. At runtime, the type is gone, there is no way to check for it.

You could catch it by making a factory for your object like this:

 public static <T> MyObject<T> createMyObject(Class<T> type) {
    return new MyObject<T>(type);
 }

And then in the object's constructor store that type, so variable so that your method could look like this:

        if (arg0 != null && !(this.type.isAssignableFrom(arg0.getClass()))
        {
            return -1;
        }

List distinct values in a vector in R

another way would be to use dplyr package:

x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))

How to list the files in current directory?

There is nothing wrong with your code. It should list all of the files and directories directly contained by the nominated directory.

The problem is most likely one of the following:

  • The "." directory is not what you expect it to be. The "." pathname actually means the "current directory" or "working directory" for the JVM. You can verify what directory "." actually is by printing out dir.getCanonicalPath().

  • You are misunderstanding what dir.listFiles() returns. It doesn't return all objects in the tree beneath dir. It only returns objects (files, directories, symlinks, etc) that are directly in dir.

The ".classpath" file suggests that you are looking at an Eclipse project directory, and Eclipse projects are normally configured with the Java files in a subdirectory such as "./src". I wouldn't expect to see any Java source code in the "." directory.


Can anyone explain to me why src isn't the current folder?"

Assuming that you are launching an application in Eclipse, then the current folder defaults to the project directory. You can change the default current directory via one of the panels in the Launcher configuration wizard.

Adding an external directory to Tomcat classpath

Just specify it in shared.loader or common.loader property of /conf/catalina.properties.

Redirect on select option in select box

to make it as globally reuse function using jquery

HTML

<select class="select_location">
   <option value="http://localhost.com/app/page1.html">Page 1</option>
   <option value="http://localhost.com/app/page2.html">Page 2</option>
   <option value="http://localhost.com/app/page3.html">Page 3</option>
</select>

Javascript using jquery

$('.select_location').on('change', function(){
   window.location = $(this).val();
});

now you will able to reuse this function by adding .select_location class to any Select element class

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

The normal way of doing it is:

  • You get the users from the database in controller.
  • You send a collection of users to the View
  • In the view to loop the list of users building the list.

You don't need a JsonResult or jQuery for this.

Command prompt won't change directory to another drive

As @nasreddine answered or you can use /d

cd /d d:\Docs\Java

For more help on the cd command use:

C:\Documents and Settings\kenny>help cd

Displays the name of or changes the current directory.

CHDIR [/D] [drive:][path] CHDIR [..] CD [/D] [drive:][path] CD [..]

.. Specifies that you want to change to the parent directory.

Type CD drive: to display the current directory in the specified drive. Type CD without parameters to display the current drive and directory.

Use the /D switch to change current drive in addition to changing current directory for a drive.

If Command Extensions are enabled CHDIR changes as follows:

The current directory string is converted to use the same case as the on disk names. So CD C:\TEMP would actually set the current directory to C:\Temp if that is the case on disk.

CHDIR command does not treat spaces as delimiters, so it is possible to CD into a subdirectory name that contains a space without surrounding the name with quotes. For example:

cd \winnt\profiles\username\programs\start menu

is the same as:

cd "\winnt\profiles\username\programs\start menu"

which is what you would have to type if extensions were disabled.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

What does %>% function mean in R?

%>% is similar to pipe in Unix. For example, in

a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()

the output of combined_data_set will go into group_by and its output will go into tally, then the final output is assigned to a.

This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.

What's the reason I can't create generic array types in Java?

If the class uses as a parameterized type, it can declare an array of type T[], but it cannot directly instantiate such an array. Instead, a common approach is to instantiate an array of type Object[], and then make a narrowing cast to type T[], as shown in the following:

  public class Portfolio<T> {
  T[] data;
 public Portfolio(int capacity) {
   data = new T[capacity];                 // illegal; compiler error
   data = (T[]) new Object[capacity];      // legal, but compiler warning
 }
 public T get(int index) { return data[index]; }
 public void set(int index, T element) { data[index] = element; }
}

Compare two dates in Java

It works best....

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

cal1.setTime(date1);
cal2.setTime(date2);

boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);

Why must wait() always be in synchronized block

When you call notify() from an object t, java notifies a particular t.wait() method. But, how does java search and notify a particular wait method.

java only looks into the synchronized block of code which was locked by object t. java cannot search the whole code to notify a particular t.wait().

How to get the width and height of an android.widget.ImageView?

your xml file :

 <ImageView android:id="@+id/imageView"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:src="@drawable/image"
               android:scaleType="fitXY"
               android:adjustViewBounds="true"/>

your java file:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
     int width = imageView.getDrawable().getIntrinsicWidth();
     int   height = imageView.getDrawable().getIntrinsicHeight();

Disable ScrollView Programmatically?

Several points to begin with:

  1. You cannot disable the scrolling of a ScrollView. You would need to extend to ScrollView and override the onTouchEvent method to return false when some condition is matched.
  2. The Gallery component scrolls horizontally regardless of whether it is in a ScrollView or not - a ScrollView provides only vertical scrolling (you need a HorizontalScrollView for horizontal scrolling)
  3. You seem to say you have a problem with the image stretching itself -- this has nothing to do with the ScrollView, you can change how an ImageView scales with the android:scaleType property (XML) or the setScaleType method - for instance ScaleType.CENTER will not stretch your image and will center it at it's original size

You could modify ScrollView as follows to disable scrolling

class LockableScrollView extends ScrollView {

    ...

    // true if we can scroll (not locked)
    // false if we cannot scroll (locked)
    private boolean mScrollable = true;

    public void setScrollingEnabled(boolean enabled) {
        mScrollable = enabled;
    }

    public boolean isScrollable() {
        return mScrollable;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // if we can scroll pass the event to the superclass
                return mScrollable && super.onTouchEvent(ev);
            default:
                return super.onTouchEvent(ev);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // Don't do anything with intercepted touch events if
        // we are not scrollable
        return mScrollable && super.onInterceptTouchEvent(ev);
    }

}

You would then use

<com.mypackagename.LockableScrollView 
    android:id="@+id/QuranGalleryScrollView" 
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent">

    <Gallery android:id="@+id/Gallery" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:scrollbars="horizontal">
    </Gallery>

</com.mypackagename.LockableScrollView>

in your XML file (just changed the ScrollView to your special LockableScrollView).

Then call

((LockableScrollView)findViewById(R.id.QuranGalleryScrollView)).setScrollingEnabled(false);

to disable scrolling of the view.

I think that you have more than just the issue of disabling scrolling though to achieve your desired result (the gallery will remain scrollable with the above code for instance) - I'd recommend doing some more research on each of the three components (Gallery, ScrollView, ImageView) to see what properties each one has and how it behaves.

How to insert data using wpdb

Use $wpdb->insert().

$wpdb->insert('wp_submitted_form', array(
    'name' => 'Kumkum',
    'email' => '[email protected]',
    'phone' => '3456734567', // ... and so on
));

Addition from @mastrianni:

$wpdb->insert sanitizes your data for you, unlike $wpdb->query which requires you to sanitize your query with $wpdb->prepare. The difference between the two is $wpdb->query allows you to write your own SQL statement, where $wpdb->insert accepts an array and takes care of sanitizing/sql for you.

How to normalize a signal to zero mean and unit variance?

To avoid division by zero!

function x = normalize(x, eps)
    % Normalize vector `x` (zero mean, unit variance)

    % default values
    if (~exist('eps', 'var'))
        eps = 1e-6;
    end

    mu = mean(x(:));

    sigma = std(x(:));
    if sigma < eps
        sigma = 1;
    end

    x = (x - mu) / sigma;
end

How can I make a checkbox readonly? not disabled?

Through CSS:

<label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>

pointer-events not supported in IE<10

https://jsfiddle.net/fl4sh/3r0v8pug/2/

Command to run a .bat file

You can use Cmd command to run Batch file.

Here is my way =>

cmd /c ""Full_Path_Of_Batch_Here.cmd" "

More information => cmd /?

How do I commit only some files?

Get a list of files you want to commit

$ git status

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

modified:   file1
modified:   file2
modified:   file3
modified:   file4

Add the files to staging

$ git add file1 file2

Check to see what you are committing

$ git status

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   file1
    modified:   file2

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   file3
    modified:   file4

Commit the files with a commit message

$ git commit -m "Fixed files 1 and 2"

If you accidentally commit the wrong files

$ git reset --soft HEAD~1

If you want to unstage the files and start over

$ git reset

Unstaged changes after reset:
M file1
M file2
M file3
M file4

Convert xlsx to csv in Linux with command line

Use csvkit

in2csv data.xlsx > data.csv

For details check their excellent docs

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

The ideal situation for resolving conflicts is when you know ahead of time which way you want to resolve them and can pass the -Xours or -Xtheirs recursive merge strategy options. Outside of this I can see three scenarious:

  1. You want to just keep a single version of the file (this should probably only be used on unmergeable binary files, since otherwise conflicted and non-conflicted files may get out of sync with each other).
  2. You want to simply decide all of the conflicts in a particular direction.
  3. You need to resolve some conflicts manually and then resolve all of the rest in a particular direction.

To address these three scenarios you can add the following lines to your .gitconfig file (or equivalent):

[merge]
  conflictstyle = diff3
[mergetool.getours]
  cmd = git-checkout --ours ${MERGED}
  trustExitCode = true
[mergetool.mergeours]
  cmd = git-merge-file --ours ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
  trustExitCode = true
[mergetool.keepours]
  cmd = sed -i '' -e '/^<<<<<<</d' -e '/^|||||||/,/^>>>>>>>/d' ${MERGED}
  trustExitCode = true
[mergetool.gettheirs]
  cmd = git-checkout --theirs ${MERGED}
  trustExitCode = true
[mergetool.mergetheirs]
  cmd = git-merge-file --theirs ${LOCAL} ${BASE} ${REMOTE} -p > ${MERGED}
  trustExitCode = true
[mergetool.keeptheirs]
  cmd = sed -i '' -e '/^<<<<<<</,/^=======/d' -e '/^>>>>>>>/d' ${MERGED}
  trustExitCode = true

The get(ours|theirs) tool just keeps the respective version of the file and throws away all of the changes from the other version (so no merging occurs).

The merge(ours|theirs) tool re-does the three way merge from the local, base, and remote versions of the file, choosing to resolve conflicts in the given direction. This has some caveats, specifically: it ignores the diff options that were passed to the merge command (such as algorithm and whitespace handling); does the merge cleanly from the original files (so any manual changes to the file are discarded, which could be good or bad); and has the advantage that it cannot be confused by diff markers that are supposed to be in the file.

The keep(ours|theirs) tool simply edits out the diff markers and enclosed sections, detecting them by regular expression. This has the advantage that it preserves the diff options from the merge command and allows you to resolve some conflicts by hand and then automatically resolve the rest. It has the disadvantage that if there are other conflict markers in the file it could get confused.

These are all used by running git mergetool -t (get|merge|keep)(ours|theirs) [<filename>] where if <filename> is not supplied it processes all conflicted files.

Generally speaking, assuming you know there are no diff markers to confuse the regular expression, the keep* variants of the command are the most powerful. If you leave the mergetool.keepBackup option unset or true then after the merge you can diff the *.orig file against the result of the merge to check that it makes sense. As an example, I run the following after the mergetool just to inspect the changes before committing:

for f in `find . -name '*.orig'`; do vimdiff $f ${f%.orig}; done

Note: If the merge.conflictstyle is not diff3 then the /^|||||||/ pattern in the sed rule needs to be /^=======/ instead.

What is the 'new' keyword in JavaScript?

For beginners to understand it better

try out the following code in the browser console.

function Foo() { 
    return this; 
}

var a = Foo();       //returns window object
var b = new Foo();   //returns empty object of foo

a instanceof Window;  // true
a instanceof Foo;     // false

b instanceof Window;  // false
b instanceof Foo;     // true

Now you can read the community wiki answer :)

How do I update a model value in JavaScript in a Razor view?

This should work

function updatePostID(val)
{
    document.getElementById('PostID').value = val;

    //and probably call document.forms[0].submit();
}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)

Use cell's color as condition in if statement (function)

Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).

In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

It is not necessary to add () in the WHERE clause as we do in a regular SQL. Because Dapper does that automatically for us. Here is the syntax:-

const string SQL = "SELECT IntegerColumn, StringColumn FROM SomeTable WHERE IntegerColumn IN @listOfIntegers";

var conditions = new { listOfIntegers };
    
var results = connection.Query(SQL, conditions);

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

If you can decode JWT, how are they secure?

Ref - JWT Structure and Security

It is important to note that JWT are used for authorization and not authentication. So a JWT will be created for you only after you have been authenticated by the server by may be specifying the credentials. Once JWT has been created for all future interactions with server JWT can be used. So JWT tells that server that this user has been authenticated, let him access the particular resource if he has the role.
Information in the payload of the JWT is visible to everyone. There can be a "Man in the Middle" attack and the contents of the JWT can be changed. So we should not pass any sensitive information like passwords in the payload. We can encrypt the payload data if we want to make it more secure. If Payload is tampered with server will recognize it.
So suppose a user has been authenticated and provided with a JWT. Generated JWT has a claim specifying role of Admin. Also the Signature is generated with

enter image description here

This JWT is now tampered with and suppose the role is changed to Super Admin
Then when the server receives this token it will again generate the signature using the secret key(which only the server has) and the payload. It will not match the signature in the JWT. So the server will know that the JWT has been tampered with.

PHP PDO returning single row

Just fetch. only gets one row. So no foreach loop needed :D

$row  = $STH -> fetch();

example (ty northkildonan):

$dbh = new PDO(" --- connection string --- "); 
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 
$stmt->execute(); 
$row = $stmt->fetch();

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

It's safe to increase the size of your varchar column. You won't corrupt your data.

If it helps your peace of mind, keep in mind, you can always run a database backup before altering your data structures.

By the way, correct syntax is:

ALTER TABLE table_name MODIFY col_name VARCHAR(10000)

Also, if the column previously allowed/did not allow nulls, you should add the appropriate syntax to the end of the alter table statement, after the column type.

jQuery checkbox change and click event

Try

_x000D_
_x000D_
checkbox1.onclick= e => {
  if(!checkbox1.checked) checkbox1.checked = !confirm("Are you sure?");
  textbox1.value = checkbox1.checked;
}
_x000D_
<input type="checkbox" id="checkbox1" /><br />
<input type="text" id="textbox1" value='false'/>
_x000D_
_x000D_
_x000D_

Height of an HTML select box (dropdown)

Actually you kind of can! Don't hassle with javascript... I was just stuck on the same thing for a website I'm making and if you increase the 'font-size' attribute in CSS for the tag then it automatically increases the height as well. Petty but it's something that bothers me a lot ha ha

Sanitizing user input before adding it to the DOM in Javascript

You can use this:

function sanitize(string) {
  const map = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;',
      "/": '&#x2F;',
  };
  const reg = /[&<>"'/]/ig;
  return string.replace(reg, (match)=>(map[match]));
}

Also see OWASP XSS Prevention Cheat Sheet.

Does functional programming replace GoF design patterns?

I think that each paradigm serves a different purpose and as such cannot be compared in this way.

I have not heard that the GoF design patterns are applicable to every language. I have heard that they are applicable to all OOP languages. If you use functional programming then the domain of problems that you solve is different from OO languages.

I wouldn't use functional language to write a user interface, but one of the OO languages like C# or Java would make this job easier. If I were writing a functional language then I wouldn't consider using OO design patterns.

How do I find the length of an array?

Avoid using the type together with sizeof, as sizeof(array)/sizeof(char), suddenly gets corrupt if you change the type of the array.

In visual studio, you have the equivivalent if sizeof(array)/sizeof(*array). You can simply type _countof(array)

jQuery - find table row containing table cell containing specific text

$(function(){
    var search = 'foo';
    $("table tr td").filter(function() {
        return $(this).text() == search;
    }).parent('tr').css('color','red');
});

Will turn the text red for rows which have a cell whose text is 'foo'.

In C, how should I read a text file and print all strings

There are plenty of good answers here about reading it in chunks, I'm just gonna show you a little trick that reads all the content at once to a buffer and prints it.

I'm not saying it's better. It's not, and as Ricardo sometimes it can be bad, but I find it's a nice solution for the simple cases.

I sprinkled it with comments because there's a lot going on.

#include <stdio.h>
#include <stdlib.h>

char* ReadFile(char *filename)
{
   char *buffer = NULL;
   int string_size, read_size;
   FILE *handler = fopen(filename, "r");

   if (handler)
   {
       // Seek the last byte of the file
       fseek(handler, 0, SEEK_END);
       // Offset from the first to the last byte, or in other words, filesize
       string_size = ftell(handler);
       // go back to the start of the file
       rewind(handler);

       // Allocate a string that can hold it all
       buffer = (char*) malloc(sizeof(char) * (string_size + 1) );

       // Read it all in one operation
       read_size = fread(buffer, sizeof(char), string_size, handler);

       // fread doesn't set it so put a \0 in the last position
       // and buffer is now officially a string
       buffer[string_size] = '\0';

       if (string_size != read_size)
       {
           // Something went wrong, throw away the memory and set
           // the buffer to NULL
           free(buffer);
           buffer = NULL;
       }

       // Always remember to close the file.
       fclose(handler);
    }

    return buffer;
}

int main()
{
    char *string = ReadFile("yourfile.txt");
    if (string)
    {
        puts(string);
        free(string);
    }

    return 0;
}

Let me know if it's useful or you could learn something from it :)

How do I remove all non alphanumeric characters from a string except dash?

I´ve made a different solution, by eliminating the Control characters, which was my original problem.

It is better than putting in a list all the "special but good" chars

char[] arr = str.Where(c => !char.IsControl(c)).ToArray();    
str = new string(arr);

it´s simpler, so I think it´s better !

sending mail from Batch file

PowerShell comes with a built in command for it. So running directly from a .bat file:

powershell -ExecutionPolicy ByPass -Command Send-MailMessage ^
    -SmtpServer server.address.name ^
    -To [email protected] ^
    -From [email protected] ^
    -Subject Testing ^
    -Body 123

NB -ExecutionPolicy ByPass is only needed if you haven't set up permissions for running PS from CMD

Also for those looking to call it from within powershell, drop everything before -Command [inclusive], and ` will be your escape character (not ^)

How to get IntPtr from byte[] in C#

This should work but must be used within an unsafe context:

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
    IntPtr ptr = (IntPtr)p;
    // do you stuff here
}

beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.

What is the official name for a credit card's 3 digit code?

You can't find a consistent reference because it seems to go by at least six different names!

  • Card Security Code
  • Card Verification Value (CVV or CV2)
  • Card Verification Value Code (CVVC)
  • Card Verification Code (CVC)
  • Verification Code (V-Code or V Code)
  • Card Code Verification (CCV)

RecyclerView onClick

Way too simple and effective.

Instead of implementing interface View.OnClickListener inside view holder or creating and interface and implementing interface in your activity - I used this code for simple on OnClickListener implementation.

public static class SimpleStringRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {

        // Your initializations goes here...
        private List<String> mValues;

        public static class ViewHolder extends RecyclerView.ViewHolder {

            //create a variable mView
            public final View mView;

            /*All your row widgets goes here
            public final ImageView mImageView;
            public final TextView mTextView;*/

            public ViewHolder(View view) {
                super(view);
                //Initialize it here
                mView = view;

                /* your row widgets initializations goes here
                mImageView = (ImageView) view.findViewById(R.id.avatar);
                mTextView = (TextView) view.findViewById(android.R.id.text1);*/
            }
        }

        public String getValueAt(int position) {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List<String> items) {

            mBackground = mTypedValue.resourceId;
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item, parent, false);
            view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.mBoundString = mValues.get(position);
            holder.mTextView.setText(mValues.get(position));

            //Here it is simply write onItemClick listener here
            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, ExampleActivity.class);

                    context.startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }
    }

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

CSS /JS to prevent dragging of ghost image?

You can use "Empty Img Element".
Empty Img Element - document.createElement("img")

[HTML Code]
<div id="hello" draggable="true">Drag!!!</div>
[JavaScript Code]
var block = document.querySelector('#hello');
block.addEventListener('dragstart', function(e){
    var img = document.createElement("img");
    e.dataTransfer.setDragImage(img, 0, 0);
})

Date query with ISODate in mongodb doesn't seem to work

Although $date is a part of MongoDB Extended JSON and that's what you get as default with mongoexport I don't think you can really use it as a part of the query.

If try exact search with $date like below:

db.foo.find({dt: {"$date": "2012-01-01T15:00:00.000Z"}})

you'll get error:

error: { "$err" : "invalid operator: $date", "code" : 10068 }

Try this:

db.mycollection.find({
    "dt" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}
})

or (following comments by @user3805045):

db.mycollection.find({
    "dt" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})

ISODate may be also required to compare dates without time (noted by @MattMolnar).

According to Data Types in the mongo Shell both should be equivalent:

The mongo shell provides various methods to return the date, either as a string or as a Date object:

  • Date() method which returns the current date as a string.
  • new Date() constructor which returns a Date object using the ISODate() wrapper.
  • ISODate() constructor which returns a Date object using the ISODate() wrapper.

and using ISODate should still return a Date object.

{"$date": "ISO-8601 string"} can be used when strict JSON representation is required. One possible example is Hadoop connector.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

  1. The syntax for specifying url is {% url namespace:url_name %}. So, check if you have added the app_name in urls.py.
  2. In my case, I had misspelled the url_name. The urls.py had the following content path('<int:question_id>/', views.detail, name='question_detail') whereas the index.html file had the following entry <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>. Notice the incorrect name.

How do I enter a multi-line comment in Perl?

POD is the official way to do multi line comments in Perl,

From faq.perl.org[perlfaq7]

The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with =cut, ending the Pod section:

=pod

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=cut

The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.

The =begin directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment. End the comment using =end with the same label. You still need the =cut to go back to Perl code from the Pod comment:

=begin comment

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=end comment

=cut

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

The shortest possible output from git log containing author and date

git log --pretty=format:"%h%x09%an%x09%ad%x09%s"

did the job. This outputs:

  fbc3503 mads    Thu Dec 4 07:43:27 2008 +0000   show mobile if phone is null...   
  ec36490 jesper  Wed Nov 26 05:41:37 2008 +0000  Cleanup after [942]: Using timezon
  ae62afd tobias  Tue Nov 25 21:42:55 2008 +0000  Fixed #67 by adding time zone supp
  164be7e mads    Tue Nov 25 19:56:43 2008 +0000  fixed tests, and a 'unending appoi
  93f1526 jesper  Tue Nov 25 09:45:56 2008 +0000  adding time.ZONE.now as time zone 
  2f0f8c1 tobias  Tue Nov 25 03:07:02 2008 +0000  Timezone configured in environment
  a33c1dc jesper  Tue Nov 25 01:26:18 2008 +0000  updated to most recent will_pagina

Inspired by stackoverflow question: "git log output like svn ls -v", i found out that I could add the exact params I needed.

To shorten the date (not showing the time) use --date=short

In case you were curious what the different options were:
%h = abbreviated commit hash
%x09 = tab (character for code 9)
%an = author name
%ad = author date (format respects --date= option)
%s = subject
From kernel.org/pub/software/scm/git/docs/git-log.html (PRETTY FORMATS section) by comment of Vivek.

Use basic authentication with jQuery and Ajax

How things change in a year. In addition to the header attribute in place of xhr.setRequestHeader, current jQuery (1.7.2+) includes a username and password attribute with the $.ajax call.

$.ajax
({
  type: "GET",
  url: "index1.php",
  dataType: 'json',
  username: username,
  password: password,
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 
  }
});

EDIT from comments and other answers: To be clear - in order to preemptively send authentication without a 401 Unauthorized response, instead of setRequestHeader (pre -1.7) use 'headers':

$.ajax
({
  type: "GET",
  url: "index1.php",
  dataType: 'json',
  headers: {
    "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
  },
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 
  }
});

Convert seconds to hh:mm:ss in Python

You can calculate the number of minutes and hours from the number of seconds by simple division:

seconds = 12345
minutes = seconds // 60
hours = minutes // 60

print "%02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)
print "%02d:%02d" % (minutes, seconds % 60)

Here // is Python's integer division.

Origin <origin> is not allowed by Access-Control-Allow-Origin

Since they are running on different ports, they are different JavaScript origin. It doesn't matter that they are on the same machine/hostname.

You need to enable CORS on the server (localhost:8080). Check out this site: http://enable-cors.org/

All you need to do is add an HTTP header to the server:

Access-Control-Allow-Origin: http://localhost:3000

Or, for simplicity:

Access-Control-Allow-Origin: *

Thought don't use "*" if your server is trying to set cookie and you use withCredentials = true

when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

You can read more about withCredentials here

How do I get total physical memory size using PowerShell without WMI?

If you don't want to use WMI, I can suggest systeminfo.exe. But, there may be a better way to do that.

(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

What is the best way to create a string array in python?

def _remove_regex(input_text, regex_pattern):
    findregs = re.finditer(regex_pattern, input_text) 
    for i in findregs: 
        input_text = re.sub(i.group().strip(), '', input_text)
    return input_text

regex_pattern = r"\buntil\b|\bcan\b|\bboat\b"
_remove_regex("row and row and row your boat until you can row no more", regex_pattern)

\w means that it matches word characters, a|b means match either a or b, \b represents a word boundary

Homebrew install specific version of formula?

Along the lines of @halfcube's suggestion, this works really well:

  1. Find the library you're looking for at https://github.com/Homebrew/homebrew-core/tree/master/Formula
  2. Click it: https://github.com/Homebrew/homebrew-core/blob/master/Formula/postgresql.rb
  3. Click the "history" button to look at old commits: https://github.com/Homebrew/homebrew-core/commits/master/Formula/postgresql.rb
  4. Click the one you want: "postgresql: update version to 8.4.4", https://github.com/Homebrew/homebrew-core/blob/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb
  5. Click the "raw" link: https://raw.githubusercontent.com/Homebrew/homebrew-core/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb
  6. brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Array vs. Object efficiency in JavaScript

It's not really a performance question at all, since arrays and objects work very differently (or are supposed to, at least). Arrays have a continuous index 0..n, while objects map arbitrary keys to arbitrary values. If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is.

If you try to set arbitrary (numeric) keys on an array, you really have a performance loss, since behaviourally the array will fill in all indexes in-between:

> foo = [];
  []
> foo[100] = 'a';
  "a"
> foo
  [undefined, undefined, undefined, ..., "a"]

(Note that the array does not actually contain 99 undefined values, but it will behave this way since you're [supposed to be] iterating the array at some point.)

The literals for both options should make it very clear how they can be used:

var arr = ['foo', 'bar', 'baz'];     // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

how to stop Javascript forEach?

Wy not use plain return?

function recurs(comment){
comment.comments.forEach(function(elem){
    recurs(elem);
    if(...) return;
});

it will return from 'recurs' function. I use it like this. Althougth this will not break from forEach but from whole function, in this simple example it might work

How to handle query parameters in angular 2

Angular 4:

I have included JS (for OG's) and TS versions below.

.html

<a [routerLink]="['/search', { tag: 'fish' } ]">A link</a>

In the above I am using the link parameter array see sources below for more information.

routing.js

(function(app) {
    app.routing = ng.router.RouterModule.forRoot([
        { path: '', component: indexComponent },
        { path: 'search', component: searchComponent }
    ]);
})(window.app || (window.app = {}));

searchComponent.js

(function(app) {
    app.searchComponent =
        ng.core.Component({
            selector: 'search',
                templateUrl: 'view/search.html'
            })
            .Class({
                constructor: [ ng.router.Router, ng.router.ActivatedRoute, function(router, activatedRoute) {
                // Pull out the params with activatedRoute...
                console.log(' params', activatedRoute.snapshot.params);
                // Object {tag: "fish"}
            }]
        }
    });
})(window.app || (window.app = {}));

routing.ts (excerpt)

const appRoutes: Routes = [
  { path: '', component: IndexComponent },
  { path: 'search', component: SearchComponent }
];
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
    // other imports here
  ],
  ...
})
export class AppModule { }

searchComponent.ts

import 'rxjs/add/operator/switchMap';
import { OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

export class SearchComponent implements OnInit {

constructor(
   private route: ActivatedRoute,
   private router: Router
) {}
ngOnInit() {
    this.route.params
      .switchMap((params: Params) => doSomething(params['tag']))
 }

More infos:

"Link Parameter Array" https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

"Activated Route - the one stop shop for route info" https://angular.io/docs/ts/latest/guide/router.html#!#activated-route

Find non-ASCII characters in varchar columns using SQL Server

running the various solutions on some real world data - 12M rows varchar length ~30, around 9k dodgy rows, no full text index in play, the patIndex solution is the fastest, and it also selects the most rows.

(pre-ran km. to set the cache to a known state, ran the 3 processes, and finally ran km again - the last 2 runs of km gave times within 2 seconds)

patindex solution by Gerhard Weiss -- Runtime 0:38, returns 9144 rows

select dodgyColumn from myTable fcc
WHERE  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,dodgyColumn ) >0

the substring-numbers solution by MT. -- Runtime 1:16, returned 8996 rows

select dodgyColumn from myTable fcc
INNER JOIN dbo.Numbers32k dn ON dn.number<(len(fcc.dodgyColumn ))
WHERE ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))<32 
    OR ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))>127

udf solution by Deon Robertson -- Runtime 3:47, returns 7316 rows

select dodgyColumn 
from myTable 
where dbo.udf_test_ContainsNonASCIIChars(dodgyColumn , 1) = 1

What's the difference between lists enclosed by square brackets and parentheses in Python?

One interesting difference :

lst=[1]
print lst          // prints [1]
print type(lst)    // prints <type 'list'>

notATuple=(1)
print notATuple        // prints 1
print type(notATuple)  // prints <type 'int'>
                                         ^^ instead of tuple(expected)

A comma must be included in a tuple even if it contains only a single value. e.g. (1,) instead of (1).

What is the difference between canonical name, simple name and class name in Java Class?

Adding local classes, lambdas and the toString() method to complete the previous two answers. Further, I add arrays of lambdas and arrays of anonymous classes (which do not make any sense in practice though):

package com.example;

public final class TestClassNames {
    private static void showClass(Class<?> c) {
        System.out.println("getName():          " + c.getName());
        System.out.println("getCanonicalName(): " + c.getCanonicalName());
        System.out.println("getSimpleName():    " + c.getSimpleName());
        System.out.println("toString():         " + c.toString());
        System.out.println();
    }

    private static void x(Runnable r) {
        showClass(r.getClass());
        showClass(java.lang.reflect.Array.newInstance(r.getClass(), 1).getClass()); // Obtains an array class of a lambda base type.
    }

    public static class NestedClass {}

    public class InnerClass {}

    public static void main(String[] args) {
        class LocalClass {}
        showClass(void.class);
        showClass(int.class);
        showClass(String.class);
        showClass(Runnable.class);
        showClass(SomeEnum.class);
        showClass(SomeAnnotation.class);
        showClass(int[].class);
        showClass(String[].class);
        showClass(NestedClass.class);
        showClass(InnerClass.class);
        showClass(LocalClass.class);
        showClass(LocalClass[].class);
        Object anonymous = new java.io.Serializable() {};
        showClass(anonymous.getClass());
        showClass(java.lang.reflect.Array.newInstance(anonymous.getClass(), 1).getClass()); // Obtains an array class of an anonymous base type.
        x(() -> {});
    }
}

enum SomeEnum {
   BLUE, YELLOW, RED;
}

@interface SomeAnnotation {}

This is the full output:

getName():          void
getCanonicalName(): void
getSimpleName():    void
toString():         void

getName():          int
getCanonicalName(): int
getSimpleName():    int
toString():         int

getName():          java.lang.String
getCanonicalName(): java.lang.String
getSimpleName():    String
toString():         class java.lang.String

getName():          java.lang.Runnable
getCanonicalName(): java.lang.Runnable
getSimpleName():    Runnable
toString():         interface java.lang.Runnable

getName():          com.example.SomeEnum
getCanonicalName(): com.example.SomeEnum
getSimpleName():    SomeEnum
toString():         class com.example.SomeEnum

getName():          com.example.SomeAnnotation
getCanonicalName(): com.example.SomeAnnotation
getSimpleName():    SomeAnnotation
toString():         interface com.example.SomeAnnotation

getName():          [I
getCanonicalName(): int[]
getSimpleName():    int[]
toString():         class [I

getName():          [Ljava.lang.String;
getCanonicalName(): java.lang.String[]
getSimpleName():    String[]
toString():         class [Ljava.lang.String;

getName():          com.example.TestClassNames$NestedClass
getCanonicalName(): com.example.TestClassNames.NestedClass
getSimpleName():    NestedClass
toString():         class com.example.TestClassNames$NestedClass

getName():          com.example.TestClassNames$InnerClass
getCanonicalName(): com.example.TestClassNames.InnerClass
getSimpleName():    InnerClass
toString():         class com.example.TestClassNames$InnerClass

getName():          com.example.TestClassNames$1LocalClass
getCanonicalName(): null
getSimpleName():    LocalClass
toString():         class com.example.TestClassNames$1LocalClass

getName():          [Lcom.example.TestClassNames$1LocalClass;
getCanonicalName(): null
getSimpleName():    LocalClass[]
toString():         class [Lcom.example.TestClassNames$1LocalClass;

getName():          com.example.TestClassNames$1
getCanonicalName(): null
getSimpleName():    
toString():         class com.example.TestClassNames$1

getName():          [Lcom.example.TestClassNames$1;
getCanonicalName(): null
getSimpleName():    []
toString():         class [Lcom.example.TestClassNames$1;

getName():          com.example.TestClassNames$$Lambda$1/1175962212
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212
getSimpleName():    TestClassNames$$Lambda$1/1175962212
toString():         class com.example.TestClassNames$$Lambda$1/1175962212

getName():          [Lcom.example.TestClassNames$$Lambda$1;
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212[]
getSimpleName():    TestClassNames$$Lambda$1/1175962212[]
toString():         class [Lcom.example.TestClassNames$$Lambda$1;

So, here are the rules. First, lets start with primitive types and void:

  1. If the class object represents a primitive type or void, all the four methods simply returns its name.

Now the rules for the getName() method:

  1. Every non-lambda and non-array class or interface (i.e, top-level, nested, inner, local and anonymous) has a name (which is returned by getName()) that is the package name followed by a dot (if there is a package), followed by the name of its class-file as generated by the compiler (whithout the suffix .class). If there is no package, it is simply the name of the class-file. If the class is an inner, nested, local or anonymous class, the compiler should generate at least one $ in its class-file name. Note that for anonymous classes, the class name would end with a dollar-sign followed by a number.
  2. Lambda class names are generally unpredictable, and you shouldn't care about they anyway. Exactly, their name is the name of the enclosing class, followed by $$Lambda$, followed by a number, followed by a slash, followed by another number.
  3. The class descriptor of the primitives are Z for boolean, B for byte, S for short, C for char, I for int, J for long, F for float and D for double. For non-array classes and interfaces the class descriptor is L followed by what is given by getName() followed by ;. For array classes, the class descriptor is [ followed by the class descriptor of the component type (which may be itself another array class).
  4. For array classes, the getName() method returns its class descriptor. This rule seems to fail only for array classes whose the component type is a lambda (which possibly is a bug), but hopefully this should not matter anyway because there is no point even on the existence of array classes whose component type is a lambda.

Now, the toString() method:

  1. If the class instance represents an interface (or an annotation, which is a special type of interface), the toString() returns "interface " + getName(). If it is a primitive, it returns simply getName(). If it is something else (a class type, even if it is a pretty weird one), it returns "class " + getName().

The getCanonicalName() method:

  1. For top-level classes and interfaces, the getCanonicalName() method returns just what the getName() method returns.
  2. The getCanonicalName() method returns null for anonymous or local classes and for array classes of those.
  3. For inner and nested classes and interfaces, the getCanonicalName() method returns what the getName() method would replacing the compiler-introduced dollar-signs by dots.
  4. For array classes, the getCanonicalName() method returns null if the canonical name of the component type is null. Otherwise, it returns the canonical name of the component type followed by [].

The getSimpleName() method:

  1. For top-level, nested, inner and local classes, the getSimpleName() returns the name of the class as written in the source file.
  2. For anonymous classes the getSimpleName() returns an empty String.
  3. For lambda classes the getSimpleName() just returns what the getName() would return without the package name. This do not makes much sense and looks like a bug for me, but there is no point in calling getSimpleName() on a lambda class to start with.
  4. For array classes the getSimpleName() method returns the simple name of the component class followed by []. This have the funny/weird side-effect that array classes whose component type is an anonymous class have just [] as their simple names.

How to listen state changes in react.js?

It's been a while but for future reference: the method shouldComponentUpdate() can be used.

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

static getDerivedStateFromProps() 
shouldComponentUpdate() 
render()
getSnapshotBeforeUpdate() 
componentDidUpdate()

ref: https://reactjs.org/docs/react-component.html

Avoid dropdown menu close on click inside

For closing the dropdown only if a click event was triggered outside the bootstrap dropdown, this is what worked for me:

JS file:

    $('.createNewElement').on('click.bs.dropdown.data-api', '.tags-btn-group.keep-open-dropdown', function (e) {
        var target = $(e.target);
        if (target.hasClass("dropdown-menu") || target.parents(".dropdown-menu").length) {
            e.stopPropagation();
        }
    });

HTML file:

<!-- button: -->
<div class="createNewElement">
                <div class="btn-group tags-btn-group keep-open-dropdown">

                    <div class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">OPEN DROPDOWN</div>

                    <ul class="dropdown-menu">
                        WHAT EVER YOU WANT HERE...
                    </ul>

                </div>
</div>

Parsing JSON from XmlHttpRequest.responseJSON

You can simply set xhr.responseType = 'json';

_x000D_
_x000D_
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
  if (this.status == 200) {_x000D_
    console.log('response', this.response); // JSON response  _x000D_
  }_x000D_
};_x000D_
xhr.send();_x000D_
  
_x000D_
_x000D_
_x000D_

Documentation for responseType

Bold & Non-Bold Text In A Single UILabel?

Check out TTTAttributedLabel. It's a drop-in replacement for UILabel that allows you to have mixed font and colors in a single label by setting an NSAttributedString as the text for that label.

Change value of input placeholder via model?

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

How to resize Twitter Bootstrap modal dynamically based on the content

I simply override the css:

.modal-dialog {
    max-width: 1000px;
}

Spring RestTemplate timeout

I had a similar scenario, but was also required to set a Proxy. The simplest way I could see to do this was to extend the SimpleClientHttpRequestFactory for the ease of setting the proxy (different proxies for non-prod vs prod). This should still work even if you don't require the proxy though. Then in my extended class I override the openConnection(URL url, Proxy proxy) method, using the same as the source, but just setting the timeouts before returning.

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
    Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
    urlConnection.setConnectTimeout(5000);
    urlConnection.setReadTimeout(5000);
    return (HttpURLConnection) urlConnection;
}

Open PDF in new browser full window

var pdf = MyPdf.pdf;
window.open(pdf);

This will open the pdf document in a full window from JavaScript

A function to open windows would look like this:

function openPDF(pdf){
  window.open(pdf);
  return false;
}

lodash multi-column sortBy descending

Deep field & multi field & different direction ordering Lodash >4

var sortedArray = _.orderBy(mixedArray,
                            ['foo','foo.bar','bar.foo.bar'],               
                            ['desc','asc','desc']);

Get selected text from a drop-down list (select box) using jQuery

Try this:

$("#myselect :selected").text();

For an ASP.NET dropdown you can use the following selector:

$("[id*='MyDropDownId'] :selected")

How to save traceback / sys.exc_info() values in a variable?

Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.

Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.

Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.

Remember to import traceback.

Here's the output from traceback.extract_stack(). Formatting added for readability.

>>> traceback.extract_stack()
[
   ('<string>', 1, '<module>', None),
   ('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
   ('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
   ('<pyshell#1>', 1, '<module>', None)
]

Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.

>>> ''.join(traceback.format_stack())
'  File "<string>", line 1, in <module>\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
       ret = method(*args, **kwargs)\n
   File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
       exec(code, self.locals)\n  File "<pyshell#2>", line 1, in <module>\n'

How to link 2 cell of excel sheet?

Just follow these Steps :

If you want the contents of, say, C1 to mirror the contents of cell A1, you just need to set the formula in C1 to =A1. From this point forward, anything you type in A1 will show up in C1 as well.

To Link Multiple Cells in Excel From Another Worksheet :

Step 1

Click the worksheet tab at the bottom of the screen that contains a range of precedent cells to which you want to link. A range is a block or group of adjacent cells. For example, assume you want to link a range of blank cells in “Sheet1” to a range of precedent cells in “Sheet2.” Click the “Sheet2” tab.

Step 2

Determine the precedent range’s width in columns and height in rows. In this example, assume cells A1 through A4 on “Sheet2” contain a list of numbers 1, 2, 3 and 4, respectively, which will be your precedent cells. This precedent range is one column wide by four rows high.

Step 3

Click the worksheet tab at the bottom of the screen that contains the blank cells in which you will insert a link. In this example, click the “Sheet1” tab.

Step 4

Select the range of blank cells you want to link to the precedent cells. This range must be the same size as the precedent range, but can be in a different location on the worksheet. Click and hold the mouse button on the top left cell of the range, drag the mouse cursor to the bottom right cell in the range and release the mouse button to select the range. In this example, assume you want to link cells C1 through C4 to the precedent range. Click and hold on cell C1, drag the mouse to cell C4 and release the mouse to highlight the range.

Step 5

Type “=,” the worksheet name containing the precedent cells, “!,” the top left cell of the precedent range, “:” and the bottom right cell of the precedent range. Press “Ctrl,” “Shift” and “Enter” simultaneously to complete the array formula. Each dependent cell is now linked to the cell in the precedent range that’s in the same respective location within the range. In this example, type “=Sheet2!A1:A4” and press “Ctrl,” “Shift” and “Enter” simultaneously. Cells C1 through C4 on “Sheet1” now contain the array formula “{=Sheet2!A1:A4}” surrounded by curly brackets, and show the same data as the precedent cells in “Sheet2.”

Good Luck !!!

How can I drop all the tables in a PostgreSQL database?

If you have the PL/PGSQL procedural language installed you can use the following to remove everything without a shell/Perl external script.

DROP FUNCTION IF EXISTS remove_all();

CREATE FUNCTION remove_all() RETURNS void AS $$
DECLARE
    rec RECORD;
    cmd text;
BEGIN
    cmd := '';

    FOR rec IN SELECT
            'DROP SEQUENCE ' || quote_ident(n.nspname) || '.'
                || quote_ident(c.relname) || ' CASCADE;' AS name
        FROM
            pg_catalog.pg_class AS c
        LEFT JOIN
            pg_catalog.pg_namespace AS n
        ON
            n.oid = c.relnamespace
        WHERE
            relkind = 'S' AND
            n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
            pg_catalog.pg_table_is_visible(c.oid)
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    FOR rec IN SELECT
            'DROP TABLE ' || quote_ident(n.nspname) || '.'
                || quote_ident(c.relname) || ' CASCADE;' AS name
        FROM
            pg_catalog.pg_class AS c
        LEFT JOIN
            pg_catalog.pg_namespace AS n
        ON
            n.oid = c.relnamespace WHERE relkind = 'r' AND
            n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
            pg_catalog.pg_table_is_visible(c.oid)
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    FOR rec IN SELECT
            'DROP FUNCTION ' || quote_ident(ns.nspname) || '.'
                || quote_ident(proname) || '(' || oidvectortypes(proargtypes)
                || ');' AS name
        FROM
            pg_proc
        INNER JOIN
            pg_namespace ns
        ON
            (pg_proc.pronamespace = ns.oid)
        WHERE
            ns.nspname =
            'public'
        ORDER BY
            proname
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    EXECUTE cmd;
    RETURN;
END;
$$ LANGUAGE plpgsql;

SELECT remove_all();

Rather than type this in at the "psql" prompt I would suggest you copy it to a file and then pass the file as input to psql using the "--file" or "-f" options:

psql -f clean_all_pg.sql

Credit where credit is due: I wrote the function, but think the queries (or the first one at least) came from someone on one of the pgsql mailing lists years ago. Don't remember exactly when or which one.

Showing all errors and warnings

PHP errors can be displayed by any of below methods:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For more details:

Displaying PHP errors

Why is "npm install" really slow?

One thing I noticed is, if you are working in new project(folder) you have to reconfigure proxy setting for the particular path

  1. Cd(change terminal window path to the destination folder.

  2. npm config set proxy http://(ip address):(port)

  3. npm config set https-proxy http://(ip address):(port)

  4. npm install -g @angular/cli

AngularJS check if form is valid in controller

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >{{ formValid = myForm.$valid}}</span>

Here is the full working example:

_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
  $scope.userType = 'guest';_x000D_
  $scope.formValid = false;_x000D_
  console.info('Ctrl init, no form.');_x000D_
  _x000D_
  $scope.$watch('myForm', function() {_x000D_
    console.info('myForm watch');_x000D_
    console.log($scope.formValid);_x000D_
  });_x000D_
  _x000D_
  $scope.isFormValid = function() {_x000D_
    //test the new scope variable_x000D_
    console.log('form valid?: ', $scope.formValid);_x000D_
  };_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
  userType: <input name="input" ng-model="userType" required>_x000D_
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
  <tt>userType = {{userType}}</tt><br>_x000D_
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
  _x000D_
  _x000D_
  /*-- Hidden Variable formValid to use in your controller --*/_x000D_
  <span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
  _x000D_
  _x000D_
  <br/>_x000D_
  <button ng-click="isFormValid()">Check Valid</button>_x000D_
 </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Css transition from display none to display block, navigation with subnav

Generally when people are trying to animate display: none what they really want is:

  1. Fade content in, and
  2. Have the item not take up space in the document when hidden

Most popular answers use visibility, which can only achieve the first goal, but luckily it's just as easy to achieve both by using position.

Since position: absolute removes the element from typing document flow spacing, you can toggle between position: absolute and position: static (global default), combined with opacity. See the below example.

_x000D_
_x000D_
.content-page {_x000D_
  position:absolute;_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.content-page.active {_x000D_
  position: static;_x000D_
  opacity: 1;_x000D_
  transition: opacity 1s linear;_x000D_
}
_x000D_
_x000D_
_x000D_

Bash array with spaces in elements

Not exactly an answer to the quoting/escaping problem of the original question but probably something that would actually have been more useful for the op:

unset FILES
for f in 2011-*.jpg; do FILES+=("$f"); done
echo "${FILES[@]}"

Where of course the expression would have to be adopted to the specific requirement (e.g. *.jpg for all or 2001-09-11*.jpg for only the pictures of a certain day).

Unable to copy file - access to the path is denied

Just make sure that the folder is NOT Read-Only and rebuild the solution

Installing PG gem on OS X - failure to build native extension

Solved! I found some lack of library for PostgreSQL on the system. Only two steps solved it:

brew install postgresql

Then run

gem install pg

How do I "decompile" Java class files?

I use JAD Decompiler.

There is an Eclipse plugin for it, jadeclipse. It is pretty nice.

Java 8 - Best way to transform a list: map or foreach?

One of the main benefits of using streams is that it gives the ability to process data in a declarative way, that is, using a functional style of programming. It also gives multi-threading capability for free meaning there is no need to write any extra multi-threaded code to make your stream concurrent.

Assuming the reason you are exploring this style of programming is that you want to exploit these benefits then your first code sample is potentially not functional since the foreach method is classed as being terminal (meaning that it can produce side-effects).

The second way is preferred from functional programming point of view since the map function can accept stateless lambda functions. More explicitly, the lambda passed to the map function should be

  1. Non-interfering, meaning that the function should not alter the source of the stream if it is non-concurrent (e.g. ArrayList).
  2. Stateless to avoid unexpected results when doing parallel processing (caused by thread scheduling differences).

Another benefit with the second approach is if the stream is parallel and the collector is concurrent and unordered then these characteristics can provide useful hints to the reduction operation to do the collecting concurrently.

Count number of times a date occurs and make a graph out of it

If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1) next to it and copy the formula down. This assumes you have your values in range A1:A100 and the de-duplicated values are in column B.

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
      AND A.ITEM_KEY = b.item_key
      AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

Convert Char to String in C

I use this to convert char to string (an example) :

char c = 'A';
char str1[2] = {c , '\0'};
char str2[5] = "";
strcpy(str2,str1);

Disabling enter key for form

In your form tag just paste this:

onkeypress="return event.keyCode != 13;"

Example

<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">

This can be useful if you want to do search when typing and ignoring ENTER.

/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)

OTP (token) should be automatically read from the message

I will recommend you not to use any third party libraries for auto fetch OTP from SMS Inbox. This can be done easily if you have basic understanding of Broadcast Receiver and how it works. Just Try following approach :

Step 1) Create single interface i.e SmsListner

package com.wnrcorp.reba;
public interface SmsListener{
public void messageReceived(String messageText);}

Step 2) Create single Broadcast Receiver i.e SmsReceiver

package com.wnrcorp.reba;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
Boolean b;
String abcd,xyz;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data  = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
    for(int i=0;i<pdus.length;i++){
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String sender = smsMessage.getDisplayOriginatingAddress();
       // b=sender.endsWith("WNRCRP");  //Just to fetch otp sent from WNRCRP
        String messageBody = smsMessage.getMessageBody();
       abcd=messageBody.replaceAll("[^0-9]","");   // here abcd contains otp 
        which is in number format
        //Pass on the text to our listener.
        if(b==true) {
            mListener.messageReceived(abcd);  // attach value to interface 
  object
        }
        else
        {
        }
    }
}
public static void bindListener(SmsListener listener) {
    mListener = listener;
}
}

Step 3) Add Listener i.e broadcast receiver in android manifest file

<receiver android:name=".SmsReceiver">    
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
</receiver>

and add permission

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

Final Step 4) The activity where you going to auto fetch otp when it is received in inbox. In my case I'm fetching otp and setting on edittext field.

public class OtpVerificationActivity extends AppCompatActivity {
EditText ed;
TextView tv;
String otp_generated,contactNo,id1;
GlobalData gd = new GlobalData();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_otp_verification);
    ed=(EditText)findViewById(R.id.otp);
    tv=(TextView) findViewById(R.id.verify_otp); 
    /*This is important because this will be called every time you receive 
     any sms */            
 SmsReceiver.bindListener(new SmsListener() {
        @Override
        public void messageReceived(String messageText) {
            ed.setText(messageText);     
        }
    });
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try
            {
                InputMethodManager imm=
  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);                    
  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
            }
            catch(Exception e)
            {}           
            if (ed.getText().toString().equals(otp_generated))
            {
                Toast.makeText(OtpVerificationActivity.this, "OTP Verified 
       Successfully !", Toast.LENGTH_SHORT).show();           
             }
    });
   }
}

Layout File for OtpVerificationActivity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_otp_verification"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wnrcorp.reba.OtpVerificationActivity">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/firstcard"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardCornerRadius="10dp"
    >
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@android:color/white">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OTP Confirmation"
            android:textSize="18sp"
            android:textStyle="bold"
            android:id="@+id/dialogTitle"
            android:layout_margin="5dp"
            android:layout_gravity="center"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/otp"
            android:layout_margin="5dp"
            android:hint="OTP Here"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Verify"
            android:textSize="18sp"
            android:id="@+id/verify_otp"
            android:gravity="center"
            android:padding="10dp"
            android:layout_gravity="center"
            android:visibility="visible"
            android:layout_margin="5dp"
            android:background="@color/colorPrimary"
            android:textColor="#ffffff"
            />
        </LinearLayout>
        </android.support.v7.widget.CardView>
        </RelativeLayout>

Screenshots for OTP Verification Activity where you fetch OTP as soons as messages received enter image description here

Trying to create a file in Android: open failed: EROFS (Read-only file system)

To use internal storage for the application, you don't need permission, but you may need to use: File directory = getApplication().getCacheDir(); to get the allowed directory for the app.

Or:
getCashDir(); <-- should work
context.getCashDir(); (if in a broadcast receiver)
getDataDir(); <--Api 24

What does the ">" (greater-than sign) CSS selector mean?

( child selector) was introduced in css2. div p{ } select all p elements decedent of div elements, whereas div > p selects only child p elements, not grand child, great grand child on so on.

<style>
  div p{  color:red  }       /* match both p*/
  div > p{  color:blue  }    /* match only first p*/

</style>

<div>
   <p>para tag, child and decedent of p.</p>
   <ul>
       <li>
            <p>para inside list. </p>
       </li>
   </ul>
</div>

For more information on CSS Ce[lectors and their use, check my blog, css selectors and css3 selectors

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

The user manual covers this topic in depth. You can:

  • pg_upgrade in-place; or

  • pg_dump and pg_restore.

If in doubt, do it with dumps. Don't delete the old data directory, just keep it in case something goes wrong / you make a mistake; that way you can just go back to your unchanged 9.3 install.

For details, see the manual.

If you're stuck, post a detailed question explaining how you're stuck, where, and what you tried first. It depends a bit on how you installed PostgreSQL too, as there are several different "distributions" of PostgreSQL for OS X (unfortunately). So you'd need to provide that info.

Set up an HTTP proxy to insert a header

If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found here.

Clear back stack using fragments

I posted something similar here

From Joachim's answer, from Dianne Hackborn:

http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42

I ended up just using:

FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {    
    fm.popBackStack();
}

But could equally have used something like:

((AppCompatActivity)getContext()).getSupportFragmentManager().popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)

Which will pop all states up to the named one. You can then just replace the fragment with what you want

How do you get the currently selected <option> in a <select> via JavaScript?

Using the selectedOptions property:

var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);

It works in all browsers except Internet Explorer.

SVN how to resolve new tree conflicts when file is added on two branches

What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full

svn resolve --accept base

Limit the length of a string with AngularJS

I know this is late, but in the latest version of angularjs (I'm using 1.2.16) the limitTo filter supports strings as well as arrays so you can limit the length of the string like this:

{{ "My String Is Too Long" | limitTo: 9 }}

which will output:

My String

Saving the PuTTY session logging

This is a bit confusing, but follow these steps to save the session.

  1. Category -> Session -> enter public IP in Host and 22 in port.
  2. Connection -> SSH -> Auth -> select the .ppk file
  3. Category -> Session -> enter a name in Saved Session -> Click Save

To open the session, double click on particular saved session.

Can I run Keras model on gpu?

Sure. I suppose that you have already installed TensorFlow for GPU.

You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.

import keras
import tensorflow as tf


config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} ) 
sess = tf.Session(config=config) 
keras.backend.set_session(sess)

Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.

Pass array to MySQL stored routine

If you don't want to use temporary tables here is a split string like function you can use

SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE 
    WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}') 
    THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1) 
    ELSE NULL
END AS Result;
  • SUBSTRING_INDEX(string, delim, n) returns the first n
  • SUBSTRING_INDEX(string, delim, -1) returns the last only
  • REGEXP '((delim).*){n}' checks if there are n delimiters (i.e. you are in bounds)

Port 80 is being used by SYSTEM (PID 4), what is that?

None of these worked for me. I had to go to a SuperUser question.

If it is a System Process—PID 4—you need to disable the HTTP.sys driver which is started on demand by another service, such as Windows Remote Management or Print Spooler on Windows 7 or 2008.

There is two ways to disable it but the first one is safer:

    • Go to device manager, select “show hidden devices” from menu/view, go to “Non-Plug and Play Driver”/HTTP, double click it to disable it (or set it to manual, some services depended on it).

    • Reboot and use netstat -nao | find ":80" to check if 80 is still used.

This is the one that worked for me!

Select distinct rows from datatable in Linq

Dim distinctValues As List(Of Double) = (From r In _
DirectCast(DataTable.AsEnumerable(),IEnumerable(Of DataRow)) Where (Not r.IsNull("ColName")) _
Select r.Field(Of Double)("ColName")).Distinct().ToList()

https with WCF error: "Could not find base address that matches scheme https"

It turned out that my problem was that I was using a load balancer to handle the SSL, which then sent it over http to the actual server, which then complained.

Description of a fix is here: http://blog.hackedbrain.com/2006/09/26/how-to-ssl-passthrough-with-wcf-or-transportwithmessagecredential-over-plain-http/

Edit: I fixed my problem, which was slightly different, after talking to microsoft support.

My silverlight app had its endpoint address in code going over https to the load balancer. The load balancer then changed the endpoint address to http and to point to the actual server that it was going to. So on each server's web config I added a listenUri for the endpoint that was http instead of https

<endpoint address="" listenUri="http://[LOAD_BALANCER_ADDRESS]" ... />

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

The problem could be:

  • the Application Pool for your site is configured for .NET Framework Version = v2.0.XXXXX
  • .NET 4 isn't installed on your server.

See also

... which helped me fix a similar issue.

Best JavaScript compressor

Js Crush is a good compressor to use after you have minified.

UNIX export command

When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME is set to /root in the parent then the child's $HOME variable is also set to /root.

This only applies to environment variable that are marked for export. If you set a variable at the command-line like

$ FOO="bar"

That variable will not be visible in child processes. Not unless you export it:

$ export FOO

You can combine these two statements into a single one in bash (but not in old-school sh):

$ export FOO="bar"

Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c creates a child shell process which inherits the parent shell's environment.

$ FOO=bar
$ sh -c 'echo $FOO'

$ export FOO
$ sh -c 'echo $FOO'
bar

Note: To get help on shell built-in commands use help export. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls.

Collections.emptyList() vs. new instance

Starting with Java 5.0 you can specify the type of element in the container:

Collections.<Foo>emptyList()

I concur with the other responses that for cases where you want to return an empty list that stays empty, you should use this approach.

How to check a boolean condition in EL?

You can check this way too

<c:if test="${theBooleanVariable ne true}">It's false!</c:if>

Setting device orientation in Swift iOS

My humble contribution (Xcode 8, Swift 3):

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
            if (rootViewController.responds(to: Selector(("canRotate")))) {
                // Unlock landscape view orientations for this view controller
                return .allButUpsideDown;
            }
        }
        return .portrait;        
    }

    private func topViewControllerWithRootViewController(rootViewController: UIViewController!) -> UIViewController? {
        if (rootViewController == nil) { return nil }
        if (rootViewController.isKind(of: (UITabBarController).self)) {
            return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UITabBarController).selectedViewController)
        } else if (rootViewController.isKind(of:(UINavigationController).self)) {
            return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UINavigationController).visibleViewController)
        } else if (rootViewController.presentedViewController != nil) {
            return topViewControllerWithRootViewController(rootViewController: rootViewController.presentedViewController)
        }
        return rootViewController
    }

... on the AppDelegate. All the credits for Gandhi Mena: http://www.jairobjunior.com/blog/2016/03/05/how-to-rotate-only-one-view-controller-to-landscape-in-ios-slash-swift/

How to list files inside a folder with SQL Server

I hunted around for ages to find a decent easy solution to this and in the end found some ridiculously complicated CLR solutions so decided to write my own simple VB one. Simply create a new VB CLR project from the Database tab under Installed Templates, and then add a new SQL CLR VB User Defined Function. I renamed it to CLRGetFilesInDir.vb. Here's the code inside it...

Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
-----------------------------------------------------------------------------
Public Class CLRFilesInDir
-----------------------------------------------------------------------------
<SqlFunction(FillRowMethodName:="FillRowFiles", IsDeterministic:=True, IsPrecise:=True, TableDefinition:="FilePath nvarchar(4000)")> _
Public Shared Function GetFiles(PathName As SqlString, Pattern As SqlString) As IEnumerable
    Dim FileNames As String()

    Try
    FileNames = Directory.GetFiles(PathName, Pattern, SearchOption.TopDirectoryOnly)
    Catch
        FileNames = Nothing
    End Try

    Return FileNames

End Function
-----------------------------------------------------------------------------
Public Shared Sub FillRowFiles(ByVal obj As Object, ByRef Val As SqlString)
    Val = CType(obj, String).ToString
End Sub

End Class

I also changed the Assembly Name in the Project Properties window to CLRExcelFiles, and the Default Namespace to CLRGetExcelFiles.

NOTE: Set the target framework to 3.5 if you are using anything less that SQL Server 2012.

Compile the project and then copy the CLRExcelFiles.dll from \bin\release to somewhere like C:\temp on the SQL Server machine, not your own.

In SSMS:-

CREATE ASSEMBLY <your assembly name in here - anything you like>
FROM 'C:\temp\CLRExcelFiles.dll';

CREATE FUNCTION dbo.fnGetFiles
(
@PathName NVARCHAR(MAX),
@Pattern NVARCHAR(MAX)
)
RETURNS TABLE (Val NVARCHAR(100))
AS
EXTERNAL NAME <your assembly name>."CLRGetExcelFiles.CLRFilesInDir".GetFiles;
GO

then call it

SELECT * FROM dbo.fnGetFiles('\\<SERVERNAME>\<$SHARE>\<folder>\' , '*.xls')

NOTE: Even though I changed the Permission Level to EXTERNAL_ACCESS on the SQLCLR tab under Project Properties, I still needed to run this every time I (re)created it.

ALTER ASSEMBLY [CLRFilesInDirAssembly] 
WITH PERMISSION_SET = EXTERNAL_ACCESS 
GO

and wullah! that should work.

Python urllib2: Receive JSON response from url

resource_url = 'http://localhost:8080/service/'
response = json.loads(urllib2.urlopen(resource_url).read())