Programs & Examples On #Ccnet config

The ccnet-config tag may be used on questions related to the configuration of CruiseControl.NET (also known as CCNet). It is closely related to the cruisecontrol.net tag.

How to get the selected radio button value using js

If you are using jQuery, following code will work for you.

$('input[name=radioName]:checked').val();

Split string with PowerShell and do something with each token

Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

$test = '   One      for the money   '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}

This will come out as:

One
for
the
money

How can I read inputs as numbers?

While in your example, int(input(...)) does the trick in any case, python-future's builtins.input is worth consideration since that makes sure your code works for both Python 2 and 3 and disables Python2's default behaviour of input trying to be "clever" about the input data type (builtins.input basically just behaves like raw_input).

get UTC time in PHP

As previously answered here, since PHP 5.2.0 you can use the DateTime class and specify the UTC timezone with an instance of DateTimeZone.

The DateTime __construct() documentation suggests passing "now" as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.

$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));

echo $date_utc->format(\DateTime::RFC850); # Saturday, 18-Apr-15 03:23:46 UTC

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

How to send a Post body in the HttpClient request in Windows Phone 8?

This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

Cannot assign requested address using ServerSocket.socketBind

Java documentation for java.net.BindExcpetion,

Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned.

Cause:

The error is due to the second condition mentioned above. When you start a server(Tomcat,Jetty etc) it listens to a port and bind a socket to an address and port. In Windows and Linux the hostname is resolved to IP address from /etc/hosts This host to IP address mapping file can be found at C:\Windows\System32\Drivers\etc\hosts. If this mapping is changed and the host name cannot be resolved to the IP address you get the error message.

Solution:

Edit the hosts file and correct the mapping for hostname and IP using admin privileges.

eg:

#127.0.0.1 localhost
192.168.52.1 localhost

Read more: java.net.BindException : cannot assign requested address.

Simplest SOAP example

Some great examples (and a ready-made JavaScript SOAP client!) here: http://plugins.jquery.com/soap/

Check the readme, and beware the same-origin browser restriction.

I don't understand -Wl,-rpath -Wl,

You could also write

-Wl,-rpath=.

To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).

LaTeX package for syntax highlighting of code in various languages

I would use the minted package as mentioned from the developer Konrad Rudolph instead of the listing package. Here is why:

listing package

The listing package does not support colors by default. To use colors you would need to include the color package and define color-rules by yourself with the \lstset command as explained for matlab code here.

Also, the listing package doesn't work well with unicode, but you can fix those problems as explained here and here.

The following code

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[language=html]
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>Hello</body>
</html>
\end{lstlisting}
\end{document}

produces the following image:

enter image description here

minted package

The minted package supports colors, unicode and looks awesome. However, in order to use it, you need to have python 2.6 and pygments. In Ubuntu, you can check your python version in the terminal with

python --version

and you can install pygments with

sudo apt-get install python-pygments

Then, since minted makes calls to pygments, you need to compile it with -shell-escape like this

pdflatex -shell-escape yourfile.tex

If you use a latex editor like TexMaker or something, I would recommend to add a user-command, so that you can still compile it in the editor.

The following code

\documentclass{article}
\usepackage{minted}
\begin{document}

\begin{minted}{html}
    <!DOCTYPE html>
    <html>
       <head>
           <title>Hello</title>
       </head>

       <body>Hello</body>
    </html>
\end{minted}
\end{document}

produces the following image:

enter image description here

How to get a value inside an ArrayList java

main class

public class Test {
    public static void main (String [] args){
        Car thisCar= new Car ("Toyota", "$10000", "2003");  
        ArrayList<Car> car= new ArrayList<Car> ();
        car.add(thisCar); 
        processCar(car);
    } 

    public static void processCar(ArrayList<Car> car){
        for(Car c : car){
            System.out.println (c.getPrice());
        }
    }
}

car class

public class Car {
    private String vehicle;
    private String price;
    private String model;

    public Car(String vehicle, String price, String model){
        this.vehicle = vehicle;
        this.model = model;
        this.price = price;
    }

    public String getVehicle() {
        return vehicle;
    }

    public String getPrice() {
        return price;
    }

    public String getModel() {
        return model;
    }  
}

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource

$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection

if(mysqli_num_rows($result) > 0 ){....}

UPDATE

Base in your edit just change:

if(is_resource($query) && mysqli_num_rows($query) > 0 ){
        $query = mysqli_fetch_assoc($query);
        echo $email . " email exists " .  $query["email"] . "\n";

By

if(is_resource($result) && mysqli_num_rows($result) == 1 ){
        $row = mysqli_fetch_assoc($result);
         echo $email . " email exists " .  $row["email"] . "\n";

and you will be fine

UPDATE 2

A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter

SELECT IF( EXISTS (
                  SELECT *
                  FROM `Table`
                  WHERE `email` = @Email)
          , 1, 0) as `Exist`

and retrieve the value in php

Pseudocodigo:

 $query = Call MYSQL_SP($EMAIL);
 $result = mysqli_query($conn,$query);
 $row = mysqli_fetch_array($result)
 $exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';

Setting action for back button in navigation controller

Here is Swift 3 version of @oneway's answer for catching navigation bar back button event before it gets fired. As UINavigationBarDelegate cannot be used for UIViewController, you need to create a delegate that will be triggered when navigationBar shouldPop is called.

@objc public protocol BackButtonDelegate {
      @objc optional func navigationShouldPopOnBackButton() -> Bool 
}

extension UINavigationController: UINavigationBarDelegate  {

    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {

        if viewControllers.count < (navigationBar.items?.count)! {                
            return true
        }

        var shouldPop = true
        let vc = self.topViewController

        if vc.responds(to: #selector(vc.navigationShouldPopOnBackButton)) {
            shouldPop = vc.navigationShouldPopOnBackButton()
        }

        if shouldPop {
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        } else {
            for subView in navigationBar.subviews {
                if(0 < subView.alpha && subView.alpha < 1) {
                    UIView.animate(withDuration: 0.25, animations: {
                        subView.alpha = 1
                    })
                }
            }
        }

        return false
    }
}

And then, in your view controller add the delegate function:

class BaseVC: UIViewController, BackButtonDelegate {
    func navigationShouldPopOnBackButton() -> Bool {
        if ... {
            return true
        } else {
            return false
        }        
    }
}

I've realised that we often want to add an alert controller for users to decide whether they wanna go back. If so, you can always return false in navigationShouldPopOnBackButton() function and close your view controller by doing something like this:

func navigationShouldPopOnBackButton() -> Bool {
     let alert = UIAlertController(title: "Warning",
                                          message: "Do you want to quit?",
                                          preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { UIAlertAction in self.yes()}))
            alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { UIAlertAction in self.no()}))
            present(alert, animated: true, completion: nil)
      return false
}

func yes() {
     print("yes")
     DispatchQueue.main.async {
            _ = self.navigationController?.popViewController(animated: true)
        }
}

func no() {
    print("no")       
}

How to remove ASP.Net MVC Default HTTP Headers?

As shown on Removing standard server headers on Windows Azure Web Sites page, you can remove headers with the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
      </customHeaders>
    </httpProtocol>
    <security>
      <requestFiltering removeServerHeader="true"/>
    </security>
  </system.webServer>
  <system.web>
    <httpRuntime enableVersionHeader="false" />
  </system.web>
</configuration>

This removes the Server header, and the X- headers.

This worked locally in my tests in Visual Studio 2015.

Putting images with options in a dropdown list

This is exactly what you need. See it in action here 8FydL/445

Example's Code below:

_x000D_
_x000D_
     $(".dropdown img.flag").addClass("flagvisibility");_x000D_
        $(".dropdown dt a").click(function() {_x000D_
            $(".dropdown dd ul").toggle();_x000D_
        });_x000D_
                    _x000D_
        $(".dropdown dd ul li a").click(function() {_x000D_
            var text = $(this).html();_x000D_
            $(".dropdown dt a span").html(text);_x000D_
            $(".dropdown dd ul").hide();_x000D_
            $("#result").html("Selected value is: " + getSelectedValue("sample"));_x000D_
        });_x000D_
                    _x000D_
        function getSelectedValue(id) {_x000D_
            return $("#" + id).find("dt a span.value").html();_x000D_
        }_x000D_
    _x000D_
        $(document).bind('click', function(e) {_x000D_
            var $clicked = $(e.target);_x000D_
            if (! $clicked.parents().hasClass("dropdown"))_x000D_
                $(".dropdown dd ul").hide();_x000D_
        });_x000D_
    _x000D_
        $(".dropdown img.flag").toggleClass("flagvisibility");
