Programs & Examples On #Fading

Simple CSS Animation Loop – Fading In & Out "Loading" Text

well looking for a simpler variation I found this:

it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.

demo and credit => http://codepen.io/Ahrengot/pen/bKdLC

_x000D_
_x000D_
@keyframes fadeIn { _x000D_
  from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
    animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
_x000D_
_x000D_

Half circle with CSS (border, outline only)

Below is a minimal code to achieve the effect.

This also works responsively since the border-radius is in percentage.

_x000D_
_x000D_
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
_x000D_
_x000D_

css transition opacity fade background

Please note that the problem is not white color. It is because it is being transparent.

When an element is made transparent, all of its child element's opacity; alpha filter in IE 6 7 etc, is changed to the new value.

So you cannot say that it is white!

You can place an element above it, and change that element's transparency to 1 while changing the image's transparency to .2 or what so ever you want to.

Bootstrap: Open Another Modal in Modal

This thread is old, but for those who come from google, Ive come with a solutions that is hybrid from all the answers Ive found on the net.

This will make sure level class is being added:

$(document).on('show.bs.modal', '.modal', function (event) {
  $(this).addClass(`modal-level-${$('.modal:visible').length}`);
});

Inside my SCSS Ive wrote a rule that supports main modal and 10 on top (10 because from z-index: 1060 popover takes place), you can add levels count inside _variables.scss if you want:

@for $level from 0 through 10 {
  .modal-level-#{$level} {
    z-index: $zindex-modal + $level;

    & + .modal-backdrop {
      z-index: $zindex-modal + $level - 1;
    }
  }
}

Do not forget that you cannot have modal inside modal as their controls will be messed up. In my case all my modals were at the end of body.

And finally as members below also mentions this, after closing one modal, you need to keep modal-open class on body:

$(document).on('hidden.bs.modal', function (e) {
  if ($('.modal:visible').length > 0) {
    $('body').addClass('modal-open');
  }
});

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

Some good answers, but the problem with all solutions I have tried is that the images doesn´t fade into each other. Instead the first one fades completely out and than the next one fades in.

After a few hours of testing a found this sollution. Thx to http://www.1squarepear.com/adding-a-responsive-bootstrap-image-carousel-that-fades-instead-of-slides/

  1. In the HTML code change from .slide to .fade on the .carousel element
  2. Add this in the css:

    .carousel.fade { opacity: 1; } .carousel.fade .item { transition: opacity ease-out .7s; left: 0; opacity: 0; /* hide all slides */ top: 0; position: absolute; width: 100%; display: block; } .carousel.fade .item:first-child { top: auto; opacity: 1; /* show first slide */ position: relative; } .carousel.fade .item.active { opacity: 1; }

Use css gradient over background image

body {
    margin: 0;
    padding: 0;
    background: url('img/background.jpg') repeat;
}

body:before {
    content: " ";
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    background: -webkit-radial-gradient(top center, ellipse cover, rgba(255,255,255,0.2) 0%,rgba(0,0,0,0.5) 100%);
}

PLEASE NOTE: This only using webkit so it will only work in webkit browsers.

try :

-moz-linear-gradient = (Firefox)
-ms-linear-gradient = (IE)
-o-linear-gradient = (Opera)
-webkit-linear-gradient = (Chrome & safari)

iterate through a map in javascript

Functional Approach for ES6+

If you want to take a more functional approach to iterating over the Map object, you can do something like this

const myMap = new Map() 
myMap.forEach((value, key) => {
    console.log(value, key)
})

No Title Bar Android Theme

use android:theme="@android:style/Theme.NoTitleBar in manifest file's application tag to remove the title bar for whole application or put it in activity tag to remove the title bar from a single activity screen.

move div with CSS transition

Just to add my answer, it seems that the transitions need to be based on initial values and final values within the css properties to be able to manage the animation.

Those reworked css classes should provide the expected result :

_x000D_
_x000D_
.box{_x000D_
    position: relative;  _x000D_
    top:0px;_x000D_
    left:0px;_x000D_
    width:0px;_x000D_
}_x000D_
_x000D_
.box:hover .hidden{_x000D_
    opacity: 1;_x000D_
     width: 500px;_x000D_
}_x000D_
_x000D_
.box .hidden{    _x000D_
   background: yellow;_x000D_
    height: 300px;    _x000D_
    position: absolute; _x000D_
    top: 0px;_x000D_
    left: 0px;    _x000D_
    width: 0px;_x000D_
    opacity: 0;    _x000D_
    transition: all 1s ease;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
    <a href="#">_x000D_
        <img src="http://farm9.staticflickr.com/8207/8275533487_5ebe5826ee.jpg"></a>_x000D_
        <div class="hidden"></div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/u2FKM/2199/

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

sizing div based on window width

html, body {
    height: 100%;
    width: 100%;
}

html {
    display: table;
    margin: auto;
}

body {
    padding-top: 50px;
    display: table-cell;
}

div {
    margin: auto;
}

This will center align objects and then also center align the items within them to center align multiple objects with different widths.

Example picture

change image opacity using javascript

First set the opacity explicitly in your HTML thus:

<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>

otherwise it is 0 or null

this is then in my .js file

document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });

Can Twitter Bootstrap alerts fade in as well as out?

This is very important question and I was struggling to get it done (show/hide) message by replacing current and add new message.

Below is working example:

_x000D_
_x000D_
function showAndDismissAlert(type, message) {_x000D_
_x000D_
  var htmlAlert = '<div class="alert alert-' + type + '">' + message + '</div>';_x000D_
  $(".alert-messages").prepend(htmlAlert);_x000D_
  $(".alert-messages .alert").hide().fadeIn(600).delay(2000).fadeOut(1000, function() {_x000D_
    $(this).remove();_x000D_
  });_x000D_
_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert-messages"></div>_x000D_
_x000D_
<div class="buttons">_x000D_
  <button type="button" name="button" onclick="showAndDismissAlert('success', 'Saved Successfully!')">Button1</button>_x000D_
  <button type="button" name="button" onclick="showAndDismissAlert('danger', 'Error Encountered')">Button2</button>_x000D_
  <button type="button" name="button" onclick="showAndDismissAlert('info', 'Message Received')">Button3</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it will help others!

Fade In Fade Out Android Animation in Java

Here is my solution using AnimatorSet which seems to be a bit more reliable than AnimationSet.

// Custom animation on image
ImageView myView = (ImageView)splashDialog.findViewById(R.id.splashscreenImage);

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(myView, "alpha",  1f, .3f);
fadeOut.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(myView, "alpha", .3f, 1f);
fadeIn.setDuration(2000);

final AnimatorSet mAnimationSet = new AnimatorSet();

mAnimationSet.play(fadeIn).after(fadeOut);

mAnimationSet.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        super.onAnimationEnd(animation);
        mAnimationSet.start();
    }
});
mAnimationSet.start();

Remove scroll bar track from ScrollView in Android

Solved my problem by adding this to my ListView:

android:scrollbars="none"

start/play embedded (iframe) youtube-video on click of an image

You can do this simply like this

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.

JQuery show/hide when hover

I hope my script help you.

<i class="mostrar-producto">mostrar...</i>
<div class="producto" style="display:none;position: absolute;">Producto</div>

My script

<script>
$(".mostrar-producto").mouseover(function(){
     $(".producto").fadeIn();
 });

 $(".mostrar-producto").mouseleave(function(){
      $(".producto").fadeOut();
  });
</script>

Image change every 30 seconds - loop

Just use That.Its Easy.

<script language="javascript" type="text/javascript">
     var images = new Array()
     images[0] = "img1.jpg";
     images[1] = "img2.jpg";
     images[2] = "img3.jpg";
     setInterval("changeImage()", 30000);
     var x=0;

     function changeImage()
     {
                document.getElementById("img").src=images[x]
                x++;
                if (images.length == x) 
                {
                    x = 0;
                }
     }
</script>

And in Body Write this Code:-

<img id="img" src="imgstart.jpg">

HorizontalScrollView within ScrollView Touch Handling

Update: I figured this out. On my ScrollView, I needed to override the onInterceptTouchEvent method to only intercept the touch event if the Y motion is > the X motion. It seems like the default behavior of a ScrollView is to intercept the touch event whenever there is ANY Y motion. So with the fix, the ScrollView will only intercept the event if the user is deliberately scrolling in the Y direction and in that case pass off the ACTION_CANCEL to the children.

Here is the code for my Scroll View class that contains the HorizontalScrollView:

public class CustomScrollView extends ScrollView {
    private GestureDetector mGestureDetector;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }

    // Return false if we're scrolling in the x direction  
    class YScrollDetector extends SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {             
            return Math.abs(distanceY) > Math.abs(distanceX);
        }
    }
}

jQuery Toggle Text?

this is not the very clean and smart way but its very easy to understand and use somtimes - its like odd and even - boolean like:

  var moreOrLess = 2;

  $('.Btn').on('click',function(){

     if(moreOrLess % 2 == 0){
        $(this).text('text1');
        moreOrLess ++ ;
     }else{
        $(this).text('more'); 
        moreOrLess ++ ;
     }

});

How to get jQuery to wait until an effect is finished?

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Is embedding background image data into CSS as Base64 good or bad practice?

I disagree with the recommendation to create separate CSS files for non-editorial images.

Assuming the images are for UI purposes, it's presentation layer styling, and as mentioned above, if you're doing mobile UI's its definitely a good idea to keep all styling in a single file so it can be cached once.

Compare two files and write it to "match" and "nomatch" files

I had used JCL about 2 years back so cannot write a code for you but here is the idea;

  1. Have 2 steps
  2. First step will have ICETOOl where you can write the matching records to matched file.
  3. Second you can write a file for mismatched by using SORT/ICETOOl or by just file operations.

again i apologize for solution without code, but i am out of touch by 2 yrs+

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

Why is a primary-foreign key relation required when we can join without it?

The main reason for primary and foreign keys is to enforce data consistency.

A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.

A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

This will also happen if you are trying to insert into a unique constraint situation, ie if you can only have one type of address per employer and you try to insert a second of that same type with the same employer, you will get the same problem.

OR

This could also happen if all of the object properties that were assigned to, they were assigned with the same values as they had before.

        using(var db = new MyContext())
        {
            var address = db.Addresses.FirstOrDefault(x => x.Id == Id);

            address.StreetAddress = StreetAddress; // if you are assigning   
            address.City = City;                   // all of the same values
            address.State = State;                 // as they are
            address.ZipCode = ZipCode;             // in the database    

            db.SaveChanges();           // Then this will throw that exception
        }

How to clear basic authentication details in chrome

