Programs & Examples On #Scroller

Console.log not working at all

In my case, all console messages were not showing because I had left a string in the "filter" textbox.

Remove the filter it by clicking the X as shown:

enter image description here

How to display pdf in php

Try this below code

<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);
?>

Demo

get parent's view from a layout

The RelativeLayout (i.e. the ViewParent) should have a resource Id defined in the layout file (for example, android:id=@+id/myParentViewId). If you don't do that, the call to getId will return null. Look at this answer for more info.

Make element fixed on scroll

There are some problems implementing this which the original accepted answer does not answer:

  1. The onscroll event of the window is firing very often. This implies that you either have to use a very performant listener, or you have to delay the listener somehow. jQuery Creator John Resig states here how a delayed mechanism can be implemented, and the reasons why you should do it. In my opinion, given todays browsers and environments, a performant listener will do as well. Here is an implementation of the pattern suggested by John Resig
  2. The way position:fixed works in css, if you scroll down the page and move an element from position:static to position: fixed, the page will "jump" a little because the document "looses" the height of the element. You can get rid of that by adding the height to the scrollTop and replace the lost height in the document body with another object. You can also use that object to determine if the sticky item has already been moved to position: fixed and reduce the calls to the code reverting position: fixed to the original state: Look at the fiddle here
  3. Now, the only expensive thing in terms of performance the handler is really doing is calling scrollTop on every call. Since the interval bound handler has also its drawbacks, I'll go as far as to argue here that you can reattach the event listener to the original scroll Event to make it feel snappier without many worries. You'll have to profile it though, on every browser you target / support. See it working here

Here's the code:

JS

/* Initialize sticky outside the event listener as a cached selector.
 * Also, initialize any needed variables outside the listener for 
 * performance reasons - no variable instantiation is happening inside the listener.
 */
var sticky = $('#sticky'),
    stickyClone,
    stickyTop = sticky.offset().top,
    scrollTop,
    scrolled = false,
    $window = $(window);

/* Bind the scroll Event */
$window.on('scroll', function (e) {
    scrollTop = $window.scrollTop();

    if (scrollTop >= stickyTop && !stickyClone) {
        /* Attach a clone to replace the "missing" body height */
        stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
        stickyClone = stickyClone.insertBefore(sticky);
        sticky.addClass('fixed');
    } else if (scrollTop < stickyTop && stickyClone) {
        /* Since sticky is in the viewport again, we can remove the clone and the class */
        stickyClone.remove();
        stickyClone = null;
        sticky.removeClass('fixed');
    }
});

CSS

body {
    margin: 0
}
.sticky {
    padding: 1em;
    background: black;
    color: white;
    width: 100%
}
.sticky.fixed {
    position: fixed;
    top: 0;
    left: 0;
}
.content {
    padding: 1em
}

HTML

<div class="container">
  <div id="page-above" class="content">
    <h2>Some Content above sticky</h2>
    ...some long text...
  </div>
  <div id="sticky" class="sticky">This is sticky</div>
  <div id="page-content" class="content">
    <h2>Some Random Page Content</h2>...some really long text...
  </div>
</div>

How to set top position using jquery

Just for reference, if you are using:

 $(el).offset().top 

To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:

$(el).offset({top: pos});

As opposed to the CSS methods above.

Auto height div with overflow and scroll when needed

You can do this just with flexboxes and overflow property.

Even if parent height is computed too.

Please see this answer or JSFiddle for details.

iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

You need to trick the browser to use hardware acceleration more effectively. You can do this with an empty 3d transform:

-webkit-transform: translate3d(0,0,0)

Particularly, you'll need this on child elements that have a position:relative; declaration (or, just go all out and do it to all child elements).

Not a guaranteed fix, but fairly successful most of the time.

Hat tip: https://web.archive.org/web/20131005175118/http://cantina.co/2012/03/06/ios-5-native-scrolling-grins-and-gothcas/

Uncaught ReferenceError: jQuery is not defined

In my case, the error occurred because I was using the wrong version of jquery.

<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

I changed it to:

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Programmatically get height of navigation bar

I have used:

let originY: CGFloat = self.navigationController!.navigationBar.frame.maxY

Working great if you want to get the navigation bar height AND its Y origin.

How to add scroll bar to the Relative Layout?

You want to enclose it with a scrollView.

Set scroll position

... Or just replace body by documentElement:

document.documentElement.scrollTop = 0;

APK signing error : Failed to read key from keystore

Most likely that your key alias does not exist for your keystore file.

This answer should fix your signing issue ;)

Why does jQuery or a DOM method such as getElementById not find the element?

When I tried your code, it worked.

The only reason that your event is not working, may be that your DOM was not ready and your button with id "event-btn" was not yet ready. And your javascript got executed and tried to bind the event with that element.

Before using the DOM element for binding, that element should be ready. There are many options to do that.

Option1: You can move your event binding code within document ready event. Like:

document.addEventListener('DOMContentLoaded', (event) => {
  //your code to bind the event
});

Option2: You can use timeout event, so that binding is delayed for few seconds. like:

setTimeout(function(){
  //your code to bind the event
}, 500);

Option3: move your javascript include to the bottom of your page.

I hope this helps you.

Listing only directories in UNIX

du -d1 is perhaps the shortest option. (As long as you don't need to pipe the input to another command.)

Writing a VLOOKUP function in vba

Have you tried:

Dim result As String 
Dim sheet As Worksheet 
Set sheet = ActiveWorkbook.Sheets("Data") 
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)

Character Limit in HTML

you can set maxlength with jquery which is very fast

jQuery(document).ready(function($){ //fire on DOM ready
 setformfieldsize(jQuery('#comment'), 50, 'charsremain')
})

UICollectionView - Horizontal scroll, horizontal layout?

We can do same Springboard behavior using UICollectionView and for that we need to write code for custom layout.

I have achieved it with my custom layout class implementation with "SMCollectionViewFillLayout"

Code repository:

https://github.com/smindia1988/SMCollectionViewFillLayout

Output as below:

1.png

First.png

2_Code_H-Scroll_V-Fill.png

enter image description here

3_Output_H-Scroll_V-Fill.png enter image description here

4_Code_H-Scroll_H-Fill.png enter image description here

5_Output_H-Scroll_H-Fill.png enter image description here

Genymotion error at start 'Unable to load virtualbox'

In Linux at least, I had to restart VirtualBox, running this command on terminal:

/lib/virtualbox/VirtualBox restart

Seems to be the same on Mac OS X.

What is a monad?

tl;dr