_x000D_
    .desc { color:#6b6b6b;}_x000D_
    .desc a {color:#0092dd;}_x000D_
    _x000D_
    .dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; }_x000D_
    .dropdown dd { position:relative; }_x000D_
    .dropdown a, .dropdown a:visited { color:#816c5b; text-decoration:none; outline:none;}_x000D_
    .dropdown a:hover { color:#5d4617;}_x000D_
    .dropdown dt a:hover { color:#5d4617; border: 1px solid #d0c9af;}_x000D_
    .dropdown dt a {background:#e4dfcb url('http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/arrow.png') no-repeat scroll right center; display:block; padding-right:20px;_x000D_
                    border:1px solid #d4ca9a; width:150px;}_x000D_
    .dropdown dt a span {cursor:pointer; display:block; padding:5px;}_x000D_
    .dropdown dd ul { background:#e4dfcb none repeat scroll 0 0; border:1px solid #d4ca9a; color:#C5C0B0; display:none;_x000D_
                      left:0px; padding:5px 0px; position:absolute; top:2px; width:auto; min-width:170px; list-style:none;}_x000D_
    .dropdown span.value { display:none;}_x000D_
    .dropdown dd ul li a { padding:5px; display:block;}_x000D_
    .dropdown dd ul li a:hover { background-color:#d0c9af;}_x000D_
    _x000D_
    .dropdown img.flag { border:none; vertical-align:middle; margin-left:10px; }_x000D_
    .flagvisibility { display:none;}
_x000D_
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>_x000D_
        <dl id="sample" class="dropdown">_x000D_
            <dt><a href="#"><span>Please select the country</span></a></dt>_x000D_
            <dd>_x000D_
                <ul>_x000D_
                    <li><a href="#">Brazil<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/br.png" alt="" /><span class="value">BR</span></a></li>_x000D_
                    <li><a href="#">France<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/fr.png" alt="" /><span class="value">FR</span></a></li>_x000D_
                   _x000D_
                </ul>_x000D_
            </dd>_x000D_
        </dl>_x000D_
        <span id="result"></span>
_x000D_
_x000D_
_x000D_

How can I change the font-size of a select option?

check this fiddle,

i just edited the above fiddle, its working

http://jsfiddle.net/narensrinivasans/FpNxn/1/

.selectDefault, .selectDiv option
{
    font-family:arial;
    font-size:12px;
}

is there a function in lodash to replace matched item

[ES6] This code works for me.

let result = array.map(item => item.id === updatedItem.id ? updatedItem : item)

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

If it is a windows system, then it may be because you are using 32 bit winpcap library in a 64 bit pc or vie versa. If it is a 64 bit pc then copy the winpcap library and header packet.lib and wpcap.lib from winpcap/lib/x64 to the winpcap/lib directory and overwrite the existing

Android Layout Right Align

You can do all that by using just one RelativeLayout (which, btw, don't need android:orientation parameter). So, instead of having a LinearLayout, containing a bunch of stuff, you can do something like:

<RelativeLayout>
    <ImageButton
        android:layout_width="wrap_content"
        android:id="@+id/the_first_one"
        android:layout_alignParentLeft="true"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_toRightOf="@+id/the_first_one"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

As you noticed, there are some XML parameters missing. I was just showing the basic parameters you had to put. You can complete the rest.

CSS3 :unchecked pseudo-class

:unchecked is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.

In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked), it's safe to assume that there is no corresponding :unchecked pseudo. Browser support for :not() and :checked is identical, so that shouldn't be a problem.

This may seem inconsistent with the :enabled and :disabled states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.

(:indeterminate does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)

Split a string by another string in C#

string data = "THExxQUICKxxBROWNxxFOX";

return data.Replace("xx","|").Split('|');

Just choose the replace character carefully (choose one that isn't likely to be present in the string already)!

Custom designing EditText

android:background="#E1E1E1" 
// background add in layout
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff">
</EditText>

How to convert a full date to a short date in javascript?

You could do this pretty easily with my date-shortcode package:

const dateShortcode = require('date-shortcode')

var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'

How do I write the 'cd' command in a makefile?

What do you want it to do once it gets there? Each command is executed in a subshell, so the subshell changes directory, but the end result is that the next command is still in the current directory.

With GNU make, you can do something like:

BIN=/bin
foo:
    $(shell cd $(BIN); ls)

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

How can I pass arguments to anonymous functions in JavaScript?

Event handlers expect one parameter which is the event that was fired. You happen to be renaming that to 'myMessage' and therefore you are alerting the event object rather than your message.

A closure can allow you to reference the variable you have defined outside the function however if you are using Jquery you may want to look at its event specific API e.g.

http://docs.jquery.com/Events/bind#typedatafn

This has an option for passing in your own data.

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

Install Android App Bundle on device

Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug

An unsigned APK is generated for each case (for debug or testing)

NOTE: On Windows, replace gradle executable for gradlew.bat

How to move/rename a file using an Ansible task on a remote system

- name: Move the src file to dest
  command: mv /path/to/src /path/to/dest
  args:
    removes: /path/to/src
    creates: /path/to/dest

This runs the mv command only when /path/to/src exists and /path/to/dest does not, so it runs once per host, moves the file, then doesn't run again.

I use this method when I need to move a file or directory on several hundred hosts, many of which may be powered off at any given time. It's idempotent and safe to leave in a playbook.

How to convert a Date to a formatted string in VB.net?

myDate.ToString("yyyy-MM-dd HH:mm:ss")

the capital HH is for 24 hours format as you specified

How to resolve "Server Error in '/' Application" error?

I opened the Properties window for the website project in question and changed Windows Authentication to "Enabled" and that resolved my issue in VS 2019.

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

jQuery: more than one handler for same event

jQuery's .bind() fires in the order it was bound:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

Source: http://api.jquery.com/bind/

Because jQuery's other functions (ex. .click()) are shortcuts for .bind('click', handler), I would guess that they are also triggered in the order they are bound.

How can the error 'Client found response content type of 'text/html'.. be interpreted

The problem I had was related to SOAP version. The asmx service was configured to accept both versions, 1.1 and 1.2, so, I think that when you are consuming the service, the client or the server doesn't know what version resolve.

To fix that, is necessary add:

using (wsWebService yourService = new wsWebService())
{
    yourService.Url = "https://myUrlService.com/wsWebService.asmx?op=someOption";
    yourService.UseDefaultCredentials = true; // this line depends on your authentication type
    yourService.SoapVersion = SoapProtocolVersion.Soap11; // asign the version of SOAP
    var result = yourService.SomeMethod("Parameter");
}

Where wsWebService is the name of the class generated as a reference.

Multiple radio button groups in one form

Just do one thing, We need to set the name property for the same types. for eg.

Try below:

<form>
    <div id="group1">
        <input type="radio" value="val1" name="group1">
        <input type="radio" value="val2" name="group1">
    </div>
</form>

And also we can do it in angular1,angular 2 or in jquery also.

<div *ngFor="let option of question.options; index as j">
<input type="radio" name="option{{j}}" value="option{{j}}" (click)="checkAnswer(j+1)">{{option}}
</div>  

Can I use VARCHAR as the PRIMARY KEY?

It is ok for sure. With just few hundred of entries, it will be fast.

You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar

Disable scrolling in an iPhone web application?

If you are using jquery 1.7+, this works well:

$("donotscrollme").on("touchmove", false);

Imported a csv-dataset to R but the values becomes factors

This only worked right for me when including strip.white = TRUE in the read.csv command.

(I found the solution here.)

Generate random string/characters in JavaScript

A functional approach. This answer is only practical if the functional prerequisites can be leveraged in other parts of your app. The performance is probably junk, but it was super fun to write.

_x000D_
_x000D_
// functional prerequisites_x000D_
const U = f=> f (f)_x000D_
const Y = U (h=> f=> f (x=> h (h) (f) (x)))_x000D_
const comp = f=> g=> x=> f (g (x))_x000D_
const foldk = Y (h=> f=> y=> ([x, ...xs])=>_x000D_
  x === undefined ? y : f (y) (x) (y=> h (f) (y) (xs)))_x000D_
const fold = f=> foldk (y=> x=> k=> k (f (y) (x)))_x000D_
const map = f=> fold (y=> x=> [...y, f (x)]) ([])_x000D_
const char = x=> String.fromCharCode(x)_x000D_
const concat = x=> y=> y.concat(x)_x000D_
const concatMap = f=> comp (fold (concat) ([])) (map (f))_x000D_
const irand = x=> Math.floor(Math.random() * x)_x000D_
const sample = xs=> xs [irand (xs.length)]_x000D_
_x000D_
// range : make a range from x to y; [x...y]_x000D_
// Number -> Number -> [Number]_x000D_
const range = Y (f=> r=> x=> y=>_x000D_
  x > y ? r : f ([...r, x]) (x+1) (y)_x000D_
) ([])_x000D_
_x000D_
// srand : make random string from list or ascii code ranges_x000D_
// [(Range a)] -> Number -> [a]_x000D_
const srand = comp (Y (f=> z=> rs=> x=>_x000D_
  x === 0 ? z : f (z + sample (rs)) (rs) (x-1)_x000D_
) ([])) (concatMap (map (char)))_x000D_
_x000D_
// idGenerator : make an identifier of specified length_x000D_
// Number -> String_x000D_
const idGenerator = srand ([_x000D_
  range (48) (57),  // include 0-9_x000D_
  range (65) (90),  // include A-Z_x000D_
  range (97) (122)  // include a-z_x000D_
])_x000D_
_x000D_
console.log (idGenerator (6))  //=> TT688X_x000D_
console.log (idGenerator (10)) //=> SzaaUBlpI1_x000D_
console.log (idGenerator (20)) //=> eYAaWhsfvLDhIBID1xRh
_x000D_
_x000D_
_x000D_

In my opinion, it's hard to beat the clarity of idGenerator without adding magical, do-too-many-things functions.

A slight improvement could be

// ord : convert char to ascii code
// Char -> Number
const ord = x => x.charCodeAt(0)

// idGenerator : make an identifier of specified length
// Number -> String
const idGenerator = srand ([
  range (ord('0')) (ord('9')),
  range (ord('A')) (ord('Z')),
  range (ord('a')) (ord('z'))
])

Have fun with it. Let me know what you like/learn ^_^

http to https through .htaccess

I try all of above code but any code is not working for my website.then i try this code and This code is running perfect for my website. You can use the following Rule in htaccess :

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

//Redirect http to https
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

//Redirect non-www to www
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

</IfModule>

Change example.com with your domain name and sorry for my poor english.

How to round to 2 decimals with Python?

Just use the formatting with %.2f which gives you rounding down to 2 decimals.

def printC(answer):
    print "\nYour Celsius value is %.2f C.\n" % answer

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

Find and replace in file and overwrite file doesn't work, it empties the file

And the ed answer:

printf "%s\n" '1,$s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' w q | ed index.html

To reiterate what codaddict answered, the shell handles the redirection first, wiping out the "input.html" file, and then the shell invokes the "sed" command passing it a now empty file.

Tomcat 7: How to set initial heap size correctly?

Go to "Tomcat Directory"/bin directory

if Linux then create setenv.sh else if Windows then create setenv.bat

content of setenv.* file :

export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx8192m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"

after this restart tomcat with new params.

explanation and full information is here

http://crunchify.com/how-to-change-jvm-heap-setting-xms-xmx-of-tomcat/

How to get resources directory path programmatically

Just use com.google.common.io.Resources class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc

SQL Server : export query as a .txt file

The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.

.bat Example:

C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch

-q MUST be used in the presence of quotations within the query itself.

BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.

Check file extension in upload form in PHP

Using if( $ext !== 'gif') might not be efficient. What if you allow like 20 different extensions?

Try:

$allowed = array('gif', 'png', 'jpg');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
    echo 'error';
}

How to replace comma (,) with a dot (.) using java

Use this:

String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12

hope help you.

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

To: Killercam Thanks for your solutions. I tried the first solution for an hour, but didn't work for me.

I used scripts generate method to move data from SQL Server 2012 to SQL Server 2008 R2 as steps bellow:

In the 2012 SQL Management Studio

  1. Tasks -> Generate Scripts (in first wizard screen, click Next - may not show)
  2. Choose Script entire database and all database objects -> Next
  3. Click [Advanced] button 3.1 Change [Types of data to script] from "Schema only" to "Schema and data" 3.2 Change [Script for Server Version] "2012" to "2008"
  4. Finish next wizard steps for creating script file
  5. Use sqlcmd to import the exported script file to your SQL Server 2008 R2 5.1 Open windows command line 5.2 Type [sqlcmd -S -i Path to your file] (Ex: [sqlcmd -S localhost -i C:\mydatabase.sql])

It works for me.

Raise error in a Bash script

Basic error handling

If your test case runner returns a non-zero code for failed tests, you can simply write:

test_handler test_case_x; test_result=$?
if ((test_result != 0)); then
  printf '%s\n' "Test case x failed" >&2  # write error message to stderr
  exit 1                                  # or exit $test_result
fi

Or even shorter:

if ! test_handler test_case_x; then
  printf '%s\n' "Test case x failed" >&2
  exit 1
fi

Or the shortest:

test_handler test_case_x || { printf '%s\n' "Test case x failed" >&2; exit 1; }

To exit with test_handler's exit code:

test_handler test_case_x || { ec=$?; printf '%s\n' "Test case x failed" >&2; exit $ec; }

Advanced error handling

If you want to take a more comprehensive approach, you can have an error handler:

exit_if_error() {
  local exit_code=$1
  shift
  [[ $exit_code ]] &&               # do nothing if no error code passed
    ((exit_code != 0)) && {         # do nothing if error code is 0
      printf 'ERROR: %s\n' "$@" >&2 # we can use better logging here
      exit "$exit_code"             # we could also check to make sure
                                    # error code is numeric when passed
    }
}

then invoke it after running your test case:

run_test_case test_case_x
exit_if_error $? "Test case x failed"

or

run_test_case test_case_x || exit_if_error $? "Test case x failed"

The advantages of having an error handler like exit_if_error are:

  • we can standardize all the error handling logic such as logging, printing a stack trace, notification, doing cleanup etc., in one place
  • by making the error handler get the error code as an argument, we can spare the caller from the clutter of if blocks that test exit codes for errors
  • if we have a signal handler (using trap), we can invoke the error handler from there

Error handling and logging library

Here is a complete implementation of error handling and logging:

https://github.com/codeforester/base/blob/master/lib/stdlib.sh


Related posts

How do I remove version tracking from a project cloned from git?

I am working with a Linux environment. I removed all Git files and folders in a recursive way:

rm -rf .git

rm -rf .gitkeep

Java enum - why use toString instead of name

name() is a "built-in" method of enum. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.

Compare MOBILE_PHONE_NUMBER and Mobile phone number. Which version is more readable? I believe the second one. This is the difference: name() always returns MOBILE_PHONE_NUMBER, toString() may be overriden to return Mobile phone number.

Is Python faster and lighter than C++?

I think those stats show that Python is much slower and uses more memory for those benchmarks - are you sure you're reading them the right way up?

In my experience, which is mostly with writing network- and file-system-bound programs in Python, Python isn't significantly slower in any way that matters. For that kind of work, its benefits outweigh its costs.

Browse files and subfolders in Python

You can use os.walk() to recursively iterate through a directory and all its subdirectories:

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".html", ".htm")):
            # whatever

To build a list of these names, you can use a list comprehension:

htmlfiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(path)
             for name in files
             if name.endswith((".html", ".htm"))]

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

You should introduce a cast inside the click event handler

MouseEventArgs me = (MouseEventArgs) e;

Cloning an array in Javascript/Typescript

Cloning Arrays and Objects in javascript have a different syntax. Sooner or later everyone learns the difference the hard way and end up here.

In Typescript and ES6 you can use the spread operator for array and object:

const myClonedArray  = [...myArray];  // This is ok for [1,2,'test','bla']
                                      // But wont work for [{a:1}, {b:2}]. 
                                      // A bug will occur when you 
                                      // modify the clone and you expect the 
                                      // original not to be modified.
                                      // The solution is to do a deep copy
                                      // when you are cloning an array of objects.

To do a deep copy of an object you need an external library:

import {cloneDeep} from 'lodash';
const myClonedArray = cloneDeep(myArray);     // This works for [{a:1}, {b:2}]

The spread operator works on object as well but it will only do a shallow copy (first layer of children)

const myShallowClonedObject = {...myObject};   // Will do a shallow copy
                                               // and cause you an un expected bug.

To do a deep copy of an object you need an external library:

 import {cloneDeep} from 'lodash';
 const deeplyClonedObject = cloneDeep(myObject);   // This works for [{a:{b:2}}]

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

Extract a substring from a string in Ruby using a regular expression

Here's a slightly more flexible approach using the match method. With this, you can extract more than one string:

s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)

# Use 'captures' to get an array of the captures
matchdata.captures   # ["ants","pants"]

# Or use raw indices
matchdata[0]   # whole regex match: "<ants> <pants>"
matchdata[1]   # first capture: "ants"
matchdata[2]   # second capture: "pants"

MVC Razor Hidden input and passing values

You are doing it wrong since you try to map WebForms in the MVC application.

There are no server side controlls in MVC. Only the View and the Controller on the back-end. You send the data from server to the client by means of initialization of the View with your model.

This is happening on the HTTP GET request to your resource.

[HttpGet]
public ActionResult Home() 
{
  var model = new HomeModel { Greeatings = "Hi" };
  return View(model);
}

You send data from client to server by means of posting data to server. To make that happen, you create a form inside your view and [HttpPost] handler in your controller.

// View

@using (Html.BeginForm()) {
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Password)
}

// Controller

[HttpPost]
public ActionResult Home(LoginModel model) 
{
  // do auth.. and stuff
  return Redirect();
}

How to change package name of Android Project in Eclipse?

Just right click on the project name and select Android tools and click Rename Application Package name and rename it. It's only for Android projects.

Apache shutdown unexpectedly

I shut down the computer and restarted after installing the software and that fixed my problem.

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

Oracle: Import CSV file

An alternative solution is using an external table: http://www.orafaq.com/node/848

Use this when you have to do this import very often and very fast.

Extract only right most n letters from a string

I use the Min to prevent the negative situations and also handle null strings

// <summary>
    /// Returns a string containing a specified number of characters from the right side of a string.
    /// </summary>
    public static string Right(this string value, int length)
    {
        string result = value;
        if (value != null)
            result = value.Substring(0, Math.Min(value.Length, length));
        return result;
    }

Why use deflate instead of gzip for text files served by Apache?

The main reason is that deflate is faster to encode than gzip and on a busy server that might make a difference. With static pages it's a different question, since they can easily be pre-compressed once.

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

List all liquibase sql types

This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:

boolean
MySQLDatabase: BIT(1)
SQLiteDatabase: BOOLEAN
H2Database: BOOLEAN
PostgresDatabase: BOOLEAN
UnsupportedDatabase: BOOLEAN
DB2Database: SMALLINT
MSSQLDatabase: [bit]
OracleDatabase: NUMBER(1)
HsqlDatabase: BOOLEAN
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: BOOLEAN
SybaseDatabase: BIT
SybaseASADatabase: BIT

tinyint
MySQLDatabase: TINYINT
SQLiteDatabase: TINYINT
H2Database: TINYINT
PostgresDatabase: SMALLINT
UnsupportedDatabase: TINYINT
DB2Database: SMALLINT
MSSQLDatabase: [tinyint]
OracleDatabase: NUMBER(3)
HsqlDatabase: TINYINT
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: TINYINT
SybaseDatabase: TINYINT
SybaseASADatabase: TINYINT

int
MySQLDatabase: INT
SQLiteDatabase: INTEGER
H2Database: INT
PostgresDatabase: INT
UnsupportedDatabase: INT
DB2Database: INTEGER
MSSQLDatabase: [int]
OracleDatabase: INTEGER
HsqlDatabase: INT
FirebirdDatabase: INT
DerbyDatabase: INTEGER
InformixDatabase: INT
SybaseDatabase: INT
SybaseASADatabase: INT

mediumint
MySQLDatabase: MEDIUMINT
SQLiteDatabase: MEDIUMINT
H2Database: MEDIUMINT
PostgresDatabase: MEDIUMINT
UnsupportedDatabase: MEDIUMINT
DB2Database: MEDIUMINT
MSSQLDatabase: [int]
OracleDatabase: MEDIUMINT
HsqlDatabase: MEDIUMINT
FirebirdDatabase: MEDIUMINT
DerbyDatabase: MEDIUMINT
InformixDatabase: MEDIUMINT
SybaseDatabase: MEDIUMINT
SybaseASADatabase: MEDIUMINT

bigint
MySQLDatabase: BIGINT
SQLiteDatabase: BIGINT
H2Database: BIGINT
PostgresDatabase: BIGINT
UnsupportedDatabase: BIGINT
DB2Database: BIGINT
MSSQLDatabase: [bigint]
OracleDatabase: NUMBER(38, 0)
HsqlDatabase: BIGINT
FirebirdDatabase: BIGINT
DerbyDatabase: BIGINT
InformixDatabase: INT8
SybaseDatabase: BIGINT
SybaseASADatabase: BIGINT

float
MySQLDatabase: FLOAT
SQLiteDatabase: FLOAT
H2Database: FLOAT
PostgresDatabase: FLOAT
UnsupportedDatabase: FLOAT
DB2Database: FLOAT
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT
HsqlDatabase: FLOAT
FirebirdDatabase: FLOAT
DerbyDatabase: FLOAT
InformixDatabase: FLOAT
SybaseDatabase: FLOAT
SybaseASADatabase: FLOAT

double
MySQLDatabase: DOUBLE
SQLiteDatabase: DOUBLE
H2Database: DOUBLE
PostgresDatabase: DOUBLE PRECISION
UnsupportedDatabase: DOUBLE
DB2Database: DOUBLE
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT(24)
HsqlDatabase: DOUBLE
FirebirdDatabase: DOUBLE PRECISION
DerbyDatabase: DOUBLE
InformixDatabase: DOUBLE PRECISION
SybaseDatabase: DOUBLE
SybaseASADatabase: DOUBLE

decimal
MySQLDatabase: DECIMAL
SQLiteDatabase: DECIMAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL
MSSQLDatabase: [decimal](18, 0)
OracleDatabase: DECIMAL
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL
DerbyDatabase: DECIMAL
InformixDatabase: DECIMAL
SybaseDatabase: DECIMAL
SybaseASADatabase: DECIMAL

number
MySQLDatabase: numeric
SQLiteDatabase: NUMBER
H2Database: NUMBER
PostgresDatabase: numeric
UnsupportedDatabase: NUMBER
DB2Database: numeric
MSSQLDatabase: [numeric](18, 0)
OracleDatabase: NUMBER
HsqlDatabase: numeric
FirebirdDatabase: numeric
DerbyDatabase: numeric
InformixDatabase: numeric
SybaseDatabase: numeric
SybaseASADatabase: numeric

blob
MySQLDatabase: LONGBLOB
SQLiteDatabase: BLOB
H2Database: BLOB
PostgresDatabase: BYTEA
UnsupportedDatabase: BLOB
DB2Database: BLOB
MSSQLDatabase: [varbinary](MAX)
OracleDatabase: BLOB
HsqlDatabase: BLOB
FirebirdDatabase: BLOB
DerbyDatabase: BLOB
InformixDatabase: BLOB
SybaseDatabase: IMAGE
SybaseASADatabase: LONG BINARY

function
MySQLDatabase: FUNCTION
SQLiteDatabase: FUNCTION
H2Database: FUNCTION
PostgresDatabase: FUNCTION
UnsupportedDatabase: FUNCTION
DB2Database: FUNCTION
MSSQLDatabase: [function]
OracleDatabase: FUNCTION
HsqlDatabase: FUNCTION
FirebirdDatabase: FUNCTION
DerbyDatabase: FUNCTION
InformixDatabase: FUNCTION
SybaseDatabase: FUNCTION
SybaseASADatabase: FUNCTION

UNKNOWN
MySQLDatabase: UNKNOWN
SQLiteDatabase: UNKNOWN
H2Database: UNKNOWN
PostgresDatabase: UNKNOWN
UnsupportedDatabase: UNKNOWN
DB2Database: UNKNOWN
MSSQLDatabase: [UNKNOWN]
OracleDatabase: UNKNOWN
HsqlDatabase: UNKNOWN
FirebirdDatabase: UNKNOWN
DerbyDatabase: UNKNOWN
InformixDatabase: UNKNOWN
SybaseDatabase: UNKNOWN
SybaseASADatabase: UNKNOWN

datetime
MySQLDatabase: datetime
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: datetime
DB2Database: TIMESTAMP
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: datetime

time
MySQLDatabase: time
SQLiteDatabase: time
H2Database: time
PostgresDatabase: TIME WITHOUT TIME ZONE
UnsupportedDatabase: time
DB2Database: time
MSSQLDatabase: [time](7)
OracleDatabase: DATE
HsqlDatabase: time
FirebirdDatabase: time
DerbyDatabase: time
InformixDatabase: INTERVAL HOUR TO FRACTION(5)
SybaseDatabase: time
SybaseASADatabase: time

timestamp
MySQLDatabase: timestamp
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: timestamp
DB2Database: timestamp
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: timestamp

date
MySQLDatabase: date
SQLiteDatabase: date
H2Database: date
PostgresDatabase: date
UnsupportedDatabase: date
DB2Database: date
MSSQLDatabase: [date]
OracleDatabase: date
HsqlDatabase: date
FirebirdDatabase: date
DerbyDatabase: date
InformixDatabase: date
SybaseDatabase: date
SybaseASADatabase: date

char
MySQLDatabase: CHAR
SQLiteDatabase: CHAR
H2Database: CHAR
PostgresDatabase: CHAR
UnsupportedDatabase: CHAR
DB2Database: CHAR
MSSQLDatabase: [char](1)
OracleDatabase: CHAR
HsqlDatabase: CHAR
FirebirdDatabase: CHAR
DerbyDatabase: CHAR
InformixDatabase: CHAR
SybaseDatabase: CHAR
SybaseASADatabase: CHAR

varchar
MySQLDatabase: VARCHAR
SQLiteDatabase: VARCHAR
H2Database: VARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: VARCHAR
DB2Database: VARCHAR
MSSQLDatabase: [varchar](1)
OracleDatabase: VARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: VARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: VARCHAR
SybaseDatabase: VARCHAR
SybaseASADatabase: VARCHAR

nchar
MySQLDatabase: NCHAR
SQLiteDatabase: NCHAR
H2Database: NCHAR
PostgresDatabase: NCHAR
UnsupportedDatabase: NCHAR
DB2Database: NCHAR
MSSQLDatabase: [nchar](1)
OracleDatabase: NCHAR
HsqlDatabase: CHAR
FirebirdDatabase: NCHAR
DerbyDatabase: NCHAR
InformixDatabase: NCHAR
SybaseDatabase: NCHAR
SybaseASADatabase: NCHAR

nvarchar
MySQLDatabase: NVARCHAR
SQLiteDatabase: NVARCHAR
H2Database: NVARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: NVARCHAR
DB2Database: NVARCHAR
MSSQLDatabase: [nvarchar](1)
OracleDatabase: NVARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: NVARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: NVARCHAR
SybaseDatabase: NVARCHAR
SybaseASADatabase: NVARCHAR

clob
MySQLDatabase: LONGTEXT
SQLiteDatabase: TEXT
H2Database: CLOB
PostgresDatabase: TEXT
UnsupportedDatabase: CLOB
DB2Database: CLOB
MSSQLDatabase: [varchar](MAX)
OracleDatabase: CLOB
HsqlDatabase: CLOB
FirebirdDatabase: BLOB SUB_TYPE TEXT
DerbyDatabase: CLOB
InformixDatabase: CLOB
SybaseDatabase: TEXT
SybaseASADatabase: LONG VARCHAR

currency
MySQLDatabase: DECIMAL
SQLiteDatabase: REAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL(19, 4)
MSSQLDatabase: [money]
OracleDatabase: NUMBER(15, 2)
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL(18, 4)
DerbyDatabase: DECIMAL
InformixDatabase: MONEY
SybaseDatabase: MONEY
SybaseASADatabase: MONEY

uuid
MySQLDatabase: char(36)
SQLiteDatabase: TEXT
H2Database: UUID
PostgresDatabase: UUID
UnsupportedDatabase: char(36)
DB2Database: char(36)
MSSQLDatabase: [uniqueidentifier]
OracleDatabase: RAW(16)
HsqlDatabase: char(36)
FirebirdDatabase: char(36)
DerbyDatabase: char(36)
InformixDatabase: char(36)
SybaseDatabase: UNIQUEIDENTIFIER
SybaseASADatabase: UNIQUEIDENTIFIER

For reference, this is the groovy script I've used to generate this output:

@Grab('org.liquibase:liquibase-core:3.5.1')

import liquibase.database.core.*
import liquibase.datatype.core.*

def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType]
def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase]
datatypes.each {
    def datatype = it.newInstance()
    datatype.finishInitialization("")
    println datatype.name
    databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"}
    println ''
}