For Chrome 66 I found the relevant option under:

  1. Top right ... menu -> More Tools -> Clear Browsing Data
  2. Click the "Advanced" tab
  3. Check the "Passwords" box (and uncheck others you don't want cleared)
  4. Click "Clear Data"

Using a new Incognito window is probably easier, but for those times you forget and want to clear the saved password, this does the trick without having to restart Chrome (which also works)

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

Magento Product Attribute Get Value

If you have an text/textarea attribute named my_attr you can get it by: product->getMyAttr();

Environment variable substitution in sed

Another easy alternative:

Since $PWD will usually contain a slash /, use | instead of / for the sed statement:

sed -e "s|xxx|$PWD|"

What integer hash function are good that accepts an integer hash key?

The answer depends on a lot of things like:

  • Where do you intend to employ it?
  • What are you trying to do with the hash?
  • Do you need a crytographically secure hash function?

I suggest that you take a look at the Merkle-Damgard family of hash functions like SHA-1 etc

javascript - match string against the array of regular expressions

You could use .test() which returns a boolean value when is find what your looking for in another string:

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);  
if (FoundIt) { /* DO STUFF */ }

What is the most efficient way of finding all the factors of a number in Python?

The simplest way of finding factors of a number:

def factors(x):
    return [i for i in range(1,x+1) if x%i==0]

AngularJS : When to use service instead of factory

There is nothing a Factory cannot do or does better in comparison with a Service. And vice verse. Factory just seems to be more popular. The reason for that is its convenience in handling private/public members. Service would be more clumsy in this regard. When coding a Service you tend to make your object members public via “this” keyword and may suddenly find out that those public members are not visible to private methods (ie inner functions).

var Service = function(){

  //public
  this.age = 13;

  //private
  function getAge(){

    return this.age; //private does not see public

  }

  console.log("age: " + getAge());

};

var s = new Service(); //prints 'age: undefined'

Angular uses the “new” keyword to create a service for you, so the instance Angular passes to the controller will have the same drawback. Of course you may overcome the problem by using this/that:

var Service = function(){

  var that = this;

  //public
  this.age = 13;

  //private
  function getAge(){

    return that.age;

  }

  console.log("age: " + getAge());

};

var s = new Service();// prints 'age: 13'  

But with a large Service constant this\that-ing would make the code poorly readable. Moreover, the Service prototypes will not see private members – only public will be available to them:

var Service = function(){

  var name = "George";

};

Service.prototype.getName = function(){

  return this.name; //will not see a private member

};

var s = new Service();
console.log("name: " + s.getName());//prints 'name: undefined'

Summing it up, using Factory is more convenient. As Factory does not have these drawbacks. I would recommend using it by default.

Initializing a list to a known number of elements in Python

Not quite sure why everyone is giving you a hard time for wanting to do this - there are several scenarios where you'd want a fixed size initialised list. And you've correctly deduced that arrays are sensible in these cases.

import array
verts=array.array('i',(0,)*1000)

For the non-pythonistas, the (0,)*1000 term is creating a tuple containing 1000 zeros. The comma forces python to recognise (0) as a tuple, otherwise it would be evaluated as 0.

I've used a tuple instead of a list because they are generally have lower overhead.

HTML5 Video not working in IE 11

I believe IE requires the H.264 or MPEG-4 codec, which it seems like you don't specify/include. You can always check for browser support by using HTML5Please and Can I use.... Both sites usually have very up-to-date information about support, polyfills, and advice on how to take advantage of new technology.

What is MVC and what are the advantages of it?

Separation of concerns is the biggy.

Being able to tease these components apart makes the code easier to re-use and independently test. If you don't actually know what MVC is, be careful about trying to understand people's opinions as there is still some contention about what the "Model" is (whether it is the business objects/DataSets/DataTables or if it represents the underlying service layer).

I've seen all sorts of implementations that call themselves MVC but aren't exactly and as the comments in Jeff's article show MVC is a contentious point that I don't think developers will ever fully agree upon.

A good round up of all of the different MVC types is available here.

Undefined index with $_POST

I know that this is old post but someone can help:

function POST($index, $default=NULL){
        if(isset($_POST[$index]))
        {
            if(!empty(trim($_POST[$index])))    
                return $_POST[$index];
        }
        return $default;
    }

This code above are my basic POST function what I use anywhere. Here you can put filters, regular expressions, etc. Is faster and clean. My advanced POST function is more complicate to accept and check arrays, string type, default values etc. Let's your imagination work here.

You easy can check username like this:

$username = POST("username");
if($username!==null){
    echo "{$username} is in the house.";
}

Also I added $default string that you can define some default value if POST is not active or content not exists.

echo "<h1>".POST("title", "Stack Overflow")."</h1>";

Play with it.

Time complexity of accessing a Python dict

It would be easier to make suggestions if you provided example code and data.

Accessing the dictionary is unlikely to be a problem as that operation is O(1) on average, and O(N) amortized worst case. It's possible that the built-in hashing functions are experiencing collisions for your data. If you're having problems with has the built-in hashing function, you can provide your own.

Python's dictionary implementation reduces the average complexity of dictionary lookups to O(1) by requiring that key objects provide a "hash" function. Such a hash function takes the information in a key object and uses it to produce an integer, called a hash value. This hash value is then used to determine which "bucket" this (key, value) pair should be placed into.

You can overwrite the __hash__ method in your class to implement a custom hash function like this:

def __hash__(self):    
    return hash(str(self))

Depending on what your data actually looks like, you might be able to come up with a faster hash function that has fewer collisions than the standard function. However, this is unlikely. See the Python Wiki page on Dictionary Keys for more information.

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

MySQL stored procedure return value

Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.

CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    GET DIAGNOSTICS CONDITION 1
    @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
    SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;

SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;

IF (resta > s.stock_minimo) THEN
    SET valido = 1;
ELSE
    SET valido = -1;
END IF;
SELECT valido;
END

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

That's because you defined your own version of name for your enum, and getByName doesn't use that.

getByName("COLUMN_HEADINGS") would probably work.

How to fire AJAX request Periodically?

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval(). If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

How to access route, post, get etc. parameters in Zend Framework 2

require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));

$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http'); 

// Register with spl_autoload:
$loader->register();

$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;

How to split a delimited string into an array in awk?

I do not like the echo "..." | awk ... solution as it calls unnecessary fork and execsystem calls.

I prefer a Dimitre's solution with a little twist

awk -F\| '{print $3 $2 $1}' <<<'12|23|11'

Or a bit shorter version:

awk -F\| '$0=$3 $2 $1' <<<'12|23|11'

In this case the output record put together which is a true condition, so it gets printed.

In this specific case the stdin redirection can be spared with setting an internal variable:

awk -v T='12|23|11' 'BEGIN{split(T,a,"|");print a[3] a[2] a[1]}'

I used quite a while, but in this could be managed by internal string manipulation. In the first case the original string is split by internal terminator. In the second case it is assumed that the string always contains digit pairs separated by a one character separator.

T='12|23|11';echo -n ${T##*|};T=${T%|*};echo ${T#*|}${T%|*}
T='12|23|11';echo ${T:6}${T:3:2}${T:0:2}

The result in all cases is

112312

Edit line thickness of CSS 'underline' attribute

Another way to do this is using ":after" (pseudo-element) on the element you want to underline.

h2{
  position:relative;
  display:inline-block;
  font-weight:700;
  font-family:arial,sans-serif;
  text-transform:uppercase;
  font-size:3em;
}
h2:after{
  content:"";
  position:absolute;
  left:0;
  bottom:0;
  right:0;
  margin:auto;
  background:#000;
  height:1px;

}

MVC 3 file upload and model binding

Solved

Model

public class Book
{
public string Title {get;set;}
public string Author {get;set;}
}

Controller

public class BookController : Controller
{
     [HttpPost]
     public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload)
     {
         throw new NotImplementedException();
     }
}

And View

@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
{      
     @Html.EditorFor(m => m)

     <input type="file" name="fileUpload[0]" /><br />      
     <input type="file" name="fileUpload[1]" /><br />      
     <input type="file" name="fileUpload[2]" /><br />      

     <input type="submit" name="Submit" id="SubmitMultiply" value="Upload" />
}

Note title of parameter from controller action must match with name of input elements IEnumerable<HttpPostedFileBase> fileUpload -> name="fileUpload[0]"

fileUpload must match

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

On a Windows machine I was able to log to to ssh from git bash with
ssh vagrant@VAGRANT_SERVER_IP without providing a password

Using Bitvise SSH client on window
Server host: VAGRANT_SERVER_IP
Server port: 22
Username: vagrant
Password: vagrant

how to find seconds since 1970 in java

The difference you see is most likely because you don't zero the hour, minute, second and milliseconds fields of your Calendar instances: Calendar.getInstance() gives you the current date and time, just like new Date() or System.currentTimeMillis().

Note that the month field of Calendar is zero-based, i.e. January is 0, not 1.

Also, don't prefix numbers with zero, this might look nice and it even works till you reach 8: 08 isn't a valid numeral in Java. Prefixing numerals with zero makes the compiler assume you're defining them as octal numerals which only works up to 07 (for single digits).

Just drop calendar1 completely (1970-01-01 00:00:00'000 is the begin of the epoch, i.e. zero anyway) and do this:

public long returnSeconds(int year, int month, int date) {
    final Calendar cal = Calendar.getInstance();
    cal.set(year, month, date, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis() / 1000;
}

How can I do a BEFORE UPDATED trigger with sql server?

The updated or deleted values are stored in DELETED. we can get it by the below method in trigger

Full example,

CREATE TRIGGER PRODUCT_UPDATE ON PRODUCTS
FOR UPDATE 
AS
BEGIN
DECLARE @PRODUCT_NAME_OLD VARCHAR(100)
DECLARE @PRODUCT_NAME_NEW VARCHAR(100)

SELECT @PRODUCT_NAME_OLD = product_name from DELETED
SELECT @PRODUCT_NAME_NEW = product_name from INSERTED

END

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

Visual Studio Code - Convert spaces to tabs

If you want to change tabs to spaces in a lot of files, but don't want to open them individually, I have found that it works equally as well to just use the Find and Replace option from the left-most tools bar.

In the first box (Find), copy and paste a tab from the source code.

In the second box (Replace), enter the number of spaces that you wish to use (i.e. 2 or 4).

If you press the ... button, you can specify directories to include or ignore (i.e. src/Data/Json).

Finally, inspect the result preview and press Replace All. All files in the workspace may be affected.

A simple algorithm for polygon intersection

You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.

One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton

Alan Murta has a complete implementation of a polygon clipper GPC.

Edit:

Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.

How to print Unicode character in C++?

If you use Windows (note, we are using printf(), not cout):

//Save As UTF8 without signature
#include <stdio.h>
#include<windows.h>
int main (){
    SetConsoleOutputCP(65001); 
    printf("?\n");
}

Not Unicode but working - 1251 instead of UTF8:

//Save As Windows 1251
#include <iostream>
#include<windows.h>
using namespace std;
int main (){
    SetConsoleOutputCP(1251); 
    cout << "?" << endl;
}

Javascript switch vs. if...else if...else

Is there a preformance difference in Javascript between a switch statement and an if...else if....else?

I don't think so, switch is useful/short if you want prevent multiple if-else conditions.

Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)

Behavior is same across all browsers :)

