Programs & Examples On #Sqldmo

SQL Distributed Management Objects (SQL-DMO) is a collection of COM objects that are designed for programming all aspects of managing Microsoft SQL Server.

Taking multiple inputs from user in python

How about something like this?

user_input = raw_input("Enter three numbers separated by commas: ")

input_list = user_input.split(',')
numbers = [float(x.strip()) for x in input_list]

(You would probably want some error handling too)

np.mean() vs np.average() in Python NumPy?

In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean, np.average doesn't allow the dtype keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5 file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64':

>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')

m1 = np.average(T, axis=(0,1))                #  garbage
m2 = np.mean(T, axis=(0,1))                   #  the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64')  # correct results

Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average again for this reason but will always use np.mean(.., dtype='float64') on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum or np.mean, as appropriate (with appropriate precision as well).

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)
BEGIN
  PRINT 'BOGUS'
END

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)
BEGIN
END

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

How to make node.js require absolute? (instead of relative)

I don't think you need to solve this in the manner you described. Just sed if you want to change the same string in a large amount of files. In your example,

find . -name "*.js" -exec sed -i 's/\.\.\/\.\.\//\.\.\//g' {} +

would have ../../ changed to ../

Alternatively, you can require a configuration file that stores a variable containing the path to the library. If you store the following as config.js in the example directory

var config = {};
config.path = '../../';

and in your example file

myConfiguration = require('./config');
express = require(config.path);

You'll be able to control the configuration for every example from one file.

It's really just personal preference.

Why is SQL Server 2008 Management Studio Intellisense not working?

For SQL Server 2008 R2, installing Cumulative Update 7 will fix the problem. The file you need is

SQLServer2008R2_RTM_CU7_2507770_10_50_1777_x86 or SQLServer2008R2_RTM_CU7_2507770_10_50_1777_x64

I also had to uninstall and re-install SQL Server 2008 first (which didn't fix it, but the CU did).

this is Direct Link From MS that i was got it Hot Fix

How to use the switch statement in R functions?

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
  if (is.na(val)) {
    val <- "NULL"
    break
  }
  if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
    val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
    break
  }
  if (inherits(val, "Date")) {
    val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
    break
  }
  if (is.numeric(val)) break
  val <- paste0("'", gsub("'", "''", val), "'")
  break
}

Cross Domain Form POSTing

The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:

<form action="http://someotherserver.com">

and there is no javascript involved in posting the form, then the same origin policy is not applicable.

See wikipedia for more information

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

log4net hierarchy and logging levels

DEBUG will show all messages, INFO all besides DEBUG messages, and so on.
Usually one uses either INFO or WARN. This dependens on the company policy.

Auto start node.js server on boot

I would recommend installing your node.js app as a Windows service, and then set the service to run at startup. That should make it a bit easier to control the startup action by using the Windows Services snapin rather than having to add or remove batch files in the Startup folder.

Another service-related question in Stackoverflow provided a couple of (apprently) really good options. Check out How to install node.js as a Windows Service. node-windows looks really promising to me. As an aside, I used similar tools for Java apps that needed to run as services. It made my life a whole lot easier. Hope this helps.

What does enumerate() mean?

The enumerate function works as follows:

doc = """I like movie. But I don't like the cast. The story is very nice"""
doc1 = doc.split('.')
for i in enumerate(doc1):
     print(i)

The output is

(0, 'I like movie')
(1, " But I don't like the cast")
(2, ' The story is very nice')

cannot call member function without object

just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:

static void Name_pairs::read_names()
{
   cout << "Enter name: ";
   cin >> name;
   names.push_back(name);
   cout << endl;
}

Is there a Python equivalent to Ruby's string interpolation?

I've developed the interpy package, that enables string interpolation in Python.

Just install it via pip install interpy. And then, add the line # coding: interpy at the beginning of your files!

Example:

#!/usr/bin/env python
# coding: interpy

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."

Remove last character from string. Swift language

A swift category that's mutating:

extension String {
    mutating func removeCharsFromEnd(removeCount:Int)
    {
        let stringLength = count(self)
        let substringIndex = max(0, stringLength - removeCount)
        self = self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

Use:

var myString = "abcd"
myString.removeCharsFromEnd(2)
println(myString) // "ab"

How to find out the server IP address (using JavaScript) that the browser is connected to?

Actually there is no way to do this through JavaScript, unless you use some external source. Even then, it might not be 100% correct.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

I have faced this problem and I made research and didn't get anything, so I was trying and finally, I knew the cause of this problem. the problem on the API, make sure you have a good variable name I used $start_date and it caused the problem, so I try $startdate and it works!

as well make sure you send all parameter that declare on API, for example, $startdate = $_POST['startdate']; $enddate = $_POST['enddate'];

you have to pass this two variable from the retrofit.

as well if you use date on SQL statement, try to put it inside '' like '2017-07-24'

I hope it helps you.

How to reload a div without reloading the entire page?

jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)

Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in

$("#mydiv").load(location.href + " #mydiv");

Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.

Why am I getting ImportError: No module named pip ' right after installing pip?

try to type pip3 instead pip. also for upgrading pip dont use pip3 in the command

python -m pip install -U pip

maybe it helps

Visibility of global variables in imported modules

A function uses the globals of the module it's defined in. Instead of setting a = 3, for example, you should be setting module1.a = 3. So, if you want cur available as a global in utilities_module, set utilities_module.cur.

A better solution: don't use globals. Pass the variables you need into the functions that need it, or create a class to bundle all the data together, and pass it when initializing the instance.

Check table exist or not before create it in Oracle

As Rene also commented, it's quite uncommon to check first and then create the table. If you want to have a running code according to your method, this will be:

declare
nCount NUMBER;
v_sql LONG;

begin
SELECT count(*) into nCount FROM dba_tables where table_name = 'EMPLOYEE';
IF(nCount <= 0)
THEN
v_sql:='
create table EMPLOYEE
(
ID NUMBER(3),
NAME VARCHAR2(30) NOT NULL
)';
execute immediate v_sql;

END IF;
end;

But I'd rather go catch on the Exception, saves you some unnecessary lines of code:

declare
v_sql LONG;
begin

v_sql:='create table EMPLOYEE
  (
  ID NUMBER(3),
  NAME VARCHAR2(30) NOT NULL
  )';
execute immediate v_sql;

EXCEPTION
    WHEN OTHERS THEN
      IF SQLCODE = -955 THEN
        NULL; -- suppresses ORA-00955 exception
      ELSE
         RAISE;
      END IF;
END; 
/

Assign result of dynamic sql to variable

You should try this while getting SEQUENCE value in a variable from the dynamic table.

DECLARE @temp table (#temp varchar (MAX));
DECLARE @SeqID nvarchar(150);
DECLARE @Name varchar(150); 

SET @Name = (Select Name from table)
SET @SeqID = 'SELECT NEXT VALUE FOR '+ @Name + '_Sequence'
insert @temp exec (@SeqID)

SET @SeqID = (select * from @temp )
PRINT @SeqID

Result:

(1 row(s) affected)
 1

Check if a row exists using old mysql_* API

function checkLectureStatus($lectureName) {
  global $con;
  $lectureName = mysql_real_escape_string($lectureName);
  $sql = "SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName'";
  $result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
  if (mysql_fetch_row($result)) {
    return 'Assigned';
  }
  return 'Available';
}

however you have to use some abstraction library for the database access.
the code would become

function checkLectureStatus($lectureName) {
  $res = db::getOne("SELECT 1 FROM preditors_assigned WHERE lecture_name=?",$lectureName);
  if($res) {
    return 'Assigned';
  }
  return 'Available';
}

How to get a value from the last inserted row?

Use sequences in postgres for id columns:

INSERT mytable(myid) VALUES (nextval('MySequence'));

SELECT currval('MySequence');

currval will return the current value of the sequence in the same session.

(In MS SQL, you would use @@identity or SCOPE_IDENTITY())

HTTP Request in Kotlin

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

However, you can also use standard Java libraries like java.net.HttpURLConnection which is part of the Java SDK:

fun sendGet() {
    val url = URL("http://www.google.com/")

    with(url.openConnection() as HttpURLConnection) {
        requestMethod = "GET"  // optional default is GET

        println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

Or simpler:

URL("https://google.com").readText()

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

The PHP function echo() prints out its input to the web server response.

echo("Hello World!");

prints out Hello World! to the web server response.

echo("<prev>");

prints out the tag to the web server response.

echo do not require valid HTML tags. You can use PHP to print XML, images, excel, HTML and so on.

<prev> is not a HTML tag. Is is a valid XML tag, but since I don't know what page you are working in, i cannot tell you what it is. Maybe it is the root tag of a XML page, or a miswritten <pre> tag.

Simple insecure two-way data "obfuscation"?

If you just want simple encryption (i.e., possible for a determined cracker to break, but locking out most casual users), just pick two passphrases of equal length, say:

deoxyribonucleicacid
while (x>0) { x-- };

and xor your data with both of them (looping the passphrases if necessary)(a). For example:

1111-2222-3333-4444-5555-6666-7777
deoxyribonucleicaciddeoxyribonucle
while (x>0) { x-- };while (x>0) { 

Someone searching your binary may well think the DNA string is a key, but they're unlikely to think the C code is anything other than uninitialized memory saved with your binary.


(a) Keep in mind this is very simple encryption and, by some definitions, may not be considered encryption at all (since the intent of encryption is to prevent unauthorised access rather than just make it more difficult). Although, of course, even the strongest encryption is insecure when someone's standing over the key-holders with a steel pipe.

As stated in the first sentence, this is a means to make it difficult enough for the casual attacker that they'll move on. It's similar to preventing burglaries on your home - you don't need to make it impregnable, you just need to make it less pregnable than the house next door :-)

How to change an image on click using CSS alone?

Try this (but once clicked, it is not reversible):

HTML:

<a id="test"><img src="normal-image.png"/></a>

CSS:

a#test {
    border: 0;
}
a#test:visited img, a#test:active img {
    background-image: url(clicked-image.png);
}

How to ensure a <select> form field is submitted when it is disabled?

I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.

// With jQuery
$('#selectbox').focus(function(e) {
    $(this).blur();
});

Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.

CONVERT Image url to Base64

You Can Used This :

function ViewImage(){
 function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}

Add To Your Input onchange=ViewImage();

Copy files to network computers on windows command line

check Robocopy:

ROBOCOPY \\server-source\c$\VMExports\ C:\VMExports\ /E /COPY:DAT

make sure you check what robocopy parameter you want. this is just an example. type robocopy /? in a comandline/powershell on your windows system.

What is the inclusive range of float and double in Java?

Java's Double class has members containing the Min and Max value for the type.

2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.

Check out the Min_VALUE and MAX_VALUE static final members of Double.

(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.

How to apply a CSS filter to a background image

I didn't write this, but I noticed there was a polyfill for the partially supported backdrop-filter using the CSS SASS compiler, so if you have a compilation pipeline it can be achieved nicely (it also uses TypeScript):

https://codepen.io/mixal_bl4/pen/EwPMWo

SQL Server : check if variable is Empty or NULL for WHERE clause

If you can use some dynamic query, you can use LEN . It will give false on both empty and null string. By this way you can implement the option parameter.

ALTER PROCEDURE [dbo].[psProducts] 
(@SearchType varchar(50))
AS
BEGIN
    SET NOCOUNT ON;

DECLARE @Query nvarchar(max) = N'
    SELECT 
        P.[ProductId],
        P.[ProductName],
        P.[ProductPrice],
        P.[Type]
    FROM [Product] P'
    -- if @Searchtype is not null then use the where clause
    SET @Query = CASE WHEN LEN(@SearchType) > 0 THEN @Query + ' WHERE p.[Type] = ' + ''''+ @SearchType + '''' ELSE @Query END   

    EXECUTE sp_executesql @Query
    PRINT @Query
END

Rename Oracle Table or View

To rename a table you can use:

RENAME mytable TO othertable;

or

ALTER TABLE mytable RENAME TO othertable;

or, if owned by another schema:

ALTER TABLE owner.mytable RENAME TO othertable;

Interestingly, ALTER VIEW does not support renaming a view. You can, however:

RENAME myview TO otherview;

The RENAME command works for tables, views, sequences and private synonyms, for your own schema only.

If the view is not in your schema, you can recompile the view with the new name and then drop the old view.

(tested in Oracle 10g)

Is there a numpy builtin to reject outliers from a list

This method is almost identical to yours, just more numpyst (also working on numpy arrays only):

def reject_outliers(data, m=2):
    return data[abs(data - np.mean(data)) < m * np.std(data)]

How can I convert an HTML element to a canvas element?

You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/

Unexpected token < in first line of HTML

We had the same problem sometime ago where a site suddenly began giving this error. The reason was that a js include was temporarily remarked with a # (i.e. src="#./js...").

Applications are expected to have a root view controller at the end of application launch

There was a slight change around iOS 5.0 or so, requiring you to have a root view controller. If your code is based off older sample code, such as GLES2Sample, then no root view controller was created in those code samples.

To fix (that GLES2Sample, for instance), right in applicationDidFinishLaunching, I create a root view controller and attach my glView to it.

- (void) applicationDidFinishLaunching:(UIApplication *)application
{
  // To make the 'Application windows are expected
  // to have a root view controller
  // at the end of application launch' warning go away,
  // you should have a rootviewcontroller,
  // but this app doesn't have one at all.
  window.rootViewController = [[UIViewController alloc] init];  // MAKE ONE
  window.rootViewController.view = glView; // MUST SET THIS UP OTHERWISE
  // THE ROOTVIEWCONTROLLER SEEMS TO INTERCEPT TOUCH EVENTS
}

That makes the warning go away, and doesn't really affect your app otherwise.

What is the difference between jQuery: text() and html() ?

Actually both do look somewhat similar but are quite different it depends on your usage or intention what you want to achieve ,

Where to use:

  • use .html() to operate on containers having html elements.
  • use .text() to modify text of elements usually having separate open and closing tags

Where not to use:

  • .text() method cannot be used on form inputs or scripts.

    • .val() for input or textarea elements.
    • .html() for value of a script element.
  • Picking up html content from .text() will convert the html tags into html entities.

Difference:

  • .text() can be used in both XML and HTML documents.
  • .html() is only for html documents.

Check this example on jsfiddle to see the differences in action

Example

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

How do I convert Int/Decimal to float in C#?

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

PostgreSQL DISTINCT ON with different ORDER BY

A subquery can solve it:

SELECT *
FROM  (
    SELECT DISTINCT ON (address_id) *
    FROM   purchases
    WHERE  product_id = 1
    ) p
ORDER  BY purchased_at DESC;

Leading expressions in ORDER BY have to agree with columns in DISTINCT ON, so you can't order by different columns in the same SELECT.

Only use an additional ORDER BY in the subquery if you want to pick a particular row from each set:

SELECT *
FROM  (
    SELECT DISTINCT ON (address_id) *
    FROM   purchases
    WHERE  product_id = 1
    ORDER  BY address_id, purchased_at DESC  -- get "latest" row per address_id
    ) p
ORDER  BY purchased_at DESC;

If purchased_at can be NULL, use DESC NULLS LAST - and match your index for best performance. See:

Related, with more explanation:

What's the best way to check if a String represents an integer in Java?

What you did works, but you probably shouldn't always check that way. Throwing exceptions should be reserved for "exceptional" situations (maybe that fits in your case, though), and are very costly in terms of performance.

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

An easier alternative to solve this problem is to return an string, and format that string to json with JavaScriptSerializer.

public string GetEntityInJson()
{
   JavaScriptSerializer j = new JavaScriptSerializer();
   var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
   return j.Serialize(entityList );
}

It is important the "Select" part, which choose the properties you want in your view. Some object have a reference for the parent. If you do not choose the attributes, the circular reference may appear, if you just take the tables as a whole.

Do not do this:

public string GetEntityInJson()
{
   JavaScriptSerializer j = new JavaScriptSerializer();
   var entityList = dataContext.Entitites.toList();
   return j.Serialize(entityList );
}

Do this instead if you don't want the whole table:

public string GetEntityInJson()
{
   JavaScriptSerializer j = new JavaScriptSerializer();
   var entityList = dataContext.Entitites.Select(x => new { ID = x.ID, AnotherAttribute = x.AnotherAttribute });
   return j.Serialize(entityList );
}

This helps render a view with less data, just with the attributes you need, and makes your web run faster.

How can I count the number of characters in a Bash variable

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Couting characters, words, lenght of the words and total lenght in a sentence

How to auto-size an iFrame?

On any other element, I would use the scrollHeight of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.

Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the offsetHeight:

function setHeight() {
    parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}

And attach that to run with the iframe-body's onLoad event.

Change a HTML5 input's placeholder color with CSS

For Bootstrap users, if you are using class="form-control", there may be a CSS specificity issue. You should get a higher priority:

.form-control::-webkit-input-placeholder {
    color: red;
}
//.. and other browsers

Or if you are using Less:

.form-control{
    .placeholder(red);
}

UTF-8 all the way through

In my case, I was using mb_split, which uses regex. Therefore I also had to manually make sure the regex encoding was utf-8 by doing mb_regex_encoding('UTF-8');

As a side note, I also discovered by running mb_internal_encoding() that the internal encoding wasn't utf-8, and I changed that by running mb_internal_encoding("UTF-8");.

How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait

and

Ctrl + F12 for Landscape

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

find all the name using mysql query which start with the letter 'a'

One can also use RLIKE as below

SELECT * FROM artists WHERE name RLIKE '^[abc]';

How to create a foreign key in phpmyadmin

A simple SQL example would be like this:

ALTER TABLE `<table_name>` ADD `<column_name>` INT(11) NULL DEFAULT NULL ;

Make sure you use back ticks `` in table name and column name

Build Android Studio app via command line

I faced the same problem and seems that there have been many changes by google.

I can tell you the steps for installing purely via command line from scratch. I tested it on Ubuntu on 22 Feb 2021.

create sdk folder

export ANDROID_SDK_ROOT=/usr/lib/android-sdk
sudo mkdir -p $ANDROID_SDK_ROOT

install openjdk

sudo apt-get install openjdk-8-jdk

download android sdk

Go to https://developer.android.com/studio/index.html Then down to Command line tools only Click on Linux link, accept the agreement and instead of downloading right click and copy link address

cd $ANDROID_SDK_ROOT
sudo wget https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip
sudo unzip commandlinetools-linux-6858069_latest.zip

move folders

Rename the unpacked directory from cmdline-tools to tools, and place it under $ANDROID_SDK_ROOT/cmdline-tools, so now it should look like: $ANDROID_SDK_ROOT/cmdline-tools/tools. And inside it, you should have: NOTICE.txt bin lib source.properties.

set path

PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin

This had no effect for me, hence the next step

browse to sdkmanager

cd $ANDROID_SDK_ROOT/cmdline-tools/tools/bin

accept licenses

yes | sudo sdkmanager --licenses

create build

Finally, run this inside your project

sudo ./gradlew assembleDebug

This creates an APK named -debug.apk at //build/outputs/apk/debug The file is already signed with the debug key and aligned with zipalign, so you can immediately install it on a device.

REFERENCES

https://gist.github.com/guipmourao/3e7edc951b043f6de30ca15a5cc2be40

Android Command line tools sdkmanager always shows: Warning: Could not create settings

"Failed to install the following Android SDK packages as some licences have not been accepted" error

https://developer.android.com/studio/build/building-cmdline#sign_cmdline

How can I import data into mysql database via mysql workbench?

  • Under Server Administration on the Home window select the server instance you want to restore database to (Create New Server Instance if doing it first time).
  • Click on Manage Import/Export
  • Click on Data Import/Restore on the left side of the screen.
  • Select Import from Self-Contained File radio button (right side of screen)
  • Select the path of .sql
  • Click Start Import button at the right bottom corner of window.

Hope it helps.

---Edited answer---

Regarding selection of the schema. MySQL Workbench (5.2.47 CE Rev1039) does not yet support exporting to the user defined schema. It will create only the schema for which you exported the .sql... In 5.2.47 we see "New" target schema. But it does not work. I use MySQL Administrator (the old pre-Oracle MySQL Admin beauty) for my work for backup/restore. You can still download it from Googled trustable sources (search MySQL Administrator 1.2.17).

Gradient of n colors ranging from color 1 and color 2

Try the following:

color.gradient <- function(x, colors=c("red","yellow","green"), colsteps=100) {
  return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
}
x <- c((1:100)^2, (100:1)^2)
plot(x,col=color.gradient(x), pch=19,cex=2)

enter image description here

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

g = nx.DiGraph()
g.add_nodes_from([1,2,3,4,5])
g.add_edge(1,2)
g.add_edge(4,2)
g.add_edge(3,5)
g.add_edge(2,3)
g.add_edge(5,4)

nx.draw(g,with_labels=True)
plt.draw()
plt.show()

This is just simple how to draw directed graph using python 3.x using networkx. just simple representation and can be modified and colored etc. See the generated graph here.

Note: It's just a simple representation. Weighted Edges could be added like

g.add_edges_from([(1,2),(2,5)], weight=2)

and hence plotted again.

jquery stop child triggering parent event

The answers here took the OP's question too literally. How can these answers be expanded into a scenario where there are MANY child elements, not just a single <a> tag? Here's one way.

Let's say you have a photo gallery with a blacked out background and the photos centered in the browser. When you click the black background (but not anything inside of it) you want the overlay to close.

Here's some possible HTML:

<div class="gallery" style="background: black">
    <div class="contents"> <!-- Let's say this div is 50% wide and centered -->
        <h1>Awesome Photos</h1>
        <img src="img1.jpg"><br>
        <img src="img2.jpg"><br>
        <img src="img3.jpg"><br>
        <img src="img4.jpg"><br>
        <img src="img5.jpg">
    </div>
</div>

And here's how the JavaScript would work:

$('.gallery').click(
    function()
    {
        $(this).hide();
    }
);

$('.gallery > .contents').click(
    function(e) {
        e.stopPropagation();
    }
);

This will stop the click events from elements inside .contents from every research .gallery so the gallery will close only when you click in the faded black background area, but not when you click in the content area. This can be applied to many different scenarios.

Microsoft.ACE.OLEDB.12.0 is not registered

The easiest solution I found was to specify excel version 97-2003 on the connection manager setup.

Check array position for null/empty

You can use boost::optional (or std::optional for newer versions), which was developed in particular for decision of your problem:

boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
   if(y[i]) { //check for null
      p[i].SetPoint(Recto.Height()-x,*y[i]);
      ....
   }
}

P.S. Do not use C-type array -> use std::array or std::vector:

std::array<int, 50> y;   //not int y[50] !!!

Set language for syntax highlighting in Visual Studio Code

In the very right bottom corner, left to the smiley there was the icon saying "Plain Text". When you click it, the menu with all languages appears where you can choose your desired language.

VSCode

How to make popup look at the centre of the screen?

In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:

.div {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50%;
}

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

It is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

which is why you can do :

ViewBag.Foo = "Bar";

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
    {
        objectDictionary = new Dictionary<string, object>();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
        {
            result = val;
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            objectDictionary[binder.Name] = value;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

How to find elements by class

Specific to BeautifulSoup 3:

soup.findAll('div',
             {'class': lambda x: x 
                       and 'stylelistrow' in x.split()
             }
            )

Will find all of these:

<div class="stylelistrow">
<div class="stylelistrow button">
<div class="button stylelistrow">

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Is Python strongly typed?

i think, this simple example should you explain the diffs between strong and dynamic typing:

>>> tup = ('1', 1, .1)
>>> for item in tup:
...     type(item)
...
<type 'str'>
<type 'int'>
<type 'float'>
>>>

java:

public static void main(String[] args) {
        int i = 1;
        i = "1"; //will be error
        i = '0.1'; // will be error
    }

C++ class forward declaration

class tile_tree_apple should be defined in a separate .h file.

tta.h:
#include "tile.h"

class tile_tree_apple : public tile
{
      public:
          tile onDestroy() {return *new tile_grass;};
          tile tick() {if (rand()%20==0) return *new tile_tree;};
          void onCreate() {health=rand()%5+4; type=TILET_TREE_APPLE;}; 
          tile onUse() {return *new tile_tree;};       
};

file tt.h
#include "tile.h"

class tile_tree : public tile
{
      public:
          tile onDestroy() {return *new tile_grass;};
          tile tick() {if (rand()%20==0) return *new tile_tree_apple;};
          void onCreate() {health=rand()%5+4; type=TILET_TREE;};        
};

another thing: returning a tile and not a tile reference is not a good idea, unless a tile is a primitive or very "small" type.

Returning value from called function in a shell script

A Bash function can't return a string directly like you want it to. You can do three things:

  1. Echo a string
  2. Return an exit status, which is a number, not a string
  3. Share a variable

This is also true for some other shells.

Here's how to do each of those options:

1. Echo strings

lockdir="somedir"
testlock(){
    retval=""
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval="true"
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval="false"
    fi
    echo "$retval"
}

retval=$( testlock )
if [ "$retval" == "true" ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

2. Return exit status

lockdir="somedir"
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
    return "$retval"
}

testlock
retval=$?
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

3. Share variable

lockdir="somedir"
retval=-1
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
}

testlock
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

How to use fetch in typescript

Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

That being said, the following works...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

callBack: (response: any) => void

But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

So that a client can call it with a callback like...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}

SQL JOIN, GROUP BY on three tables to get totals

First of all, shouldn't there be a CustomerId in the Invoices table? As it is, You can't perform this query for Invoices that have no payments on them as yet. If there are no payments on an invoice, that invoice will not even show up in the ouput of the query, even though it's an outer join...

Also, When a customer makes a payment, how do you know what Invoice to attach it to ? If the only way is by the InvoiceId on the stub that arrives with the payment, then you are (perhaps inappropriately) associating Invoices with the customer that paid them, rather than with the customer that ordered them... . (Sometimes an invoice can be paid by someone other than the customer who ordered the services)

How to print formatted BigDecimal values?

To set thousand separator, say 123,456.78 you have to use DecimalFormat:

     DecimalFormat df = new DecimalFormat("#,###.00");
     System.out.println(df.format(new BigDecimal(123456.75)));
     System.out.println(df.format(new BigDecimal(123456.00)));
     System.out.println(df.format(new BigDecimal(123456123456.78)));

Here is the result:

123,456.75
123,456.00
123,456,123,456.78

Although I set #,###.00 mask, it successfully formats the longer values too. Note that the comma(,) separator in result depends on your locale. It may be just space( ) for Russian locale.

Bi-directional Map in Java?

There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

display: inline-block extra margin

White space affects inline elements.

This should not come as a surprise. We see it every day with span, strong and other inline elements. Set the font size to zero to remove the extra margin.

.container {
  font-size: 0px;
  letter-spacing: 0px;
  word-spacing: 0px;
}

.container > div {
  display: inline-block;
  margin: 0px;
  padding: 0px;
  font-size: 15px;
  letter-spacing: 1em;
  word-spacing: 2em;
}

The example would then look like this.

<div class="container">
  <div>First</div>
  <div>Second</div>
</div>

A jsfiddle version of this. http://jsfiddle.net/QtDGJ/1/

Good ways to sort a queryset? - Django

Here's a way that allows for ties for the cut-off score.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

Marquee text in Android

In XML file, you need to add following additional attributes in a TextView to get a marquee like feature:

android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"

In MainActivity.java file, you can get the reference of this TextView by using findViewById() and you can set the following property to this TextView to make it appear like a marquee text:

setSelected(true);

That's all you need.

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

Wait until a process ends

Like Jon Skeet says, use the Process.Exited:

proc.StartInfo.FileName = exportPath + @"\" + fileExe;
proc.Exited += new EventHandler(myProcess_Exited);
proc.Start();
inProcess = true;

while (inProcess)
{
    proc.Refresh();
    System.Threading.Thread.Sleep(10);
    if (proc.HasExited)
    {
        inProcess = false;
    }
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
    inProcess = false;
    Console.WriteLine("Exit time:    {0}\r\n" +
      "Exit code:    {1}\r\n", proc.ExitTime, proc.ExitCode);
}

Get current scroll position of ScrollView in React Native

This is how ended up getting the current scroll position live from the view. All I am doing is using the on scroll event listener and the scrollEventThrottle. I am then passing it as an event to handle scroll function I made and updating my props.

 export default class Anim extends React.Component {
          constructor(props) {
             super(props);
             this.state = {
               yPos: 0,
             };
           }

        handleScroll(event){
            this.setState({
              yPos : event.nativeEvent.contentOffset.y,
            })
        }

        render() {
            return (
          <ScrollView onScroll={this.handleScroll.bind(this)} scrollEventThrottle={16} />
    )
    }
    }

SELECT INTO Variable in MySQL DECLARE causes syntax error?

I am using version 6 (MySQL Workbench Community (GPL) for Windows version 6.0.9 revision 11421 build 1170) on Windows Vista. I have no problem with the following options. Probably they fixed it since these guys got the problems three years ago.

/* first option */
SELECT ID 
INTO @myvar 
FROM party 
WHERE Type = 'individual';

-- get the result
select @myvar;

/* second option */
SELECT @myvar:=ID
FROM party
WHERE Type = 'individual';


/* third option. The same as SQL Server does */
SELECT @myvar = ID FROM party WHERE Type = 'individual';

All option above give me a correct result.

Enter export password to generate a P12 certificate

I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...

Per manual, you don't necessary want to use -password option.

Let's say mykey.key has a password and your want to protect iphone-dev.p12 with another password, this is what you'd use:

pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev

Have fun scripting!!

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

For me worked when I changed "directory" content into this:

<Directory  "*YourLocation*">
Options All
AllowOverride All
Require all granted  
</Directory>

How to pass a function as a parameter in Java?

I used the command pattern that @jk. mentioned, adding a return type:

public interface Callable<I, O> {

    public O call(I input);   
}

Parsing a JSON string in Ruby

As of Ruby v1.9.3 you don't need to install any Gems in order to parse JSON, simply use require 'json':

require 'json'

json = JSON.parse '{"foo":"bar", "ping":"pong"}'
puts json['foo'] # prints "bar"

See JSON at Ruby-Doc.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Actually the "Remote" option in Configuration Menu for Plug-In works by me (Win7 64, ie8 with all updates), however:

  1. You need administrator rights
  2. The plug-in should be disabled before pressing the remove button
  3. You need restart internet-explorer to see the changes.

Also the previous comment about browsing-history->view objects was also useful if plug-in was installed right now.

Regards!

Unable to get spring boot to automatically create database schema

The configurations below worked for me:

spring.jpa.properties.javax.persistence.schema-generation.database.action=create
spring.jpa.properties.javax.persistence.schema-generation.create-database-schemas=true
spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.drop-source=metadata
spring.jpa.properties.javax.persistence.schema-generation.connection=jdbc:mysql://localhost:3306/your_database

How to remove all CSS classes using jQuery/JavaScript?

Just set the className attribute of the real DOM element to '' (nothing).

$('#item')[0].className = ''; // the real DOM element is at [0]

Edit: Other people have said that just calling removeClass works - I tested this with the Google JQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:

$("#item").removeClass();

Revert to a commit by a SHA hash in Git?

Updated:

This answer is simpler than my answer: https://stackoverflow.com/a/21718540/541862

Original answer:

# Create a backup of master branch
git branch backup_master

# Point master to '56e05fce' and
# make working directory the same with '56e05fce'
git reset --hard 56e05fce

# Point master back to 'backup_master' and
# leave working directory the same with '56e05fce'.
git reset --soft backup_master

# Now working directory is the same '56e05fce' and
# master points to the original revision. Then we create a commit.
git commit -a -m "Revert to 56e05fce"

# Delete unused branch
git branch -d backup_master

The two commands git reset --hard and git reset --soft are magic here. The first one changes the working directory, but it also changes head (the current branch) too. We fix the head by the second one.

What is null in Java?

null is a special value that is not an instance of any class. This is illustrated by the following program:

public class X {
   void f(Object o)
   { 
      System.out.println(o instanceof String);   // Output is "false"
   }
   public static void main(String[] args) {
      new X().f(null);
   }
}

Asking the user for input until they give a valid response

Below code may help.

age=(lambda i,f: f(i,f))(input("Please enter your age: "),lambda i,f: i if i.isdigit() else f(input("Please enter your age: "),f))
print("You are able to vote in the united states" if int(age)>=18 else "You are not able to vote in the united states",end='')

If you want to have maximum tries, say 3, use below code

age=(lambda i,n,f: f(i,n,f))(input("Please enter your age: "),1,lambda i,n,f: i if i.isdigit() else (None if n==3 else f(input("Please enter your age: "),n+1,f)))
print("You are able to vote in the united states" if age and int(age)>=18 else "You are not able to vote in the united states",end='')

Note: This uses recursion.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

To do the same I did following in terminal-

$ wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
$ sudo tar -xzf postman.tar.gz -C /opt
$ rm postman.tar.gz
$ sudo ln -s /opt/Postman/Postman /usr/bin/postman
  1. Now open file system, move to /usr/bin/ and search form "Postman"
  2. There was a sh file with name 'Postman'
  3. Double clicked on it which opened postman.
  4. Locked icon to launcher on right clicking its icon for further use.

Hope will hell others too.

How to make my layout able to scroll down?

For using scroll view along with Relative layout :

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/background_image"
    >

    <!-- Bla Bla Bla i.e. Your Textviews/Buttons etc. -->
    </RelativeLayout>
</ScrollView>

How can I add a username and password to Jenkins?

Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.

For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.

Defining a variable with or without export

export makes the variable available to sub-processes.

That is,

export name=value

means that the variable name is available to any process you run from that shell process. If you want a process to make use of this variable, use export, and run the process from that shell.

name=value

means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc.

It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.

store and retrieve a class object in shared preference

Using Gson Library:

dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}

Store:

Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);

Retrieve:

String json = getPrefs().getUserJson();

How to fix a locale setting warning from Perl

You need to configure locale appropriately in /etc/default/locale, logout, login, and then run the regular commands

root@host:~# echo -e 'LANG=en_US.UTF-8\nLC_ALL=en_US.UTF-8' > /etc/default/locale
root@host:~# exit
local-user@local:~$ ssh root@host
root@host:~# locale-gen en_US.UTF-8
root@host:~# dpkg-reconfigure locales

Finding the next available id in MySQL

The problem with many solutions is they only find the next "GAP", while ignoring if "1" is available, or if there aren't any rows they'll return NULL as the next "GAP".

The following will not only find the next available gap, it'll also take into account if the first available number is 1:

SELECT CASE WHEN MIN(MyID) IS NULL OR MIN(MyID)>1
-- return 1 if it's available or if there are no rows yet
THEN
    1
ELSE -- find next gap
    (SELECT MIN(t.MyID)+1
    FROM MyTable t (updlock)
    WHERE NOT EXISTS (SELECT NULL FROM MyTable n WHERE n.MyID=t.MyID+1))
END AS NextID
FROM MyTable

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

This is the problem that is occurring,

if the JAR file was loaded from "C:\java\apps\appli.jar", and your manifest file has the Class-Path: reference "lib/other.jar", the class loader will look in "C:\java\apps\lib\" for "other.jar". It won't look at the JAR file entry "lib/other.jar".

Solution:-