Using Mockito to mock classes with generic parameters

With JUnit5 I think the best way is to @ExtendWith(MockitoExtension.class) with @Mock in the method parameter or the field.

The following example demonstrates that with Hamcrest matchers.

package com.vogella.junit5;                                                                    
                                                                                               
import static org.hamcrest.MatcherAssert.assertThat;                                           
import static org.hamcrest.Matchers.hasItem;                                                   
import static org.mockito.Mockito.verify;                                                      
                                                                                               
import java.util.Arrays;                                                                       
import java.util.List;                                                                         
                                                                                               
import org.junit.jupiter.api.Test;                                                             
import org.junit.jupiter.api.extension.ExtendWith;                                             
import org.mockito.ArgumentCaptor;                                                             
import org.mockito.Captor;                                                                     
import org.mockito.Mock;                                                                       
import org.mockito.junit.jupiter.MockitoExtension;                                             
                                                                                               
@ExtendWith(MockitoExtension.class)                                                            
public class MockitoArgumentCaptureTest {                                                      
                                                                                               
                                                                                               
    @Captor                                                                                    
    private ArgumentCaptor<List<String>> captor;                                               
                                                                                               
    @Test                                                                                      
    public final void shouldContainCertainListItem(@Mock List<String> mockedList) {            
        var asList = Arrays.asList("someElement_test", "someElement");                         
        mockedList.addAll(asList);                                                             
                                                                                               
        verify(mockedList).addAll(captor.capture());                                           
        List<String> capturedArgument = captor.getValue();                                     
        assertThat(capturedArgument, hasItem("someElement"));                                  
    }                                                                                          
}                                                                                              
                                                                                              