How do I debug Windows services in Visual Studio?

I found this question, but I think a clear and simple answer is missing.

I don't want to attach my debugger to a process, but I still want to be able to call the service OnStart and OnStop methods. I also want it to run as a console application so that I can log information from NLog to a console.

I found these brilliant guides that does this:

Start by changing the projects Output type to Console Application.

Enter image description here

Change your Program.cs to look like this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        // Startup as service.
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        };

        if (Environment.UserInteractive)
        {
            RunInteractive(ServicesToRun);
        }
        else
        {
            ServiceBase.Run(ServicesToRun);
        }
    }
}

Then add the following method to allow services running in interactive mode.

static void RunInteractive(ServiceBase[] servicesToRun)
{
    Console.WriteLine("Services running in interactive mode.");
    Console.WriteLine();

    MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Starting {0}...", service.ServiceName);
        onStartMethod.Invoke(service, new object[] { new string[] { } });
        Console.Write("Started");
    }

    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine(
        "Press any key to stop the services and end the process...");
    Console.ReadKey();
    Console.WriteLine();

    MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Stopping {0}...", service.ServiceName);
        onStopMethod.Invoke(service, null);
        Console.WriteLine("Stopped");
    }

    Console.WriteLine("All services stopped.");
    // Keep the console alive for a second to allow the user to see the message.
    Thread.Sleep(1000);
}

Send File Attachment from Form Using phpMailer and PHP

Use this code for sending attachment with upload file option using html form in phpmailer

 <form method="post" action="" enctype="multipart/form-data">


                    <input type="text" name="name" placeholder="Your Name *">
                    <input type="email" name="email" placeholder="Email *">
                    <textarea name="msg" placeholder="Your Message"></textarea>


                    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                    <input type="file" name="userfile"  />


                <input name="contact" type="submit" value="Submit Enquiry" />
   </form>


    <?php




        if(isset($_POST["contact"]))
        {

            /////File Upload

            // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
            // of $_FILES.

            $uploaddir = 'uploads/';
            $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

            echo '<pre>';
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                echo "File is valid, and was successfully uploaded.\n";
            } else {
                echo "Possible invalid file upload !\n";
            }

            echo 'Here is some more debugging info:';
            print_r($_FILES);

            print "</pre>";


            ////// Email


            require_once("class.phpmailer.php");
            require_once("class.smtp.php");



            $mail_body = array($_POST['name'], $_POST['email'] , $_POST['msg']);
            $new_body = "Name: " . $mail_body[0] . ", Email " . $mail_body[1] . " Description: " . $mail_body[2];



            $d=strtotime("today"); 

            $subj = 'New enquiry '. date("Y-m-d h:i:sa", $d);

            $mail = new PHPMailer(); // create a new object


            //$mail->IsSMTP(); // enable SMTP
            $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only ,false = Disable 
            $mail->Host = "mail.yourhost.com";
            $mail->Port = '465';
            $mail->SMTPAuth = true; // enable 
            $mail->SMTPSecure = true;
            $mail->IsHTML(true);
            $mail->Username = "[email protected]"; //[email protected]
            $mail->Password = "password";
            $mail->SetFrom("[email protected]", "Your Website Name");
            $mail->Subject = $subj;
            $mail->Body    = $new_body;

            $mail->AddAttachment($uploadfile);

            $mail->AltBody = 'Upload';
            $mail->AddAddress("[email protected]");
             if(!$mail->Send())
                {
                echo "Mailer Error: " . $mail->ErrorInfo;
                }
                else
                {

                echo '<p>       Success              </p> ';

                }

        }



?>

Use this link for reference.

How can I get key's value from dictionary in Swift?

For finding value use below

if let a = companies["AAPL"] {
   // a is the value
}

For traversing through the dictionary

for (key, value) in companies {
    print(key,"---", value)
}

Finally for searching key by value you firstly add the extension

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}

Then just call

companies.findKey(val : "Apple Inc")

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

How to set fake GPS location on IOS real device

I had a similar issue, but with no source code to run on Xcode.

So if you want to test an application on a real device with a fake location you should use a VPN application.

There are plenty in the App Store to choose from - free ones without the option to choose a specific country/city and free ones which assign you a random location or asks you to choose from a limited set of default options.

How can I get zoom functionality for images?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageDetail = (ImageView) findViewById(R.id.imageView1);
    imageDetail.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            System.out.println("matrix=" + savedMatrix.toString());
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    savedMatrix.set(matrix);
                    startPoint.set(event.getX(), event.getY());
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    if (oldDist > 10f) {
                        savedMatrix.set(matrix);
                        midPoint(midPoint, event);
                        mode = ZOOM;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        matrix.set(savedMatrix);
                        matrix.postTranslate(event.getX() - startPoint.x, event.getY() - startPoint.y);
                    } else if (mode == ZOOM) {
                        float newDist = spacing(event);
                        if (newDist > 10f) {
                            matrix.set(savedMatrix);
                            float scale = newDist / oldDist;
                            matrix.postScale(scale, scale, midPoint.x, midPoint.y);
                        }
                    }
                    break;
            }
            view.setImageMatrix(matrix);
            return true;

        }

        @SuppressLint("FloatMath")
        private float spacing(MotionEvent event) {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return FloatMath.sqrt(x * x + y * y);
        }

        private void midPoint(PointF point, MotionEvent event) {
            float x = event.getX(0) + event.getX(1);
            float y = event.getY(0) + event.getY(1);
            point.set(x / 2, y / 2);
        }
    });
}

and drawable folder should have bticn image file. perfectly works :)

Integer value in TextView

TextView tv = new TextView(this);
tv.setText(String.valueOf(number));

or

tv.setText(""+number);

how to use math.pi in java

Replace

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;

Calling a JavaScript function named in a variable

If it´s in the global scope it´s better to use:

function foo()
{
    alert('foo');
}

var a = 'foo';
window[a]();

than eval(). Because eval() is evaaaaaal.

Exactly like Nosredna said 40 seconds before me that is >.<

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

I spent almost a day trying to figure out why I was getting this exception. After lots of struggle, this config worked perfectly (Kotlin):

AndroidManifest.xml

<provider
  android:name="androidx.core.content.FileProvider"
  android:authorities="com.lomza.moviesroom.fileprovider"
  android:exported="false"
  android:grantUriPermissions="true">
  <meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/file_paths" />
</provider>

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
  <files-path name="movies_csv_files" path="."/>
</paths>

Intent itself

fun goToFileIntent(context: Context, file: File): Intent {
    val intent = Intent(Intent.ACTION_VIEW)
    val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
    val mimeType = context.contentResolver.getType(contentUri)
    intent.setDataAndType(contentUri, mimeType)
    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION

    return intent
}

I explain the whole process here.

Objective-C: Extract filename from path string

If you're displaying a user-readable file name, you do not want to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath: method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.

How to use relative paths without including the context root name?

Just use <c:url>-tag with an application context relative path.

When the value parameter starts with an /, then the tag will treat it as an application relative url, and will add the application-name to the url. Example:

jsp:

<c:url value="/templates/style/main.css" var="mainCssUrl" />`
<link rel="stylesheet" href="${mainCssUrl}" />
...
<c:url value="/home" var="homeUrl" />`
<a href="${homeUrl}">home link</a>

will become this html, with an domain relative url:

<link rel="stylesheet" href="/AppName/templates/style/main.css" />
...
<a href="/AppName/home">home link</a>

How do I set the eclipse.ini -vm option?

I'd like to share this little hack:

A click on the Eclipse's icon indicated a problem with the JRE. So, I put this command in the destination field of the icon's properties:

C:\...\eclipse.exe -vm c:\'Program Files'\Java\jdk1.7.0_51\jre\bin\javaw

Thinking that the "'" would solve the problem with the space in the path. That did not function. Then, I tried this command:

C:\...\eclipse.exe -vm c:\Progra~1\Java\jdk1.7.0_51\jre\bin\javaw

with success

add new row in gridview after binding C#, ASP.net

try using the cloning technique.

{
    DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
    // then for each of the values use a loop like below.
    int cc = yourdatagrid.Columns.Count;
    for (int i2 = 0; i < cc; i2++)
    {
        row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
    }
    yourdatagrid.Rows.Add(row);
    i++;
    }
}

This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

Determine SQL Server Database Size

According to SQL2000 help, sp_spaceused includes data and indexes.

This script should do:

CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18), 
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))

EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

Node.js: for each … in not working

for (var i in conf) {
  val = conf[i];
  console.log(val.path);
}

Java Serializable Object to Byte Array

The best way to do it is to use SerializationUtils from Apache Commons Lang.

To serialize:

byte[] data = SerializationUtils.serialize(yourObject);

To deserialize:

YourObject yourObject = SerializationUtils.deserialize(data)

As mentioned, this requires Commons Lang library. It can be imported using Gradle:

compile 'org.apache.commons:commons-lang3:3.5'

Maven:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

Jar file

And more ways mentioned here

Alternatively, the whole collection can be imported. Refer this link

OpenSSL Command to check if a server is presenting a certificate

I was getting the below as well trying to get out to github.com as our proxy re-writes the HTTPS connection with their self-signed cert:

no peer certificate available No client certificate CA names sent

In my output there was also:

Protocol : TLSv1.3

I added -tls1_2 and it worked fine and now I can see which CA it is using on the outgoing request. e.g.:
openssl s_client -connect github.com:443 -tls1_2

jQuery event handlers always execute in order they were bound - any way around this?

The selected answer authored by Anurag is only partially correct. Due to some internals of jQuery's event handling, the proposed bindFirst function will not work if you have a mix of handlers with and without filters (ie: $(document).on("click", handler) vs $(document).on("click", "button", handler)).

The issue is that jQuery will place (and expect) that the first elements in the handler array will be these filtered handlers, so placing our event without a filter at the beginning breaks this logic and things start to fall apart. The updated bindFirst function should be as follows:

$.fn.bindFirst = function (name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.on(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    this.each(function () {
        var handlers = $._data(this, 'events')[name.split('.')[0]];
        // take out the handler we just inserted from the end
        var handler = handlers.pop();
        // get the index of the first handler without a selector
        var firstNonDelegate = handlers.first(function(h) { return !h.selector; });
        var index = firstNonDelegate ? handlers.indexOf(firstNonDelegate)
                                     : handlers.length; // Either all handlers are selectors or we have no handlers
        // move it at the beginning
        handlers.splice(index, 0, handler);
    });
};

Which Eclipse version should I use for an Android app?

As of 10/2011 ... classic is fine for Android development.

See Compare Eclipse Packages for a nice chart.

Convert java.util.date default format to Timestamp in Java

Best one

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

Python conversion from binary string to hexadecimal

int given base 2 and then hex:

>>> int('010110', 2)
22
>>> hex(int('010110', 2))
'0x16'
>>> 

>>> hex(int('0000010010001101', 2))
'0x48d'

The doc of int:

int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating

point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If base is zero, the proper base is guessed based on the string content. If the argument is outside the integer range a long object will be returned instead.

The doc of hex:

hex(number) -> string

Return the hexadecimal representation of an integer or long

integer.

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

How can I see the request headers made by curl when sending a request to the server?

curl -s -v -o/dev/null -H "Testheader: test" http://www.example.com

You could also use -I option if you want to send a HEAD request and not a GET request.

Why does intellisense and code suggestion stop working when Visual Studio is open?

It didn't work for me with all those steps. Strangely enough I noticed Intellisense was working for another solution in visual studio 2015, but not for a specific one.

I located and deleted the .suo file and restarted visual studio. That fixed it for me.

Make $JAVA_HOME easily changable in Ubuntu

Traditionally, if you only want to change the variable in your terminal windows, set it in .bashrc file, which is sourced each time a new terminal is opened. .profile file is not sourced each time you open a new terminal.

See the difference between .profile and .bashrc in question: What's the difference between .bashrc, .bash_profile, and .environment?

.bashrc should solve your problem. However, it is not the proper solution since you are using Ubuntu. See the relevant Ubuntu help page "Session-wide environment variables". Thus, no wonder that .profile does not work for you. I use Ubuntu 12.04 and xfce. I set up my .profile and it is simply not taking effect even if I log out and in. Similar experience here. So you may have to use .pam_environment file and totally forget about .profile, and .bashrc. And NOTE that .pam_environment is not a script file.

Create directory if it does not exist

From your situation it sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number, Get-NextRevisionNumber. Or you could do something like this:

foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
    # Select all the Revision folders from the project folder.
    $Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory

    # The next revision number is just going to be one more than the highest number.
    # You need to cast the string in the first pipeline to an int so Sort-Object works.
    # If you sort it descending the first number will be the biggest so you select that one.
    # Once you have the highest revision number you just add one to it.
    $NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1

    # Now in this we kill two birds with one stone.
    # It will create the "Reports" folder but it also creates "Revision#" folder too.
    New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory

    # Move on to the next project folder.
    # This untested example loop requires PowerShell version 3.0.
}

PowerShell 3.0 installation.

Location of the android sdk has not been setup in the preferences in mac os?

Here is, how I've handled this issue (Mac OS X 10.8.4):

1) Because I previously have installed Android Studio the sdk located here: Applications/Android Studio.app/sdk

You can dig into Android Studio.app folder by hitting "Show package contents" in context menu

2) Simply copy the "sdk" folder to another location and write it down to Eclipse preferences. Because I couldn't find how to properly add adress like "/Android Studio.app/sdk" (folder with .app extension) to Eclipse preferences.

I know that this solution is not smooth and best, but it works (at least for me). And I've tried all advices in this theme, and installed the ADT from http://dl-ssl.google.com/android/eclipse/ before, but the error window have kept appearing every time.

How to convert color code into media.brush?

For WinRT (Windows Store App)

using Windows.UI;
using Windows.UI.Xaml.Media;

    public static Brush ColorToBrush(string color) // color = "#E7E44D"
    {
        color = color.Replace("#", "");
        if (color.Length == 6)
        {
            return new SolidColorBrush(ColorHelper.FromArgb(255,
                byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
        }
        else
        {
            return null;
        }
    }

how to query for a list<String> in jdbctemplate

To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)

Android findViewById() in Custom View

You can try something like this:

Inside customview constructor:

mContext = context;

Next inside customview you can call:

((MainActivity) mContext).updateText( text );

Inside MainAcivity define:

public void updateText(final String text) {

     TextView txtView = (TextView) findViewById(R.id.text);
     txtView.setText(text);
}

It works for me.

syntax error, unexpected T_VARIABLE

If that is the entire line, it very well might be because you are missing a ; at the end of the line.

Count occurrences of a char in a string using Bash

I Would suggest the following:

var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"

No call to any other program

How to get duplicate items from a list using LINQ?

I wrote this extension method based off @Lee's response to the OP. Note, a default parameter was used (requiring C# 4.0). However, an overloaded method call in C# 3.0 would suffice.

/// <summary>
/// Method that returns all the duplicates (distinct) in the collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <param name="source">The source collection to detect for duplicates</param>
/// <param name="distinct">Specify <b>true</b> to only return distinct elements.</param>
/// <returns>A distinct list of duplicates found in the source collection.</returns>
/// <remarks>This is an extension method to IEnumerable&lt;T&gt;</remarks>
public static IEnumerable<T> Duplicates<T>
         (this IEnumerable<T> source, bool distinct = true)
{
     if (source == null)
     {
        throw new ArgumentNullException("source");
     }

     // select the elements that are repeated
     IEnumerable<T> result = source.GroupBy(a => a).SelectMany(a => a.Skip(1));

     // distinct?
     if (distinct == true)
     {
        // deferred execution helps us here
        result = result.Distinct();
     }

     return result;
}

PHP preg_match - only allow alphanumeric strings and - _ characters

Here is one equivalent of the accepted answer for the UTF-8 world.

if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}

Explanation:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • p{N} => matches any kind of numeric character
  • _- => matches underscore and hyphen
  • + => Quantifier — Matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

onchange file input change img src and change image color

Try with this code, you will get the image preview while uploading

<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />

 function readURL(input){
 var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) 
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#img').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}else{
     $('#img').attr('src', '/assets/no_preview.png');
}
}

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

How do I find out my MySQL URL, host, port and username?

default-username = root
password = you-know-it-better
url for localhost =  jdbc:mysql://localhost
default-port = 3306

How do you discover model attributes in Rails?

There is a rails plugin called Annotate models, that will generate your model attributes on the top of your model files here is the link:

https://github.com/ctran/annotate_models

to keep the annotation in sync, you can write a task to re-generate annotate models after each deploy.

How to SELECT by MAX(date)?

Accordig to this: https://bugs.mysql.com/bug.php?id=54784 casting as char should do the trick:

SELECT report_id, computer_id, MAX(CAST(date_entered AS CHAR))
FROM reports
GROUP BY report_id, computer_id

Change bullets color of an HTML list without using span

For me the best option is to use CSS pseudo elements, so for disc bullet styling it would look like that:

_x000D_
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li:before {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  width: 5px; /* adjust to suit your needs */_x000D_
  height: 5px; /* adjust to suit your needs */_x000D_
  border-radius: 50%;_x000D_
  left: -15px; /* adjust to suit your needs */_x000D_
  top: 0.5em;_x000D_
  background: #f00; /* adjust to suit your needs */_x000D_
}
_x000D_
<ul>_x000D_
  <li>first</li>_x000D_
  <li>second</li>_x000D_
  <li>third</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Notes:

  • width and height should have equal values to keep pointers rounded
  • you may set border-radius to zero if you want to have square list bullets

For more bullets styles you may use other css shapes https://css-tricks.com/examples/ShapesOfCSS/ (choose this which doesn't require pseudo elements to work, so for example triangles)

Using union and order by clause in mysql

(select add_date,col2 from table_name) 
  union 
(select add_date,col2 from table_name) 
  union 
(select add_date,col2 from table_name) 

order by add_date

AngularJS - Building a dynamic table based on a json

Just want to share with what I used so far to save your time.

Here are examples of hard-coded headers and dynamic headers (in case if don't care about data structure). In both cases I wrote some simple directive: customSort

customSort

.directive("customSort", function() {
    return {
        restrict: 'A',
        transclude: true,    
        scope: {
          order: '=',
          sort: '='
        },
        template : 
          ' <a ng-click="sort_by(order)" style="color: #555555;">'+
          '    <span ng-transclude></span>'+
          '    <i ng-class="selectedCls(order)"></i>'+
          '</a>',
        link: function(scope) {

        // change sorting order
        scope.sort_by = function(newSortingOrder) {       
            var sort = scope.sort;

            if (sort.sortingOrder == newSortingOrder){
                sort.reverse = !sort.reverse;
            }                    

            sort.sortingOrder = newSortingOrder;        
        };


        scope.selectedCls = function(column) {
            if(column == scope.sort.sortingOrder){
                return ('icon-chevron-' + ((scope.sort.reverse) ? 'down' : 'up'));
            }
            else{            
                return'icon-sort' 
            } 
        };      
      }// end link
    }
    });

[1st option with static headers]

I used single ng-repeat

This is a good example in Fiddle (Notice, there is no jQuery library!)

enter image description here

           <tbody>
                <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.description}}</td>
                    <td>{{item.field3}}</td>
                    <td>{{item.field4}}</td>
                    <td>{{item.field5}}</td>
                </tr>
            </tbody>

[2nd option with dynamic headers]

Demo 2: Fiddle


HTML

<table class="table table-striped table-condensed table-hover">
            <thead>
                <tr>
                   <th ng-repeat="header in table_headers"  
                     class="{{header.name}}" custom-sort order="header.name" sort="sort"
                    >{{ header.name }}

                        </th> 
                  </tr>
            </thead>
            <tfoot>
                <td colspan="6">
                    <div class="pagination pull-right">
                        <ul>
                            <li ng-class="{disabled: currentPage == 0}">
                                <a href ng-click="prevPage()">« Prev</a>
                            </li>

                            <li ng-repeat="n in range(pagedItems.length, currentPage, currentPage + gap) "
                                ng-class="{active: n == currentPage}"
                            ng-click="setPage()">
                                <a href ng-bind="n + 1">1</a>
                            </li>

                            <li ng-class="{disabled: (currentPage) == pagedItems.length - 1}">
                                <a href ng-click="nextPage()">Next »</a>
                            </li>
                        </ul>
                    </div>
                </td>
            </tfoot>
            <pre>pagedItems.length: {{pagedItems.length|json}}</pre>
            <pre>currentPage: {{currentPage|json}}</pre>
            <pre>currentPage: {{sort|json}}</pre>
            <tbody>

                <tr ng-repeat="item in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
                     <td ng-repeat="val in item" ng-bind-html-unsafe="item[table_headers[$index].name]"></td>
                </tr>
            </tbody>
        </table>