{-# LANGUAGE InstanceSigs #-}

newtype Id t = Id t

instance Monad Id where
   return :: t -> Id t
   return = Id

   (=<<) :: (a -> Id b) -> Id a -> Id b
   f =<< (Id x) = f x

Prologue

The application operator $ of functions

forall a b. a -> b

is canonically defined

($) :: (a -> b) -> a -> b
f $ x = f x

infixr 0 $

in terms of Haskell-primitive function application f x (infixl 10).

Composition . is defined in terms of $ as

(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \ x -> f $ g x

infixr 9 .

and satisfies the equivalences forall f g h.

     f . id  =  f            :: c -> d   Right identity
     id . g  =  g            :: b -> c   Left identity
(f . g) . h  =  f . (g . h)  :: a -> d   Associativity

. is associative, and id is its right and left identity.

The Kleisli triple

In programming, a monad is a functor type constructor with an instance of the monad type class. There are several equivalent variants of definition and implementation, each carrying slightly different intuitions about the monad abstraction.

A functor is a type constructor f of kind * -> * with an instance of the functor type class.

{-# LANGUAGE KindSignatures #-}

class Functor (f :: * -> *) where
   map :: (a -> b) -> (f a -> f b)

In addition to following statically enforced type protocol, instances of the functor type class must obey the algebraic functor laws forall f g.

       map id  =  id           :: f t -> f t   Identity
map f . map g  =  map (f . g)  :: f a -> f c   Composition / short cut fusion

Functor computations have the type

forall f t. Functor f => f t

A computation c r consists in results r within context c.

Unary monadic functions or Kleisli arrows have the type

forall m a b. Functor m => a -> m b

Kleisi arrows are functions that take one argument a and return a monadic computation m b.

Monads are canonically defined in terms of the Kleisli triple forall m. Functor m =>

(m, return, (=<<))

implemented as the type class

class Functor m => Monad m where
   return :: t -> m t
   (=<<)  :: (a -> m b) -> m a -> m b

infixr 1 =<<

The Kleisli identity return is a Kleisli arrow that promotes a value t into monadic context m. Extension or Kleisli application =<< applies a Kleisli arrow a -> m b to results of a computation m a.

Kleisli composition <=< is defined in terms of extension as

(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
f <=< g = \ x -> f =<< g x

infixr 1 <=<

<=< composes two Kleisli arrows, applying the left arrow to results of the right arrow’s application.

Instances of the monad type class must obey the monad laws, most elegantly stated in terms of Kleisli composition: forall f g h.

   f <=< return  =  f                :: c -> m d   Right identity
   return <=< g  =  g                :: b -> m c   Left identity
(f <=< g) <=< h  =  f <=< (g <=< h)  :: a -> m d   Associativity

<=< is associative, and return is its right and left identity.

Identity

The identity type

type Id t = t

is the identity function on types

Id :: * -> *

Interpreted as a functor,

   return :: t -> Id t
=      id :: t ->    t

    (=<<) :: (a -> Id b) -> Id a -> Id b
=     ($) :: (a ->    b) ->    a ->    b

    (<=<) :: (b -> Id c) -> (a -> Id b) -> (a -> Id c)
=     (.) :: (b ->    c) -> (a ->    b) -> (a ->    c)

In canonical Haskell, the identity monad is defined

newtype Id t = Id t

instance Functor Id where
   map :: (a -> b) -> Id a -> Id b
   map f (Id x) = Id (f x)

instance Monad Id where
   return :: t -> Id t
   return = Id

   (=<<) :: (a -> Id b) -> Id a -> Id b
   f =<< (Id x) = f x

Option

An option type

data Maybe t = Nothing | Just t

encodes computation Maybe t that not necessarily yields a result t, computation that may “fail”. The option monad is defined

instance Functor Maybe where
   map :: (a -> b) -> (Maybe a -> Maybe b)
   map f (Just x) = Just (f x)
   map _ Nothing  = Nothing

instance Monad Maybe where
   return :: t -> Maybe t
   return = Just

   (=<<) :: (a -> Maybe b) -> Maybe a -> Maybe b
   f =<< (Just x) = f x
   _ =<< Nothing  = Nothing

a -> Maybe b is applied to a result only if Maybe a yields a result.

newtype Nat = Nat Int

The natural numbers can be encoded as those integers greater than or equal to zero.

toNat :: Int -> Maybe Nat
toNat i | i >= 0    = Just (Nat i)
        | otherwise = Nothing

The natural numbers are not closed under subtraction.

(-?) :: Nat -> Nat -> Maybe Nat
(Nat n) -? (Nat m) = toNat (n - m)

infixl 6 -?

The option monad covers a basic form of exception handling.

(-? 20) <=< toNat :: Int -> Maybe Nat

List

The list monad, over the list type

data [] t = [] | t : [t]

infixr 5 :

and its additive monoid operation “append”

(++) :: [t] -> [t] -> [t]
(x : xs) ++ ys = x : xs ++ ys
[]       ++ ys = ys

infixr 5 ++

encodes nonlinear computation [t] yielding a natural amount 0, 1, ... of results t.

instance Functor [] where
   map :: (a -> b) -> ([a] -> [b])
   map f (x : xs) = f x : map f xs
   map _ []       = []

instance Monad [] where
   return :: t -> [t]
   return = (: [])

   (=<<) :: (a -> [b]) -> [a] -> [b]
   f =<< (x : xs) = f x ++ (f =<< xs)
   _ =<< []       = []

Extension =<< concatenates ++ all lists [b] resulting from applications f x of a Kleisli arrow a -> [b] to elements of [a] into a single result list [b].

Let the proper divisors of a positive integer n be

divisors :: Integral t => t -> [t]
divisors n = filter (`divides` n) [2 .. n - 1]

divides :: Integral t => t -> t -> Bool
(`divides` n) = (== 0) . (n `rem`)

then

forall n.  let { f = f <=< divisors } in f n   =   []

In defining the monad type class, instead of extension =<<, the Haskell standard uses its flip, the bind operator >>=.

class Applicative m => Monad m where
   (>>=) :: forall a b. m a -> (a -> m b) -> m b

   (>>) :: forall a b. m a -> m b -> m b
   m >> k = m >>= \ _ -> k
   {-# INLINE (>>) #-}

   return :: a -> m a
   return = pure

For simplicity's sake, this explanation uses the type class hierarchy

class              Functor f
class Functor m => Monad m

In Haskell, the current standard hierarchy is

class                  Functor f
class Functor p     => Applicative p
class Applicative m => Monad m

because not only is every monad a functor, but every applicative is a functor and every monad is an applicative, too.

Using the list monad, the imperative pseudocode

for a in (1, ..., 10)
   for b in (1, ..., 10)
      p <- a * b
      if even(p)
         yield p

roughly translates to the do block,

do a <- [1 .. 10]
   b <- [1 .. 10]
   let p = a * b
   guard (even p)
   return p

the equivalent monad comprehension,

[ p | a <- [1 .. 10], b <- [1 .. 10], let p = a * b, even p ]

and the expression

[1 .. 10] >>= (\ a ->
   [1 .. 10] >>= (\ b ->
      let p = a * b in
         guard (even p) >>       -- [ () | even p ] >>
            return p
      )
   )

Do notation and monad comprehensions are syntactic sugar for nested bind expressions. The bind operator is used for local name binding of monadic results.

let x = v in e    =   (\ x -> e)  $  v   =   v  &  (\ x -> e)
do { r <- m; c }  =   (\ r -> c) =<< m   =   m >>= (\ r -> c)

where

(&) :: a -> (a -> b) -> b
(&) = flip ($)

infixl 0 &

The guard function is defined

guard :: Additive m => Bool -> m ()
guard True  = return ()
guard False = fail

where the unit type or “empty tuple”

data () = ()

Additive monads that support choice and failure can be abstracted over using a type class

class Monad m => Additive m where
   fail  :: m t
   (<|>) :: m t -> m t -> m t

infixl 3 <|>

instance Additive Maybe where
   fail = Nothing

   Nothing <|> m = m
   m       <|> _ = m

instance Additive [] where
   fail = []
   (<|>) = (++)

where fail and <|> form a monoid forall k l m.

     k <|> fail  =  k
     fail <|> l  =  l
(k <|> l) <|> m  =  k <|> (l <|> m)

and fail is the absorbing/annihilating zero element of additive monads

_ =<< fail  =  fail

If in

guard (even p) >> return p

even p is true, then the guard produces [()], and, by the definition of >>, the local constant function

\ _ -> return p

is applied to the result (). If false, then the guard produces the list monad’s fail ( [] ), which yields no result for a Kleisli arrow to be applied >> to, so this p is skipped over.

State

Infamously, monads are used to encode stateful computation.

A state processor is a function

forall st t. st -> (t, st)

that transitions a state st and yields a result t. The state st can be anything. Nothing, flag, count, array, handle, machine, world.

The type of state processors is usually called

type State st t = st -> (t, st)

The state processor monad is the kinded * -> * functor State st. Kleisli arrows of the state processor monad are functions

forall st a b. a -> (State st) b

In canonical Haskell, the lazy version of the state processor monad is defined

newtype State st t = State { stateProc :: st -> (t, st) }

instance Functor (State st) where
   map :: (a -> b) -> ((State st) a -> (State st) b)
   map f (State p) = State $ \ s0 -> let (x, s1) = p s0
                                     in  (f x, s1)

instance Monad (State st) where
   return :: t -> (State st) t
   return x = State $ \ s -> (x, s)

   (=<<) :: (a -> (State st) b) -> (State st) a -> (State st) b
   f =<< (State p) = State $ \ s0 -> let (x, s1) = p s0
                                     in  stateProc (f x) s1

A state processor is run by supplying an initial state:

run :: State st t -> st -> (t, st)
run = stateProc

eval :: State st t -> st -> t
eval = fst . run

exec :: State st t -> st -> st
exec = snd . run

State access is provided by primitives get and put, methods of abstraction over stateful monads:

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}

class Monad m => Stateful m st | m -> st where
   get :: m st
   put :: st -> m ()

m -> st declares a functional dependency of the state type st on the monad m; that a State t, for example, will determine the state type to be t uniquely.

instance Stateful (State st) st where
   get :: State st st
   get = State $ \ s -> (s, s)

   put :: st -> State st ()
   put s = State $ \ _ -> ((), s)

with the unit type used analogously to void in C.

modify :: Stateful m st => (st -> st) -> m ()
modify f = do
   s <- get
   put (f s)

gets :: Stateful m st => (st -> t) -> m t
gets f = do
   s <- get
   return (f s)

gets is often used with record field accessors.

The state monad equivalent of the variable threading

let s0 = 34
    s1 = (+ 1) s0
    n = (* 12) s1
    s2 = (+ 7) s1
in  (show n, s2)

where s0 :: Int, is the equally referentially transparent, but infinitely more elegant and practical

(flip run) 34
   (do
      modify (+ 1)
      n <- gets (* 12)
      modify (+ 7)
      return (show n)
   )

modify (+ 1) is a computation of type State Int (), except for its effect equivalent to return ().

(flip run) 34
   (modify (+ 1) >>
      gets (* 12) >>= (\ n ->
         modify (+ 7) >>
            return (show n)
      )
   )

The monad law of associativity can be written in terms of >>= forall m f g.

(m >>= f) >>= g  =  m >>= (\ x -> f x >>= g)

or

do {                 do {                   do {
   r1 <- do {           x <- m;                r0 <- m;
      r0 <- m;   =      do {            =      r1 <- f r0;
      f r0                 r1 <- f x;          g r1
   };                      g r1             }
   g r1                 }
}                    }

Like in expression-oriented programming (e.g. Rust), the last statement of a block represents its yield. The bind operator is sometimes called a “programmable semicolon”.

Iteration control structure primitives from structured imperative programming are emulated monadically

for :: Monad m => (a -> m b) -> [a] -> m ()
for f = foldr ((>>) . f) (return ())

while :: Monad m => m Bool -> m t -> m ()
while c m = do
   b <- c
   if b then m >> while c m
        else return ()

forever :: Monad m => m t
forever m = m >> forever m

Input/Output

data World

The I/O world state processor monad is a reconciliation of pure Haskell and the real world, of functional denotative and imperative operational semantics. A close analogue of the actual strict implementation:

type IO t = World -> (t, World)

Interaction is facilitated by impure primitives

getChar         :: IO Char
putChar         :: Char -> IO ()
readFile        :: FilePath -> IO String
writeFile       :: FilePath -> String -> IO ()
hSetBuffering   :: Handle -> BufferMode -> IO ()
hTell           :: Handle -> IO Integer
. . .              . . .

The impurity of code that uses IO primitives is permanently protocolized by the type system. Because purity is awesome, what happens in IO, stays in IO.

unsafePerformIO :: IO t -> t

Or, at least, should.

The type signature of a Haskell program

main :: IO ()
main = putStrLn "Hello, World!"

expands to

World -> ((), World)

A function that transforms a world.

Epilogue

The category whiches objects are Haskell types and whiches morphisms are functions between Haskell types is, “fast and loose”, the category Hask.

A functor T is a mapping from a category C to a category D; for each object in C an object in D

Tobj :  Obj(C) -> Obj(D)
   f :: *      -> *

and for each morphism in C a morphism in D

Tmor :  HomC(X, Y) -> HomD(Tobj(X), Tobj(Y))
 map :: (a -> b)   -> (f a -> f b)

where X, Y are objects in C. HomC(X, Y) is the homomorphism class of all morphisms X -> Y in C. The functor must preserve morphism identity and composition, the “structure” of C, in D.

                    Tmor    Tobj

      T(id)  =  id        : T(X) -> T(X)   Identity
T(f) . T(g)  =  T(f . g)  : T(X) -> T(Z)   Composition

The Kleisli category of a category C is given by a Kleisli triple

<T, eta, _*>

of an endofunctor

T : C -> C

(f), an identity morphism eta (return), and an extension operator * (=<<).

Each Kleisli morphism in Hask

      f :  X -> T(Y)
      f :: a -> m b

by the extension operator

   (_)* :  Hom(X, T(Y)) -> Hom(T(X), T(Y))
  (=<<) :: (a -> m b)   -> (m a -> m b)

is given a morphism in Hask’s Kleisli category

     f* :  T(X) -> T(Y)
(f =<<) :: m a  -> m b

Composition in the Kleisli category .T is given in terms of extension

 f .T g  =  f* . g       :  X -> T(Z)
f <=< g  =  (f =<<) . g  :: a -> m c

and satisfies the category axioms

       eta .T g  =  g                :  Y -> T(Z)   Left identity
   return <=< g  =  g                :: b -> m c

       f .T eta  =  f                :  Z -> T(U)   Right identity
   f <=< return  =  f                :: c -> m d

  (f .T g) .T h  =  f .T (g .T h)    :  X -> T(U)   Associativity
(f <=< g) <=< h  =  f <=< (g <=< h)  :: a -> m d

which, applying the equivalence transformations

     eta .T g  =  g
     eta* . g  =  g               By definition of .T
     eta* . g  =  id . g          forall f.  id . f  =  f
         eta*  =  id              forall f g h.  f . h  =  g . h  ==>  f  =  g

(f .T g) .T h  =  f .T (g .T h)
(f* . g)* . h  =  f* . (g* . h)   By definition of .T
(f* . g)* . h  =  f* . g* . h     . is associative
    (f* . g)*  =  f* . g*         forall f g h.  f . h  =  g . h  ==>  f  =  g

in terms of extension are canonically given

               eta*  =  id                 :  T(X) -> T(X)   Left identity
       (return =<<)  =  id                 :: m t -> m t

           f* . eta  =  f                  :  Z -> T(U)      Right identity
   (f =<<) . return  =  f                  :: c -> m d

          (f* . g)*  =  f* . g*            :  T(X) -> T(Z)   Associativity
(((f =<<) . g) =<<)  =  (f =<<) . (g =<<)  :: m a -> m c

Monads can also be defined in terms not of Kleislian extension, but a natural transformation mu, in programming called join. A monad is defined in terms of mu as a triple over a category C, of an endofunctor

     T :  C -> C
     f :: * -> *

and two natural tranformations

   eta :  Id -> T
return :: t  -> f t

    mu :  T . T   -> T
  join :: f (f t) -> f t

satisfying the equivalences

       mu . T(mu)  =  mu . mu               :  T . T . T -> T . T   Associativity
  join . map join  =  join . join           :: f (f (f t)) -> f t

      mu . T(eta)  =  mu . eta       =  id  :  T -> T               Identity
join . map return  =  join . return  =  id  :: f t -> f t

The monad type class is then defined

class Functor m => Monad m where
   return :: t -> m t
   join   :: m (m t) -> m t

The canonical mu implementation of the option monad:

instance Monad Maybe where
   return = Just

   join (Just m) = m
   join Nothing  = Nothing

The concat function

concat :: [[a]] -> [a]
concat (x : xs) = x ++ concat xs
concat []       = []

is the join of the list monad.

instance Monad [] where
   return :: t -> [t]
   return = (: [])

   (=<<) :: (a -> [b]) -> ([a] -> [b])
   (f =<<) = concat . map f

Implementations of join can be translated from extension form using the equivalence

     mu  =  id*           :  T . T -> T
   join  =  (id =<<)      :: m (m t) -> m t

The reverse translation from mu to extension form is given by

     f*  =  mu . T(f)     :  T(X) -> T(Y)
(f =<<)  =  join . map f  :: m a -> m b

But why should a theory so abstract be of any use for programming?

The answer is simple: as computer scientists, we value abstraction! When we design the interface to a software component, we want it to reveal as little as possible about the implementation. We want to be able to replace the implementation with many alternatives, many other ‘instances’ of the same ‘concept’. When we design a generic interface to many program libraries, it is even more important that the interface we choose have a variety of implementations. It is the generality of the monad concept which we value so highly, it is because category theory is so abstract that its concepts are so useful for programming.

It is hardly suprising, then, that the generalisation of monads that we present below also has a close connection to category theory. But we stress that our purpose is very practical: it is not to ‘implement category theory’, it is to find a more general way to structure combinator libraries. It is simply our good fortune that mathematicians have already done much of the work for us!

from Generalising Monads to Arrows by John Hughes

How can I loop over entries in JSON?

To decode json, you have to pass the json string. Currently you're trying to pass an object:

>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>

You can fetch the data with response.read().

How to style HTML5 range input to have different color before and after slider?

input type="range" min="0" max="50" value="0"  style="margin-left: 6%;width: 88%;background-color: whitesmoke;"

above code changes range input style.....

How do you remove the title text from the Android ActionBar?

you have two choice:

first:

getActionBar().setDisplayShowTitleEnabled(false);

If usign getActionBar() produced null pointer exception, you should use getSupportActionBar()

Second

getSupportActionBar().setTitle("your title");

or

getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().hide();

How to print last two columns using awk

@jim mcnamara: try using parentheses for around NF, i. e. $(NF-1) and $(NF) instead of $NF-1 and $NF (works on Mac OS X 10.6.8 for FreeBSD awkand gawk).

echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'

# output:
# 1 2
# 2 3
# two three

How to rebuild docker container in docker-compose.yml?

This should fix your problem:

docker-compose ps # lists all services (id, name)
docker-compose stop <id/name> #this will stop only the selected container
docker-compose rm <id/name> # this will remove the docker container permanently 
docker-compose up # builds/rebuilds all not already built container 

Check if cookies are enabled

JavaScript

You could create a cookie using JavaScript and check if it exists:

//Set a Cookie`
document.cookie="testcookie"`

//Check if cookie exists`
cookiesEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false`

Or you could use a jQuery Cookie plugin

//Set a Cookie`
$.cookie("testcookie", "testvalue")

//Check if cookie exists`
cookiesEnabled=( $.cookie("testcookie") ) ? true : false`

Php

setcookie("testcookie", "testvalue");

if( isset( $_COOKIE['testcookie'] ) ) {

}

Not sure if the Php will work as I'm unable to test it.

Professional jQuery based Combobox control?

For large datasets, how about JQuery UI Autocomplete, which is basically the "official" version of Jorn Zaeferrer's Autocomplete plugin?

I also wrote a straight JQuery combobox plugin that's gotten pretty good feedback from its users. It's explicitly not meant for large datasets though; I figure that if you want something that prunes the list based on what the user types, you're better off with Jorn's autocompletion plugin.

Custom "confirm" dialog in JavaScript?

SweetAlert

You should take a look at SweetAlert as an option to save some work. It's beautiful from the default state and is highly customizable.

Confirm Example

sweetAlert(
  {
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"
  }, 
  deleteIt()
);

Sample Alert

Illegal mix of collations error in MySql

If you want to avoid changing syntax to solve this problem, try this:

Update your MySQL to version 5.5 or greater.

This resolved the problem for me.

Anaconda export Environment file

The easiest way to save the packages from an environment to be installed in another computer is:

$ conda list -e > req.txt

then you can install the environment using

$ conda create -n <environment-name> --file req.txt

if you use pip, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/

$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt

Plot multiple boxplot in one graph

You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.

require(reshape2)
df <- read.csv("TestData.csv", header=T)
# melting by "Label". `melt is from the reshape2 package. 
# do ?melt to see what other things it can do (you will surely need it)
df.m <- melt(df, id.var = "Label")
> df.m # pasting some rows of the melted data.frame

#     Label variable      value
# 1    Good       F1 0.64778924
# 2    Good       F1 0.54608791
# 3    Good       F1 0.46134200
# 4    Good       F1 0.79421221
# 5    Good       F1 0.56919951
# 6    Good       F1 0.73568570
# 7    Good       F1 0.65094207
# 8    Good       F1 0.45749702
# 9    Good       F1 0.80861929
# 10   Good       F1 0.67310067
# 11   Good       F1 0.68781739
# 12   Good       F1 0.47009455
# 13   Good       F1 0.95859182
# 14   Good       F1 1.00000000
# 15   Good       F1 0.46908343
# 16    Bad       F1 0.57875528
# 17    Bad       F1 0.28938046
# 18    Bad       F1 0.68511766

require(ggplot2)
ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))

boxplot_ggplot2

Edit: I realise that you might need to facet. Here's an implementation of that as well:

p <- ggplot(data = df.m, aes(x=variable, y=value)) + 
             geom_boxplot(aes(fill=Label))
p + facet_wrap( ~ variable, scales="free")

ggplot2_faceted

Edit 2: How to add x-labels, y-labels, title, change legend heading, add a jitter?

p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill=Label))
p <- p + geom_jitter()
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p 