See https://www.vogella.com/tutorials/Mockito/article.html for the required Maven/Gradle dependencies.

How can I copy a file on Unix using C?

Another variant of the copy function using normal POSIX calls and without any loop. Code inspired from the buffer copy variant of the answer of caf. Warning: Using mmap can easily fail on 32 bit systems, on 64 bit system the danger is less likely.

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/mman.h>

int cp(const char *to, const char *from)
{
  int fd_from = open(from, O_RDONLY);
  if(fd_from < 0)
    return -1;
  struct stat Stat;
  if(fstat(fd_from, &Stat)<0)
    goto out_error;

  void *mem = mmap(NULL, Stat.st_size, PROT_READ, MAP_SHARED, fd_from, 0);
  if(mem == MAP_FAILED)
    goto out_error;

  int fd_to = creat(to, 0666);
  if(fd_to < 0)
    goto out_error;

  ssize_t nwritten = write(fd_to, mem, Stat.st_size);
  if(nwritten < Stat.st_size)
    goto out_error;

  if(close(fd_to) < 0) {
    fd_to = -1;
    goto out_error;
  }
  close(fd_from);

  /* Success! */
  return 0;
}
out_error:;
  int saved_errno = errno;

  close(fd_from);
  if(fd_to >= 0)
    close(fd_to);

  errno = saved_errno;
  return -1;
}

EDIT: Corrected the file creation bug. See comment in http://stackoverflow.com/questions/2180079/how-can-i-copy-a-file-on-unix-using-c/2180157#2180157 answer.

deleted object would be re-saved by cascade (remove deleted object from associations)

I also ran into this error on a badly designed database, where there was a Person table with a one2many relationship with a Code table and an Organization table with a one2many relationship with the same Code table. The Code could apply to both an Organization and Or a Person depending on situation. Both the Person object and the Organization object were set to Cascade=All delete orphans.

What became of this overloaded use of the Code table however was that neither the Person nor the Organization could cascade delete because there was always another collection that had a reference to it. So no matter how it was deleted in the Java code out of whatever referencing collections or objects the delete would fail. The only way to get it to work was to delete it out of the collection I was trying to save then delete it out of the Code table directly then save the collection. That way there was no reference to it.

How to convert list data into json in java

public static List<Product> getCartList() {

    JSONObject responseDetailsJson = new JSONObject();
    JSONArray jsonArray = new JSONArray();

    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
        JSONObject formDetailsJson = new JSONObject();
        formDetailsJson.put("id", "1");
        formDetailsJson.put("name", "name1");
       jsonArray.add(formDetailsJson);
    }
    responseDetailsJson.put("forms", jsonArray);//Here you can see the data in json format

    return cartList;

}

you can get the data in the following form

{
    "forms": [
        { "id": "1", "name": "name1" },
        { "id": "2", "name": "name2" } 
    ]
}

Best practices for catching and re-throwing .NET exceptions

I would definitely use:

try
{
    //some code
}
catch
{
    //you should totally do something here, but feel free to rethrow
    //if you need to send the exception up the stack.
    throw;
}

That will preserve your stack.

Equivalent of explode() to work with strings in MySQL

if explode is used together with foreach to build a new string you can simulate explode by using a while loop like this:

CREATE FUNCTION explode_and_loop(sep VARCHAR(),inputstring VARCHAR()) RETURNS VARCHAR() 
BEGIN
    DECLARE part,returnstring VARCHAR();
    DECLARE cnt,partsCnt INT();
    SET returnstring = '';
    SET partsCnt = ((LENGTH(inputstring ) - LENGTH(REPLACE(inputstring,sep,''))) DIV LENGTH(sep);
    SET cnt = 0;
    WHILE cnt <= partsCnt DO
        SET cnt = cnt + 1;
        SET part = SUBSTRING_INDEX(SUBSTRING_INDEX(inputstring ,sep,cnt),sep,-1);
        -- DO SOMETHING with the part eg make html:
        SET returnstring = CONCAT(returnstring,'<li>',part,'</li>')
    END WHILE;
    RETURN returnstring;
END

this example will return a html list of the parts. (required variable legths have to be added)

What's the reason I can't create generic array types in Java?

Quote:

Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked. Here is how you could exploit the loophole:

class Box<T> {
    final T x;
    Box(T x) {
        this.x = x;
    }
}

class Loophole {
    public static void main(String[] args) {
        Box<String>[] bsa = new Box<String>[3];
        Object[] oa = bsa;
        oa[0] = new Box<Integer>(3); // error not caught by array store check
        String s = bsa[0].x; // BOOM!
    }
}

We had proposed to resolve this problem using statically safe arrays (aka Variance) bute that was rejected for Tiger.

-- gafter

(I believe it is Neal Gafter, but am not sure)

See it in context here: http://forums.sun.com/thread.jspa?threadID=457033&forumID=316

Use placeholders in yaml

I suppose https://get-ytt.io/ would be an acceptable solution to your problem

How can I get color-int from color resource?

Based on the new Android Support Library (and this update), now you should call:

ContextCompat.getColor(context, R.color.name.color);

According to the documentation:

public int getColor (int id)

This method was deprecated in API level 23. Use getColor(int, Theme) instead

It is the same solution for getResources().getColorStateList(id):

You have to change it like this:

ContextCompat.getColorStateList(getContext(),id);

EDIT 2019

Regarding ThemeOverlay use the context of the closest view:

val color = ContextCompat.getColor(
  closestView.context,
  R.color.name.color
)

So this way you get the right color based on your ThemeOverlay.

Specially needed when in same activity you use different themes, like dark/light theme. If you would like to understand more about Themes and Styles this talk is suggested: Developing Themes with Style

Nick Butcher - Droidcon Berlin - Developing Themes with Style

How to create JSON string in C#

If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:

http://www.asp.net/learn/ajax/tutorial-05-cs.aspx

It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.

Find where java class is loaded from

Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: -verbose:class

Segmentation fault on large array sizes

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

Format date and Subtract days using Moment.js

var date = new Date();

var targetDate = moment(date).subtract(1, 'day').toDate(); // date object

Now, you can format how you wanna see this date or you can compare this date with another etc.

toDate() function is the point.

What is the difference between pip and conda?

To answer the original question,
For installing packages, PIP and Conda are different ways to accomplish the same thing. Both are standard applications to install packages. The main difference is the source of the package files.

  • PIP/PyPI will have more "experimental" packages, or newer, less common, versions of packages
  • Conda will typically have more well established packages or versions

An important cautionary side note: If you use both sources (pip and conda) to install packages in the same environment, this may cause issues later.

  • Recreate the environment will be more difficult
  • Fix package incompatibilities becomes more complicated

Best practice is to select one application, PIP or Conda, to install packages, and use that application to install any packages you need. However, there are many exceptions or reasons to still use pip from within a conda environment, and vice versa. For example:

  • When there are packages you need that only exist on one, and the other doesn't have them.
  • You need a certain version that is only available in one environment

How to create a function in SQL Server

This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.

CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @URL

    SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))   
    SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))

    --Alternate:
    --SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)   

    RETURN @work
END

Android Fragment onAttach() deprecated

If you use the the framework fragments and the SDK version of the device is lower than 23, OnAttach(Context context) wouldn't be called.

I use support fragments instead, so deprecation is fixed and onAttach(Context context) always gets called.

How to change font-size of a tag using inline css?

Strange it doesn't change, as inline styles are most specific, if style sheet has !important declared, it wont over ride, try this and see

<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