As a side note:

The ng-bind-html-unsafe is deprecated, so I used it only for Demo (2nd example). You welcome to edit.

Do we have router.reload in vue-router?

`<router-link :to='`/products`' @click.native="$router.go()" class="sub-link"></router-link>`

I have tried this for reloading current page.

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

What is the difference between single and double quotes in SQL?

A simple rule for us to remember what to use in which case:

  • [S]ingle quotes are for [S]trings ; [D]ouble quotes are for [D]atabase identifiers;

In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE has ANSI_QUOTES enabled.

How do I jump to a closing bracket in Visual Studio Code?

enter image description here

(For anybody looking how to do it in Visual Studio!)

Fetch frame count with ffmpeg

Since my comment got a few upvotes, I figured I'd leave it as an answer:

ffmpeg -i 00000.avi -map 0:v:0 -c copy -f null -y /dev/null 2>&1 | grep -Eo 'frame= *[0-9]+ *' | grep -Eo '[0-9]+' | tail -1

This should be fast, since no encoding is being performed. ffmpeg will just demux the file and read (decode) the first video stream as quickly as possible. The first grep command will grab the text that shows the frame. The second grep command will grab just the number from that. The tail command will just show the final line (final frame count).

Open Facebook Page in Facebook App (if installed) on Android

you can use this:

try {
                Intent followIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://facewebmodal/f?href=" +
                        "https://www.facebook.com/app_scoped_user_id/"+scoped user id+"/"));
                activity.startActivity(followIntent);
            } catch (Exception e) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + user name)));
                String errorMessage = (e.getMessage() == null) ? "Message is empty" : e.getMessage();
            }

attention: you can get scoped user id from "link" permission facebook api

How to get the command line args passed to a running process on unix/linux systems?

try ps -n in a linux terminal. This will show:

1.All processes RUNNING, their command line and their PIDs

  1. The program intiate the processes.

Afterwards you will know which process to kill

how do I query sql for a latest record date for each user

SELECT Username, date, value
 from MyTable mt
 inner join (select username, max(date) date
              from MyTable
              group by username) sub
  on sub.username = mt.username
   and sub.date = mt.date

Would address the updated problem. It might not work so well on large tables, even with good indexing.

$lookup on ObjectId's in an array

use $unwind you will get the first object instead of array of objects

query:

db.getCollection('vehicles').aggregate([
  {
    $match: {
      status: "AVAILABLE",
      vehicleTypeId: {
        $in: Array.from(newSet(d.vehicleTypeIds))
      }
    }
  },
  {
    $lookup: {
      from: "servicelocations",
      localField: "locationId",
      foreignField: "serviceLocationId",
      as: "locations"
    }
  },
  {
    $unwind: "$locations"
  }
]);

result:

{
    "_id" : ObjectId("59c3983a647101ec58ddcf90"),
    "vehicleId" : "45680",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Isuzu/2003-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}


{
    "_id" : ObjectId("59c3983a647101ec58ddcf91"),
    "vehicleId" : "81765",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Hino/2004-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}

What does "The APR based Apache Tomcat Native library was not found" mean?

On RHEL Linux just issue:

yum install tomcat-native.x86_64

/Note:depending on Your architecture 64bit or 32bit package may have different extension/

That is all. After that You will find in the log file next informational message:

INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].

All operations will be noticeably faster than before.

How to place and center text in an SVG rectangle

For horizontal and vertical alignment of text in graphics, you might want to use the following CSS styles. In particular, note that dominant-baseline:middle is probably wrong, since this is (usually) half way between the top and the baseline, rather than half way between the top and the bottom. Also, some some sources (e.g. Mozilla) use dominant-baseline:hanging instead of dominant-baseline:text-before-edge. This is also probably wrong, since hanging is designed for Indic scripts. Of course, if you're using a mixture of Latin, Indic, ideographs or whatever, you'll probably need to read the documentation.

/* Horizontal alignment */
text.goesleft{text-anchor:end}
text.equalleftright{text-anchor:middle}
text.goesright{text-anchor:start}
/* Vertical alignment */
text.goesup{dominant-baseline:text-after-edge}
text.equalupdown{dominant-baseline:central}
text.goesdown{dominant-baseline:text-before-edge}
text.ruledpaper{dominant-baseline:alphabetic}

Edit: I've just noticed that Mozilla also uses dominant-baseline:baseline which is definitely wrong: it's not even a recognized value! I assume it's defaulting to the font default, which is alphabetic, so they got lucky.

More edit: Safari (11.1.2) understands text-before-edge but not text-after-edge. It also fails on ideographic. Great stuff, Apple. So you might be forced to use alphabetic and allow for descenders after all. Sorry.

How to insert element as a first child?

Required here

<div class="outer">Outer Text <div class="inner"> Inner Text</div> </div>

added by

$(document).ready(function(){ $('.inner').prepend('<div class="middle">New Text Middle</div>'); });

How to convert number of minutes to hh:mm format in TSQL?

For those who need convert minutes to time with more than 24h format:

DECLARE @minutes int = 7830
SELECT CAST(@minutes / 60 AS VARCHAR(8)) + ':' + FORMAT(@minutes % 60, 'D2') AS [Time]

Result:

130:30

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]

It's a warning, not an error. It occurs because fsevents is an optional dependency, used only when project is run on macOS environment (the package provides 'Native Access to Mac OS-X FSEvents').

And since you're running your project on Windows, fsevents is skipped as irrelevant.

There is a PR to fix this behaviour here: https://github.com/npm/cli/pull/169

How to import and use image in a Vue single file component?

I came across this issue recently, and i'm using Typescript. If you're using Typescript like I am, then you need to import assets like so:

<img src="@/assets/images/logo.png" alt="">

Javascript onload not working

Try this one:

<body onload="imageRefreshBig();">