ggplot2_geom_plot

Edit 3: How to align geom_point() points to the center of box-plot? It could be done using position_dodge. This should work.

require(ggplot2)
p <- ggplot(data = df.m, aes(x=variable, y=value)) 
p <- p + geom_boxplot(aes(fill = Label))
# if you want color for points replace group with colour=Label
p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p 

ggplot2_position_dodge_geom_point

How do I force a DIV block to extend to the bottom of a page even if it has no content?

The min-height property is not supported by all browsers. If you need your #content to extend it's height on longer pages the height property will cut it short.

It's a bit of a hack but you could add an empty div with a width of 1px and height of e.g. 1000px inside your #content div. That will force the content to be at least 1000px high and still allow longer content to extend the height when needed

<img>: Unsafe value used in a resource URL context

I usually add separate safe pipe reusable component as following

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>

Insert variable values in the middle of a string

String.Format("Hi We have these flights for you: {0}. Which one do you want",
                              flights);

EDIT: you can even save the "template" string separately (for instance you could store it in a configuration file and retrieve it from there), like this:

string flights = "Flight A, B,C,D";

string template = @"Hi We have these flights for you: {0}. Which one do you want";
Console.WriteLine(String.Format(template, flights));

EDIT2: whoops, sorry I see that @DanPuzey had already suggested something very similar to my EDIT (but somewhat better)

How can I start an interactive console for Perl?

You can always just drop into the built-in debugger and run commands from there.

   perl -d -e 1

What does the explicit keyword mean?

The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.

Here's an example class with a constructor that can be used for implicit conversions:

class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }

  int GetFoo () { return m_foo; }

private:
  int m_foo;
};

Here's a simple function that takes a Foo object:

void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}

and here's where the DoBar function is called:

int main ()
{
  DoBar (42);
}

The argument is not a Foo object, but an int. However, there exists a constructor for Foo that takes an int so this constructor can be used to convert the parameter to the correct type.

The compiler is allowed to do this once for each parameter.

Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42). It is now necessary to call for conversion explicitly with DoBar (Foo (42))

The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:

  • You have a MyString(int size) class with a constructor that constructs a string of the given size. You have a function print(const MyString&), and you call print(3) (when you actually intended to call print("3")). You expect it to print "3", but it prints an empty string of length 3 instead.

How do I change the font-size of an <option> element within <select>?

One solution could be to wrap the options inside optgroup:

_x000D_
_x000D_
optgroup { font-size:40px; }
_x000D_
<select>
  <optgroup>
    <option selected="selected" class="service-small">Service area?</option>
    <option class="service-small">Volunteering</option>
    <option class="service-small">Partnership &amp; Support</option>
    <option class="service-small">Business Services</option>
  </optgroup>
</select>
_x000D_
_x000D_
_x000D_

to remove first and last element in array

You can use Array.prototype.reduce().

Code:

_x000D_
_x000D_
const fruits = ['Banana', 'Orange', 'Apple', 'Mango'],_x000D_
      result = fruits.reduce((a, c, i, array) => 0 === i || array.length - 1 === i ? a : [...a, c], []);_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Custom HTTP Authorization Header

No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string ) (see section 1.2), and your example doesn't use "=" that way.

how to send multiple data with $.ajax() jquery

You can create an object of key/value pairs and jQuery will do the rest for you:

$.ajax({
    ...
    data : { foo : 'bar', bar : 'foo' },
    ...
});

This way the data will be properly encoded automatically. If you do want to concoct you own string then make sure to use encodeURIComponent(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

Your current code is not working because the string is not concocted properly:

'id='+ id  & 'name='+ name

should be:

'id='+ encodeURIComponent(id) + '&name='+ encodeURIComponent(name)

Retrieving a random item from ArrayList

anyItem has never been declared as a variable, so it makes sense that it causes an error. But more importantly, you have code after a return statement and this will cause an unreachable code error.

how to instanceof List<MyType>?

That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:

public class GenericList <T> extends ArrayList<T>
{
     private Class<T> genericType;

     public GenericList(Class<T> c)
     {
          this.genericType = c;
     }

     public Class<T> getGenericType()
     {
          return genericType;
     }
}

UICollectionView Self Sizing Cells with Auto Layout

contentView anchor mystery:

In one bizarre case this

    contentView.translatesAutoresizingMaskIntoConstraints = false

would not work. Added four explicit anchors to the contentView and it worked.

class AnnoyingCell: UICollectionViewCell {
    
    @IBOutlet var word: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame); common() }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder); common() }
    
    private func common() {
        contentView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            contentView.leftAnchor.constraint(equalTo: leftAnchor),
            contentView.rightAnchor.constraint(equalTo: rightAnchor),
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
}

and as usual

    estimatedItemSize = UICollectionViewFlowLayout.automaticSize

in YourLayout: UICollectionViewFlowLayout

Who knows? Might help someone.

Credit

https://www.vadimbulavin.com/collection-view-cells-self-sizing/

stumbled on to the tip there - never saw it anywhere else in all the 1000s articles on this.

When to use "ON UPDATE CASCADE"

A few days ago I've had an issue with triggers, and I've figured out that ON UPDATE CASCADE can be useful. Take a look at this example (PostgreSQL):

CREATE TABLE club
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE band
(
    key SERIAL PRIMARY KEY,
    name TEXT UNIQUE
);

CREATE TABLE concert
(
    key SERIAL PRIMARY KEY,
    club_name TEXT REFERENCES club(name) ON UPDATE CASCADE,
    band_name TEXT REFERENCES band(name) ON UPDATE CASCADE,
    concert_date DATE
);

In my issue, I had to define some additional operations (trigger) for updating the concert's table. Those operations had to modify club_name and band_name. I was unable to do it, because of reference. I couldn't modify concert and then deal with club and band tables. I couldn't also do it the other way. ON UPDATE CASCADE was the key to solve the problem.

What do 3 dots next to a parameter type mean in Java?

Arguably, it is an example of syntactic sugar, since it is implemented as an array anyways (which doesn't mean it's useless) - I prefer passing an array to keep it clear, and also declare methods with arrays of given type. Rather an opinion than an answer, though.

Where is web.xml in Eclipse Dynamic Web Project

I think you are creating a project in the wrong way,I am going to post here in step by step

Step 1: File>>New>>Project>>Web>>Dynamic Web Project

Step 2: Enter Project Name>>Next>>Next>>

Step 3: Check the checkbox for Generate web.xml deployment descriptor

Step 4: Finish

Please follow this way you will get you web.xml file under WEB-INF folder

How to change a field name in JSON using Jackson

Have you tried using @JsonProperty?

@Entity
public class City {
   @id
   Long id;
   String name;

   @JsonProperty("label")
   public String getName() { return name; }

   public void setName(String name){ this.name = name; }

   @JsonProperty("value")
   public Long getId() { return id; }

   public void setId(Long id){ this.id = id; }
}

How can you get the build/version number of your Android application?

If you're using the Gradle plugin/Android Studio, as of version 0.7.0, version code and version name are available statically in BuildConfig. Make sure you import your app's package, and not another BuildConfig:

import com.yourpackage.BuildConfig;
...
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;

No Context object needed!

Also make sure to specify them in your build.gradle file instead of the AndroidManifest.xml.

defaultConfig {
    versionCode 1
    versionName "1.0"
}

AngularJs event to call after content is loaded

var myM = angular.module('data-module');

myM.directive('myDirect',['$document', function( $document ){

    function link( scope , element , attrs ){

        element.ready( function(){

        } );

        scope.$on( '$viewContentLoaded' , function(){

            console.log(" ===> Called on View Load ") ;

        } );

    }

    return {
        link: link
    };

}] );

Above method worked for me

Retrieve the commit log for a specific line in a file?

If the position of the line (line number) stays the same through the history of the file, this will show you the contents of the line at each commit:

git log --follow --pretty=format:"%h" -- 'path/to/file' | while read -r hash; do echo $hash && git show $hash:'path/to/file' | head -n 544 | tail -n1; done

Change 544 to the line number and path/to/file to the file path.