I ran into this same issue. Someone had logged onto my computer and used their TFS credentials. I'm running VS2012, Windows 7, and the network admins have Credential Manager disabled.

Run this command from a command window with the same user your running visual studio as.

rundll32.exe keymgr.dll,KRShowKeyMgr

You'll see a popup with all your stored credentials. Remove the one for your TFS server.

Note: You will need to restart visual studio because it caches the tfs credentials.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

Should I use @EJB or @Inject

@Inject can inject any bean, while @EJB can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject everywhere.

Passing capturing lambda as function pointer

Not a direct answer, but a slight variation to use the "functor" template pattern to hide away the specifics of the lambda type and keeps the code nice and simple.

I was not sure how you wanted to use the decide class so I had to extend the class with a function that uses it. See full example here: https://godbolt.org/z/jtByqE

The basic form of your class might look like this:

template <typename Functor>
class Decide
{
public:
    Decide(Functor dec) : _dec{dec} {}
private:
    Functor _dec;
};

Where you pass the type of the function in as part of the class type used like:

auto decide_fc = [](int x){ return x > 3; };
Decide<decltype(decide_fc)> greaterThanThree{decide_fc};

Again, I was not sure why you are capturing x it made more sense (to me) to have a parameter that you pass in to the lambda) so you can use like:

int result = _dec(5); // or whatever value

See the link for a complete example

jQuery animate scroll

var page_url = windws.location.href;
var page_id = page_url.substring(page_url.lastIndexOf("#") + 1);
if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
} else if (page_id == "") {
    $("html, body").animate({
        scrollTop: $("#scroll-" + page_id).offset().top
    }, 2000)
}

});

Why does Python code use len() function instead of a length method?

There are some great answers here, and so before I give my own I'd like to highlight a few of the gems (no ruby pun intended) I've read here.

  • Python is not a pure OOP language -- it's a general purpose, multi-paradigm language that allows the programmer to use the paradigm they are most comfortable with and/or the paradigm that is best suited for their solution.
  • Python has first-class functions, so len is actually an object. Ruby, on the other hand, doesn't have first class functions. So the len function object has it's own methods that you can inspect by running dir(len).

If you don't like the way this works in your own code, it's trivial for you to re-implement the containers using your preferred method (see example below).

>>> class List(list):
...     def len(self):
...         return len(self)
...
>>> class Dict(dict):
...     def len(self):
...         return len(self)
...
>>> class Tuple(tuple):
...     def len(self):
...         return len(self)
...
>>> class Set(set):
...     def len(self):
...         return len(self)
...
>>> my_list = List([1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'])
>>> my_dict = Dict({'key': 'value', 'site': 'stackoverflow'})
>>> my_set = Set({1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'})
>>> my_tuple = Tuple((1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'))
>>> my_containers = Tuple((my_list, my_dict, my_set, my_tuple))
>>>
>>> for container in my_containers:
...     print container.len()
...
15
2
15
15

How to return rows from left table not found in right table?

If you are asking for T-SQL then lets look at fundamentals first. There are three types of joins here each with its own set of logical processing phases as:

  1. A cross join is simplest of all. It implements only one logical query processing phase, a Cartesian Product. This phase operates on the two tables provided as inputs to the join and produces a Cartesian product of the two. That is, each row from one input is matched with all rows from the other. So if you have m rows in one table and n rows in the other, you get m×n rows in the result.
  2. Then are Inner joins : They apply two logical query processing phases: A Cartesian product between the two input tables as in a cross join, and then it filters rows based on a predicate that you specify in ON clause (also known as Join condition).
  3. Next comes the third type of joins, Outer Joins:

    In an outer join, you mark a table as a preserved table by using the keywords LEFT OUTER JOIN, RIGHT OUTER JOIN, or FULL OUTER JOIN between the table names. The OUTER keyword is optional. The LEFT keyword means that the rows of the left table are preserved; the RIGHT keyword means that the rows in the right table are preserved; and the FULL keyword means that the rows in both the left and right tables are preserved.

    The third logical query processing phase of an outer join identifies the rows from the preserved table that did not find matches in the other table based on the ON predicate. This phase adds those rows to the result table produced by the first two phases of the join, and uses NULL marks as placeholders for the attributes from the nonpreserved side of the join in those outer rows.

Now if we look at the question: To return records from the left table which are not found in the right table use Left outer join and filter out the rows with NULL values for the attributes from the right side of the join.

How to open maximized window with Javascript?

If I use Firefox then screen.width and screen.height works fine but in IE and Chrome they don't work properly instead it opens with the minimum size.

And yes I tried giving too large numbers too like 10000 for both height and width but not exactly the maximized effect.

When to use CouchDB over MongoDB and vice versa

The answers above all over complicate the story.

  1. If you plan to have a mobile component, or need desktop users to work offline and then sync their work to a server you need CouchDB.
  2. If your code will run only on the server then go with MongoDB

That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

You can always just export the registry, change the setting, then export the registry again and do a diff.

How to handle button clicks using the XML onClick within Fragments

Best solution IMHO:

in fragment:

protected void addClick(int id) {
    try {
        getView().findViewById(id).setOnClickListener(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void onClick(View v) {
    if (v.getId()==R.id.myButton) {
        onMyButtonClick(v);
    }
}

then in Fragment's onViewStateRestored:

addClick(R.id.myButton);

command/usr/bin/codesign failed with exit code 1- code sign error

Today, 2020 year, I've solved this problem with Xcode 11.7, Xcode 12.0 and Xcode 12.1 following these steps:

Identifying the bad certificate:

  • From you Keychains select Login
  • From Category select Certificates
  • Find any Apple Certificate that has the blue +
  • Double click on the certificate.
  • Expand the Trust

If it's messed up then the "When using this certificate" is set to "Always Trust" along with the blue +

Fixing the bad certificate:

  • Just set it to "Use System Defaults" and close it.
  • You'll get a pop up. Type in your password to update settings.
  • Close KeyChain.
  • Go back to your project, clean and run.

Problem should have gone away. If that didn't work then go back to Keychain and just double check and see if there are any other Apple certificates that are set to Always Trust and repeat the process.

Declaring an enum within a class

Nowadays - using C++11 - you can use enum class for this:

enum class Color { RED, BLUE, WHITE };

AFAII this does exactly what you want.

An "and" operator for an "if" statement in Bash

Try this:

if [ $STATUS -ne 200 -a "$STRING" != "$VALUE" ]; then

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

I was able to fix this issue by changing the mail settings in the system.net portion of my web.config:

<mailSettings>
    <smtp deliveryMethod="Network">
        <network host="yourserver" defaultCredentials="true"/>
    </smtp>
</mailSettings>

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You need to add the following line:

using FootballLeagueSystem;

into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login.

At the moment the compiler can't find the Login class.

MySQL Multiple Where Clause

SELECT a.image_id 
FROM list a
INNER JOIN list b
   ON a.image_id = b.image_id
   AND b.style_id = 25
   AND b.style_value = 'big'
INNER JOIN list c
   ON a.image_id = c.image_id
   AND c.style_id = 27
   AND c.style_value = 'round'
WHERE a.style_id = 24 
   AND a.style_value = 'red'

Creating CSS Global Variables : Stylesheet theme management

You will either need LESS or SASS for the same..

But here is another alternative which I believe will work out in CSS3..

http://css3.bradshawenterprises.com/blog/css-variables/

Example :

 :root {
    -webkit-var-beautifulColor: rgba(255,40,100, 0.8);
    -moz-var-beautifulColor: rgba(255,40,100, 0.8);
    -ms-var-beautifulColor: rgba(255,40,100, 0.8);
    -o-var-beautifulColor: rgba(255,40,100, 0.8);
    var-beautifulColor: rgba(255,40,100, 0.8);
 }
  .example1 h1 {
    color: -webkit-var(beautifulColor);
    color: -moz-var(beautifulColor);
    color: -ms-var(beautifulColor);
    color: -o-var(beautifulColor);
    color: var(beautifulColor);
 }

C# "as" cast vs classic cast

With the "classic" method, if the cast fails, an InvalidCastException is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown.

Also, you can only use as with reference types, so if you are typecasting to a value type, you must still use the "classic" method.

Note:

The as method can only be used for types that can be assigned a null value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null value, they are valid to use with the as operator.

Batch file. Delete all files and folders in a directory

You could use robocopy to mirror an empty folder to the folder you are clearing.

robocopy "C:\temp\empty" "C:\temp\target" /E /MIR

It also works if you can't remove or recreate the actual folder.

It does require an existing empty directory.

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

How to make canvas responsive

try using max-width: 100%; on your canvas.

canvas {
  max-width: 100%;
}

Live-stream video from one android phone to another over WiFi

You can use IP Webcam, or perhaps use DLNA. For example Samsung devices come with an app called AllShare which can share and access DLNA enabled devices on the network. I think IP Webcam is your best bet, though. You should be able to open the stream it creates using MX Video player or something like that.

What are the differences between delegates and events?

In addition to the syntactic and operational properties, there's also a semantical difference.

Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.

Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.

Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).

CSS selector based on element text?

Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.

Difference between checkout and export in SVN

Any chance the build process is looking into the subdirectories and including something it shouldn't? BTW, you can do a legal checkout, then remove the .svn and all it contains. That should give you the same as an export. Try compiling that, before and after removing the metadata, as it were.

Service Temporarily Unavailable Magento?

You need to follow these steps:

  1. Go to magento root directory via cPanel/FTP
  2. In case of Magento1, you will find maintenance.flag and delete it
  3. In case of Magento2, delete var/maintenance.flag

jQuery: Adding two attributes via the .attr(); method

Something like this:

$(myObj).attr({"data-test-1": num1, "data-test-2": num2});

How to delete zero components in a vector in Matlab?

Data

a=[0  3   0   0   7   10   3   0   1   0   7   7   1   7   4]

Do

aa=nonzeros(a)'

Result

aa=[3   7   10   3   1   7   7   1   7   4]

apache mod_rewrite is not working or not enabled

To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.

<Directory /var/www>
   # Required if running apache > 2.4
   Require all granted

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:

<Directory /var/www>
   # Required if running apache 2.2
   Order allow,deny
   Allow from all

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

Note that an ErrorDocument 404 directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.

Char array in a struct - incompatible assignment?

You can use strcpy to populate it. You can also initialize it from another struct.

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

struct name {
    char first[20];
    char last[20];
};

int main() {
    struct name sara;
    struct name other;

    strcpy(sara.first,"Sara");
    strcpy(sara.last, "Black");

    other = sara;

    printf("struct: %s\t%s\n", sara.first, sara.last);
    printf("other struct: %s\t%s\n", other.first, other.last);

}

Sorting options elements alphabetically using jQuery

Accepted answer is not the best in all cases because sometimes you want to perserve classes of options and different arguments (for example data-foo).

My solution is:

var sel = $('#select_id');
var selected = sel.val(); // cache selected value, before reordering
var opts_list = sel.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
sel.html('').append(opts_list);
sel.val(selected); // set cached selected value

//For ie11 or those who get a blank options, replace html('') empty()

How does Java import work?

javac (or java during runtime) looks for the classes being imported in the classpath. If they are not there in the classpath then classnotfound exceptions are thrown.

classpath is just like the path variable in a shell, which is used by the shell to find a command or executable.

Entire directories or individual jar files can be put in the classpath. Also, yes a classpath can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.

More than one file was found with OS independent path 'META-INF/LICENSE'

You can add this in yourProject/app/build.gradle inside android{}

android {      
      packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module") 
      }          
}

Merging dictionaries in C#

Try the following

static Dictionary<TKey, TValue>
    Merge<TKey, TValue>(this IEnumerable<Dictionary<TKey, TValue>> enumerable)
{
    return enumerable.SelectMany(x => x).ToDictionary(x => x.Key, y => y.Value);
}

Can you use a trailing comma in a JSON object?

No. The "railroad diagrams" in https://json.org are an exact translation of the spec and make it clear a , always comes before a value, never directly before ]:

railroad diagram for array

or }:

railroad diagram for object

convert UIImage to NSData

Create the reference of image....

UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];

displaying image in image view... imagedisplay is reference of imageview:

imagedisplay.image = rainyImage;

convert it into NSData by passing UIImage reference and provide compression quality in float values:

NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);

Double Iteration in List Comprehension

ThomasH has already added a good answer, but I want to show what happens:

>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, 3, 4, 4]

I guess Python parses the list comprehension from left to right. This means, the first for loop that occurs will be executed first.

The second "problem" of this is that b gets "leaked" out of the list comprehension. After the first successful list comprehension b == [3, 4].

How to create a self-signed certificate with OpenSSL

This is the script I use on local boxes to set the SAN (subjectAltName) in self-signed certificates.

This script takes the domain name (example.com) and generates the SAN for *.example.com and example.com in the same certificate. The sections below are commented. Name the script (e.g. generate-ssl.sh) and give it executable permissions. The files will be written to the same directory as the script.

Chrome 58 an onward requires SAN to be set in self-signed certificates.

#!/usr/bin/env bash

# Set the TLD domain we want to use
BASE_DOMAIN="example.com"

# Days for the cert to live
DAYS=1095

# A blank passphrase
PASSPHRASE=""

# Generated configuration file
CONFIG_FILE="config.txt"

cat > $CONFIG_FILE <<-EOF
[req]
default_bits = 2048
prompt = no
default_md = sha256
x509_extensions = v3_req
distinguished_name = dn

[dn]
C = CA
ST = BC
L = Vancouver
O = Example Corp
OU = Testing Domain
emailAddress = webmaster@$BASE_DOMAIN
CN = $BASE_DOMAIN

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = *.$BASE_DOMAIN
DNS.2 = $BASE_DOMAIN
EOF

# The file name can be anything
FILE_NAME="$BASE_DOMAIN"

# Remove previous keys
echo "Removing existing certs like $FILE_NAME.*"
chmod 770 $FILE_NAME.*
rm $FILE_NAME.*

echo "Generating certs for $BASE_DOMAIN"

# Generate our Private Key, CSR and Certificate
# Use SHA-2 as SHA-1 is unsupported from Jan 1, 2017

openssl req -new -x509 -newkey rsa:2048 -sha256 -nodes -keyout "$FILE_NAME.key" -days $DAYS -out "$FILE_NAME.crt" -passin pass:$PASSPHRASE -config "$CONFIG_FILE"

# OPTIONAL - write an info to see the details of the generated crt
openssl x509 -noout -fingerprint -text < "$FILE_NAME.crt" > "$FILE_NAME.info"

# Protect the key
chmod 400 "$FILE_NAME.key"

This script also writes an information file, so you can inspect the new certificate and verify the SAN is set properly.

                ...
                28:dd:b8:1e:34:b5:b1:44:1a:60:6d:e3:3c:5a:c4:
                da:3d
            Exponent: 65537 (0x10001)
    X509v3 extensions:
        X509v3 Subject Alternative Name: 
            DNS:*.example.com, DNS:example.com
Signature Algorithm: sha256WithRSAEncryption
     3b:35:5a:d6:9e:92:4f:fc:f4:f4:87:78:cd:c7:8d:cd:8c:cc:
     ...

If you are using Apache, then you can reference the above certificate in your configuration file like so:

<VirtualHost _default_:443>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/htdocs

    SSLEngine on
    SSLCertificateFile path/to/your/example.com.crt
    SSLCertificateKeyFile path/to/your/example.com.key
</VirtualHost>

Remember to restart your Apache (or Nginx, or IIS) server for the new certificate to take effect.

Concatenate two NumPy arrays vertically

If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate to perform this operation, I would suggest the use of np.column_stack:

In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
       [2, 5],
       [3, 6]])

comparing two strings in ruby

From what you printed, it seems var2 is an array containing one string. Or actually, it appears to hold the result of running .inspect on an array containing one string. It would be helpful to show how you are initializing them.

irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]