Also you might want to check Javascript console for errors (in Chrome it's under Shift + Ctrl + J).

Renew Provisioning Profile

They change how this works so often. This is what I had to do this time (May 2016):

  • Add a new provisioning profile in the Developer Member Center
  • Open XCode preferences, Account > Choose Apple ID > Choose Team Name > View Details
  • Click the Download button in the Action column for the newly-created provisioning profile

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

You need to make sure that the previous container you launched is killed, before launching a new one that uses the same port.

docker container ls
docker rm -f <container-name>

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

Caesar Cipher Function in Python

I realize that this answer doesn't really answer your question, but I think it's helpful anyway. Here's an alternative way to implementing the caesar cipher with string methods:

def caesar(plaintext, shift):
    alphabet = string.ascii_lowercase
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    table = string.maketrans(alphabet, shifted_alphabet)
    return plaintext.translate(table)

In fact, since string methods are implemented in C, we will see an increase in performance with this version. This is what I would consider the 'pythonic' way of doing this.

Best way to copy a database (SQL Server 2008)

If you want to take a copy of a live database, do the Backup/Restore method.

[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.

Version vs build in Xcode

The script to autoincrement the build number in the answer above didn't work for me if the build number is a floating point value, so I modified it a little:

#!/bin/bash    
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=`echo $buildNumber +1|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

Locking pattern for proper use of .NET MemoryCache

It is difficult to choose which one is better; lock or ReaderWriterLockSlim. You need real world statistics of read and write numbers and ratios etc.

But if you believe using "lock" is the correct way. Then here is a different solution for different needs. I also include the Allan Xu's solution in the code. Because both can be needed for different needs.

Here are the requirements, driving me to this solution:

  1. You don't want to or cannot supply the 'GetData' function for some reason. Perhaps the 'GetData' function is located in some other class with a heavy constructor and you do not want to even create an instance till ensuring it is unescapable.
  2. You need to access the same cached data from different locations/tiers of the application. And those different locations don't have access to same locker object.
  3. You don't have a constant cache key. For example; need of caching some data with the sessionId cache key.

Code:

using System;
using System.Runtime.Caching;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace CachePoc
{
    class Program
    {
        static object everoneUseThisLockObject4CacheXYZ = new object();
        const string CacheXYZ = "CacheXYZ";
        static object everoneUseThisLockObject4CacheABC = new object();
        const string CacheABC = "CacheABC";

        static void Main(string[] args)
        {
            //Allan Xu's usage
            string xyzData = MemoryCacheHelper.GetCachedDataOrAdd<string>(CacheXYZ, everoneUseThisLockObject4CacheXYZ, 20, SomeHeavyAndExpensiveXYZCalculation);
            string abcData = MemoryCacheHelper.GetCachedDataOrAdd<string>(CacheABC, everoneUseThisLockObject4CacheXYZ, 20, SomeHeavyAndExpensiveXYZCalculation);

            //My usage
            string sessionId = System.Web.HttpContext.Current.Session["CurrentUser.SessionId"].ToString();
            string yvz = MemoryCacheHelper.GetCachedData<string>(sessionId);
            if (string.IsNullOrWhiteSpace(yvz))
            {
                object locker = MemoryCacheHelper.GetLocker(sessionId);
                lock (locker)
                {
                    yvz = MemoryCacheHelper.GetCachedData<string>(sessionId);
                    if (string.IsNullOrWhiteSpace(yvz))
                    {
                        DatabaseRepositoryWithHeavyConstructorOverHead dbRepo = new DatabaseRepositoryWithHeavyConstructorOverHead();
                        yvz = dbRepo.GetDataExpensiveDataForSession(sessionId);
                        MemoryCacheHelper.AddDataToCache(sessionId, yvz, 5);
                    }
                }
            }
        }


        private static string SomeHeavyAndExpensiveXYZCalculation() { return "Expensive"; }
        private static string SomeHeavyAndExpensiveABCCalculation() { return "Expensive"; }

        public static class MemoryCacheHelper
        {
            //Allan Xu's solution
            public static T GetCachedDataOrAdd<T>(string cacheKey, object cacheLock, int minutesToExpire, Func<T> GetData) where T : class
            {
                //Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
                T cachedData = MemoryCache.Default.Get(cacheKey, null) as T;

                if (cachedData != null)
                    return cachedData;

                lock (cacheLock)
                {
                    //Check to see if anyone wrote to the cache while we where waiting our turn to write the new value.
                    cachedData = MemoryCache.Default.Get(cacheKey, null) as T;

                    if (cachedData != null)
                        return cachedData;

                    cachedData = GetData();
                    MemoryCache.Default.Set(cacheKey, cachedData, DateTime.Now.AddMinutes(minutesToExpire));
                    return cachedData;
                }
            }

            #region "My Solution"

            readonly static ConcurrentDictionary<string, object> Lockers = new ConcurrentDictionary<string, object>();
            public static object GetLocker(string cacheKey)
            {
                CleanupLockers();

                return Lockers.GetOrAdd(cacheKey, item => (cacheKey, new object()));
            }

            public static T GetCachedData<T>(string cacheKey) where T : class
            {
                CleanupLockers();

                T cachedData = MemoryCache.Default.Get(cacheKey) as T;
                return cachedData;
            }

            public static void AddDataToCache(string cacheKey, object value, int cacheTimePolicyMinutes)
            {
                CleanupLockers();

                MemoryCache.Default.Add(cacheKey, value, DateTimeOffset.Now.AddMinutes(cacheTimePolicyMinutes));
            }

            static DateTimeOffset lastCleanUpTime = DateTimeOffset.MinValue;
            static void CleanupLockers()
            {
                if (DateTimeOffset.Now.Subtract(lastCleanUpTime).TotalMinutes > 1)
                {
                    lock (Lockers)//maybe a better locker is needed?
                    {
                        try//bypass exceptions
                        {
                            List<string> lockersToRemove = new List<string>();
                            foreach (var locker in Lockers)
                            {
                                if (!MemoryCache.Default.Contains(locker.Key))
                                    lockersToRemove.Add(locker.Key);
                            }

                            object dummy;
                            foreach (string lockerKey in lockersToRemove)
                                Lockers.TryRemove(lockerKey, out dummy);

                            lastCleanUpTime = DateTimeOffset.Now;
                        }
                        catch (Exception)
                        { }
                    }
                }

            }
            #endregion
        }
    }

    class DatabaseRepositoryWithHeavyConstructorOverHead
    {
        internal string GetDataExpensiveDataForSession(string sessionId)
        {
            return "Expensive data from database";
        }
    }

}

Serializing class instance to JSON

JSON is not really meant for serializing arbitrary Python objects. It's great for serializing dict objects, but the pickle module is really what you should be using in general. Output from pickle is not really human-readable, but it should unpickle just fine. If you insist on using JSON, you could check out the jsonpickle module, which is an interesting hybrid approach.

https://github.com/jsonpickle/jsonpickle

Android EditText for password with android:hint

Hint text not bold, I try to below code.

When I change inputtype=email, other edittext is bold. But when I change input type to password, hint is normal.

I need hint text to be bold, my code is:

 <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="56dp"
            app:theme="@style/Widget.Design.TextInputLayout"
            >
                <EditText
                    android:id="@+id/login_password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Password"
                    android:textStyle="bold"
                    android:inputType="textPassword"
                    android:textColor="@color/White"
                    style="@style/Base.TextAppearance.AppCompat.Small"
                    android:drawableLeft="@drawable/ic_password"
                    android:drawablePadding="10dp"
                    />
            </android.support.design.widget.TextInputLayout>

How to communicate between iframe and the parent site?

It must be here, because accepted answer from 2012

In 2018 and modern browsers you can send a custom event from iframe to parent window.

iframe:

var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)

parent:

window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
  console.log(e.detail) // outputs: {foo: 'bar'}
}

PS: Of course, you can send events in opposite direction same way.

document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)

How to print instances of a class using print()?

A prettier version of response by @user394430

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return  str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))

elem = Element('my_name', 'some_symbol', 3)
print(elem)

Produces visually nice list of the names and values.

<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3

An even fancier version (thanks Ruud) sorts the items:

def __str__(self):
    return  str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))

How to submit an HTML form without redirection

You need Ajax to make it happen. Something like this:

$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
        if(name=='' || email=='' || password=='' || contact=='')
        {
            alert("Please fill in all fields");
        }
        else
        {
            // Ajax code to submit form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

what is the difference between json and xml

They are two formats of representation of information. While JSON was designed to be more compact, XML was design to be more readable.

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.

package com.ajinkya.th.controller;

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  @Controller
  public class HomePageController {

      @RequestMapping("/")
      public String homePage() {
        return "home";
      }

  }

Thats it ! Now restart your gradle server. ./gradlew bootRun

Install NuGet via PowerShell script

With PowerShell but without the need to create a script:

Invoke-WebRequest https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile Nuget.exe

Disable webkit's spin buttons on input type="number"?

I discovered that there is a second portion of the answer to this.

The first portion helped me, but I still had a space to the right of my type=number input. I had zeroed out the margin on the input, but apparently I had to zero out the margin on the spinner as well.

This fixed it:

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

How are booleans formatted in Strings in Python?

To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'

how concatenate two variables in batch script?

The way is correct, but can be improved a bit with the extended set-syntax.

set "var=xyz"

Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.

Your code would look like

set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar

How to find path of active app.config file?

The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.

Problem solved

I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.

installing apache: no VCRUNTIME140.dll

I was gone through same problem & I resolved it by following steps.

  1. Uninstall earlier version of wamp server, which you are trying to install.
  2. Install which ever file supports to your configuration (64, 86) from en this link
  3. Restart your computer.
  4. Install wampserver now.

Sound alarm when code finishes

import subprocess

subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])

Writing a list to a file with Python

In Python3 You Can use this loop

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

How to implement HorizontalScrollView like Gallery?

I have created a horizontal ListView in every row of ListView if you want single You can do the following

Here I am just creating horizontalListView of Thumbnail of Videos Like this

enter image description here

The idea is just continuously add the ImageView to the child of LinearLayout in HorizontalscrollView

Note: remember to fire .removeAllViews(); before next time load other wise it will add duplicate child

Cursor mImageCursor = db.getPlaylistVideoImage(playlistId);
mVideosThumbs.removeAllViews();
if (mImageCursor != null && mImageCursor.getCount() > 0) {
    for (int index = 0; index < mImageCursor.getCount(); index++) {
        mImageCursor.moveToPosition(index);
        ImageView iv = (ImageView) imageViewInfalter.inflate(
            R.layout.image_view, null);
                    name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoDefaultName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
                    if (logoFile.exists()) {    
                Uri uri = Uri.fromFile(logoFile);
                iv.setImageURI(uri);                    
            }
            iv.setScaleType(ScaleType.FIT_XY);
            mVideosThumbs.addView(iv);
    }
    mImageCursor.close();
    mImageCursor = null;
    } else {
        ImageView iv = (ImageView) imageViewInfalter.inflate(
                    R.layout.image_view, null);
        String name = "";
        File logoFile;
        name = mImageCursor.getString(mImageCursor
                    .getColumnIndex("LogoMediumName"));
        logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
        if (logoFile.exists()) {
            Uri uri = Uri.fromFile(logoFile);
            iv.setImageURI(uri);
            }
        }

My xml for HorizontalListView

<HorizontalScrollView
    android:id="@+id/horizontalScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/linearLayoutTitle"
    android:background="@drawable/shelf"
    android:paddingBottom="@dimen/Playlist_TopBottom_margin"
    android:paddingLeft="@dimen/playlist_RightLeft_margin"
    android:paddingRight="@dimen/playlist_RightLeft_margin"
    android:paddingTop="@dimen/Playlist_TopBottom_margin" >

    <LinearLayout
        android:id="@+id/linearLayoutVideos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left|center_vertical"
        android:orientation="horizontal" >
    </LinearLayout>
</HorizontalScrollView>

and Also my Image View as each child

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


  android:id="@+id/imageViewThumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginRight="20dp"
    android:adjustViewBounds="true"
    android:background="@android:color/transparent"
    android:contentDescription="@string/action_settings"
    android:cropToPadding="true"
    android:maxHeight="200dp"
    android:maxWidth="240dp"
    android:padding="@dimen/playlist_image_padding"
    android:scaleType="centerCrop"
    android:src="@drawable/loading" />

To learn More you can follow the following links which have some easy samples

  1. http://www.dev-smart.com/?p=34
  2. Horizontal ListView in Android?

How to load images dynamically (or lazily) when users scrolls them into view

Lazy loading images by attaching listener to scroll events or by making use of setInterval is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.

Use Lozad.js (just 569 bytes with no dependencies), which uses IntersectionObserver to lazy load images performantly.

Executing a shell script from a PHP script

I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP.

e.g. /var/www/scripts/testscript

Make sure the user/group for your testscript is the same as your webfiles. For instance if your client.php is owned by apache:apache, change the bash script to the same user/group using chown. You can find out what your client.php and web files are owned by doing ls -al.

Then run

<?php
      $message=shell_exec("/var/www/scripts/testscript 2>&1");
      print_r($message);
    ?>  

EDIT:

If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do.

Execute root commands via PHP

HTML - Arabic Support

The W3C has a good introduction.

In short:

HTML is a text markup language. Text means any characters, not just ones in ASCII.

  1. Save your text using a character encoding that includes the characters you want (UTF-8 is a good bet). This will probably require configuring your editor in a way that is specific to the particular editor you are using. (Obviously it also requires that you have a way to input the characters you want)
  2. Make sure your server sends the correct character encoding in the headers (how you do this depends on the server software you us)
  3. If the document you serve over HTTP specifies its encoding internally, then make sure that is correct too
  4. If anything happens to the document between you saving it and it being served up (e.g. being put in a database, being munged by a server side script, etc) then make sure that the encoding isn't mucked about with on the way.

You can also represent any unicode character with ASCII

How to install sshpass on mac?

Another option in 2020 is this homebrew tap, maintained by esolitos

brew install esolitos/ipa/sshpass

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

How to echo out table rows from the db (php)

$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
    echo "<tr>";
    foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
        echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function. 
    }
    echo "</tr>";
}
echo "</table>";

Importing class/java files in Eclipse

I had the same problem. But What I did is I imported the .java files and then I went to Search->File-> and then changed the package name to whatever package it should belong in this way I fixed a lot of java files which otherwise would require to go to every file and change them manually.

Simple IEnumerator use (with example)

Here is the documentation on IEnumerator. They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate, which means "to count off or name one by one".

IEnumerator and IEnumerator<T> is provided by all IEnumerable and IEnumerable<T> interfaces (the latter providing both) in .NET via GetEnumerator(). This is important because the foreach statement is designed to work directly with enumerators through those interface methods.

So for example:

IEnumerator enumerator = enumerable.GetEnumerator();

while (enumerator.MoveNext())
{
    object item = enumerator.Current;
    // Perform logic on the item
}

Becomes:

foreach(object item in enumerable)
{
    // Perform logic on the item
}

As to your specific scenario, almost all collections in .NET implement IEnumerable. Because of that, you can do the following:

public IEnumerator Enumerate(IEnumerable enumerable)
{
    // List implements IEnumerable, but could be any collection.
    List<string> list = new List<string>(); 

    foreach(string value in enumerable)
    {
        list.Add(value + "roxxors");
    }
    return list.GetEnumerator();
}

How to list all functions in a Python module?

This will append all the functions that are defined in your_module in a list.

result=[]
for i in dir(your_module):
    if type(getattr(your_module, i)).__name__ == "function":
        result.append(getattr(your_module, i))

Can't bind to 'dataSource' since it isn't a known property of 'table'

The problem is your angular material version, I have the same, and I have resolved this when I have installed the good version of angular material in local.

Hope it solve yours too.

Why use multiple columns as primary keys (composite primary key)

Your second question

How many columns can be used together as a primary key in a given table?

is implementation specific: it's defined in the actual DBMS being used.[1],[2],[3] You have to inspect the technical specification of the database system you use. Some are very detailed, some are not. Searching the web about such limitations can be hard because the terminology varies. The term composite primary key should be mandatory ;)

If you cannot find explicit information, try creating a test database to ensure you can expect stable (and specific) handling of the limit violations (which are to be expected). Be careful to get the right information about this: sometimes the limits are accumulated, and you'll see different results with different database layouts.


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))

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How can I combine hashes in Perl?

Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

@hash1{ keys %hash2 } = values %hash2;

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

How can I create database tables from XSD files?

XML Schemas describe hierarchial data models and may not map well to a relational data model. Mapping XSD's to database tables is very similar mapping objects to database tables, in fact you could use a framework like Castor that does both, it allows you to take a XML schema and generate classes, database tables, and data access code. I suppose there are now many tools that do the same thing, but there will be a learning curve and the default mappings will most like not be what you want, so you have to spend time customizing whatever tool you use.

XSLT might be the fastest way to generate exactly the code that you want. If it is a small schema hardcoding it might be faster than evaluating and learing a bunch of new technologies.

Unstaged changes left after git reset --hard

I believe that there is an issue with git for Windows where git randomly writes the wrong line endings on checkout and the only workaround is to checkout some other branch and force git to ignore changes. Then checkout the branch you actually want to work on.

git checkout master -f
git checkout <your branch>

Be aware that this will discard any changes you might have intentionally made, so only do this if you have this problem immediately after checkout.

Edit: I might have actually got lucky the first time. It turns out that I got bit again after switching branches. It turned out that the files git was reporting as modified after changing branches was changing. (Apparently because git was not consistently applying the CRLF line ending to files properly.)

I updated to the latest git for Windows and hope the problem is gone.

What exactly is an instance in Java?

When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Take a look here
Creating Objects


The types of the Java programming language are divided into two categories: primitive types and reference types.
The reference types are class types, interface types, and array types.
There is also a special null type.
An object is a dynamically created instance of a class type or a dynamically created array.
The values of a reference type are references to objects.

Refer Types, Values, and Variables for more information

Sorting a tab delimited file

You need to put an actual tab character after the -t\ and to do that in a shell you hit ctrl-v and then the tab character. Most shells I've used support this mode of literal tab entry.

Beware, though, because copying and pasting from another place generally does not preserve tabs.

Is there "\n" equivalent in VBscript?

Tried and tested. I know that this works:

Replace(EmailText, vbNewLine, "<br>")

i.e. vbNewLine is also the equivalent of \n

Keyword not supported: "data source" initializing Entity Framework Context

The real reason you were getting this error is because of the &quot; values in your connection string.

If you replace those with single quotes then it will work fine.

https://docs.microsoft.com/archive/blogs/rickandy/explicit-connection-string-for-ef

(Posted so others can get the fix faster than I did.)

How to select the Date Picker In Selenium WebDriver

I think this could be done in a much simpler way:

  1. Find the locator for the Month (use Firebug/Firepath)
  2. This is probably a Select element, use Selenium to select Month
  3. Do the same for Year
  4. Click by linkText "31" or whatever date you want to click

So code would look something like this:

WebElement month = driver.findElement(month combo locator);
Select monthCombo = new Select(month);
monthCombo.selectByVisibleText("March");

WebElement year = driver.findElement(year combo locator);
Select yearCombo = new Select(year);
yearCombo.selectByVisibleText("2015");

driver.click(By.linkText("31"));

This won't work if the date picker dropdowns are not Select, but most of the ones I've seen are individual elements (select, links, etc.)

Command to open file with git

I used Atom, to open files this works for me

atom index.html

Hopefully this helps.

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

I used to use a class like this. The statusCode is set when there is an error with the error message set in message. Data is stored either in the Map or in a List as and when appropriate.

/**
* 
*/
package com.test.presentation.response;

import java.util.Collection;
import java.util.Map;

/**
 * A simple POJO to send JSON response to ajax requests. This POJO enables  us to
 * send messages and error codes with the actual objects in the application.
 * 
 * 
 */
@SuppressWarnings("rawtypes")
public class GenericResponse {

/**
 * An array that contains the actual objects
 */
private Collection rows;

/**
 * An Map that contains the actual objects
 */
private Map mapData;

/**
 * A String containing error code. Set to 1 if there is an error
 */
private int statusCode = 0;

/**
 * A String containing error message.
 */
private String message;

/**
 * An array that contains the actual objects
 * 
 * @return the rows
 */
public Collection getRows() {
    return rows;
}

/**
 * An array that contains the actual objects
 * 
 * @param rows
 *            the rows to set
 */
public void setRows(Collection rows) {
    this.rows = rows;
}

/**
 * An Map that contains the actual objects
 * 
 * @return the mapData
 */
public Map getMapData() {
    return mapData;
}

/**
 * An Map that contains the actual objects
 * 
 * @param mapData
 *            the mapData to set
 */
public void setMapData(Map mapData) {
    this.mapData = mapData;
}

/**
 * A String containing error code.
 * 
 * @return the errorCode
 */
public int getStatusCode() {
    return statusCode;
}

/**
 * A String containing error code.
 * 
 * @param errorCode
 *            the errorCode to set
 */
public void setStatusCode(int errorCode) {
    this.statusCode = errorCode;
}

/**
 * A String containing error message.
 * 
 * @return the errorMessage
 */
public String getMessage() {
    return message;
}

/**
 * A String containing error message.
 * 
 * @param errorMessage
 *            the errorMessage to set
 */
public void setMessage(String errorMessage) {
    this.message = errorMessage;
}

}

Hope this helps.

array_push() with key value pair

So what about having:

$data['cat']='wagon';

Python code to remove HTML tags from a string

Note that this isn't perfect, since if you had something like, say, <a title=">"> it would break. However, it's about the closest you'd get in non-library Python without a really complex function:

import re

TAG_RE = re.compile(r'<[^>]+>')

def remove_tags(text):
    return TAG_RE.sub('', text)

However, as lvc mentions xml.etree is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml version:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

How do I split a string so I can access item x?

A modern approach using STRING_SPLIT, requires SQL Server 2016 and above.

DECLARE @string varchar(100) = 'Hello John Smith'

SELECT
    ROW_NUMBER() OVER (ORDER BY value) AS RowNr,
    value
FROM string_split(@string, ' ')

Result:

RowNr   value
1       Hello
2       John
3       Smith

Now it is possible to get th nth element from the row number.

SQL Server : SUM() of multiple rows including where clauses

This will bring back totals per property and type

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
GROUP BY    PropertyID,
            TYPE

This will bring back only active values

SELECT  PropertyID,
        TYPE,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID,
            TYPE

and this will bring back totals for properties

SELECT  PropertyID,
        SUM(Amount)
FROM    yourTable
WHERE   EndDate IS NULL
GROUP BY    PropertyID

......

Install Node.js on Ubuntu

You can use nvm to install Node.js. It allows you work with different versions without conflicts.

Javascript Cookie with no expiration date

You can make a cookie never end by setting it to whatever date plus one more than the current year like this :

var d = new Date();    
document.cookie = "username=John Doe; expires=Thu, 18 Dec " + (d.getFullYear() + 1) + " 12:00:00 UTC";

How to get the integer value of day of week

DateTime currentDateTime = DateTime.Now;
int week = (int) currentDateTime.DayOfWeek;

MySQL: Set user variable from result of query

First lets take a look at how can we define a variable in mysql

To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

  1. Using keyword 'SET'.

Example :-

mysql >  SET @a = 1;
  1. Without using keyword 'SET' and using ':='.

Example:-

mysql > @a:=1;
  1. By using 'SELECT' statement.

Example:-

mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-

mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

1.

@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;

Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.

refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql

error TS2339: Property 'x' does not exist on type 'Y'

I was getting this error on Vue 3. It was because defineComponent must be imported like this:

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "HelloWorld",
    props: {
        msg: String,
    },
    created() {
        this.testF();
    },
    methods: {
        testF() {
            console.log("testF");
        },
    },
});
</script>

How to make ConstraintLayout work with percentage values?

With the ConstraintLayout v1.1.2, the dimension should be set to 0dp and then set the layout_constraintWidth_percent or layout_constraintHeight_percent attributes to a value between 0 and 1 like :

<!-- 50% width centered Button -->
<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintWidth_percent=".5" />

(You don't need to set app:layout_constraintWidth_default="percent" or app:layout_constraintHeight_default="percent" with ConstraintLayout 1.1.2 and following versions)

How to force deletion of a python object?

  1. Add an exit handler that closes all the bars.
  2. __del__() gets called when the number of references to an object hits 0 while the VM is still running. This may be caused by the GC.
  3. If __init__() raises an exception then the object is assumed to be incomplete and __del__() won't be invoked.

Get Time from Getdate()

You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:

declare @fromtime time = '09:30'
declare @totime time
SET @totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if @fromtime <= @totime 
begin print 'true' end
else begin print 'no' end

Set Session variable using javascript in PHP

If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.

An attempt was made to access a socket in a way forbidden by its access permissions

My situation and solution: I had created and enabled a HyperV ethernet adapter. For some reason, my main windows machine was using the "virtual" ethernet adapter instead of the 'hardware' adapter.

I disabled the virtual ethernet and my network settings to change the network public/privacy settings were revealed.

What's the name for hyphen-separated case?

I've always known it as kebab-case.

On a funny note, I've heard people call it a SCREAM-KEBAB when all the letters are capitalized.

Kebab Case Warning

I've always liked kebab-case as it seems the most readable when you need whitespace. However, some programs interpret the dash as a minus sign, and it can cause problems as what you think is a name turns into a subtraction operation.

first-second  // first minus second?
ten-2 // ten minus two?

Also, some frameworks parse dashes in kebab cased property. For example, GitHub Pages uses Jekyll, and Jekyll parses any dashes it finds in an md file. For example, a file named 2020-1-2-homepage.md on GitHub Pages gets put into a folder structured as \2020\1\2\homepage.html when the site is compiled.

Snake_case vs kebab-case

A safer alternative to kebab-case is snake_case, or SCREAMING_SNAKE_CASE, as underscores cause less confusion when compared to a minus sign.

How to set the From email address for mailx command?

The package nail provides an enhanced mailx like interface. It includes the -r option.

On Centos 5 installing the package mailx gives you a program called mail, which doesn't support the mailx options.

Replace a newline in TSQL

If you have an issue where you only want to remove trailing characters, you can try this:

WHILE EXISTS
(SELECT * FROM @ReportSet WHERE
    ASCII(right(addr_3,1)) = 10
    OR ASCII(right(addr_3,1)) = 13
    OR ASCII(right(addr_3,1)) = 32)
BEGIN
    UPDATE @ReportSet
    SET addr_3 = LEFT(addr_3,LEN(addr_3)-1)
    WHERE 
    ASCII(right(addr_3,1)) = 10
    OR ASCII(right(addr_3,1)) = 13
    OR ASCII(right(addr_3,1)) = 32
END

This solved a problem I had with addresses where a procedure created a field with a fixed number of lines, even if those lines were empty. To save space in my SSRS report, I cut them down.

How to make external HTTP requests with Node.js

I would combine node-http-proxy and express.

node-http-proxy will support a proxy inside your node.js web server via RoutingProxy (see the example called Proxy requests within another http server).

Inside your custom server logic you can do authentication using express. See the auth sample here for an example.

Combining those two examples should give you what you want.

Parsing arguments to a Java command line program

You could just do it manually.

NB: might be better to use a HashMap instead of an inner class for the opts.

/** convenient "-flag opt" combination */
private class Option {
     String flag, opt;
     public Option(String flag, String opt) { this.flag = flag; this.opt = opt; }
}

static public void main(String[] args) {
    List<String> argsList = new ArrayList<String>();  
    List<Option> optsList = new ArrayList<Option>();
    List<String> doubleOptsList = new ArrayList<String>();

    for (int i = 0; i < args.length; i++) {
        switch (args[i].charAt(0)) {
        case '-':
            if (args[i].length < 2)
                throw new IllegalArgumentException("Not a valid argument: "+args[i]);
            if (args[i].charAt(1) == '-') {
                if (args[i].length < 3)
                    throw new IllegalArgumentException("Not a valid argument: "+args[i]);
                // --opt
                doubleOptsList.add(args[i].substring(2, args[i].length));
            } else {
                if (args.length-1 == i)
                    throw new IllegalArgumentException("Expected arg after: "+args[i]);
                // -opt
                optsList.add(new Option(args[i], args[i+1]));
                i++;
            }
            break;
        default:
            // arg
            argsList.add(args[i]);
            break;
        }
    }
    // etc
}

Programmatically open new pages on Tabs

<a href="http://www.google.com/" target="_self">New Tab Example</a>

Works in IE7.

Regards,

Glenn

Getting first and last day of the current month

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Inserting an image with PHP and FPDF

You can't treat a PDF like an HTML document. Images can't "float" within a document and have things flow around them, or flow with surrounding text. FPDF allows you to embed html in a text block, but only because it parses the tags and replaces <i> and <b> and so on with Postscript equivalent commands. It's not smart enough to dynamically place an image.

In other words, you have to specify coordinates (and if you don't, the current location's coordinates will be used anyways).

SQL Server Insert Example

To insert a single row of data:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

Safest way to get last record ID from a table

SELECT IDENT_CURRENT('Table')

You can use one of these examples:

SELECT * FROM Table 
WHERE ID = (
    SELECT IDENT_CURRENT('Table'))

SELECT * FROM Table
WHERE ID = (
    SELECT MAX(ID) FROM Table)

SELECT TOP 1 * FROM Table
ORDER BY ID DESC

But the first one will be more efficient because no index scan is needed (if you have index on Id column).

The second one solution is equivalent to the third (both of them need to scan table to get max id).

Notepad++ Multi editing

Notepad++ only has column editing. This is not completely the same as multiple cursors.

Sublime Text has a marvelous implementation of this, might be worth checking out...
It's a relatively new editor (2011) that is gaining popularity quite fast: http://www.google.com/trends/explore#q=Notepad%2B%2B%2C%20Sublime%20Text&cmpt=q

Edit: Apparently somewhere around Notepad++ version 6.x multi-cursor editing got added, but there are still a few more advanced features for it in Sublime, like "select next occurrence".

Simplest way to read json from a URL in java

I am not sure if this is efficient, but this is one of the possible ways:

Read json from url use url.openStream() and read contents into a string.

construct a JSON object with this string (more at json.org)

JSONObject(java.lang.String source)
      Construct a JSONObject from a source JSON text string.

How do you dynamically allocate a matrix?

The other answer describing arrays of arrays are correct.
BUT if you are planning of doing a anything mathematical with the arrays - or need something special like sparse matrices you should look at one of the many maths libs like TNT before re-inventing too many wheels

How to generate JAXB classes from XSD?

  1. Download http://java.net/downloads/jaxb-workshop/IDE%20plugins/org.jvnet.jaxbw.zip
  2. Extract the zip file .
  3. Place the org.jvnet.jaxbw.eclipse_1.0.0 folder into .eclipse\plugins folder
  4. Restart the eclipse.
  5. Right click on XSD file and you can find contect menu. JAXB 2.0 -> Run XJC .

Renaming column names of a DataFrame in Spark Scala

def aliasAllColumns(t: DataFrame, p: String = "", s: String = ""): DataFrame =
{
  t.select( t.columns.map { c => t.col(c).as( p + c + s) } : _* )
}

In case is isn't obvious, this adds a prefix and a suffix to each of the current column names. This can be useful when you have two tables with one or more columns having the same name, and you wish to join them but still be able to disambiguate the columns in the resultant table. It sure would be nice if there were a similar way to do this in "normal" SQL.

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

StringBuilder vs String concatenation in toString() in Java

Performance wise String concatenation using '+' is costlier because it has to make a whole new copy of String since Strings are immutable in java. This plays particular role if concatenation is very frequent, eg: inside a loop. Following is what my IDEA suggests when I attempt to do such a thing:

enter image description here

General Rules:

  • Within a single string assignment, using String concatenation is fine.
  • If you're looping to build up a large block of character data, go for StringBuffer.
  • Using += on a String is always going to be less efficient than using a StringBuffer, so it should ring warning bells - but in certain cases the optimisation gained will be negligible compared with the readability issues, so use your common sense.

Here is a nice Jon Skeet blog around this topic.

Updating .class file in jar

Jar is an archive, you can replace a file in it by yourself in your favourite file manager (Total Commander for example).

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

You should change the

<a href="#">My Link</a>

to

<a href="javascript:;">My Link</a>

This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.

I have good reasons for this on the first answer to this question, like the return false; will not execute if the called function throws an error, or you may add the return false; to a doSomething() function and then forget to use return doSomething();

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Index all *except* one item in python

>>> l = range(1,10)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[:2] 
[1, 2]
>>> l[3:]
[4, 5, 6, 7, 8, 9]
>>> l[:2] + l[3:]
[1, 2, 4, 5, 6, 7, 8, 9]
>>> 

See also

Explain Python's slice notation

VBA, if a string contains a certain letter

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))

changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>

If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
    color:#069;
}
</style>

How to create a generic array in Java?

I made this code snippet to reflectively instantiate a class which is passed for a simple automated test utility.

Object attributeValue = null;
try {
    if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }
    else if(!clazz.isInterface()){
        attributeValue = BeanUtils.instantiateClass(clazz);
    }
} catch (Exception e) {
    logger.debug("Cannot instanciate \"{}\"", new Object[]{clazz});
}

Note this segment:

    if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }

for array initiating where Array.newInstance(class of array, size of array). Class can be both primitive (int.class) and object (Integer.class).

BeanUtils is part of Spring.

How to insert &nbsp; in XSLT

One can also do this :

<xsl:text disable-output-escaping="yes"><![CDATA[&nbsp;]]></xsl:text>

Disable submit button on form submit

I have been using blockUI to avoid browser incompatibilies on disabled or hidden buttons.

http://malsup.com/jquery/block/#element

Then my buttons have a class autobutton:

  $(".autobutton").click(
     function(event) {
        var nv = $(this).html();
        var nv2 = '<span class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></span> ' + nv;
        $(this).html(nv2);
        var form = $(this).parents('form:first');

        $(this).block({ message: null });
        form.submit();                
        });   

Then a form is like that:

<form>
....
<button class="autobutton">Submit</button>   
</form>

How to escape indicator characters (i.e. : or - ) in YAML

Quotes:

"url: http://www.example-site.com/"

To clarify, I meant “quote the value” and originally thought the entire thing was the value. If http://www.example-site.com/ is the value, just quote it like so:

url: "http://www.example-site.com/"

Understanding lambda in python and using it to pass multiple arguments

Why do you need to state both 'x' and 'y' before the ':'?

Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to

def f(x, y) : return x + y

just without binding it to a name like f.

Also how do you make it return multiple arguments?

The same way like with a function. Preferably, you return a tuple:

lambda x, y: (x+y, x-y)

Or a list, or a class, or whatever.

The thing with self.entry_1.bind should be answered by Demosthenex.

Styling a input type=number

the above code for chrome is working fine. i have tried like this in mozila but its not working. i found the solution for that

For mozila

input[type=number] { 
  -moz-appearance: textfield;
  appearance: textfield;
  margin: 0; 
}

Thanks Sanjib

Implementing a slider (SeekBar) in Android

How to implement a SeekBar

enter image description here

Add the SeekBar to your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:max="100"
        android:progress="50"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Notes

  • max is the highest value that the seek bar can go to. The default is 100. The minimum is 0. The xml min value is only available from API 26, but you can just programmatically convert the 0-100 range to whatever you need for earlier versions.
  • progress is the initial position of the slider dot (called a "thumb").
  • For a vertical SeekBar use android:rotation="270".

Listen for changes in code

public class MainActivity extends AppCompatActivity {

    TextView tvProgressLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // set a change listener on the SeekBar
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        int progress = seekBar.getProgress();
        tvProgressLabel = findViewById(R.id.textView);
        tvProgressLabel.setText("Progress: " + progress);
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvProgressLabel.setText("Progress: " + progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
}

Notes

  • If you don't need to do any updates while the user is moving the seekbar, then you can just update the UI in onStopTrackingTouch.

See also

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div> 

jsfiddle: http://jsfiddle.net/00qggsjj/2/

http://getbootstrap.com/components/#responsive-embed

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.