How to force keyboard with numbers in mobile website in Android

Some browsers igoners sending leading zero to the server when the input type is "number". So I use a mixing of jquery and html to load a numeric keypad and also make sure that the value is sent as a text not as a number:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$(".numberonly").focus(function(){$(this).attr("type","number")});_x000D_
$(".numberonly").blur(function(){$(this).attr("type","text")});_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" class="numberonly">
_x000D_
_x000D_
_x000D_

How can I split a string with a string delimiter?

string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);

If you have a single character delimiter (like for instance ,), you can reduce that to (note the single quotes):

string[] tokens = str.Split(',');

How do I make my string comparison case insensitive?

  • The best would be using s1.equalsIgnoreCase(s2): (see javadoc)
  • You can also convert them both to upper/lower case and use s1.equals(s2)

How to get full width in body element

If its in a landscape then you will be needing more width and less height! That's just what all websites have.

Lets go with a basic first then the rest!

The basic CSS:

By CSS you can do this,

#body {
width: 100%;
height: 100%;
}

Here you are using a div with id body, as:

<body>
  <div id="body>
    all the text would go here!
  </div>
</body>

Then you can have a web page with 100% height and width.

What if he tries to resize the window?

The issues pops up, what if he tries to resize the window? Then all the elements inside #body would try to mess up the UI. For that you can write this:

#body {
height: 100%;
width: 100%;
}

And just add min-height max-height min-width and max-width.

This way, the page element would stay at the place they were at the page load.

Using JavaScript:

Using JavaScript, you can control the UI, use jQuery as:

$('#body').css('min-height', '100%');

And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.

How to not add scroll to the web page:

If you are not trying to add a scroll, then you can use this JS

$('#body').css('min-height', screen.height); // or anyother like window.height

This way, the document will get a new height whenever the user would load the page.

Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!

Tip: So try using JS to find current Screen size and edit the page! :)

LaTeX beamer: way to change the bullet indentation?

Setting \itemindent for a new itemize environment solves the problem:

\newenvironment{beameritemize}
{ \begin{itemize}
  \setlength{\itemsep}{1.5ex}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}   
  \addtolength{\itemindent}{-2em}  }
{ \end{itemize} } 

How to stop docker under Linux

if you have no systemctl and started the docker daemon by:

sudo service docker start

you can stop it by:

sudo service docker stop

Make multiple-select to adjust its height to fit options without scroll bar

For jQuery you can try this. I always do the following and it works.

$(function () {
   $("#multiSelect").attr("size",$("#multiSelect option").length);
});

What is the difference between dict.items() and dict.iteritems() in Python2?

If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:

DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))

Use it like this:

for key, value in DICT_ITER_ITEMS(myDict):
    # Do something with 'key' and/or 'value'.

Can I extend a class using more than 1 class in PHP?

You cannot have a class that extends two base classes. You could not have.

// this is NOT allowed (for all you google speeders)
Matron extends Nurse, HumanEntity

You could however have a hierarchy as follows...

Matron extends Nurse    
Consultant extends Doctor

Nurse extends HumanEntity
Doctor extends HumanEntity

HumanEntity extends DatabaseTable
DatabaseTable extends AbstractTable

and so on.

in angularjs how to access the element that triggered the event?

if you wanna ng-model value, if you can write like this in the triggered event: $scope.searchText

Import existing source code to GitHub

Here are some instructions on how to initiate a GitHub repository and then push code you've already created to it. The first set of instructions are directly from GitHub.

Source: https://help.github.com/articles/create-a-repo/

  1. In the upper-right corner of any page, click, and then click New repository.

  2. Create a short, memorable name for your repository. For example, "hello-world".

  3. Optionally, add a description of your repository. For example, "My first repository on GitHub."

  4. Choose between creating a public or private repository.

  5. Initialize this repository with a README.

  6. Create repository.

Congratulations! You've successfully created your first repository, and initialized it with a README file.

Now after these steps you will want to push the code on your local computer up to the repository you just created and you do this following these steps:

  1. git init (in the root folder where your code is located)

  2. git add -A (this will add all the files and folders in your directory to be committed)

  3. git commit -am "First Project commit"

  4. git remote add origin [email protected]:YourGithubName/your-repo-name.git (you'll find this address on the GitHub repository you just created under "ssh clone URL" on the main page)

  5. git push -u origin master

That's it. Your code will now be pushed up to GitHub. Now every time you want to keep pushing code that has changed just do.

  1. git commit -m "New changes"

  2. git push origin master (if master is the branch you are working on)

Get current language in CultureInfo

This is what i used:

var culture = System.Globalization.CultureInfo.CurrentCulture;

and it's working :)

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

... or if you really want to use NOT IN you can use

SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)

Can you do a partial checkout with Subversion?

I wrote a script to automate complex sparse checkouts.

#!/usr/bin/env python

'''
This script makes a sparse checkout of an SVN tree in the current working directory.

Given a list of paths in an SVN repository, it will:
1. Checkout the common root directory
2. Update with depth=empty for intermediate directories
3. Update with depth=infinity for the leaf directories
'''

import os
import getpass
import pysvn

__author__ = "Karl Ostmo"
__date__ = "July 13, 2011"

# =============================================================================

# XXX The os.path.commonprefix() function does not behave as expected!
# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html
# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
# and here (what ever happened?): http://bugs.python.org/issue400788
from itertools import takewhile
def allnamesequal(name):
    return all(n==name[0] for n in name[1:])

def commonprefix(paths, sep='/'):
    bydirectorylevels = zip(*[p.split(sep) for p in paths])
    return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))

# =============================================================================
def getSvnClient(options):

    password = options.svn_password
    if not password:
        password = getpass.getpass('Enter SVN password for user "%s": ' % options.svn_username)

    client = pysvn.Client()
    client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)
    return client

# =============================================================================
def sparse_update_with_feedback(client, new_update_path):
    revision_list = client.update(new_update_path, depth=pysvn.depth.empty)

# =============================================================================
def sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):

    path_segments = sparse_path.split(os.sep)
    path_segments.reverse()

    # Update the middle path segments
    new_update_path = local_checkout_root
    while len(path_segments) > 1:
        path_segment = path_segments.pop()
        new_update_path = os.path.join(new_update_path, path_segment)
        sparse_update_with_feedback(client, new_update_path)
        if options.verbose:
            print "Added internal node:", path_segment

    # Update the leaf path segment, fully-recursive
    leaf_segment = path_segments.pop()
    new_update_path = os.path.join(new_update_path, leaf_segment)

    if options.verbose:
        print "Will now update with 'recursive':", new_update_path
    update_revision_list = client.update(new_update_path)

    if options.verbose:
        for revision in update_revision_list:
            print "- Finished updating %s to revision: %d" % (new_update_path, revision.number)

# =============================================================================
def group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):

    if not sparse_path_list:
        print "Nothing to do!"
        return

    checkout_path = None
    if len(sparse_path_list) > 1:
        checkout_path = commonprefix(sparse_path_list)
    else:
        checkout_path = sparse_path_list[0].split(os.sep)[0]



    root_checkout_url = os.path.join(repo_url, checkout_path).replace("\\", "/")
    revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)

    checkout_path_segments = checkout_path.split(os.sep)
    for sparse_path in sparse_path_list:

        # Remove the leading path segments
        path_segments = sparse_path.split(os.sep)
        start_segment_index = 0
        for i, segment in enumerate(checkout_path_segments):
            if segment == path_segments[i]:
                start_segment_index += 1
            else:
                break

        pruned_path = os.sep.join(path_segments[start_segment_index:])
        sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)

# =============================================================================
if __name__ == "__main__":

    from optparse import OptionParser
    usage = """%prog  [path2] [more paths...]"""

    default_repo_url = "http://svn.example.com/MyRepository"
    default_checkout_path = "sparse_trunk"

    parser = OptionParser(usage)
    parser.add_option("-r", "--repo_url", type="str", default=default_repo_url, dest="repo_url", help='Repository URL (default: "%s")' % default_repo_url)
    parser.add_option("-l", "--local_path", type="str", default=default_checkout_path, dest="local_path", help='Local checkout path (default: "%s")' % default_checkout_path)

    default_username = getpass.getuser()
    parser.add_option("-u", "--username", type="str", default=default_username, dest="svn_username", help='SVN login username (default: "%s")' % default_username)
    parser.add_option("-p", "--password", type="str", dest="svn_password", help="SVN login password")

    parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="Verbose output")
    (options, args) = parser.parse_args()

    client = getSvnClient(options)
    group_sparse_checkout(
        options,
        client,
        options.repo_url,
        map(os.path.relpath, args),
        options.local_path)

Dropping connected users in Oracle database

Sometimes Oracle drop user takes long time to execute. In that case user might be connected to the database. Better you can kill user session and drop the user.

SQL> select 'alter system kill session ''' || sid || ',' || serial# || ''' immediate;' from v$session where username ='&USERNAME';

SQL> DROP USER barbie CASCADE;

How can I view the contents of an ElasticSearch index?

If you didn't index too much data into the index yet, you can use term facet query on the field that you would like to debug to see the tokens and their frequencies:

curl -XDELETE 'http://localhost:9200/test-idx'
echo
curl -XPUT 'http://localhost:9200/test-idx' -d '
{
    "settings": {
        "index.number_of_shards" : 1,
        "index.number_of_replicas": 0
    },
    "mappings": {            
        "doc": {
            "properties": {
                "message": {"type": "string", "analyzer": "snowball"}
            }
        }
    }

}'
echo
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '
{
  "message": "How is this going to be indexed?"
}
'
echo
curl -XPOST 'http://localhost:9200/test-idx/_refresh'
echo
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true&search_type=count' -d '{
    "query": {
        "match": {
            "_id": "1"
        }
    },
    "facets": {
        "tokens": {
            "terms": {
                "field": "message"
            }
        }
    }
}
'
echo

"Could not find a part of the path" error message

I resolved a similar issue by simply restarting Visual Studio with admin rights.

The problem was because it couldn't open one project related to Sharepoint without elevated access.

whitespaces in the path of windows filepath

path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"

Closing the path in r"string" also solved this problem very well.

Web API Put Request generates an Http 405 Method Not Allowed error

Add this to your web.config. You need to tell IIS what PUT PATCH DELETE and OPTIONS means. And which IHttpHandler to invoke.

<configuation>
    <system.webServer>
    <handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    </system.webServer>
</configuration>

Also check you don't have WebDAV enabled.

Create a function with optional call variables

Not sure I understand the question correctly.

From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?

I changed the code to reassemble the assumptions made above.

Function DoStuff($computername, $arg2, $domain)
{
    if($domain -ne $null)
    {
        $domain = "Domain1"
    }

    if($arg2 -eq $null)
    {
    }
    else
    {
    }
}

DoStuff -computername "Test" -arg2 "" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Test"  -domain ""
DoStuff -computername "Test" -domain "Domain2"
DoStuff -computername "Test" -arg2 "Domain2"

Did that help?

What does \d+ mean in regular expression terms?

\d is called a character class and will match digits. It is equal to [0-9].

+ matches 1 or more occurrences of the character before.

So \d+ means match 1 or more digits.

android TextView: setting the background color dynamically doesn't work

Try this:

TextView c1 = new TextView(activity);
c1.setTextColor(getResources().getColor(R.color.solid_red));
c1.setText("My Text");

I agree that a color and a resource have the same type, but I also spend a few hours to find this solution.

Excel formula to display ONLY month and year?

First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.

Apache Cordova - uninstall globally

Try sudo npm uninstall cordova -g to uninstall it globally and then just npm install cordova without the -g flag after cding to the local app directory

Composer - the requested PHP extension mbstring is missing from your system

  1. find your php.ini
  2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir)
  3. make sure the directive extension=php_mbstring.dll is set (uncommented)

If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.

how to get all markers on google-maps-v3

If you are using JQuery Google map plug-in then below code will work for you -

var markers = $('#map_canvas').gmap('get','markers');

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

Scraping html tables into R data frames using the XML package

The rvest along with xml2 is another popular package for parsing html web pages.

library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

The syntax is easier to use than the xml package and for most web pages the package provides all of the options ones needs.

Can you put two conditions in an xslt test attribute?

It does have to be wrapped in an <xsl:choose> since it's a when. And lowercase the "and".