Good font for code presentations?

I use DejaVu Sans Mono at Size 16.

UPDATE : I have switched to Envy Code R for coding and Anonymous Pro for terminal

How do I fetch only one branch of a remote Git repository?

git fetch <remote_name> <branch_name>

Worked for me.

What is ViewModel in MVC?

View model is same as your datamodel but you can add 2 or more data model classes in it. According to that you have to change your controller to take 2 models at once

Converting file size in bytes to human-readable string

For those who use Angular, there's a package called angular-pipes that has a pipe for this:

File

import { BytesPipe } from 'angular-pipes';

Usage

{{ 150 | bytes }} <!-- 150 B -->
{{ 1024 | bytes }} <!-- 1 KB -->
{{ 1048576 | bytes }} <!-- 1 MB -->
{{ 1024 | bytes: 0 : 'KB' }} <!-- 1 MB -->
{{ 1073741824 | bytes }} <!-- 1 GB -->
{{ 1099511627776 | bytes }} <!-- 1 TB -->
{{ 1073741824 | bytes : 0 : 'B' : 'MB' }} <!-- 1024 MB -->

Link to the docs.

Adjusting HttpWebRequest Connection Timeout in C#

Something I found later which helped, is the .ReadWriteTimeout property. This, in addition to the .Timeout property seemed to finally cut down on the time threads would spend trying to download from a problematic server. The default time for .ReadWriteTimeout is 5 minutes, which for my application was far too long.

So, it seems to me:

.Timeout = time spent trying to establish a connection (not including lookup time) .ReadWriteTimeout = time spent trying to read or write data after connection established

More info: HttpWebRequest.ReadWriteTimeout Property

Edit:

Per @KyleM's comment, the Timeout property is for the entire connection attempt, and reading up on it at MSDN shows:

Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned within the time-out period, the request throws a WebException with the Status property set to WebExceptionStatus.Timeout.

(Emphasis mine.)

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

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

Pytorch reshape tensor dimension

import torch
>>>a = torch.Tensor([1,2,3,4,5])
>>>a.size()
torch.Size([5])
#use view to reshape

>>>b = a.view(1,a.shape[0])
>>>b
tensor([[1., 2., 3., 4., 5.]])
>>>b.size()
torch.Size([1, 5])
>>>b.type()
'torch.FloatTensor'

iterating and filtering two lists using java 8

`List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())<1)
                        .collect(Collectors.toList());`
for this if i change to 
`List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())>0)
                        .collect(Collectors.toList());`
will it give me list1 matched with list2 right? 

Java code To convert byte to Hexadecimal

You can use the method from Bouncy Castle Provider library:

org.bouncycastle.util.encoders.Hex.toHexString(byteArray);

The Bouncy Castle Crypto package is a Java implementation of cryptographic algorithms. This jar contains JCE provider and lightweight API for the Bouncy Castle Cryptography APIs for JDK 1.5 to JDK 1.8.

Maven dependency:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.60</version>
</dependency>

or from Apache Commons Codec:

org.apache.commons.codec.binary.Hex.encodeHexString(byteArray);

The Apache Commons Codec package contains simple encoder and decoders for various formats such as Base64 and Hexadecimal. In addition to these widely used encoders and decoders, the codec package also maintains a collection of phonetic encoding utilities.

Maven dependency:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>

How to make Regular expression into non-greedy?

I believe it would be like this

takedata.match(/(\[.+\])/g);

the g at the end means global, so it doesn't stop at the first match.

SSIS Convert Between Unicode and Non-Unicode Error

  1. First, add a data conversion block into your data flow diagram.

  2. Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.

  3. Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.

  4. Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).

Twitter Bootstrap modal on mobile devices

EDIT: An unofficial Bootstrap Modal modification has been built to address responsive/mobile issues. This is perhaps the simplest and easiest way to remedy the problem.

There has since been a fix found in one of the issues you discussed earlier

in bootstrap-responsive.css

.modal { 
    position: fixed; 
    top: 3%; 
    right: 3%; 
    left: 3%; 
    width: auto; 
    margin: 0; 
}
.modal-body { 
    height: 60%; 
}

and in bootstrap.css

.modal-body { 
    max-height: 350px; 
    padding: 15px; 
    overflow-y: auto; 
    -webkit-overflow-scrolling: touch; 
 }

How to decompile a whole Jar file?

First of all, it's worth remembering that all Java archive files (.jar/.war/etc...) are all basically just fancy.zip files, with a few added manifests and metadata.

Second, to tackle this problem I personally use several tools which handle this problem on all levels:

  • Jad + Jadclipse while working in IDE for decompiling .class files
  • WinRAR, my favorite compression tool natively supports Java archives (again, see first paragraph).
  • Beyond Compare, my favorite diff tool, when configured correctly can do on-the-fly comparisons between any archive file, including jars. Well worth a try.

The advantage of all the aforementioned, is that I do not need to hold any other external tool which clutters my work environment. Everything I will ever need from one of those files can be handled inside my IDE or diffed with other files natively.

Makefiles with source files in different directories

If the sources are spread in many folders, and it makes sense to have individual Makefiles then as suggested before, recursive make is a good approach, but for smaller projects I find it easier to list all the source files in the Makefile with their relative path to the Makefile like this:

# common sources
COMMON_SRC := ./main.cpp \
              ../src1/somefile.cpp \
              ../src1/somefile2.cpp \
              ../src2/somefile3.cpp \

I can then set VPATH this way:

VPATH := ../src1:../src2

Then I build the objects:

COMMON_OBJS := $(patsubst %.cpp, $(ObjDir)/%$(ARCH)$(DEBUG).o, $(notdir $(COMMON_SRC)))

Now the rule is simple:

# the "common" object files
$(ObjDir)/%$(ARCH)$(DEBUG).o : %.cpp Makefile
    @echo creating $@ ...
    $(CXX) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $<

And building the output is even easier:

# This will make the cbsdk shared library
$(BinDir)/$(OUTPUTBIN): $(COMMON_OBJS)
    @echo building output ...
    $(CXX) -o $(BinDir)/$(OUTPUTBIN) $(COMMON_OBJS) $(LFLAGS)

One can even make the VPATH generation automated by:

VPATH := $(dir $(COMMON_SRC))

Or using the fact that sort removes duplicates (although it should not matter):

VPATH := $(sort  $(dir $(COMMON_SRC)))

C# compiler error: "not all code paths return a value"

class Program
{
    double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
    double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
    double[] result;


    public double[] CheckSorting()
    {
        for(int i = 1; i < a.Length; i++)
        {
            if (a[i] < a[i - 1])
                result = b;
            else
                result = a;
        }
        return result;
    }

    static void Main(string[] args)
    {
        Program checkSorting = new Program();
        checkSorting.CheckSorting();
        Console.ReadLine();
    }
}

This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

NUnit is probably the most supported by the 3rd party tools. It's also been around longer than the other three.

I personally don't care much about unit test frameworks, mocking libraries are IMHO much more important (and lock you in much more). Just pick one and stick with it.

Difference in months between two dates

Expanded Kirks struct with ToString(format) and Duration(long ms)

 public struct DateTimeSpan
{
    private readonly int years;
    private readonly int months;
    private readonly int days;
    private readonly int hours;
    private readonly int minutes;
    private readonly int seconds;
    private readonly int milliseconds;