  1. Right click on project, Select Export.
  2. Select Java Folder and in it select Runnable JAR File instead of JAR file.
  3. Select the proper options and in the Library Handling section select the 3rd option i.e. (Copy required libraries into a sub-folder next to the generated JAR).

[ EDIT = 3rd option generates a folder in addition to the jar, 2nd option ("Package required libraries into generated JAR") can also be used as you have the jar. ]

  1. Click finish and your JAR is created at the specified position along with a folder that contains the JARS mentioned in the manifest file.
  2. open the terminal,give the proper path to your jar and run it using this command java -jar abc.jar

    Now what will happen is the class loader will look in the correct folder for the referenced JARS since now they are present in the same folder that contains your app JAR..There is no "java.lang.NoClassDefFoundError" exception thrown now.

This worked for me... Hope it works for you too!!!

How to install a previous exact version of a NPM package?

For yarn users:

yarn add package_name@version_number

Python 3 Building an array of bytes

what about simply constructing your frame from a standard list ?

frame = bytes([0xA2,0x01,0x02,0x03,0x04])

the bytes() constructor can build a byte frame from an iterable containing int values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()...

Installing packages in Sublime Text 2

Here is a link to a shorter and to the point description: http://www.granneman.com/webdev/editors/sublime-text/packages/how-to-install-and-use-package-control/

The steps are:

  1. Install package control.
  2. Go to http://wbond.net/sublime_packages/package_control/installation and grab the install code.
  3. In Sublime Text 2 open the console (Ctrl+`) and paste the code.
  4. Restart Sublime Text 2.
  5. Open command palette via Command+Shift+P (Mac OSX) or Ctrl+Shift+P (Windows).
  6. Start typing Package Control and choose the package you are looking for.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Add list to set?

Here is how I usually do it:

def add_list_to_set(my_list, my_set):
    [my_set.add(each) for each in my_list]
return my_set

Installed SSL certificate in certificate store, but it's not in IIS certificate list

when you have one certificate and 2 different web servers here how I fixed it:

  1. List item
  2. You should generate certificate at one of the servers as usually in IIS Then at that server you can also complete the certificate in IIS.
  3. Run the program DigiCertUtil and export that working certificate
  4. Go to the other web server in IIS in security certificates Import that file from step 3.
  5. Then use that certificate to create the Binding.

How to set up a PostgreSQL database in Django

Also make sure you have the PostgreSQL development package installed. On Ubuntu you need to do something like this:

$ sudo apt-get install libpq-dev

What does the "@" symbol do in Powershell?

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is denoted @().

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Another solution I have found to a similar error but the same error message is to increase the number of service handlers found. (My instance of this error was caused by too many connections in the Weblogic Portal Connection pools.)

  • Run SQL*Plus and login as SYSTEM. You should know what password you’ve used during the installation of Oracle DB XE.
  • Run the command alter system set processes=150 scope=spfile; in SQL*Plus
  • VERY IMPORTANT: Restart the database.

From here:

http://www.atpeaz.com/index.php/2010/fixing-the-ora-12519-tnsno-appropriate-service-handler-found-error/

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

onSaveInstance will be called if a user rotates the screen so that it can load resources associated with the new orientation.

It's possible that this user rotated the screen followed by pressing the back button (because it's also possible that this user fumbled their phone while using your app)

Format the date using Ruby on Rails

First you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

Then to format it nicely in the view, you can just use to_s (for the default formatting):

<%= my_date.to_s %>

Note that if you don't put to_s, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s on the date:

<%= "Here is a date: #{my_date}" %>

or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime as outlined in the other answer.

How to calculate a mod b in Python?

Why don't you use % ?


print 4 % 2 # 0

How can I convert string date to NSDate?

try this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)

For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.

Swift 3 and later (Swift 4 included)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
guard let date = dateFormatter.date(from: /* your_date_string */) else {
   fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here

addClass - can add multiple classes on same div?

$('.page-address-edit').addClass('test1 test2 test3');

Ref- jQuery

Algorithm to randomly generate an aesthetically-pleasing color palette

David Crow's method in an R two-liner:

GetRandomColours <- function(num.of.colours, color.to.mix=c(1,1,1)) {
  return(rgb((matrix(runif(num.of.colours*3), nrow=num.of.colours)*color.to.mix)/2))
}

Submitting HTML form using Jquery AJAX

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })

for each inside a for each - Java

So you really want:

for each tweet
    unless tweet is in db
        insert tweet

If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.

What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.

How to generate and manually insert a uniqueidentifier in sql server?

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE
(
  TEST UNIQUEIDENTIFIER
)

DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();

INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);

SELECT * FROM @TTEST

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

How to manually include external aar package using new Gradle Android Build System

If you use Gradle Kotlin DSL, you need to add a file in your module directory.

For example: libs/someAndroidArchive.aar

After just write this in your module build.gradle.kts in the dependency block:

implementation(files("libs/someAndroidArchive.aar"))

How do you do natural logs (e.g. "ln()") with numpy in Python?

You could simple just do the reverse by making the base of log to e.

import math

e = 2.718281

math.log(e, 10) = 2.302585093
ln(10) = 2.30258093

Rotating a view in Android

Joininig @Rudi's and @Pete's answers. I have created an RotateAnimation that keeps buttons functionality also after rotation.

setRotation() method preserves buttons functionality.

Code Sample:

Animation an = new RotateAnimation(0.0f, 180.0f, mainLayout.getWidth()/2, mainLayout.getHeight()/2);

    an.setDuration(1000);              
    an.setRepeatCount(0);                     
    an.setFillAfter(false);              // DO NOT keep rotation after animation
    an.setFillEnabled(true);             // Make smooth ending of Animation
    an.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationRepeat(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation) {
                mainLayout.setRotation(180.0f);      // Make instant rotation when Animation is finished
            }
            }); 

mainLayout.startAnimation(an);

mainLayout is a (LinearLayout) field

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

Sorry, but I think the accepted answer is an overkill. All you need to do is this:

public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
    public void OnException (ExceptionContext context)
    {
        // Log only handled exceptions, because all other will be caught by ELMAH anyway.
        if (context.ExceptionHandled)
            ErrorSignal.FromCurrentContext().Raise(context.Exception);
    }
}

and then register it (order is important) in Global.asax.cs:

public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
    filters.Add(new ElmahHandledErrorLoggerFilter());
    filters.Add(new HandleErrorAttribute());
}

How to ping a server only once from within a batch file?

The only thing you need to think about in this case is, in which directory you are on your computer. Your command line window shows C:\users\rei0d\desktop\ as your current directory.

So the only thing you really need to do is:
Remove the desktop by "going up" with the command cd ...

So the complete command would be:

cd ..
ping XXX.XXX.XXX.XXX -t

Hash table in JavaScript

You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.

How to return a result from a VBA function

The below code stores the return value in to the variable retVal and then MsgBox can be used to display the value:

Dim retVal As Integer
retVal = test()
Msgbox retVal

How can I avoid running ActiveRecord callbacks?

I needed a solution for Rails 4, so I came up with this:

app/models/concerns/save_without_callbacks.rb

module SaveWithoutCallbacks

  def self.included(base)
    base.const_set(:WithoutCallbacks,
      Class.new(ActiveRecord::Base) do
        self.table_name = base.table_name
      end
      )
  end

  def save_without_callbacks
    new_record? ? create_without_callbacks : update_without_callbacks
  end

  def create_without_callbacks
    plain_model = self.class.const_get(:WithoutCallbacks)
    plain_record = plain_model.create(self.attributes)
    self.id = plain_record.id
    self.created_at = Time.zone.now
    self.updated_at = Time.zone.now
    @new_record = false
    true
  end

  def update_without_callbacks
    update_attributes = attributes.except(self.class.primary_key)
    update_attributes['created_at'] = Time.zone.now
    update_attributes['updated_at'] = Time.zone.now
    update_columns update_attributes
  end

end

in any model:

include SaveWithoutCallbacks

then you can:

record.save_without_callbacks

or

Model::WithoutCallbacks.create(attributes)

Finding the last index of an array

The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.

string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;

When declaring an array in C#, the number you give is the length of the array:

string[] items = new string[5]; // five items, index ranging from 0 to 4.

Displaying better error message than "No JSON object could be decoded"

Just hit the same issue and in my case the problem was related to BOM (byte order mark) at the beginning of the file.

json.tool would refuse to process even empty file (just curly braces) until i removed the UTF BOM mark.

What I have done is:

  • opened my json file with vim,
  • removed byte order mark (set nobomb)
  • save file

This resolved the problem with json.tool. Hope this helps!

Numpy where function multiple conditions

This should work:

dists[((dists >= r) & (dists <= r+dr))]

The most elegant way~~

Change the row color in DataGridView based on the quantity of a cell value

Try this (Note: I don't have right now Visual Studio ,so code is copy paste from my archive(I haven't test it) :

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    Dim drv As DataRowView
    If e.RowIndex >= 0 Then
        If e.RowIndex <= ds.Tables("Products").Rows.Count - 1 Then
            drv = ds.Tables("Products").DefaultView.Item(e.RowIndex)
            Dim c As Color
            If drv.Item("Quantity").Value < 5  Then
                c = Color.LightBlue
            Else
                c = Color.Pink
            End If
            e.CellStyle.BackColor = c
        End If
    End If
End Sub

PHP: Show yes/no confirmation dialog

The best way that I found is here.

HTML CODE

<a href="delete.cfm" onclick="return confirm('Are you sure you want to delete?');">Delete</a>

ADD THIS TO HEAD SECTION

$(document).ready(function() {
    $('a[data-confirm]').click(function(ev) {
        var href = $(this).attr('href');
        if (!$('#dataConfirmModal').length) {
            $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
        } 
        $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
        $('#dataConfirmOK').attr('href', href);
        $('#dataConfirmModal').modal({show:true});
        return false;
    });
});

You should add Jquery and Bootstrap for this to work.

How to leave space in HTML

Either use literal non-breaking space symbol (yes, you can copy/paste it), HTML entity, or, if you're dealing with big pre-formatted block, use white-space CSS property.

in_array() and multidimensional array

I found really small simple solution:

If your array is :

Array
(
[details] => Array
    (
        [name] => Dhruv
        [salary] => 5000
    )

[score] => Array
    (
        [ssc] => 70
        [diploma] => 90
        [degree] => 70
    )

)

then the code will be like:

 if(in_array("5000",$array['details'])){
             echo "yes found.";
         }
     else {
             echo "no not found";
          }

Escaping regex string

Please give a try:

\Q and \E as anchors

Put an Or condition to match either a full word or regex.

Ref Link : How to match a whole word that includes special characters in regex

Ruby: How to get the first character of a string

In Rails

name = 'Smith'
name.first 

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Call your hosting company and either have them set up regular log backups or set the recovery model to simple. I'm sure you know what informs the choice, but I'll be explicit anyway. Set the recovery model to full if you need the ability to restore to an arbitrary point in time. Either way the database is misconfigured as is.

Convert byte[] to char[]

You must know the source encoding.

string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);

How to create a multi line body in C# System.Net.Mail.MailMessage

Beginning each new line with two white spaces will avoid the auto-remove perpetrated by Outlook.

var lineString = "  line 1\r\n";
linestring += "  line 2";

Will correctly display:

line 1
line 2

It's a little clumsy feeling to use, but it does the job without a lot of extra effort being spent on it.

What's the "Content-Length" field in HTTP header?

Consider if you have headers such as:

content-encoding: gzip
content-length: 52098
content-type: text/javascript; charset=UTF-8

The content-length is the size of the compressed message body, in "octets" (i.e. in units of 8 bits, which happen to be "bytes" for all modern computers).

The size of the actual message body can be something else, perhaps 150280 bytes.

The number of characters can be different again, perhaps 150231 characters, because some unicode characters use multiple bytes (note UTF-8 is a standard encoding).

So, different numbers depending on whether you care how much data is transmitted, or how much data is held, or how many symbols are seen. Of course, there is no guarantee that these headers will be provided..

How to use OpenSSL to encrypt/decrypt files?

Additional comments to mti2935 good answer.

It seems the higher iteration the better protection against brute force, and you should use a high iteration as you can afford performance/resource wise.

On my my old Intel i3-7100 encrypting a rather big file 1.5GB:

 time openssl enc -aes256 -e -pbkdf2 -iter 10000 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds: 2,564s

 time openssl enc -aes256 -e -pbkdf2 -iter 262144 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
 Seconds:  2,775s

Not really any difference, didn't check memory usage though(?)

With today's GPUs, and even faster tomorrows, I guess billion brute-force iteration seems possible every seconds.

12 years ago a NVIDIA GeForce 8800 Ultra could iterate over 200.000 millions/sec iterations (MD5 hashing though)

source: Ainane-Barrett-Johnson-Vivar-OpenSSL.pdf

Find provisioning profile in Xcode 5

If it's sufficient to use the following criteria to locate the profile:

<key>Name</key>
<string>iOS Team Provisioning Profile: *</string>

you can scan the directory using awk. This one-liner will find the first file that contains the name starting with "iOS Team".

awk 'BEGIN{e=1;pat="<string>"tolower("iOS Team")}{cur=tolower($0);if(cur~pat &&prev~/<key>name<\/key>/){print FILENAME;e=0;exit};if($0!~/^\s*$/)prev=cur}END{exit e}' *

Here's a script that also returns the first match, but is easier to work with.

#!/bin/bash

if [ $# != 1 ] ; then
    echo Usage: $0 \<start of provisioning profile name\>
    exit 1
fi

read -d '' script << 'EOF'
BEGIN {
    e = 1
    pat = "<string>"tolower(prov)
}
{
    cur = tolower($0)
    if (cur ~ pat && prev ~ /<key>name<\\/key>/) {
        print FILENAME
        e = 0
        exit
    }
    if ($0 !~ /^\s*$/) {
        prev = cur
    }
}
END {
 exit e
}
EOF


awk -v "prov=$1" "$script" *

It can be called from within the profiles directory, $HOME/Library/MobileDevice/Provisioning Profiles:

~/findprov "iOS Team"

To use the script, save it to a suitable location and remember to set the executable mode; e.g., chmod ugo+x

Apache is downloading php files instead of displaying them

I had this problem. It turned out that I had both nginx and apache installed and automatically starting on boot. The problem was that nginx was binding to the http port first which prevented apache from starting.

Adding external library into Qt Creator project

I would like to add for the sake of completeness that you can also add just the LIBRARY PATH where it will look for a dependent library (which may not be directly referenced in your code but a library you use may need it).

For comparison, this would correspond to what LIBPATH environment does but its kind of obscure in Qt Creator and not well documented.

The way i came around this is following:

LIBS += -L"$$_PRO_FILE_PWD_/Path_to_Psapi_lib/"

Essentially if you don't provide the actual library name, it adds the path to where it will search dependent libraries. The difference in syntax is small but this is very useful to supply just the PATH where to look for dependent libraries. It sometime is just a pain to supply each path individual library where you know they are all in certain folder and Qt Creator will pick them up.

UPDATE with CASE and IN - Oracle

Use to_number to convert budgpost to a number:

when to_number(budgpost,99999) in (1001,1012,50055) THEN 'BP_GR_A' 

EDIT: Make sure there are enough 9's in to_number to match to largest budget post.

If there are non-numeric budget posts, you could filter them out with a where clause at then end of the query:

where regexp_like(budgpost, '^-?[[:digit:],.]+$')

Clear contents of cells in VBA using column reference

You need a With statement prior to this. Or make the .Cells into Cells

How to create a file in Android?

I used the following code to create a temporary file for writing bytes. And its working fine.

File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
     OutputStream fo = new FileOutputStream(file);              
     fo.write(data1);
     fo.close();
     System.out.println("file created: "+file);
}               

//deleting the file             
file.delete();
System.out.println("file deleted");

Managing large binary files with Git

Have a look at camlistore. It is not really Git-based, but I find it more appropriate for what you have to do.

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

How to align checkboxes and their labels consistently cross-browsers

Maybe some folk are making the same mistake I did? Which was... I had set a width for the input boxes, because they were mostly of type 'text' , but then forgotten to over-ride that width for checkboxes - so my checkbox was trying to occupy a lot of excess width and so it was tough to align a label beside it.

.checkboxlabel {
    width: 100%;
    vertical-align: middle;
}
.checkbox {
    width: 20px !important;
}
<label for='acheckbox' class='checkboxlabel'>
    <input name="acheckbox" id='acheckbox' type="checkbox" class='checkbox'>Contact me</label>

Gives clickable labels and and proper alignment as far back as IE6 (using a class selector) and in late versions of Firefox, Safari and Chrome

How do I download a tarball from GitHub using cURL?

with a specific dir:

cd your_dir && curl -L https://download.calibre-ebook.com/3.19.0/calibre-3.19.0-x86_64.txz | tar zx

String to decimal conversion: dot separation instead of comma

    usCulture = new CultureInfo("vi-VN");
Thread.CurrentThread.CurrentCulture = usCulture;
Thread.CurrentThread.CurrentUICulture = usCulture;
usCulture = Thread.CurrentThread.CurrentCulture;
dbNumberFormat = usCulture.NumberFormat;
number = decimal.Parse("1.332,23", dbNumberFormat); //123.456.789,00

usCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = usCulture;
Thread.CurrentThread.CurrentUICulture = usCulture;
usCulture = Thread.CurrentThread.CurrentCulture;
dbNumberFormat = usCulture.NumberFormat;
number = decimal.Parse("1,332.23", dbNumberFormat); //123.456.789,00

/*Decision*/
var usCulture = Thread.CurrentThread.CurrentCulture;
var dbNumberFormat = usCulture.NumberFormat;
decimal number;
decimal.TryParse("1,332.23", dbNumberFormat, out number); //123.456.789,00

How to remove last n characters from every element in the R vector

The same may be achieved with the stringi package:

library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap"   "b" 

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

I solved it with my own function. If you want to update specified field in document you need to address it clearly.

Example:

{
    _id : ...,
    some_key: { 
        param1 : "val1",
        param2 : "val2",
        param3 : "val3"
    }
}

If you want to update param2 only, it's wrong to do:

db.collection.update(  { _id:...} , { $set: { some_key : new_info  } }  //WRONG

You must use:

db.collection.update(  { _id:...} , { $set: { some_key.param2 : new_info  } } 

So i wrote a function something like that:

function _update($id, $data, $options=array()){

    $temp = array();
    foreach($data as $key => $value)
    {
        $temp["some_key.".$key] = $value;
    } 

    $collection->update(
        array('_id' => $id),
        array('$set' => $temp)
    );

}

_update('1', array('param2' => 'some data'));

(How) can I count the items in an enum?

There's not really a good way to do this, usually you see an extra item in the enum, i.e.

enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};

So then you can do:

int fuz[FOOBAR_NR_ITEMS];

Still not very nice though.

But of course you do realize that just the number of items in an enum is not safe, given e.g.

enum foobar {foo, bar = 5, baz, quz = 20};

the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.

edit: as requested, made the special entry stick out more.

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

https://help.eclipse.org/2019-09/index.jsp?nav=%2F1

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

Linux/Unix command to determine if process is running?

Just a minor addition: if you add the -c flag to ps, you don't need to remove the line containing the grep process with grep -v afterwards. I.e.

ps acux | grep cron

is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u away if you need less information.

On a system where the genetics of the native ps command point back to SysV, you'd use

ps -e |grep cron

or

ps -el |grep cron 

for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...> option.

Algorithm to compare two images

I believe if you're willing to apply the approach to every possible orientation and to negative versions, a good start to image recognition (with good reliability) is to use eigenfaces: http://en.wikipedia.org/wiki/Eigenface

Another idea would be to transform both images into vectors of their components. A good way to do this is to create a vector that operates in x*y dimensions (x being the width of your image and y being the height), with the value for each dimension applying to the (x,y) pixel value. Then run a variant of K-Nearest Neighbours with two categories: match and no match. If it's sufficiently close to the original image it will fit in the match category, if not then it won't.

K Nearest Neighbours(KNN) can be found here, there are other good explanations of it on the web too: http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm

The benefits of KNN is that the more variants you're comparing to the original image, the more accurate the algorithm becomes. The downside is you need a catalogue of images to train the system first.

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

This problem exists when you upgrade from one version to another.because jdk is not automatically upgraded.

For the same you can change the environmental varibles. In system variables look for the PATH and add the jdk bin location in the front of the string(not at the back). Once you have done that check in CMD if "java" and "javac" works. if it works, again go to system variables. add "CLASSPATH" A the variable and set value " . c:\Program Files\Java\jdk1.8.0_91\lib;"

Uncaught ReferenceError: $ is not defined error in jQuery

Change the order you're including your scripts (jQuery first):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
    src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>

What should be the sizeof(int) on a 64-bit machine?

Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but not necessarily size of int.

How can I add an element after another element?

try using the after() method:

$('#bla').after('<div id="space"></div>');

Documentation

Select method in List<t> Collection

Try this:

using System.Data.Linq;
var result = from i in list
             where i.age > 45
             select i;

Using lambda expression please use this Statement:

var result = list.where(i => i.age > 45);

Converting NSData to NSString in Objective c

Unsure of data's encoding type? No problem!

Without need to know potential encoding types, in which wrong encoding types will give you nil/null, this should cover all your bases:

NSString *dataString = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];

Done!




Note: In the event this somehow fails, you can unpack your NSData with NSKeyedUnarchiver , then repack the (id)unpacked again via NSKeyedArchiver, and that NSData form should be base64 encodeable.

id unpacked = [NSKeyedUnarchiver unarchiveObjectWithData:data];
data = [NSKeyedArchiver archivedDataWithRootObject:unpacked];

Selecting a row in DataGridView programmatically

 <GridViewName>.ClearSelection(); ----------------------------------------------------1
 foreach(var item in itemList) -------------------------------------------------------2
 {
    rowHandle =<GridViewName>.LocateByValue("UniqueProperty_Name", item.unique_id );--3
    if (rowHandle != GridControl.InvalidRowHandle)------------------------------------4
    {
        <GridViewName>.SelectRow(rowHandle);------------------------------------ -----5
    }
  }
  1. Clear all previous selection.
  2. Loop through rows needed to be selected in your grid.
  3. Get their row handles from grid (Note here grid is already updated with new rows)
  4. Checking if the row handle is valid or not.
  5. When valid row handle then select it.

Where itemList is list of rows to be selected in the grid view.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

I had these SQL behavior settings enabled on options query execution: ANSI SET IMPLICIT_TRANSACTIONS checked. On execution of your query e.g create, alter table or stored procedure, you have to COMMIT it.

Just type COMMIT and execute it F5

How to stop VBA code running?

This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).

As Microsoft states:

Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).

Here is an illustrative example:

Sub RunSomeMacros()

    Call FirstPart
    Call SecondPart

    'the below code will not be executed if user clicks yes during SecondPart.
    Call ThirdPart
    MsgBox "All of the macros have been run."

End Sub

Private Sub FirstPart()
    MsgBox "This is the first macro"

End Sub

Private Sub SecondPart()
    Dim answer As Long
    answer = MsgBox("Do you want to stop the macros?", vbYesNo)

    If answer = vbYes Then
        'Stops All macros!
        End
    End If

    MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub

Private Sub ThirdPart()
    MsgBox "Final Macro was run."
End Sub

Do AJAX requests retain PHP Session info?

put your session() auth in all server side pages accepting an ajax request:

if(require_once("auth.php")) {

//run json code

}

// do nothing otherwise

that's about the only way I've ever done it.

Is there a way to get a list of column names in sqlite?

As far as I can tell Sqlite doesn't support INFORMATION_SCHEMA. Instead it has sqlite_master.

I don't think you can get the list you want in just one command. You can get the information you need using sql or pragma, then use regex to split it into the format you need

SELECT sql FROM sqlite_master WHERE name='tablename';

gives you something like

CREATE TABLE tablename(
        col1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        col2 NVARCHAR(100) NOT NULL,
        col3 NVARCHAR(100) NOT NULL,
)

Or using pragma

PRAGMA table_info(tablename);

gives you something like

0|col1|INTEGER|1||1
1|col2|NVARCHAR(100)|1||0
2|col3|NVARCHAR(100)|1||0

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

Latex Remove Spaces Between Items in List

You could do something like this:

\documentclass{article}

\begin{document}

Normal:

\begin{itemize}
  \item foo
  \item bar
  \item baz
\end{itemize}

Less space:

\begin{itemize}
  \setlength{\itemsep}{1pt}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}
  \item foo
  \item bar
  \item baz
\end{itemize}

\end{document}

how to get files from <input type='file' .../> (Indirect) with javascript

Above answers are pretty sufficient. Additional to the onChange, if you upload a file using drag and drop events, you can get the file in drop event by accessing eventArgs.dataTransfer.files.

How to fix the height of a <div> element?

change the div to display block

.topbar{
    display:block;
    width:100%;
    height:70px;
    background-color:#475;
    overflow:scroll;
    }

i made a jsfiddle example here please check

http://jsfiddle.net/TgPRM/

How to get value of checked item from CheckedListBox?

I've already posted GetItemValue extension method in this post Get the value for a listbox item by index. This extension method will work for all ListControl classes including CheckedListBox, ListBox and ComboBox.


None of the existing answers are general enough, but there is a general solution for the problem.

In all cases, the underlying Value of an item should be calculated regarding to ValueMember, regardless of the type of data source.

The data source of the CheckedListBox may be a DataTable or it may be a list which contains objects, like a List<T>, so the items of a CheckedListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types.

GetItemValue Extension Method

We need a GetItemValue which works similar to GetItemText, but return an object, the underlying value of an item, regardless of the type of object you added as item.

We can create GetItemValue extension method to get item value which works like GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.

This method is applicable on ComboBox and CheckedListBox too.

jQuery Validate Plugin - Trigger validation of single field

If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.

Here is example

var validator = $("#form").data('validator');
if(validator.check('#element')){
    /*field is valid*/
}else{
    /*field is not valid (but no errors will be displayed)*/
}

How to remove space from string?

Since you're using bash, the fastest way would be:

shopt -s extglob # Allow extended globbing
var=" lakdjsf   lkadsjf "
echo "${var//+([[:space:]])/}"

It's fastest because it uses built-in functions instead of firing up extra processes.

However, if you want to do it in a POSIX-compliant way, use sed:

var=" lakdjsf   lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'

Concatenating string and integer in python

String formatting, using the new-style .format() method (with the defaults .format() provides):

 '{}{}'.format(s, i)

Or the older, but "still sticking around", %-formatting:

 '%s%d' %(s, i)

In both examples above there's no space between the two items concatenated. If space is needed, it can simply be added in the format strings.

These provide a lot of control and flexibility about how to concatenate items, the space between them etc. For details about format specifications see this.

Get time of specific timezone

before you get too excited this was written in 2011

if I were to do this these days I would use Intl.DateTimeFormat. Here is a link to give you an idea of what type of support this had in 2011

original answer now (very) outdated

Date.getTimezoneOffset()

The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.

For example, If your time zone is GMT+2, -120 will be returned.

Note: This method is always used in conjunction with a Date object.

var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11

How to comment multiple lines with space or indent

  • You can customize every short cut operation according to your habbit.

Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

Go: panic: runtime error: invalid memory address or nil pointer dereference

According to the docs for func (*Client) Do:

"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.

When err is nil, resp always contains a non-nil resp.Body."

Then looking at this code:

res, err := client.Do(req)
defer res.Body.Close()

if err != nil {
    return nil, err
}

I'm guessing that err is not nil. You're accessing the .Close() method on res.Body before you check for the err.

The defer only defers the function call. The field and method are accessed immediately.


So instead, try checking the error immediately.

res, err := client.Do(req)

if err != nil {
    return nil, err
}
defer res.Body.Close()

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

Credit due to @Blorgbeard for sharing his script. I'll certainly bookmark it in case I need it.

Yes, you can "right click" on the table and script the CREATE TABLE script, but:

  • The a script will contain loads of cruft (interested in the extended properties anyone?)
  • If you have 200+ tables in your schema, it's going to take you half a day to script the lot by hand.

With this script converted into a stored procedure, and combined with a wrapper script you would have a nice automated way to dump your table design into source control etc.

The rest of your DB code (SP's, FK indexes, Triggers etc) would be under source control anyway ;)

Visual Studio 2017 errors on standard headers

If anyone's still stuck on this, the easiest solution I found was to "Retarget Solution". In my case, the project was built of SDK 8.1, upgrading to VS2017 brought with it SDK 10.0.xxx.

To retarget solution: Project->Retarget Solution->"Select whichever SDK you have installed"->OK

From there on you can simply build/debug your solution. Hope it helps

enter image description here

How to resize image (Bitmap) to a given size?

 Bitmap yourBitmap;
 Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

or:

 resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

PHP json_encode json_decode UTF-8

Work for me :)

function jsonEncodeArray( $array ){
    array_walk_recursive( $array, function(&$item) { 
       $item = utf8_encode( $item ); 
    });
    return json_encode( $array );
}

Convert NSDate to String in iOS Swift

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

Event for Handling the Focus of the EditText

Here is the focus listener example.

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
        }
    }
});

Query based on multiple where clauses in Firebase

var ref = new Firebase('https://your.firebaseio.com/');

Query query = ref.orderByChild('genre').equalTo('comedy');
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
            Movie movie = dataSnapshot.getValue(Movie.class);
            if (movie.getLead().equals('Jack Nicholson')) {
                console.log(movieSnapshot.getKey());
            }
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

Spring boot Security Disable security

You need to add this entry to application.properties to bypass Springboot Default Security

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

Then there won't be any authentication box. otrws, credentials are:- user and 99b962fa-1848-4201-ae67-580bdeae87e9 (password randomly generated)

Note: my springBootVersion = '1.5.14.RELEASE'

How to create a number picker dialog?

Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:

Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);

How to show text on image when hovering?

This is what I use to make the text appear on hover:

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
div {_x000D_
  position: relative;_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border-radius: 50%;_x000D_
  overflow: hidden;_x000D_
  text-align: center_x000D_
}_x000D_
_x000D_
img {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: absolute;_x000D_
  border-radius: 50%_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
  opacity: 0;_x000D_
  transition:opacity 2s;_x000D_
}_x000D_
_x000D_
heading {_x000D_
  line-height: 40px;_x000D_
  font-weight: bold;_x000D_
  font-family: "Trebuchet MS";_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  display: block_x000D_
}_x000D_
_x000D_
div p {_x000D_
  z-index: -1;_x000D_
  width: 420px;_x000D_
  line-height: 20px;_x000D_
  display: inline-block;_x000D_
  padding: 200px 0px;_x000D_
  vertical-align: middle;_x000D_
  font-family: "Trebuchet MS";_x000D_
  height: 450px_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://68.media.tumblr.com/20b34e8d12d4230f9b362d7feb148c57/tumblr_oiwytz4dh41tf8vylo1_1280.png">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing <br>elit. Reiciendis temporibus iure dolores aspernatur excepturi <br> corporis nihil in suscipit, repudiandae. Totam._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_