<xsl:choose>
   <xsl:when test="4 &lt; 5 and 1 &lt; 2" >
   <!-- do something -->
   </xsl:when>
   <xsl:otherwise>
   <!-- do something else -->
   </xsl:otherwise>
</xsl:choose>

How can I use Google's Roboto font on a website?

It's actually quite simple. Go to the font on Google's website, and add its link to the head of every page you want to include the font.

show all tables in DB2 using the LIST command

select * from syscat.tables where type = 'T'

you may want to restrict the query to your tabschema

Best Way to Refresh Adapter/ListView on Android

You should use adapter.notifyDataSetChanged(). What does the logs says when you use that?

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I have tested this on EF core 2.1

Here you cannot use either Conventions or Data Annotations. You must use the Fluent API.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Created)
            .HasDefaultValueSql("getdate()");
    }
}

Official doc

Can we pass an array as parameter in any function in PHP?

What should be clarified here.

Just pass the array when you call this function.

function sendemail($id,$userid){
Some Process....
}
$id=array(1,2);
sendmail($id,$userid);

Mockito match any class argument

How about:

when(a.method(isA(A.class))).thenReturn(b);

or:

when(a.method((A)notNull())).thenReturn(b);

Spark: subtract two DataFrames

From spark 3.0

data_cl = reg_data.exceptAll(data_fr)

Determining the last row in a single column

I am using getDataRange() followed by getNumRows(). The first function

Returns a Range corresponding to the dimensions in which data is present

and the second function

Returns the number of rows in this range.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getActiveSheet();
var lastRow = ws.getDataRange().getNumRows();

P.S I hope this works for all cases.

What's the key difference between HTML 4 and HTML 5?

HTML5 has several goals which differentiate it from HTML4.

Consistency in Handling Malformed Documents

The primary one is consistent, defined error handling. As you know, HTML purposely supports 'tag soup', or the ability to write malformed code and have it corrected into a valid document. The problem is that the rules for doing this aren't written down anywhere. When a new browser vendor wants to enter the market, they just have to test malformed documents in various browsers (especially IE) and reverse-engineer their error handling. If they don't, then many pages won't display correctly (estimates place roughly 90% of pages on the net as being at least somewhat malformed).

So, HTML5 is attempting to discover and codify this error handling, so that browser developers can all standardize and greatly reduce the time and money required to display things consistently. As well, long in the future after HTML has died as a document format, historians may still want to read our documents, and having a completely defined parsing algorithm will greatly aid this.

Better Web Application Features

The secondary goal of HTML5 is to develop the ability of the browser to be an application platform, via HTML, CSS, and Javascript. Many elements have been added directly to the language that are currently (in HTML4) Flash or JS-based hacks, such as <canvas>, <video>, and <audio>. Useful things such as Local Storage (a js-accessible browser-built-in key-value database, for storing information beyond what cookies can hold), new input types such as date for which the browser can expose easy user interface (so that we don't have to use our js-based calendar date-pickers), and browser-supported form validation will make developing web applications much simpler for the developers, and make them much faster for the users (since many things will be supported natively, rather than hacked in via javascript).

Improved Element Semantics

There are many other smaller efforts taking place in HTML5, such as better-defined semantic roles for existing elements (<strong> and <em> now actually mean something different, and even <b> and <i> have vague semantics that should work well when parsing legacy documents) and adding new elements with useful semantics - <article>, <section>, <header>, <aside>, and <nav> should replace the majority of <div>s used on a web page, making your pages a bit more semantic, but more importantly, easier to read. No more painful scanning to see just what that random </div> is closing - instead you'll have an obvious </header>, or </article>, making the structure of your document much more intuitive.

Add animated Gif image in Iphone UIImageView

I know that an answer has already been approved, but its hard not to try to share that I've created an embedded framework that adds Gif support to iOS that feels just like if you were using any other UIKit Framework class.

Here's an example:

UIGifImage *gif = [[UIGifImage alloc] initWithData:imageData];
anUiImageView.image = gif;

Download the latest release from https://github.com/ObjSal/UIGifImage/releases

-- Sal

How to use JavaScript to change div backgroundColor

It's very simple just use a function on javaScript and call it onclick

   <script type="text/javascript">
            function change()
            {
            document.getElementById("catestory").style.backgroundColor="#666666";
            }
            </script>

    <a href="#" onclick="change()">Change Bacckground Color</a>

Where does Internet Explorer store saved passwords?

I found the answer. IE stores passwords in two different locations based on the password type:

  • Http-Auth: %APPDATA%\Microsoft\Credentials, in encrypted files
  • Form-based: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2, encrypted with the url

From a very good page on NirSoft.com:

Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:

  • AutoComplete Passwords: These passwords are saved in the following location in the Registry: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2 The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).

  • HTTP Authentication Passwords: These passwords are stored in the Credentials file under Documents and Settings\Application Data\Microsoft\Credentials, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.

In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead/CredWrite, where the user can manage their passwords from within an established UI system in Windows.

How to describe table in SQL Server 2008?

You can use keyboard short-cut for Description/ detailed information of Table in SQL Server 2008.

Follow steps:

  1. Write Table Name,
  2. Select it, and press Alt + F1
  3. It will show detailed information/ description of mentioned table as,

    1) Table created date,
    2) Columns Description,
    3) Identity,
    4) Indexes,
    5) Constraints,
    6) References etc. As shown Below [example]:

Alt+F1 Demo

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Got the same error, CHECK THIS : MINOR SILLY MISTAKE

check findviewbyid(R.id.yourID); If you have put the id correct or not.

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

How to increase maximum execution time in php

use below statement if safe_mode is off

set_time_limit(0);

Java HTML Parsing

Jericho: http://jericho.htmlparser.net/docs/index.html

Easy to use, supports not well formed HTML, a lot of examples.

Define a fixed-size list in Java

Yes,

Commons library provides a built-in FixedSizeList which does not support the add, remove and clear methods (but the set method is allowed because it does not modify the List's size). In other words, if you try to call one of these methods, your list still retain the same size.

To create your fixed size list, just call

List<YourType> fixed = FixedSizeList.decorate(Arrays.asList(new YourType[100]));

You can use unmodifiableList if you want an unmodifiable view of the specified list, or read-only access to internal lists.

List<YourType> unmodifiable = java.util.Collections.unmodifiableList(internalList);

No == operator found while comparing structs in C++

Because you did not write a comparison operator for your struct. The compiler does not generate it for you, so if you want comparison, you have to write it yourself.

Compare two files in Visual Studio

File Comparer VS Extension by Akhil Mittal. Excellent lightweight tool that gets the job done.

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Create Carriage Return in PHP String?

Fragment PHP (in console Cloud9):

echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";

resulting output:

  1: first_srt=1
  secnd_srt=2

  2: first_srt=1\nsecnd_srt=2\n
  ==============

Difference between 1 and 2: " versus '

Add a reference column migration in Rails 4

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID

Where does linux store my syslog?

On my Ubuntu machine, I can see the output at /var/log/syslog.

On a RHEL/CentOS machine, the output is found in /var/log/messages.

This is controlled by the rsyslog service, so if this is disabled for some reason you may need to start it with systemctl start rsyslog.

As noted by others, your syslog() output would be logged by the /var/log/syslog file.
You can see system, user, and other logs at /var/log.

For more details: here's an interesting link.

Laravel 5.5 ajax call 419 (unknown status)

If you are loading .js from a file you have to set a variable with the csrf_token in your "main" .blade.php file where you are importing the .js and use the variable in your ajax call.

index.blade.php

...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
        var token = '{{ csrf_token() }}';
</script>

anotherfile.js

$.ajax({
    url: 'yourUrl',
    type: 'POST',
    data: {
        '_token': token
    },
    dataType: "json",
    beforeSend:function(){
        //do stuff
    },
    success: function(data) {
        //do stuff
    },
    error: function(data) {
        //do stuff
    },
    complete: function(){
        //do stuff
    }
});

how to display a div triggered by onclick event

You'll have to give an ID to the div you want to show/hide, then use this code:

html:

<div id="one">
    <div id="tow">
        This is text
    </div>
    <button onclick="javascript:showDiv();">Click to show div</button>
</div>

javascript:

function showDiv() {
    div = document.getElementById('tow');
    div.style.display = "block";
}

CSS:

?#tow { display: none; }?

Fiddle: http://jsfiddle.net/xkdNa/

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

How to make a smaller RatingBar?

<RatingBar
    android:id="@+id/rating_bar"
    style="@style/Widget.AppCompat.RatingBar.Small"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I got the same error {AttributeError: 'bytes' object has no attribute 'read'} in python3. This worked for me later without using json:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Integrated application pool mode

When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.

There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.

Classic application pool mode

When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.

This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.

Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.

Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?

Original source: Introduction to IIS Architecture

Reference - What does this error mean in PHP?

Warning: [function]: failed to open stream: [reason]

It happens when you call a file usually by include, require or fopen and PHP couldn't find the file or have not enough permission to load the file.

This can happen for a variety of reasons :

  • the file path is wrong
  • the file path is relative
  • include path is wrong
  • permissions are too restrictive
  • SELinux is in force
  • and many more ...

One common mistake is to not use an absolute path. This can be easily solved by using a full path or magic constants like __DIR__ or dirname(__FILE__):

include __DIR__ . '/inc/globals.inc.php';

or:

require dirname(__FILE__) . '/inc/globals.inc.php';

Ensuring the right path is used is one step in troubleshooting these issues, this can also be related to non-existing files, rights of the filesystem preventing access or open basedir restrictions by PHP itself.

The best way to solve this problem quickly is to follow the troubleshooting checklist below.

Related Questions:

Related Errors:

Make a negative number positive

You're looking for absolute value, mate. Math.abs(-5) returns 5...

How can I split a text file using PowerShell?

Here is my solution to split a file called patch6.txt (about 32,000 lines) into separate files of 1000 lines each. Its not quick, but it does the job.

$infile = "D:\Malcolm\Test\patch6.txt"
$path = "D:\Malcolm\Test\"
$lineCount = 1
$fileCount = 1

foreach ($computername in get-content $infile)
{
    write $computername | out-file -Append $path_$fileCount".txt"
    $lineCount++

    if ($lineCount -eq 1000)
    {
        $fileCount++
        $lineCount = 1
    }
}

'do...while' vs. 'while'

I've used a do while when I'm reading a sentinel value at the beginning of a file, but other than that, I don't think it's abnormal that this structure isn't too commonly used--do-whiles are really situational.

-- file --
5
Joe
Bob
Jake
Sarah
Sue

-- code --
int MAX;
int count = 0;
do {
MAX = a.readLine();
k[count] = a.readLine();
count++;
} while(count <= MAX)

macro run-time error '9': subscript out of range

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

android: stretch image in imageview to fit screen

if you use android:scaleType="fitXY" then you must specify

android:layout_width="75dp" and android:layout_height="75dp"

if use wrap_content it will not stretch to what you need

<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="@+id/listItemNoteImage"
android:src="@drawable/MyImage"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="12dp"
android:scaleType="fitXY"/>

Coding Conventions - Naming Enums

enum MyEnum {VALUE_1,VALUE_2}

is (approximately) like saying

class MyEnum {

    public static final MyEnum VALUE_1 = new MyEnum("VALUE_1");
    public static final MyEnum VALUE_2 = new MyEnum("VALUE_2");

    private final name;

    private MyEnum(String name) {
        this.name = name;
    }

    public String name() { return this.name }
}

so I guess the all caps is strictly more correct, but still I use the class name convention since I hate all caps wherever

update columns values with column of another table based on condition

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);

check all socket opened in linux OS

/proc/net/tcp -a list of open tcp sockets

/proc/net/udp -a list of open udp sockets

/proc/net/raw -a list all the 'raw' sockets

These are the files, use cat command to view them. For example:

cat /proc/net/tcp

You can also use the lsof command.

lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.

How to get the sign, mantissa and exponent of a floating point number

Find out the format of the floating point numbers used on the CPU that directly supports floating point and break it down into those parts. The most common format is IEEE-754.

Alternatively, you could obtain those parts using a few special functions (double frexp(double value, int *exp); and double ldexp(double x, int exp);) as shown in this answer.

Another option is to use %a with printf().

How do you import classes in JSP?

Use the following import statement to import java.util.List:

<%@ page import="java.util.List" %>

BTW, to import more than one class, use the following format:

<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>

How to set image for bar button with swift?

Similar to the accepted solution, but you can replace the

let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton

with