    public DateTimeSpan(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
    {
        this.years = years;
        this.months = months;
        this.days = days;
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;
        this.milliseconds = milliseconds;
    }

    public int Years { get { return years; } }
    public int Months { get { return months; } }
    public int Days { get { return days; } }
    public int Hours { get { return hours; } }
    public int Minutes { get { return minutes; } }
    public int Seconds { get { return seconds; } }
    public int Milliseconds { get { return milliseconds; } }

    enum Phase { Years, Months, Days, Done }


    public string ToString(string format)
    {
        format = format.Replace("YYYY", Years.ToString());
        format = format.Replace("MM", Months.ToString());
        format = format.Replace("DD", Days.ToString());
        format = format.Replace("hh", Hours.ToString());
        format = format.Replace("mm", Minutes.ToString());
        format = format.Replace("ss", Seconds.ToString());
        format = format.Replace("ms", Milliseconds.ToString());
        return format;
    }


    public static DateTimeSpan Duration(long ms)
    {
        DateTime dt = new DateTime();
        return CompareDates(dt, dt.AddMilliseconds(ms));
    }


    public static DateTimeSpan CompareDates(DateTime date1, DateTime date2)
    {
        if (date2 < date1)
        {
            var sub = date1;
            date1 = date2;
            date2 = sub;
        }

        DateTime current = date1;
        int years = 0;
        int months = 0;
        int days = 0;

        Phase phase = Phase.Years;
        DateTimeSpan span = new DateTimeSpan();

        while (phase != Phase.Done)
        {
            switch (phase)
            {
                case Phase.Years:
                    if (current.AddYears(years + 1) > date2)
                    {
                        phase = Phase.Months;
                        current = current.AddYears(years);
                    }
                    else
                    {
                        years++;
                    }
                    break;
                case Phase.Months:
                    if (current.AddMonths(months + 1) > date2)
                    {
                        phase = Phase.Days;
                        current = current.AddMonths(months);
                    }
                    else
                    {
                        months++;
                    }
                    break;
                case Phase.Days:
                    if (current.AddDays(days + 1) > date2)
                    {
                        current = current.AddDays(days);
                        var timespan = date2 - current;
                        span = new DateTimeSpan(years, months, days, timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
                        phase = Phase.Done;
                    }
                    else
                    {
                        days++;
                    }
                    break;
            }
        }

        return span;
    }
}

How do I get the scroll position of a document?

document.getElementById("elementID").scrollHeight

$("elementID").scrollHeight

ValueError: could not convert string to float: id

My error was very simple: the text file containing the data had some space (so not visible) character on the last line.

As an output of grep, I had 45  instead of just 45

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

Python copy files to a new directory and rename if file name already exists

For me shutil.copy is the best:

import shutil

#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)

You can change the path of the files as you want.

int array to string

I like using StringBuilder with Aggregate(). The "trick" is that Append() returns the StringBuilder instance itself:

var sb = arr.Aggregate( new StringBuilder(), ( s, i ) => s.Append( i ) );
var result = sb.ToString();     

JavaScript alert box with timer

I finished my time alert with a unwanted effect.... Browsers add stuff to windows. My script is an aptated one and I will show after the following text.

I found a CSS script for popups, which doesn't have unwanted browser stuff. This was written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO. This script I will show after the following text.

This CSS script above looks professional and is alot more tidy. This button could be a clickable company logo image. By suppressing this button/image from running a function, this means you can run this function from inside javascript or call it with CSS, without it being run by clicking it.

This popup alert stays inside the window that popped it up. So if you are a multi-tasker you won't have trouble knowing what alert goes with what window.

The statements above are valid ones.... (Please allow). How these are achieved will be down to experimentation, as my knowledge of CSS is limited at the moment, but I learn fast.

CSS menus/DHTML use mouseover(valid statement).

I have a CSS menu script of my own which is adapted from 'Javascript for dummies' that pops up a menu alert. This works, but text size is limited. This hides under the top window banner. This could be set to be timed alert. This isn't great, but I will show this after the following text.

The Prakash script above I feel could be the answer if you can adapt it.

Scripts that follow:- My adapted timed window alert, Prakash's CSS popup script, my timed menu alert.

1.

<html>
      <head>
            <title></title>
            <script language="JavaScript">
        // Variables
            leftposition=screen.width-350
            strfiller0='<table border="1" cellspacing="0" width="98%"><tr><td><br>'+'Alert: '+'<br><hr width="98%"><br>'
            strfiller1='&nbsp;&nbsp;&nbsp;&nbsp; This alert is a timed one.'+'<br><br><br></td></tr></table>'
            temp=strfiller0+strfiller1
        // Javascript
            // This code belongs to Stephen Mayes Date: 25/07/2016 time:8:32 am


            function preview(){
                            preWindow= open("", "preWindow","status=no,toolbar=no,menubar=yes,width=350,height=180,left="+leftposition+",top=0");
                            preWindow.document.open();
                            preWindow.document.write(temp);
                            preWindow.document.close();
                    setTimeout(function(){preWindow.close()},4000); 
            }

             </script>
      </head>
<body>
    <input type="button" value=" Open " onclick="preview()">
</body>
</html>

2.

<style>
body {
  font-family: Arial, sans-serif;
  background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
  background-size: cover;
  height: 100vh;
}

h1 {
  text-align: center;
  font-family: Tahoma, Arial, sans-serif;
  color: #06D85F;
  margin: 80px 0;
}

.box {
  width: 40%;
  margin: 0 auto;
  background: rgba(255,255,255,0.2);
  padding: 35px;
  border: 2px solid #fff;
  border-radius: 20px/50px;
  background-clip: padding-box;
  text-align: center;
}

.button {
  font-size: 1em;
  padding: 10px;
  color: #fff;
  border: 2px solid #06D85F;
  border-radius: 20px/50px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.button:hover {
  background: #06D85F;
}

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}

.popup {
  margin: 70px auto;
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  width: 30%;
  position: relative;
  transition: all 5s ease-in-out;
}

.popup h2 {
  margin-top: 0;
  color: #333;
  font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  top: 20px;
  right: 30px;
  transition: all 200ms;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}
.popup .close:hover {
  color: #06D85F;
}
.popup .content {
  max-height: 30%;
  overflow: auto;
}

@media screen and (max-width: 700px){
  .box{
    width: 70%;
  }
  .popup{
    width: 70%;
  }
}
</style>
<script>
    // written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO 
</script>
<body>
<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
    <a class="button" href="#popup1">Let me Pop up</a>
</div>

<div id="popup1" class="overlay">
    <div class="popup">
        <h2>Here i am</h2>
        <a class="close" href="#">&times;</a>
        <div class="content">
            Thank to pop me out of that button, but now i'm done so you can close this window.
        </div>
    </div>
</div>
</body>

3.

<HTML>
<HEAD>
<TITLE>Using DHTML to Create Sliding Menus (From JavaScript For Dummies, 4th Edition)</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from older browsers

function displayMenu(currentPosition,nextPosition) {

    // Get the menu object located at the currentPosition on the screen
    var whichMenu = document.getElementById(currentPosition).style;

    if (displayMenu.arguments.length == 1) {
        // Only one argument was sent in, so we need to
        // figure out the value for "nextPosition"

        if (parseInt(whichMenu.top) == -5) {
            // Only two values are possible: one for mouseover
            // (-5) and one for mouseout (-90). So we want
            // to toggle from the existing position to the
            // other position: i.e., if the position is -5,
            // set nextPosition to -90...
            nextPosition = -90;
        }
        else {
            // Otherwise, set nextPosition to -5
            nextPosition = -5;
        }
    }

    // Redisplay the menu using the value of "nextPosition"
    whichMenu.top = nextPosition + "px";
}

// End hiding-->
</SCRIPT>

<STYLE TYPE="text/css">
<!--

.menu {position:absolute; font:10px arial, helvetica, sans-serif; background-color:#ffffcc; layer-background-color:#ffffcc; top:-90px}
#resMenu {right:10px; width:-130px}
A {text-decoration:none; color:#000000}
A:hover {background-color:pink; color:blue}

 -->

</STYLE>

</HEAD>

<BODY BGCOLOR="white">

<div id="resMenu" class="menu" onmouseover="displayMenu('resMenu',-5)" onmouseout="displayMenu('resMenu',-90)"><br />
<a href="#"> Alert:</a><br>
<a href="#"> </a><br>
<a href="#"> You pushed that button again... Didn't yeah? </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
<a href="#"> </a><br>
</div>
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
<input type="button" value="Wake that alert up" onclick="displayMenu('resMenu',-5)">
</BODY>
</HTML>

Google Maps setCenter()

in your code, at line

map.setCenter(new GLatLng(lat, lon), 5);

the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?

I suggest you should change it to,

map.setCenter(new GLatLng(lat, lon));

Ansible: filter a list by its attributes

I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:

- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"

would return:

ok: [localhost] => {
    "msg": [
        "172.16.1.100"
    ]
}

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

Adding a css class to select using @Html.DropDownList()

Try below code:

@Html.DropDownList("ProductTypeID",null,"",new { @class = "form-control"})

Check if value exists in Postgres array

Hi that one works fine for me, maybe useful for someone

select * from your_table where array_column ::text ilike ANY (ARRAY['%text_to_search%'::text]);

Permanently hide Navigation Bar in an activity

AFAIK, this is not possible without root access. It would be a security issue to be able to have an app that cannot be exited with system buttons.

Edit, see here: Hide System Bar in Tablets

React-Router open Link in new tab

Starting with react_router 1.0, the props will be passed onto the anchor tag. You can directly use target="_blank". Discussed here: https://github.com/ReactTraining/react-router/issues/2188

CKEditor automatically strips classes from div

if you're using ckeditor 4.x you can try

config.allowedContent = true;

if you're using ckeditor 3.x you may be having this issue.

try putting the following line in config.js

config.ignoreEmptyParagraph = false;

How do HashTables deal with collisions?

It will use the equals method to see if the key is present even and especially if there are more than one element in the same bucket.

JQuery Calculate Day Difference in 2 date textboxes

   **This is a simple way of getting the DAYS between two dates** 
    var d1 = moment($("#StartDate").data("DateTimePicker").date());
    var d2 = moment($("#EndDate").data("DateTimePicker").date());

    var diffInDays = d2.diff(d1, 'days');

    if (diffInDays > 0)
    {
        $("#Total").val(diffInDays);
    }
    else
    {
        $("#Total").val(0);
    }

How to store values from foreach loop into an array?

Declare the $items array outside the loop and use $items[] to add items to the array:

$items = array();
foreach($group_membership as $username) {
 $items[] = $username;
}

print_r($items);

How to change the project in GCP using CLI commands

You can try: gcloud config set project [project_id]

Datetime in where clause

WHERE datetime_column >= '20081220 00:00:00.000'
  AND datetime_column < '20081221 00:00:00.000'

how do you increase the height of an html textbox

Increasing the font size on a text box will usually expand its size automatically.

<input type="text" style="font-size:16pt;">

If you want to set a height that is not proportional to the font size, I would recommend using something like the following. This prevents browsers like IE from rendering the text inside at the top rather than vertically centered.

.form-text{
    padding:15px 0;
}

How to calculate md5 hash of a file using javascript

Apart from the impossibility to get file system access in JS, I would not put any trust at all in a client-generated checksum. So generating the checksum on the server is mandatory in any case. – Tomalak Apr 20 '09 at 14:05

Which is useless in most cases. You want the MD5 computed at client side, so that you can compare it with the code recomputed at server side and conclude the upload went wrong if they differ. I have needed to do that in applications working with large files of scientific data, where receiving uncorrupted files were key. My cases was simple, cause users had the MD5 already computed from their data analysis tools, so I just needed to ask it to them with a text field.

CSS Box Shadow Bottom Only

Try this

-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);

You can see it in http://jsfiddle.net/wJ7qp/

Using Javascript in CSS

I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:

width:expression(document.body.clientWidth > 800? "800px": "auto" );

This code makes IE emulate the max-width property it doesn't support.

All things considered, however, avoid using these. They are a bad, bad thing.

Is there an XSLT name-of element?

Nobody did point the subtle difference in the semantics of the functions name() and local-name().

  • name(someNode) returns the full name of the node, and that includes the prefix and colon in case the node is an element or an attribute.
  • local-name(someNode) returns only the local name of the node, and that doesn't include the prefix and colon in case the node is an element or an attribute.

Therefore, in situations where a name may belong to two different namespaces, one must use the name() function in order for these names to be still distinguished.

And, BTW, it is possible to specify both functions without any argument:

name() is an abbreviation for name(.)

local-name() is an abbreviation for local-name(.)

Finally, do remember that not only elements and attributes have names, these two functions can also be used on PIs and on these they are identical).

Error 1022 - Can't write; duplicate key in table

I just spent the last 4 hours with the same issue. What I did was to simply make sure the constraints had unique names.

You can rename the constraints. I appended a number to mine so I could easily trace the number of occurrences.

Example

If a constraint in a table is named boy with a foreign key X The next constraint with the foreign key X can be called boy1

I'm sure you'd figure out better names than I did.

Android : How to set onClick event for Button in List item of ListView

In your custom adapter inside getView method :

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do things Here 
    }
});

Populate a Drop down box from a mySQL table in PHP

No need to do this:

while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;
}

You can directly do this:

while ($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row['value'] . "'>" . $row['value'] . "</option>";
    }

How do I request a file but not save it with Wget?

Curl does that by default without any parameters or flags, I would use it for your purposes:

curl $url > /dev/null 2>&1

Curl is more about streams and wget is more about copying sites based on this comparison.

How to Empty Caches and Clean All Targets Xcode 4 and later

Here's my shell script solution, which deletes derived data and cleans a project's cached assets, for Xcode 4, 5 and 6.

Sometimes, simply calling rm -rf on the Derived Data directory leaves a lingering file or two, but my script loops until all files are deleted.

Show percent % instead of counts in charts of categorical variables

Since this was answered there have been some meaningful changes to the ggplot syntax. Summing up the discussion in the comments above:

 require(ggplot2)
 require(scales)

 p <- ggplot(mydataf, aes(x = foo)) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        ## version 3.0.0
        scale_y_continuous(labels=percent)

Here's a reproducible example using mtcars:

 ggplot(mtcars, aes(x = factor(hp))) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        scale_y_continuous(labels = percent) ## version 3.0.0

enter image description here

This question is currently the #1 hit on google for 'ggplot count vs percentage histogram' so hopefully this helps distill all the information currently housed in comments on the accepted answer.

Remark: If hp is not set as a factor, ggplot returns:

enter image description here

How to stop java process gracefully?

Similar Question Here

Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.

The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.

What is the best method to merge two PHP objects?

This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!

Once an Object is in array format you can use array_merge and convert back to Object if you need to.

abstract class Util {
    public static function object_to_array($d) {
        if (is_object($d))
            $d = get_object_vars($d);

        return is_array($d) ? array_map(__METHOD__, $d) : $d;
    }

    public static function array_to_object($d) {
        return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
    }
}

Procedural way

function object_to_array($d) {
    if (is_object($d))
        $d = get_object_vars($d);

    return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}

function array_to_object($d) {
    return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}

All credit goes to: Jason Oakley

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

Checking if a variable is not nil and not zero in ruby

You can convert your empty row to integer value and check zero?.

"".to_i.zero? => true
nil.to_i.zero? => true

How to access the services from RESTful API in my angularjs page?

The $http service can be used for general purpose AJAX. If you have a proper RESTful API, you should take a look at ngResource.

You might also take a look at Restangular, which is a third party library to handle REST APIs easy.

CSS background image alt attribute

It''s not clear to me what you want.

If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:

IMG:before { content: attr(alt) }

If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.

Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

I was then able to use the JObject.Parse(jsonResult) and everything worked.

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

how to load CSS file into jsp

I had the same problem too. Then i realized that in the MainPageServlet the urlPatterns parameter in @WebServlet annotation contained "/", because i wanted to forward to the MainPage if the user entered the section www.site.com/ . When i tried to open the css file from the browser, the url was www.site.com/css/desktop.css, but the page content was THE PAGE MainPage.jsp. So, i removed the "/" urlPattern and now i can use CSS files in my jsp file using one of the most common solutions (${pageContext.request.contextPath}/css/desktop.css). Make sure your servlet doesn't contain the "/" urlPattern. I hope this worked for u too, - Axel Montini

Command line for looking at specific port

For Windows 8 User : Open Command Prompt, type netstat -an | find "your port number" , enter .

If reply comes like LISTENING then the port is in use, else it is free .

HTML / CSS How to add image icon to input type="button"?

sshow's answer did it for me, too:

navigation.css:

[...]

.buttonConfiguration {
    width: 40px;
    background-color: red; /* transparent; */
    border: none;
    color: white;
    padding: 5px 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-family: corbel;
    font-size: 12px;
    font-weight: normal;
    margin: 1px 1px;
    cursor: pointer;

    background-image: url('../images/icons5/gear_16.png');
    background-position: center; /* 0px 0px; */
    background-repeat: no-repeat;
    vertical-align: middle;
}

[...]

frameMenu.php:

[... PHP, Javascript and HTML code ...]

<!-- <li><a target="frameBody" href="admin/conf/confFunctions.php"><input type="button" class="buttonSuperAdmin" value="<?= $oLanguage->getExpression('confSettings', 'title', 'C e n t e r s') ?>"></a> -->
<li><a target="frameBody" href="admin/conf/confFunctions.php"><input type="button" class="buttonConfiguration" value=""></a>
<ul>
<li><a target="frameBody" href="admin/conf/getglobals.php "><input type="button" class="buttonSuperAdminSub" value="<?= $oLanguage->getExpression('centerSettings', 'confAdmin1', 'GetGlobals') ?>"></a></li>
<li><a target="frameBody" href="admin/conf/getcwd.php "><input type="button" class="buttonSuperAdminSub" value="<?= $oLanguage->getExpression('confSettings', 'centerAdmin2', 'GetCWD') ?>"></a></li>
</ul>
</li>

[...]

I have tested this successfully under the lastest versions of Firefox and Chrome (as of February 9th, 2019).

SQL Server NOLOCK and joins

I won't address the READ UNCOMMITTED argument, just your original question.

Yes, you need WITH(NOLOCK) on each table of the join. No, your queries are not the same.

Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK) hint on it.

exception in thread 'main' java.lang.NoClassDefFoundError:

Run it like this:

java -jar HelloWorld.jar

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

groupByKey:

Syntax:

sparkContext.textFile("hdfs://")
                    .flatMap(line => line.split(" ") )
                    .map(word => (word,1))
                    .groupByKey()
                    .map((x,y) => (x,sum(y)))

groupByKey can cause out of disk problems as data is sent over the network and collected on the reduce workers.

reduceByKey:

Syntax:

sparkContext.textFile("hdfs://")
                    .flatMap(line => line.split(" "))
                    .map(word => (word,1))
                    .reduceByKey((x,y)=> (x+y))

Data are combined at each partition, only one output for one key at each partition to send over the network. reduceByKey required combining all your values into another value with the exact same type.

aggregateByKey:

same as reduceByKey, which takes an initial value.

3 parameters as input i. initial value ii. Combiner logic iii. sequence op logic

Example:

val keysWithValuesList = Array("foo=A", "foo=A", "foo=A", "foo=A", "foo=B", "bar=C", "bar=D", "bar=D")
    val data = sc.parallelize(keysWithValuesList)
    //Create key value pairs
    val kv = data.map(_.split("=")).map(v => (v(0), v(1))).cache()
    val initialCount = 0;
    val addToCounts = (n: Int, v: String) => n + 1
    val sumPartitionCounts = (p1: Int, p2: Int) => p1 + p2
    val countByKey = kv.aggregateByKey(initialCount)(addToCounts, sumPartitionCounts)

ouput: Aggregate By Key sum Results bar -> 3 foo -> 5

combineByKey:

3 parameters as input

  1. Initial value: unlike aggregateByKey, need not pass constant always, we can pass a function that will return a new value.
  2. merging function
  3. combine function

Example:

val result = rdd.combineByKey(
                        (v) => (v,1),
                        ( (acc:(Int,Int),v) => acc._1 +v , acc._2 +1 ) ,
                        ( acc1:(Int,Int),acc2:(Int,Int) => (acc1._1+acc2._1) , (acc1._2+acc2._2)) 
                        ).map( { case (k,v) => (k,v._1/v._2.toDouble) })
        result.collect.foreach(println)

reduceByKey,aggregateByKey,combineByKey preferred over groupByKey

Reference: Avoid groupByKey

The identity used to sign the executable is no longer valid

I had this problem and tried everything here but it didn't help. Then I noticed that the cord I was using was a little frayed, so I tried a new cord and it worked.

Read .doc file with python

I agree with Shivam's answer except for textract doesn't exist for windows. And, for some reason antiword also fails to read the '.doc' files and gives an error:

'filename.doc' is not a word document. # This happens when the file wasn't generated via MS Office. Eg: Web-pages may be stored in .doc format offline.

So, I've got the following workaround to extract the text:

from bs4 import BeautifulSoup as bs
soup = bs(open(filename).read())
[s.extract() for s in soup(['style', 'script'])]
tmpText = soup.get_text()
text = "".join("".join(tmpText.split('\t')).split('\n')).encode('utf-8').strip()
print text

This script will work with most kinds of files. Have fun!

Showing an image from an array of images - Javascript

Just as Diodeus said, you're comparing an Image to a HTMLDomObject. Instead compare their .src attribute:

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'images/img/Splash_image1.jpg';

imgArray[1] = new Image();
imgArray[1].src = 'images/img/Splash_image2.jpg';

/* ... more images ... */

imgArray[5] = new Image();
imgArray[5].src = 'images/img/Splash_image6.jpg';

/*------------------------------------*/

function nextImage(element)
{
    var img = document.getElementById(element);

    for(var i = 0; i < imgArray.length;i++)
    {
        if(imgArray[i].src == img.src) // << check this
        {
            if(i === imgArray.length){
                document.getElementById(element).src = imgArray[0].src;
                break;
            }
            document.getElementById(element).src = imgArray[i+1].src;
            break;
        }
    }
}

Multidimensional arrays in Swift

var array: Int[][] = [[1,2,3],[4,5,6],[7,8,9]]

for first in array {
    for second in first {
        println("value \(second)")
    }
}

To achieve what you're looking for you need to initialize the array to the correct template and then loop to add the row and column arrays:

var NumColumns = 27
var NumRows = 52
var array = Array<Array<Int>>()
var value = 1

for column in 0..NumColumns {
    var columnArray = Array<Int>()
    for row in 0..NumRows {
        columnArray.append(value++)
    }
    array.append(columnArray)
}

println("array \(array)")

What is the difference between WCF and WPF?

WCF = Windows COMMUNICATION Foundation

WPF = Windows PRESENTATION Foundation.

WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)

How to simulate a click with JavaScript?

You could save yourself a bunch of space by using jQuery. You only need to use:

$('#myElement').trigger("click")

Formatting text in a TextBlock

You need to use Inlines:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " />
    <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />
</TextBlock.Inlines>

With binding:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" />
    <Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" />
</TextBlock.Inlines>

You can also bind the other properties:

<TextBlock.Inlines>
    <Run FontWeight="{Binding Weight}"
         FontSize="{Binding Size}"
         Text="{Binding LineOne}" />
    <Run FontStyle="{Binding Style}"
         Foreground="Binding Colour}"
         Text="{Binding LineTwo}" />
</TextBlock.Inlines>

You can bind through converters if you have bold as a boolean (say).

How to format dateTime in django template?

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

How to find substring inside a string (or how to grep a variable)?

If you're using bash you can just say

if grep -q "$SOURCE" <<< "$LIST" ; then
    ...
fi