let button = UIButton()

Here is the full solution, enjoy: (it's just a bit cleaner than the accepted solution)

let button = UIButton()
button.frame = CGRectMake(0, 0, 51, 31) //won't work if you don't set frame
button.setImage(UIImage(named: "fb"), forState: .Normal)
button.addTarget(self, action: Selector("fbButtonPressed"), forControlEvents: .TouchUpInside)

let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton

How do I get the number of elements in a list?

While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a length property:

class slist(list):
    @property
    def length(self):
        return len(self)

You can use it like so:

>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly length property.

As always, your mileage may vary.

Converting Secret Key into a String and Vice Versa

Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:

  1. *.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html

  2. Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

  3. Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html

Code snippets: For encoding:

String temp = new String(Base64.getEncoder().encode(key.getEncoded()));

For decoding:

byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");

How do I break a string across more than one line of code in JavaScript?

You can just use

1:  alert("Please select file" +
2:        " to delete");

That should work

HTML anchor tag with Javascript onclick event

Use following code to show menu instead go to href addres

_x000D_
_x000D_
function show_more_menu(e) {_x000D_
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
_x000D_
_x000D_

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

What is a Windows Handle?

It's an abstract reference value to a resource, often memory or an open file, or a pipe.

Properly, in Windows, (and generally in computing) a handle is an abstraction which hides a real memory address from the API user, allowing the system to reorganize physical memory transparently to the program. Resolving a handle into a pointer locks the memory, and releasing the handle invalidates the pointer. In this case think of it as an index into a table of pointers... you use the index for the system API calls, and the system can change the pointer in the table at will.

Alternatively a real pointer may be given as the handle when the API writer intends that the user of the API be insulated from the specifics of what the address returned points to; in this case it must be considered that what the handle points to may change at any time (from API version to version or even from call to call of the API that returns the handle) - the handle should therefore be treated as simply an opaque value meaningful only to the API.

I should add that in any modern operating system, even the so-called "real pointers" are still opaque handles into the virtual memory space of the process, which enables the O/S to manage and rearrange memory without invalidating the pointers within the process.

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Hope this Helps:

public String getSystemTimeInBelowFormat() {
    String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
    return timestamp;
}

Regex any ASCII character

If you really mean any and ASCII (not e.g. all Unicode characters):

xxx[\x00-\x7F]+xxx

JavaScript example:

var re = /xxx[\x00-\x7F]+xxx/;

re.test('xxxabcxxx')
// true

re.test('xxx???xxx')
// false

download a file from Spring boot rest service

If you need to download a huge file from the server's file system, then ByteArrayResource can take all Java heap space. In that case, you can use FileSystemResource

Do HttpClient and HttpClientHandler have to be disposed between requests?

Dispose() calls the code below, which closes the connections opened by the HttpClient instance. The code was created by decompiling with dotPeek.

HttpClientHandler.cs - Dispose

ServicePointManager.CloseConnectionGroups(this.connectionGroupName);

If you don't call dispose then ServicePointManager.MaxServicePointIdleTime, which runs by a timer, will close the http connections. The default is 100 seconds.

ServicePointManager.cs

internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(ServicePointManager.IdleServicePointTimeoutCallback);
private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100000);

private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
  ServicePoint servicePoint = (ServicePoint) context;
  if (Logging.On)
    Logging.PrintInfo(Logging.Web, SR.GetString("net_log_closed_idle", (object) "ServicePoint", (object) servicePoint.GetHashCode()));
  lock (ServicePointManager.s_ServicePointTable)
    ServicePointManager.s_ServicePointTable.Remove((object) servicePoint.LookupString);
  servicePoint.ReleaseAllConnectionGroups();
}

If you haven't set the idle time to infinite then it appears safe not to call dispose and let the idle connection timer kick-in and close the connections for you, although it would be better for you to call dispose in a using statement if you know you are done with an HttpClient instance and free up the resources faster.

About catching ANY exception

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

remove empty lines from text file with PowerShell

You can't do replacing, you have to replace SOMETHING with SOMETHING, and you neither have both.

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

How to check if a file exists from a url

You have to use CURL

function does_url_exists($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 200) {
        $status = true;
    } else {
        $status = false;
    }
    curl_close($ch);
    return $status;
}

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How can we generate getters and setters in Visual Studio?

In visual studio 2019, select your properties like this:

enter image description here

Then press Ctrl+r Then press Ctrl+e

A dialog will appear showing you the preview of the changes that are going to be done to your code. If everything looks good (which it mostly will), press OK.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

Chosen Jquery Plugin - getting selected values

If anyone wants to get only the selected value on click to an option, he can do the follow:

$('.chosen-select').on('change', function(evt, params) {
    var selectedValue = params.selected;
    console.log(selectedValue);
});

How to run a Powershell script from the command line and pass a directory as a parameter

Add the param declation at the top of ps1 file

test.ps1

param(
  # Our preferred encoding
  [parameter(Mandatory=$false)]
  [ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
  [string]$Encoding = "UTF8"
)

write ("Encoding : {0}" -f $Encoding)

result

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII

grep for special characters in Unix

Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)

But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:

Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)

   -F, --fixed-strings
          Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.  (-F is specified
          by POSIX.)

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I disagree with the selected answer, and as davidxxx correctly pointed out, getReference does not provide such behaviour of dynamic updations without select. I asked a question concerning the validity of this answer, see here - cannot update without issuing select on using setter after getReference() of hibernate JPA.

I quite honestly haven't seen anybody who's actually used that functionality. ANYWHERE. And i don't understand why it's so upvoted.

Now first of all, no matter what you call on a hibernate proxy object, a setter or a getter, an SQL is fired and the object is loaded.

But then i thought, so what if JPA getReference() proxy doesn't provide that functionality. I can just write my own proxy.

Now, we can all argue that selects on primary keys are as fast as a query can get and it's not really something to go to great lengths to avoid. But for those of us who can't handle it due to one reason or another, below is an implementation of such a proxy. But before i you see the implementation, see it's usage and how simple it is to use.

USAGE

Order example = ProxyHandler.getReference(Order.class, 3);
example.setType("ABCD");
example.setCost(10);
PersistenceService.save(example);

And this would fire the following query -

UPDATE Order SET type = 'ABCD' and cost = 10 WHERE id = 3;

and even if you want to insert, you can still do PersistenceService.save(new Order("a", 2)); and it would fire an insert as it should.

IMPLEMENTATION

Add this to your pom.xml -

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>

Make this class to create dynamic proxy -

@SuppressWarnings("unchecked")
public class ProxyHandler {

public static <T> T getReference(Class<T> classType, Object id) {
    if (!classType.isAnnotationPresent(Entity.class)) {
        throw new ProxyInstantiationException("This is not an entity!");
    }

    try {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(classType);
        enhancer.setCallback(new ProxyMethodInterceptor(classType, id));
        enhancer.setInterfaces((new Class<?>[]{EnhancedProxy.class}));
        return (T) enhancer.create();
    } catch (Exception e) {
        throw new ProxyInstantiationException("Error creating proxy, cause :" + e.getCause());
    }
}

Make an interface with all the methods -

public interface EnhancedProxy {
    public String getJPQLUpdate();
    public HashMap<String, Object> getModifiedFields();
}

Now, make an interceptor which will allow you to implement these methods on your proxy -

import com.anil.app.exception.ProxyInstantiationException;
import javafx.util.Pair;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Anil Kumar
*/
public class ProxyMethodInterceptor implements MethodInterceptor, EnhancedProxy {

private Object target;
private Object proxy;
private Class classType;
private Pair<String, Object> primaryKey;
private static HashSet<String> enhancedMethods;

ProxyMethodInterceptor(Class classType, Object id) throws IllegalAccessException, InstantiationException {
    this.classType = classType;
    this.target = classType.newInstance();
    this.primaryKey = new Pair<>(getPrimaryKeyField().getName(), id);
}

static {
    enhancedMethods = new HashSet<>();
    for (Method method : EnhancedProxy.class.getDeclaredMethods()) {
        enhancedMethods.add(method.getName());
    }
}

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    //intercept enhanced methods
    if (enhancedMethods.contains(method.getName())) {
        this.proxy = obj;
        return method.invoke(this, args);
    }
    //else invoke super class method
    else
        return proxy.invokeSuper(obj, args);
}

@Override
public HashMap<String, Object> getModifiedFields() {
    HashMap<String, Object> modifiedFields = new HashMap<>();
    try {
        for (Field field : classType.getDeclaredFields()) {

            field.setAccessible(true);

            Object initialValue = field.get(target);
            Object finalValue = field.get(proxy);

            //put if modified
            if (!Objects.equals(initialValue, finalValue)) {
                modifiedFields.put(field.getName(), finalValue);
            }
        }
    } catch (Exception e) {
        return null;
    }
    return modifiedFields;
}

@Override
public String getJPQLUpdate() {
    HashMap<String, Object> modifiedFields = getModifiedFields();
    if (modifiedFields == null || modifiedFields.isEmpty()) {
        return null;
    }
    StringBuilder fieldsToSet = new StringBuilder();
    for (String field : modifiedFields.keySet()) {
        fieldsToSet.append(field).append(" = :").append(field).append(" and ");
    }
    fieldsToSet.setLength(fieldsToSet.length() - 4);
    return "UPDATE "
            + classType.getSimpleName()
            + " SET "
            + fieldsToSet
            + "WHERE "
            + primaryKey.getKey() + " = " + primaryKey.getValue();
}

private Field getPrimaryKeyField() throws ProxyInstantiationException {
    for (Field field : classType.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(Id.class))
            return field;
    }
    throw new ProxyInstantiationException("Entity class doesn't have a primary key!");
}
}

And the exception class -

public class ProxyInstantiationException extends RuntimeException {
public ProxyInstantiationException(String message) {
    super(message);
}

A service to save using this proxy -

@Service
public class PersistenceService {

@PersistenceContext
private EntityManager em;

@Transactional
private void save(Object entity) {
    // update entity for proxies
    if (entity instanceof EnhancedProxy) {
        EnhancedProxy proxy = (EnhancedProxy) entity;
        Query updateQuery = em.createQuery(proxy.getJPQLUpdate());
        for (Entry<String, Object> entry : proxy.getModifiedFields().entrySet()) {
            updateQuery.setParameter(entry.getKey(), entry.getValue());
        }
        updateQuery.executeUpdate();
    // insert otherwise
    } else {
        em.persist(entity);
    }

}
}

ValueError: not enough values to unpack (expected 11, got 1)

The error message is fairly self-explanatory

(a,b,c,d,e) = line.split()

expects line.split() to yield 5 elements, but in your case, it is only yielding 1 element. This could be because the data is not in the format you expect, a rogue malformed line, or maybe an empty line - there's no way to know.

To see what line is causing the issue, you could add some debug statements like this:

if len(line.split()) != 11:
    print line

As Martin suggests, you might also be splitting on the wrong delimiter.

in iPhone App How to detect the screen resolution of the device

Use this code it will help for getting any type of device's screen resolution

 [[UIScreen mainScreen] bounds].size.height
 [[UIScreen mainScreen] bounds].size.width

DateTime fields from SQL Server display incorrectly in Excel

This is a very old post, but I recently encountered the problem and for me the following solved the issue by formatting the SQL as follows,

SELECT CONVERT (varchar, getdate(), 120) AS Date

If you copy the result from SQL Server and paste in Excel then Excel holds the proper formatting.

How to get back Lost phpMyAdmin Password, XAMPP

Hi this worked for me "/opt/lampp/xampp security" in Centos

[root@XXXXX ~]# /opt/lampp/xampp security

XAMPP: Quick security check...

XAMPP: Your XAMPP pages are secured by a password.

XAMPP: Do you want to change the password anyway? [no] yes

XAMPP: Password:

XAMPP: Password (again):

XAMPP: Password protection active. Please use 'xampp' as user name!

XAMPP: MySQL is not accessable via network. Good.

XAMPP: MySQL has a root passwort set. Fine! :)

XAMPP: The FTP password for user 'daemon' is still set to 'xampp'.

XAMPP: Do you want to change the password? [yes]

XAMPP: Password:

XAMPP: Password (again):

XAMPP: Reload ProFTPD...ok.

XAMPP: Done.

[root@XXXXX ~]#

Binary Data in JSON String. Something better than Base64

I ran into the same problem, and thought I'd share a solution: multipart/form-data.

By sending a multipart form you send first as string your JSON meta-data, and then separately send as raw binary (image(s), wavs, etc) indexed by the Content-Disposition name.

Here's a nice tutorial on how to do this in obj-c, and here is a blog article that explains how to partition the string data with the form boundary, and separate it from the binary data.

The only change you really need to do is on the server side; you will have to capture your meta-data which should reference the POST'ed binary data appropriately (by using a Content-Disposition boundary).

Granted it requires additional work on the server side, but if you are sending many images or large images, this is worth it. Combine this with gzip compression if you want.

IMHO sending base64 encoded data is a hack; the RFC multipart/form-data was created for issues such as this: sending binary data in combination with text or meta-data.

How to get height of entire document with JavaScript?

This cross browser code below evaluates all possible heights of the body and html elements and returns the max found:

            var body = document.body;
            var html = document.documentElement;
            var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight); // The max height of the body

A working example:

_x000D_
_x000D_
function getHeight()_x000D_
{_x000D_
  var body = document.body;_x000D_
  var html = document.documentElement; _x000D_
  var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight);_x000D_
  return bodyH;_x000D_
}_x000D_
_x000D_
document.getElementById('height').innerText = getHeight();
_x000D_
body,html_x000D_
{_x000D_
  height: 3000px;_x000D_
}_x000D_
_x000D_
#posbtm_x000D_
{_x000D_
  bottom: 0;_x000D_
  position: fixed;_x000D_
  background-color: Yellow;_x000D_
}
_x000D_
<div id="posbtm">The max Height of this document is: <span id="height"></span> px</div>_x000D_
_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />_x000D_
example document body content example document body content example document body content example document body content <br />
_x000D_
_x000D_
_x000D_

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

You are so close! All you need to do is select BOTH the home and its max date time, then join back to the topten table on BOTH fields:

SELECT tt.*
FROM topten tt
INNER JOIN
    (SELECT home, MAX(datetime) AS MaxDateTime
    FROM topten
    GROUP BY home) groupedtt 
ON tt.home = groupedtt.home 
AND tt.datetime = groupedtt.MaxDateTime

How do I set the background color of my main screen in Flutter?

Here's one way that I found to do it. I don't know if there are better ways, or what the trade-offs are.

Container "tries to be as big as possible", according to https://flutter.io/layout/. Also, Container can take a decoration, which can be a BoxDecoration, which can have a color (which, is the background color).

Here's a sample that does indeed fill the screen with red, and puts "Hello, World!" into the center:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new Container(
      decoration: new BoxDecoration(color: Colors.red),
      child: new Center(
        child: new Text("Hello, World!"),
      ),
    );
  }
}

Note, the Container is returned by the MyApp build(). The Container has a decoration and a child, which is the centered text.

See it in action here:

enter image description here

RESTful Authentication via Spring

You might consider Digest Access Authentication. Essentially the protocol is as follows:

  1. Request is made from client
  2. Server responds with a unique nonce string
  3. Client supplies a username and password (and some other values) md5 hashed with the nonce; this hash is known as HA1
  4. Server is then able to verify client's identity and serve up the requested materials
  5. Communication with the nonce can continue until the server supplies a new nonce (a counter is used to eliminate replay attacks)

All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.

Digest Access Authentication is supported by Spring Security. Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.

Call to a member function fetch_assoc() on boolean in <path>

This error happen usually when tables in the query doesn't exist. Just check the table's spelling in the query, and it will work.

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

Why is using "for...in" for array iteration a bad idea?

Because for...in enumerates through the object that holds the array, not the array itself. If I add a function to the arrays prototype chain, that will also be included. I.e.

Array.prototype.myOwnFunction = function() { alert(this); }
a = new Array();
a[0] = 'foo';
a[1] = 'bar';
for(x in a){
 document.write(x + ' = ' + a[x]);
}

This will write:

0 = foo
1 = bar
myOwnFunction = function() { alert(this); }

And since you can never be sure that nothing will be added to the prototype chain just use a for loop to enumerate the array:

for(i=0,x=a.length;i<x;i++){
 document.write(i + ' = ' + a[i]);
}

This will write:

0 = foo
1 = bar

How do I view executed queries within SQL Server Management Studio?

You need a SQL profiler, which actually runs outside SQL Management Studio. If you have a paid version of SQL Server (like the developer edition), it should be included in that as another utility.

If you're using a free edition (SQL Express), they have freeware profiles that you can download. I've used AnjLab's profiler (available at http://sites.google.com/site/sqlprofiler), and it seemed to work well.

C pointer to array/array of pointers disambiguation

Here's how I interpret it:

int *something[n];

Note on precedence: array subscript operator ([]) has higher priority than dereference operator (*).

So, here we will apply the [] before *, making the statement equivalent to:

int *(something[i]);

Note on how a declaration makes sense: int num means num is an int, int *ptr or int (*ptr) means, (value at ptr) is an int, which makes ptr a pointer to int.

This can be read as, (value of the (value at ith index of the something)) is an integer. So, (value at the ith index of something) is an (integer pointer), which makes the something an array of integer pointers.

In the second one,

int (*something)[n];

To make sense out of this statement, you must be familiar with this fact:

Note on pointer representation of array: somethingElse[i] is equivalent to *(somethingElse + i)

So, replacing somethingElse with (*something), we get *(*something + i), which is an integer as per declaration. So, (*something) given us an array, which makes something equivalent to (pointer to an array).

Qt: How do I handle the event of the user pressing the 'X' (close) button?

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
    // do what you need here
    // then call parent's procedure
    QWidget::closeEvent(event);
}

Android Paint: .measureText() vs .getTextBounds()

My experience with this is that getTextBounds will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText assumes one line.

In order to get accurate measuring results, you should use the StaticLayout to render the text and pull out the measurements.

For example:

String text = "text";
TextPaint textPaint = textView.getPaint();
int boundedWidth = 1000;

StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int height = layout.getHeight();

PHP function overloading

In PHP 5.6 you can use the splat operator ... as the last parameter and do away with func_get_args() and func_num_args():

function example(...$args)
{
   count($args); // Equivalent to func_num_args()
}

example(1, 2);
example(1, 2, 3, 4, 5, 6, 7);

You can use it to unpack arguments as well:

$args[] = 1;
$args[] = 2;
$args[] = 3;
example(...$args);

Is equivalent to:

example(1, 2, 3);

'router-outlet' is not a known element

This issue was with me also. Simple trick for it.

 @NgModule({
  imports: [
   .....       
  ],
 declarations: [
  ......
 ],

 providers: [...],
 bootstrap: [...]
 })

use it as in above order.first imports then declarations.It worked for me.

How can I get a process handle by its name in C++?

OpenProcess Function

From MSDN:

To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.

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

If you turn things around, you can declare your base class abstract, and have descendants declare setUp and tearDown methods (without annotations) that are called in the base class' annotated setUp and tearDown methods.

if else statement in AngularJS templates

Ternary is the most clear way of doing this.

<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>

Cast int to varchar

use :

SELECT cast(CHAR(50),id) as colI1 from t9;

How to add a new project to Github using VS Code

today is 2020-12-25, my VSC is 1.52.1, tried all above not very successful. Here is complete steps I did to add my existing local project to GitHub using VSC (Note: Do not create a corresponding repository at GitHub):

  1. Install the GibHub extension to VSC.
  2. Close and re-open VSC.
  3. Sign in to GibHub if prompted.
  4. Open my own local folder, up to this moment, it's not pushed to GibHub yet.
  5. Ctrl + Shift + P, click on Publish to GitHub.

enter image description here

  1. VSC and GitHub will automatically provide you a choice of adding it as private or public, and make up a name for your to-be new repository in this format: <your username>/<your new repository name>. For example, my username is "myname" and my local folder is named "HelloWorld". So, it will be myname/HelloWorld in the type-in box.
  2. update or accept this name, click on the private or public choice will Create a new repository at GitHub and Publish your folder to it.

enter image description here

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Perform the following steps:

  1. Start the Registry Editor by typing regedit in the Run window.
  2. Select the following key in the registry: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC.
  3. In the Security menu, click Permissions.
  4. Grant Full Permission to the account which is being used for making connections.
  5. Quit the Registry Editor.

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {
        this.dialog.open(DialogComponent, { disableClose: true });
      }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;
      }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

C: Run a System Command and Get Output?

Usually, if the command is an external program, you can use the OS to help you here.

command > file_output.txt

So your C code would be doing something like

exec("command > file_output.txt");

Then you can use the file_output.txt file.

How to iterate through table in Lua?

To iterate over all the key-value pairs in a table you can use pairs:

for k, v in pairs(arr) do
  print(k, v[1], v[2], v[3])
end

outputs:

pears   2   p   green
apples  0   a   red
oranges 1   o   orange

Edit: Note that Lua doesn't guarantee any iteration order for the associative part of the table. If you want to access the items in a specific order, retrieve the keys from arr and sort it. Then access arr through the sorted keys:

local ordered_keys = {}

for k in pairs(arr) do
    table.insert(ordered_keys, k)
end

table.sort(ordered_keys)
for i = 1, #ordered_keys do
    local k, v = ordered_keys[i], arr[ ordered_keys[i] ]
    print(k, v[1], v[2], v[3])
end

outputs:

  apples  a   red     5
  oranges o   orange  12
  pears   p   green   7

Renaming part of a filename

You'll need to learn how to use sed http://unixhelp.ed.ac.uk/CGI/man-cgi?sed

And also to use for so you can loop through your file entries http://www.cyberciti.biz/faq/bash-for-loop/

Your command will look something like this, I don't have a term beside me so I can't check

for i in `dir` do mv $i `echo $i | sed '/orig/new/g'`

Swing vs JavaFx for desktop applications

As stated by Oracle, JavaFX is the next step in their Java based rich client strategy. Accordingly, this is what I recommend for your situation:

What would be easier and cleaner to maintain

  • JavaFX has introduced several improvements over Swing, such as, possibility to markup UIs with FXML, and theming with CSS. It has great potential to write a modular, clean & maintainable code.

What would be faster to build from scratch

  • This is highly dependent on your skills and the tools you use.
    • For swing, various IDEs offer tools for rapid development. The best I personally found is the GUI builder in NetBeans.
    • JavaFX has support from various IDEs as well, though not as mature as the support Swing has at the moment. However, its support for markup in FXML & CSS make GUI development on JavaFX intuitive.

MVC Pattern Support

  • JavaFX is very friendly with MVC pattern, and you can cleanly separate your work as: presentation (FXML, CSS), models(Java, domain objects) and logic(Java).
  • IMHO, the MVC support in Swing isn't very appealing. The flow you'll see across various components lacks consistency.

For more info, please take a look these FAQ post by Oracle regarding JavaFX here.

The type initializer for 'MyClass' threw an exception

One other thing to check when these initialize errors are thrown would be to check if the target .NET version is installed on the server. You can right click the project and see what .NET version the application is targeting.

How to use Apple's new .p8 certificate for APNs in firebase console

Apple have recently made new changes in APNs and now apple insist us to use "Token Based Authentication" instead of the traditional ways which we are using for push notification.

So does not need to worry about their expiration and this p8 certificates are for both development and production so again no need to generate 2 separate certificate for each mode.

To generate p8 just go to your developer account and select this option "Apple Push Notification Authentication Key (Sandbox & Production)"

enter image description here

Then will generate directly p8 file.

I hope this will solve your issue.

Read this new APNs changes from apple: https://developer.apple.com/videos/play/wwdc2016/724/

Also you can read this: https://developer.apple.com/library/prerelease/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html

set up device for development (???????????? no permissions)

Please DO NOT follow solutions suggesting to use sudo (sudo adb start-server)! This run adb as root (administrator) and it is NOT supposed to run like that!!! It's a BAD workaround!

Everything running as root can do anything in your system, if it creates or modify a file can change its permission to be only used by root. Again, DON'T!

The right thing to do is set up your system to make the USER have the permission, check out this guide i wrote on how to do it properly.

How do I open the "front camera" on the Android platform?

As of Android 2.1, Android only supports a single camera in its SDK. It is likely that this will be added in a future Android release.

How to pass multiple parameters to a get method in ASP.NET Core

You also can use this:

// GET api/user/firstname/lastname/address
[HttpGet("{firstName}/{lastName}/{address}")]
public string GetQuery(string id, string firstName, string lastName, string address)
{
    return $"{firstName}:{lastName}:{address}";
}

Note: Please refer to metalheart's and metalheart and Mark Hughes for a possibly better approach.

Can I set an unlimited length for maxJsonLength in web.config?

You can configure the max length for json requests in your web.config file:

<configuration>
    <system.web.extensions>
        <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="....">
                </jsonSerialization>
            </webServices>
        </scripting>
    </system.web.extensions>
</configuration>

The default value for maxJsonLength is 102400. For more details, see this MSDN page: http://msdn.microsoft.com/en-us/library/bb763183.aspx

How to fix: "HAX is not working and emulator runs in emulation mode"

Either increase the ram size allocated while doing HAX installation , so as to fit exactly or a bit more higher space than the ram size of the emulator which you want to launch in "Intel x86 Emulator Accelerator (HAXM) " mode,

Once you succeed with that, you can now able to view this in the console /log

enter image description here

How can I create an object and add attributes to it?

The built-in object can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) It doesn't have a __dict__ to hold the attributes.

I generally just do this:

class Object(object):
    pass

a = Object()
a.somefield = somevalue

When I can, I give the Object class a more meaningful name, depending on what kind of data I'm putting in it.

Some people do a different thing, where they use a sub-class of dict that allows attribute access to get at the keys. (d.key instead of d['key'])

Edit: For the addition to your question, using setattr is fine. You just can't use setattr on object() instances.

params = ['attr1', 'attr2', 'attr3']
for p in params:
    setattr(obj.a, p, value)

running php script (php function) in linux bash

From the command line, enter this:

php -f filename.php

Make sure that filename.php both includes and executes the function you want to test. Anything you echo out will appear in the console, including errors.

Be wary that often the php.ini for Apache PHP is different from CLI PHP (command line interface).

Reference: https://secure.php.net/manual/en/features.commandline.usage.php

How to get a list of properties with a given attribute?

There's always LINQ:

t.GetProperties().Where(
    p=>p.GetCustomAttributes(typeof(MyAttribute), true).Length != 0)

No plot window in matplotlib

Any errors show up? This might an issue of not having set the backend. You can set it from the Python interpreter or from a config file (.matplotlib/matplotlibrc) in you home directory.

To set the backend in code you can do

import matplotlib
matplotlib.use('Agg')

where 'Agg' is the name of the backend. Which backends are present depend on your installation and OS.

http://matplotlib.sourceforge.net/faq/installing_faq.html#backends

http://matplotlib.org/users/customizing.html

Check a collection size with JSTL

As suggested by @Joel and @Mark Chorley in earlier comments:

${empty companies}

This checks for null and empty lists/collections/arrays. It doesn't get you the length but it satisfies the example in the OP. If you can get away with it this is just cleaner than importing a tag library and its crusty syntax like gt.

How an 'if (A && B)' statement is evaluated?

Yes, it is called Short-circuit Evaluation.

If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.

This is very important when some of the statements have side-effects.

How to write multiple conditions in Makefile.am with "else if"

ptomato's code can also be written in a cleaner manner like:

ifeq ($(TARGET_CPU),x86)
  TARGET_CPU_IS_X86 := 1
else ifeq ($(TARGET_CPU),x86_64)
  TARGET_CPU_IS_X86 := 1
else
  TARGET_CPU_IS_X86 := 0
endif

This doesn't answer OP's question but as it's the top result on google, I'm adding it here in case it's useful to anyone else.

Selecting multiple columns in a Pandas dataframe

The different approaches discussed in the previous answers are based on the assumption that either the user knows column indices to drop or subset on, or the user wishes to subset a dataframe using a range of columns (for instance between 'C' : 'E').

pandas.DataFrame.drop() is certainly an option to subset data based on a list of columns defined by user (though you have to be cautious that you always use copy of dataframe and inplace parameters should not be set to True!!)

Another option is to use pandas.columns.difference(), which does a set difference on column names, and returns an index type of array containing desired columns. Following is the solution:

df = pd.DataFrame([[2,3,4], [3,4,5]], columns=['a','b','c'], index=[1,2])
columns_for_differencing = ['a']
df1 = df.copy()[df.columns.difference(columns_for_differencing)]
print(df1)

The output would be:

    b   c
1   3   4
2   4   5

Indexes of all occurrences of character in a string

This is a java 8 solution.

public int[] solution (String s, String subString){
        int initialIndex = s.indexOf(subString);
        List<Integer> indexList = new ArrayList<>();
        while (initialIndex >=0){
            indexList.add(initialIndex);
            initialIndex = s.indexOf(subString, initialIndex+1);
        }
        int [] intA = indexList.stream().mapToInt(i->i).toArray();
        return intA;
    }

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

Try to specify the port in

conn = DriverManager.getConnection("jdbc:mysql://localhost/mysql?"
                                        + "user=root&password=onelife");

I think you should have something like this:

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?"
                                            + "user=root&password=onelife");

Also, the port number in my example (3306) is the default port, but you may change it while installing MySQL.

I think that a better way to specify password and user is to separate them from the URL like this:

connection = DriverManager.getConnection(url, login, password);

Failed to decode downloaded font

Make sure your server is sending the font files with the right mime/type.

I recently have the same problem using nginx because some font mime types are missing from its vanilla /etc/nginx/mime.types file.

I fixed the issue adding the missing mime types in the location where I needed them like this:

location /app/fonts/ {

  #Fonts dir
  alias /var/www/app/fonts/;

  #Include vanilla types
  include mime.types;

  #Missing mime types
  types  {font/truetype ttf;}
  types  {application/font-woff woff;}
  types  {application/font-woff2 woff2;}
}

You can also check this out for extending the mime.types in nginx: extending default nginx mime.types file

Pass Multiple Parameters to jQuery ajax call

data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}',

MySQL SELECT DISTINCT multiple columns

Taking a guess at the results you want so maybe this is the query you want then

SELECT DISTINCT a FROM my_table
UNION 
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table

Get nodes where child node contains an attribute

Try to use this xPath expression:

//book/title[@lang='it']/..

That should give you all book nodes in "it" lang

How to style icon color, size, and shadow of Font Awesome Icons

text-shadow: 1px 1px 3px rgba(0,0,0,0.5);

How get an apostrophe in a string in javascript

This is plain Javascript and has nothing to do with the jQuery library.

You simply escape the apostrophe with a backslash:

theAnchorText = 'I\'m home';

Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:

theAnchorText = "I'm home";

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

i also faced this problem,

i found password field was blank in config file of phpmyadmin. i put that password which i filled in database settings. now it is working fine

How do you check if a certain index exists in a table?

For SQL 2008 and newer, a more concise method, coding-wise, to detect index existence is by using the INDEXPROPERTY built-in function:

INDEXPROPERTY ( object_ID , index_or_statistics_name , property )  

The simplest usage is with the IndexID property:

If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexID') Is Null

If the index exists, the above will return its ID; if it doesn't, it will return NULL.

How to Parse a JSON Object In Android

In your JSON format, it do not have starting JSON object

Like :

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}

Above Json starts with info as JSON object. So while executing :

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

Now, we can access result field :

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

I think this was missing and so the problem was solved while we use JSONTokener like answer of yours.

Your answer is very fine. Just i think i add this information so i answered

Thank you

MySQL foreach alternative for procedure

This can be done with MySQL, although it's highly unintuitive:

CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
  DECLARE a,b INT;
  DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET b = 1;
  OPEN cur_1;
  REPEAT
    FETCH cur_1 INTO a;
    UNTIL b = 1
  END REPEAT;
  CLOSE cur_1;
  SET return_val = a;
END;//

Check out this guide: mysql-storedprocedures.pdf

Force DOM redraw/refresh on Chrome/Mac

This works for me. Kudos go here.

jQuery.fn.redraw = function() {
    return this.hide(0, function() {
        $(this).show();
    });
};

$(el).redraw();

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

Return different type of data from a method in java?

I know this is late but I thought it'd be helpful to someone who'll come searching for an answer to this. You can use a Bundle to return multiple datatype values without creating another method. I tried it and worked perfectly.

In Your MainActivity where you call the method:

Bundle myBundle = method();
String myString = myBundle.getString("myS");
String myInt = myBundle.getInt("myI");

Method:

public Bundle method() {
    mBundle = new Bundle();
    String typicalString = "This is String";
    Int typicalInt = 1;
    mBundle.putString("myS", typicalString);
    mBundle.putInt("myI", typicalInt);
    return mBundle;
}

P.S: I'm not sure if it's OK to implement a Bundle like this, but for me, it worked out perfectly.

multiple prints on the same line in Python

sys.stdout.write will print without return carriage

import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")

http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines

how to run vibrate continuously in iphone?

Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.

List files in local git repo?

Try this command:

git ls-files 

This lists all of the files in the repository, including those that are only staged but not yet committed.

http://www.kernel.org/pub/software/scm/git/docs/git-ls-files.html

jQuery prevent change for select

In the event someone needs a generic version of mattsven's answer (as I did), here it is:

$('select').each(function() {
    $(this).data('lastSelected', $(this).find('option:selected'));
});

$('select').change(function() {
    if(my_condition) {
        $(this).data('lastSelected').attr('selected', true);
    }
});

$('select').click(function() {
    $(this).data('lastSelected', $(this).find('option:selected'));
});

Redirecting to a relative URL in JavaScript

You can do a relative redirect:

window.location.href = '../'; //one level up

or

window.location.href = '/path'; //relative to domain

QComboBox - set selected item based on the item's data

If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.

ui->comboBox->setCurrentText("choice 2");

From the Qt 5.7 documentation

The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.

So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.

Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop

How do I auto-hide placeholder text upon focus using css or jquery?

have you tried placeholder attr?

<input id ="myID" type="text" placeholder="enter your text " />

-EDIT-

I see, try this then:

$(function () {

    $('#myId').data('holder', $('#myId').attr('placeholder'));

    $('#myId').focusin(function () {
        $(this).attr('placeholder', '');
    });
    $('#myId').focusout(function () {
        $(this).attr('placeholder', $(this).data('holder'));
    });


});

Test: http://jsfiddle.net/mPLFf/4/

-EDIT-

Actually, since placeholder should be used to describe the value, not the name of the input. I suggest the following alternative

html:

<label class="overlabel"> 
    <span>First Name</span>
    <input name="first_name" type="text" />
</label>

javascript:

$('.overlabel').each(function () {
    var $this = $(this);
    var field = $this.find('[type=text], [type=file], [type=email], [type=password], textarea');
    var span = $(this).find('> span');
    var onBlur = function () {
        if ($.trim(field.val()) == '') {
            field.val('');
            span.fadeIn(100);
        } else {
            span.fadeTo(100, 0);
        }
    };
    field.focus(function () {
        span.fadeOut(100);
    }).blur(onBlur);
    onBlur();
});

css:

.overlabel {
  border: 0.1em solid;
  color: #aaa;
  position: relative;
  display: inline-block;
  vertical-align: middle;
  min-height: 2.2em;
}
.overlabel span {
  position: absolute;
  left: 0;
  top: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.overlabel span, .overlabel input {
  text-align: left;
  font-size: 1em;
  line-height: 2em;
  padding: 0 0.5em;
  margin: 0;
  background: transparent;
  -webkit-appearance: none; /* prevent ios styling */
  border-width: 0;
  width: 100%;
  outline: 0;
}

Test:

http://jsfiddle.net/kwynwrcf/

How to get post slug from post in WordPress?

Here is most advanced and updated version what cover many cases:

if(!function_exists('the_slug')):
    function the_slug($post_id=false, $echo=true) {
        global $product, $page;

        if(is_numeric($post_id) && $post_id == intval($post_id)) {} else {
            if(!is_object($post_id)){}else if(property_exists($post_id, 'ID')){
                $post_id = $post_id->ID;
            }
            if(empty($post_id) && property_exists($product, 'ID')) $post_id = $product->ID;
            if(empty($post_id)) $post_id =  get_the_ID();

            if(empty($post_id) && property_exists($page, 'ID')) $post_id =  $page->ID;
        }

        if(!empty($post_id))
            $slug = basename(get_permalink($post_id));
        else
            $slug = basename(get_permalink());
        do_action('before_slug', $slug);
        $slug = apply_filters('slug_filter', $slug);
        if( $echo ) echo $slug;
        do_action('after_slug', $slug);
        return $slug;
      }
endif;

This is collections from the best answers and few my updates.