Programs & Examples On #Downtime

Service Temporarily Unavailable Magento?

In Magento 2 You have to remove file located in /var/.maintenance.flag - just realized that after some searching, so i shall share.

How to finish current activity in Android

I found many answers but not one is simple... I hope this will help you...

try{
    Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
    startActivity(intent);
} finally {
    finish();
}

so, Very simple logic is here, as we know that in java we write code that has some chances of exception in a try block and handle that exception in catch block but in finally block we write code that has to be executed in any cost (Either the exception comes or not).

Best way to copy a database (SQL Server 2008)

Easiest way is actually a script.

Run this on production:

USE MASTER;

BACKUP DATABASE [MyDatabase]
TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder. 
WITH COPY_ONLY

This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.

To restore, just run this on your dev or test SQL Server:

USE MASTER;

RESTORE DATABASE [MyDatabase]
FROM DISK = 'C:\temp\MyDatabase1.bak'
WITH
MOVE 'MyDatabase'   TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log'   TO 'C:\Sql\MyDatabase_log.ldf',
REPLACE, RECOVERY

Then save these scripts on each server. One-click convenience.

Edit:
if you get an error when restoring that the logical names don't match, you can get them like this:

RESTORE FILELISTONLY
FROM disk = 'C:\temp\MyDatabaseName1.bak'

If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):

use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';

How to get an Android WakeLock to work?

Add permission in AndroidManifest.xml, as given below

<uses-permission android:name="android.permission.WAKE_LOCK" />

preferably BEFORE your <application> declaration tags but AFTER the <manifest> tags, afterwards, try making your onCreate() method contain only the WakeLock instantiation.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
}

and then in your onResume() method place

@Override
public void onResume() {
   mWakeLock.aquire();
}

and in your onFinish() method place

@Override
public void onFinish() {
   mWakeLock.release();
}

Change the URL in the browser without loading the new page using JavaScript

With HTML 5, use the history.pushState function. As an example:

<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
   history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>

and a href:

<a href="#" id='click'>Click to change url to bar.html</a>

If you want to change the URL without adding an entry to the back button list, use history.replaceState instead.

How to use the PRINT statement to track execution as stored procedure is running?

I'm sure you can use RAISERROR ... WITH NOWAIT

If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

How to split one text file into multiple *.txt files?

Regardless to what is said above, on my ubuntu 16 i had to do :

> split -b 10M -d  system.log system_split.log 

Please note the space between -b and the value

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

UML diagram shapes missing on Visio 2013

If you are looking for UML sequence diagrams, try searching for UML Sequence in the search box and add them.

  • Search for UML Sequence in the search box -> Select all shapes and add to My shapes (user defined name).

You can either browse through My shapes to access them. They will be available in the in the sidebar nevertheless once you search.

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

The error message is fairly self-explanatory

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

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

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

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

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

HTML5 Canvas vs. SVG vs. div

I agree with Simon Sarris's conclusions:

I have compared some visualization in Protovis (SVG) to Processingjs (Canvas) which display > 2000 points and processingjs is much faster than protovis.

Handling events with SVG is of course much easer because you can attach them to the objects. In Canvas you have to do it manually (check mouse position, etc) but for simple interaction it shouldn't be hard.

There is also the dojo.gfx library of the dojo toolkit. It provides an abstraction layer and you can specify the renderer (SVG, Canvas, Silverlight). That might be also an viable choice although I don't know how much overhead the additional abstraction layer adds but it makes it easy to code interactions and animations and is renderer-agnostic.

Here are some interesting benchmarks:

build-impl.xml:1031: The module has not been deployed

may its so late but the response useful for others so : Sometimes, when you don't specify a server or servlet container at the creation of the project, NetBeans fails to create a context.xml file.

  1. In your project under Web Pages, create a folder called META-INF.

Do this by right mouse button clicking on Web pages, and select:

New->Other->Other->File Folder

Name the folder META-INF. Case is important, even on Windows.

  1. Create a file called context.xml in the META-INF folder.

Do this by right mouse button clicking on the new META-INF folder, and select:

New->Other->XML->XML Document

Name it context (NetBeans adds the .xml) Select Well-formed Document Press Finish

  1. Edit the new document (context.xml), and add the following:

    <?xml version="1.0" encoding="UTF-8"?> 
    <Context antiJARLocking="true" path="/app-name"/> 
    

Replace app-name with the name of your application.

Now your in-place deployment should work. If not, make sure that the file can be read by everyone.

The context.xml file is specific to Tomcat. For more information about that file, see the Tomcat documentation at tomcat.apache.org.

Find integer index of rows with NaN in pandas dataframe

I was looking for all indexes of rows with NaN values.
My working solution:

def get_nan_indexes(data_frame):
    indexes = []
    print(data_frame)
    for column in data_frame:
        index = data_frame[column].index[data_frame[column].apply(np.isnan)]
        if len(index):
            indexes.append(index[0])
    df_index = data_frame.index.values.tolist()
    return [df_index.index(i) for i in set(indexes)]

Read files from a Folder present in project

This was helpful for me, if you use the

var dir = Directory.GetCurrentDirectory()

the path fill be beyond the current folder, it will incluide this path \bin\debug What I recommend you, is that you can use the

string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName

then print the dir value and verify the path is giving you

Why do we need to use flatMap?

flatMap transform the items emitted by an Observable into new Observables, then flattens the emissions from those into a single Observable.

Check out the scenario below where get("posts") returns an Observable that is "flattened" by flatMap.

myObservable.map(e => get("posts")).subscribe(o => console.log(o));
// this would log Observable objects to console.  

myObservable.flatMap(e => get("posts")).subscribe(o => console.log(o));
// this would log posts to console.

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

How to generate access token using refresh token through google drive API?

All you need to do is a post request like below :-

POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json

{
  "client_id": <client_id>,
  "client_secret": <client_secret>,
  "refresh_token": <refresh_token>,
  "grant_type": "refresh_token"
}

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

How to output only captured groups with sed?

Try

sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

I got this under cygwin:

$ (echo "asdf"; \
   echo "1234"; \
   echo "asdf1234adsf1234asdf"; \
   echo "1m2m3m4m5m6m7m8m9m0m1m2m3m4m5m6m7m8m9") | \
  sed -n -e "/[0-9]/s/^[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\)[^0-9]*\([0-9]*\).*$/\1 \2 \3 \4 \5 \6 \7 \8 \9/p"

1234
1234 1234
1 2 3 4 5 6 7 8 9
$

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Run a .bat file using python code

Probably the simplest way to do this is ->

import os
os.chdir("X:\Enter location of .bat file")
os.startfile("ask.bat")

How to expand 'select' option width after the user wants to select an option

Sample

function PopulateDropdown() {
    $.ajax({
        type: "POST",
        url: "../CommonWebService.asmx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("select[id^='MyDropDown']").empty();
            $.each(msg.d, function () {
                $("select[id^='MyDropDownSelect']").append($("<option></option>").val(this['IdIndexDataType']).html(this['DataTypeName']));
            }); 
            $("select[id^='MyDropDown']").css("width", "auto");  
        },
        error: function (e1) {
            alert("Error - " + e1.toString());
        }
    });
}

The below code will solve your problem of dropdownlist width by adding this code after insertion of Data to dropdownlist.

$("select[id^='MyDropDown']").css("width", "auto");

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

Android Lint contentDescription warning

Since I need the ImageView to add an icon just for aesthetics I've added tools:ignore="ContentDescription" within each ImageView I had in my xml file.

I'm no longer getting any error messages

How to check if a character in a string is a digit or letter

You could use:

    if (Character.isLetter(character.charAt(0))){
    ....

Align labels in form next to input

Answered a question such as this before, you can take a look at the results here:

Creating form to have fields and text next to each other - what is the semantic way to do it?

So to apply the same rules to your fiddle you can use display:inline-block to display your label and input groups side by side, like so:

CSS

input {
    margin-top: 5px;
    margin-bottom: 5px;
    display:inline-block;
    *display: inline;     /* for IE7*/
    zoom:1;              /* for IE7*/
    vertical-align:middle;
    margin-left:20px
}

label {
    display:inline-block;
    *display: inline;     /* for IE7*/
    zoom:1;              /* for IE7*/
    float: left;
    padding-top: 5px;
    text-align: right;
    width: 140px;
}

updated fiddle

What is the difference between a definition and a declaration?

From the C++ standard section 3.1:

A declaration introduces names into a translation unit or redeclares names introduced by previous declarations. A declaration specifies the interpretation and attributes of these names.

The next paragraph states (emphasis mine) that a declaration is a definition unless...

... it declares a function without specifying the function’s body:

void sqrt(double);  // declares sqrt

... it declares a static member within a class definition:

struct X
{
    int a;         // defines a
    static int b;  // declares b
};

... it declares a class name:

class Y;

... it contains the extern keyword without an initializer or function body:

extern const int i = 0;  // defines i
extern int j;  // declares j
extern "C"
{
    void foo();  // declares foo
}

... or is a typedef or using statement.

typedef long LONG_32;  // declares LONG_32
using namespace std;   // declares std

Now for the big reason why it's important to understand the difference between a declaration and definition: the One Definition Rule. From section 3.2.1 of the C++ standard:

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

Groovy String to Date

Date#parse is deprecated . The alternative is :

java.text.DateFormat#parse 

thereFore :

 new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)

Note that SimpleDateFormat is an implementation of DateFormat

How to generate components in a specific folder with Angular CLI?

Use 'ng generate component ./target_directory/Component_Name'

How to perform a real time search and filter on a HTML table

Datatable JS plugin is also one good alternate to accomedate search feature for html table

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on( 'keyup', function () {
    table.search( this.value ).draw();
} );

https://datatables.net/examples/basic_init/zero_configuration.html

How to declare an array of objects in C#

With LINQ, you can transform the array of uninitialized elements into the new collection of created objects with one line of code.

var houses = new GameObject[200].Select(h => new GameObject()).ToArray();

Actually, you can use any other source for this, even generated sequence of integers:

var houses = Enumerable.Repeat(0, 200).Select(h => new GameObject()).ToArray();

However, the first case seems to me more readable, although the type of original sequence is not important.

How to replace all dots in a string using JavaScript

Simplest way

"Mr.".split('.').join("");

..............

Console

enter image description here

grep using a character vector with multiple patterns

Not sure whether this answer has already appeared...

For the particular pattern in the question, you can just do it with a single grep() call,

grep("A[169]", myfile$Letter)

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I hope this will help somebody, I solved the problem like this

There was a problem because the database was not open. Command startup opens the database.

This you can solve with command alter database open in some case with alter database open resetlogs

$ sqlplus / sysdba

SQL> startup
ORACLE instance started.

Total System Global Area 1073741824 bytes
Fixed Size          8628936 bytes
Variable Size         624952632 bytes
Database Buffers      436207616 bytes
Redo Buffers            3952640 bytes
Database mounted.
Database opened.

SQL> conn user/pass123
Connected.

Detecting when user scrolls to bottom of div with jQuery

Here's another version.

The key code is function scroller() which takes input as the height of the div containing the scrolling section, using overflow:scroll. It approximates 5px from the top or 10px from the bottom as at the top or bottom. Otherwise it's too sensitive. It seems 10px is about the minimum. You'll see it adds 10 to the div height to get the bottom height. I assume 5px might work, I didn't test extensively. YMMV. scrollHeight returns the height of the inner scrolling area, not the displayed height of the div, which in this case is 400px.

<?php

$scrolling_area_height=400;
echo '
<script type="text/javascript">
          function scroller(ourheight) {
            var ourtop=document.getElementById(\'scrolling_area\').scrollTop;
            if (ourtop > (ourheight-\''.($scrolling_area_height+10).'\')) {
                alert(\'at the bottom; ourtop:\'+ourtop+\' ourheight:\'+ourheight);
            }
            if (ourtop <= (5)) {
                alert(\'Reached the top\');
            }
          }
</script>

<style type="text/css">
.scroller { 
            display:block;
            float:left;
            top:10px;
            left:10px;
            height:'.$scrolling_area_height.';
            border:1px solid red;
            width:200px;
            overflow:scroll; 
        }
</style>

$content="your content here";

<div id="scrolling_area" class="scroller">
onscroll="var ourheight=document.getElementById(\'scrolling_area\').scrollHeight;
        scroller(ourheight);"
        >'.$content.'
</div>';

?>

How to remove tab indent from several lines in IDLE?

If you're using IDLE, you can use Ctrl+] to indent and Ctrl+[ to unindent.

Javascript/DOM: How to remove all events of a DOM object?

One method is to add a new event listener that calls e.stopImmediatePropagation().

How can I see the entire HTTP request that's being sent by my Python application?

If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.

import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

remove url parameters with javascript or jquery

No splits.. :) The correct/foolproof way is to let the native browser BUILT-IN functions do the heavy lifting using urlParams, the heavy lifting is done for you.

//summary answer - this one line will correctly replace in all current browsers
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// 1 Get your URL 
let url = new URL('https://tykt.org?unicorn=1&printer=2&scanner=3');
console.log("URL: "+ url.toString());

// 2 get your params
let params = new URLSearchParams(url.search);
console.log("querys: " + params.toString());

// 3 Delete the printer param, Query string is now gone
params.delete('printer'); 
console.log("Printer Removed: " + params.toString()); 

// BELOW = Add it back to the URL, DONE!
___________

NOW Putting it all together in your live browser

// Above is a breakdown of how to get your params
// 4 then you simply replace those in your current browser!! 
window.history.replaceState({}, '', `${location.pathname}?${params}`);

Sample working Javascript Fiddle here working sample code to replace query substring and query params

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

Build fat static library (device + simulator) using Xcode and SDK 4+

I have spent many hours trying to build a fat static library that will work on armv7, armv7s, and the simulator. Finally found a solution.

The gist is to build the two libraries (one for the device and then one for the simulator) separately, rename them to distinguish from each other, and then lipo -create them into one library.

lipo -create libPhone.a libSimulator.a -output libUniversal.a

I tried it and it works!

Center Oversized Image in Div

This is an old Q, but a modern solution without flexbox or position absolute works like this.

margin-left: 50%;
transform: translateX(-50%);

_x000D_
_x000D_
.outer {_x000D_
  border: 1px solid green;_x000D_
  margin: 20px auto;_x000D_
  width: 20%;_x000D_
  padding: 10px 0;_x000D_
  /*   overflow: hidden; */_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  width: 150%;_x000D_
  background-color: gold;_x000D_
  /* Set left edge of inner element to 50% of the parent element */_x000D_
  margin-left: 50%; _x000D_
  /* Move to the left by 50% of own width */_x000D_
  transform: translateX(-50%); _x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parent element, while the transform will be 50% relative to the same element.

We have this situation before we add the CSS

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       +-----------------------------------------------------------+
       | Element E                                                 |
       +-----------------------------------------------------------+
       |                                           |
       +-------------------------------------------+

With the added style margin-left: 50% we have

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       |                     +-----------------------------------------------------------+
       |                     | Element E                                                 |
       |                     +-----------------------------------------------------------+
       |                     |                     |
       +---------------------|---------------------+
       |========= a ========>|

       a is 50% width of P

And the transform: translateX(-50%) shifts back to the left

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
+-----------------------------------------------------------+
| Element E                 |                               |
+-----------------------------------------------------------+
|<============ b ===========|                      |
       |                    |                      |
       +--------------------|----------------------+
       |========= a =======>|

       a is 50% width of P
       b is 50% width of E

Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left and margin-right, but also margin-top and margin-bottom are calculated with respect to width.

Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d

How to shrink/purge ibdata1 file in MySQL

Adding to John P's answer,

For a linux system, steps 1-6 can be accomplished with these commands:

  1. mysqldump -u [username] -p[root_password] [database_name] > dumpfilename.sql
  2. mysqladmin -u [username] -p[root_password] drop [database_name]
  3. sudo /etc/init.d/mysqld stop
  4. sudo rm /var/lib/mysql/ibdata1
    sudo rm /var/lib/mysql/ib_logfile*
  5. sudo /etc/init.d/mysqld start
  6. mysqladmin -u [username] -p[root_password] create [database_name]
  7. mysql -u [username] -p[root_password] [database_name] < dumpfilename.sql

Warning: these instructions will cause you to lose other databases if you have other databases on this mysql instance. Make sure that steps 1,2 and 6,7 are modified to cover all databases you wish to keep.

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

I think I have an idea. This has been doing my nut in too and I'm still having trouble getting it to display in Chrome.

Save document(name.docx) in word as single file webpage (name.mht) In your html use

<iframe src= "name.mht" width="100%" height="800"> </iframe>

Alter the heights and widths as you see fit.

Which is a better way to check if an array has more than one element?

Obviously using count($arr) > 1 (sizeof is just an alias for count) is the best solution. Depending on the structure of your array, there might be tons of elements but no $array['1'] element.

jQuery first child of "this"

element.children().first();

Find all children and get first of them.

LINQ equivalent of foreach for IEnumerable<T>

Now we have the option of...

        ParallelOptions parallelOptions = new ParallelOptions();
        parallelOptions.MaxDegreeOfParallelism = 4;
#if DEBUG
        parallelOptions.MaxDegreeOfParallelism = 1;
#endif
        Parallel.ForEach(bookIdList, parallelOptions, bookID => UpdateStockCount(bookID));

Of course, this opens up a whole new can of threadworms.

ps (Sorry about the fonts, it's what the system decided)

jQuery: checking if the value of a field is null (empty)

The value of a field can not be null, it's always a string value.

The code will check if the string value is the string "NULL". You want to check if it's an empty string instead:

if ($('#person_data[document_type]').val() != ''){}

or:

if ($('#person_data[document_type]').val().length != 0){}

If you want to check if the element exist at all, you should do that before calling val:

var $d = $('#person_data[document_type]');
if ($d.length != 0) {
  if ($d.val().length != 0 ) {...}
}

Scheduling Python Script to run every hour accurately

the simplest option I can suggest is using the schedule library.

In your question, you said "I will need to run a function once every hour" the code to do this is very simple:

    import schedule

    def thing_you_wanna_do():
        ...
        ...
        return


    schedule.every().hour.do(thing_you_wanna_do)

    while True:
        schedule.run_pending()

you also asked how to do something at a certain time of the day some examples of how to do this are:

    import schedule


    def thing_you_wanna_do():
        ...
        ...
        return


    schedule.every().day.at("10:30").do(thing_you_wanna_do)
    schedule.every().monday.do(thing_you_wanna_do)
    schedule.every().wednesday.at("13:15").do(thing_you_wanna_do)
    # If you would like some randomness / variation you could also do something like this
    schedule.every(1).to(2).hours.do(thing_you_wanna_do)

    while True:
        schedule.run_pending()

90% of the code used is the example code of the schedule library. Happy scheduling!

How to detect scroll position of page using jQuery

$(window).scroll( function() { 
 var scrolled_val = $(document).scrollTop().valueOf();
 alert(scrolled_val+ ' = scroll value');
});

This is another way of getting the value of scroll.

"Continue" (to next iteration) on VBScript

One option would be to put all the code in the loop inside a Sub and then just return from that Sub when you want to "continue".

Not perfect, but I think it would be less confusing that the extra loop.

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

Getting first value from map in C++

You can use the iterator that is returned by the begin() method of the map template:

std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()

But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

If your project has Roslyn references and you are deploying it on an IIS server, you might get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn.

To resolve this issue, you will need to remove the Roslyn compiler from the project template. Removing Roslyn shouldn't affect your code's functionality. It worked fine for me and some other projects (C# 4.5.2) on which I worked.

Do the following steps:

  1. Remove from following Nuget Packages using command line shown below (or you can use GUI of Nuget Package manager by Right Clicking on Root Project Solution and removing them).

    PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
    PM> Uninstall-package Microsoft.Net.Compilers
    
  2. Remove the following code from your Web.Config file and restart IIS. (Use this method only if step 1 doesn't solve your problem.)

    <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
    

How to wrap text using CSS?

This will work everywhere.

<body>
  <table style="table-layout:fixed;">
  <tr>
    <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
  </tr>
  </table>
 </body>

JSON.parse unexpected character error

You're not parsing a string, you're parsing an already-parsed object :)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

Creating an instance using the class name and calling constructor

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

Case 1:- Here, is a small code in this Main class:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        // Get class name as string.
        String myClassName = Base.class.getName();
        // Create class of type Base.
        Class<?> myClass = Class.forName(myClassName);
        // Create constructor call with argument types.
        Constructor<?> ctr = myClass.getConstructor(String.class);
        // Finally create object of type Base and pass data to constructor.
        String arg1 = "My User Data";
        Object object = ctr.newInstance(new Object[] { arg1 });
        // Type-cast and access the data from class Base.
        Base base = (Base)object;
        System.out.println(base.data);
    }

}

And, here is the Base class structure:

public class Base {

    public String data = null;

    public Base() 
    {
        data = "default";
        System.out.println("Base()");
    }

    public Base(String arg1) {
        data = arg1;
        System.out.println("Base("+arg1+")");
    }

}

Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base constructor will need the constructor to be created in class and a code change in above as:

Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" }); 

And here the Base class should somehow look like:

public class Base {

    public Base(String a, String b, String c){
        // This constructor need to be created in this case.
    }   
}

Note:- Don't forget to handle the various exceptions which need to be handled in the code.

Show two digits after decimal point in c++

It is possible to print a 15 decimal number in C++ using the following:

#include <iomanip>
#include <iostream>

cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();

return 0;

Difference between web reference and service reference?

Another point to take in consideration is that the new UI for Service Interface will give you much more flexibility on how you want to create your proxy class. For example, it will allow you to map data contracts to existing dlls, if they match (actually this is the default behaviour).

How to get text from EditText?

If you are doing it before the setContentView() method call, then the values will be null.

This will result in null:

super.onCreate(savedInstanceState);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

setContentView(R.layout.main_contacts);

while this will work fine:

super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

How to get current timestamp in milliseconds since 1970 just the way Java gets

This answer is pretty similar to Oz.'s, using <chrono> for C++ -- I didn't grab it from Oz. though...

I picked up the original snippet at the bottom of this page, and slightly modified it to be a complete console app. I love using this lil' ol' thing. It's fantastic if you do a lot of scripting and need a reliable tool in Windows to get the epoch in actual milliseconds without resorting to using VB, or some less modern, less reader-friendly code.

#include <chrono>
#include <iostream>

int main() {
    unsigned __int64 now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
    std::cout << now << std::endl;
    return 0;
}

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

-Using application initalization feature -requesting wrong pages (.asp) because of config inheritance

500.21 will occur on the first user connection only. Subsequent connections work.

Resolved by correcting the applicationInitialization url collection on the .NET website.

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

I am adding few more understanding.

  1. Cursor is only about a statement objecct; It is neither resultSet nor the connection object.
  2. But still we have to close the resultset to free some oracle memory. Still if you don't close the resultset that won't be counted for CURSORS.
  3. Closing Statement object will automatically close resultset object too.
  4. Cursor will be created for all the SELECT/INSERT/UPDATE/DELETE statement.
  5. Each ORACLE DB instance can be identified using oracle SID; similarly ORACLE DB can identify each connection using connection SID. Both SID are different.
  6. So ORACLE session is nothing but a jdbc(tcp) connection; which is nothing but one SID.
  7. If we set maximum cursors as 500 then it is only for one JDBC session/connection/SID.
  8. So we can have many JDBC connection with its respective no of cursors (statements).
  9. Once the JVM is terminated all the connections/cursors will be closed, OR JDBCConnection is closed CURSORS with respect to that connection will be closed.

Loggin as sysdba.

In Putty (Oracle login):

  [oracle@db01 ~]$ sqlplus / as sysdba

In SqlPlus:

UserName: sys as sysdba

Set session_cached_cursors value to 0 so that it wont have closed cursors.

 alter session set session_cached_cursors=0
 select * from V$PARAMETER where name='session_cached_cursors'

Select existing OPEN_CURSORS valuse set per connection in DB

 SELECT max(a.value) as highest_open_cur, p.value as max_open_cur FROM v$sesstat a, v$statname b, v$parameter p WHERE a.statistic# = b.statistic# AND b.name = 'opened cursors current' AND p.name= 'open_cursors'  GROUP BY p.value;

Below is the query to find the SID/connections list with open cursor values.

 SELECT a.value, s.username, s.sid, s.serial#
 FROM v$sesstat a, v$statname b, v$session s
 WHERE a.statistic# = b.statistic#  AND s.sid=a.sid 
 AND b.name = 'opened cursors current' AND username = 'SCHEMA_NAME_IN_CAPS'

Use the below query to identify the sql's in the open cursors

 SELECT oc.sql_text, s.sid 
 FROM v$open_cursor oc, v$session s
 WHERE OC.sid = S.sid
 AND s.sid=1604
 AND OC.USER_NAME ='SCHEMA_NAME_IN_CAPS'

Now debug the Code and Enjoy!!! :)

How can I get log4j to delete old rotating log files?

There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.

Simple instructions found here

From 1:

If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.

Import existing Gradle Git project into Eclipse

You can do the following steps:

  1. Install the Buildship Gradle Integration using the Eclipse Marketplace. Simply type Buildship and click on search item. Now click on Install.

  2. Click on File -> Import ? Existing Gradle Project.

  3. Navigate to project root directory.

  4. Click on a finish to load your project.

Might be it will take some time for the first time to import Gradle project. So please be patient on it.

How to check whether a Button is clicked by using JavaScript

All the answers here discuss about onclick method, however you can also use addEventListener().

Syntax of addEventListener()

document.getElementById('button').addEventListener("click",{function defination});

The function defination above is known as anonymous function.

If you don't want to use anonymous functions you can also use function refrence.

function functionName(){
//function defination
}



document.getElementById('button').addEventListener("click",functionName);

You can check the detail differences between onclick() and addEventListener() in this answer here.

Font awesome is not showing icon

It's something to do with v5, some of the icons don't work with older versions.

This link worked for me!

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">

How do I declare a 2d array in C++ using new?

If your project is CLI (Common Language Runtime Support), then:

You can use the array class, not that one you get when you write:

#include <array>
using namespace std;

In other words, not the unmanaged array class you get when using the std namespace and when including the array header, not the unmanaged array class defined in the std namespace and in the array header, but the managed class array of the CLI.

with this class, you can create an array of any rank you want.

The following code below creates new two dimensional array of 2 rows and 3 columns and of type int, and I name it "arr":

array<int, 2>^ arr = gcnew array<int, 2>(2, 3);

Now you can access elements in the array, by name it and write only one squared parentheses [], and inside them, add the row and column, and separate them with the comma ,.

The following code below access an element in 2nd row and 1st column of the array I already created in previous code above:

arr[0, 1]

writing only this line is to read the value in that cell, i.e. get the value in this cell, but if you add the equal = sign, you are about to write the value in that cell, i.e. set the value in this cell. You also can use the +=, -=, *= and /= operators of course, for numbers only (int, float, double, __int16, __int32, __int64 and etc), but sure you know it already.

If your project is not CLI, then you can use the unmanaged array class of the std namespace, if you #include <array>, of course, but the problem is that this array class is different than the CLI array. Create array of this type is same like the CLI, except that you will have to remove the ^ sign and the gcnew keyword. But unfortunately the second int parameter in the <> parentheses specifies the length (i.e. size) of the array, not its rank!

There is no way to specify rank in this kind of array, rank is CLI array's feature only..

std array behaves like normal array in c++, that you define with pointer, for example int* and then: new int[size], or without pointer: int arr[size], but unlike the normal array of the c++, std array provides functions that you can use with the elements of the array, like fill, begin, end, size, and etc, but normal array provides nothing.

But still std array are one dimensional array, like the normal c++ arrays. But thanks to the solutions that the other guys suggest about how you can make the normal c++ one dimensional array to two dimensional array, we can adapt the same ideas to std array, e.g. according to Mehrdad Afshari's idea, we can write the following code:

array<array<int, 3>, 2> array2d = array<array<int, 3>, 2>();

This line of code creates a "jugged array", which is an one dimensional array that each of its cells is or points to another one dimensional array.

If all one dimensional arrays in one dimensional array are equal in their length/size, then you can treat the array2d variable as a real two dimensional array, plus you can use the special methods to treat rows or columns, depends on how you view it in mind, in the 2D array, that std array supports.

You also can use Kevin Loney's solution:

int *ary = new int[sizeX*sizeY];

// ary[i][j] is then rewritten as
ary[i*sizeY+j]

but if you use std array, the code must look different:

array<int, sizeX*sizeY> ary = array<int, sizeX*sizeY>();
ary.at(i*sizeY+j);

And still have the unique functions of the std array.

Note that you still can access the elements of the std array using the [] parentheses, and you don't have to call the at function. You also can define and assign new int variable that will calculate and keep the total number of elements in the std array, and use its value, instead of repeating sizeX*sizeY

You can define your own two dimensional array generic class, and define the constructor of the two dimensional array class to receive two integers to specify the number of rows and columns in the new two dimensional array, and define get function that receive two parameters of integer that access an element in the two dimensional array and returns its value, and set function that receives three parameters, that the two first are integers that specify the row and column in the two dimensional array, and the third parameter is the new value of the element. Its type depends on the type you chose in the generic class.

You will be able to implement all this by using either the normal c++ array (pointers or without) or the std array and use one of the ideas that other people suggested, and make it easy to use like the cli array, or like the two dimensional array that you can define, assign and use in C#.

How to execute a MySQL command from a shell script?

mysql_config_editor set --login-path=storedPasswordKey --host=localhost --user=root --password

How do I execute a command line with a secure password?? use the config editor!!!

As of mysql 5.6.6 you can store the password in a config file and then execute cli commands like this....

mysql --login-path=storedPasswordKey ....

--login-path replaces variables... host, user AND password. excellent right!

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

This is how you get rid of that notice and be able to open those grid cells for edit

1) click "STRUCTURE"

2) go to the field you want to be a primary key (and this usually is the 1st one ) and then click on the "PRIMARY" and "INDEX" fields for that field and accept the PHPMyadmin's pop-up question "OK".

3) pad yourself in the back.

Change background color on mouseover and remove it after mouseout

If you don't care about IE =6, you could use pure CSS ...

.forum:hover { background-color: #380606; }

_x000D_
_x000D_
.forum { color: white; }_x000D_
.forum:hover { background-color: #380606 !important; }_x000D_
/* we use !important here to override specificity. see http://stackoverflow.com/q/5805040/ */_x000D_
_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_


With jQuery, usually it is better to create a specific class for this style:

.forum_hover { background-color: #380606; }

and then apply the class on mouseover, and remove it on mouseout.

$('.forum').hover(function(){$(this).toggleClass('forum_hover');});

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('.forum').hover(function(){$(this).toggleClass('forum_hover');});_x000D_
});
_x000D_
.forum_hover { background-color: #380606 !important; }_x000D_
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_


If you must not modify the class, you could save the original background color in .data():

  $('.forum').data('bgcolor', '#380606').hover(function(){
    var $this = $(this);
    var newBgc = $this.data('bgcolor');
    $this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
  });

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('.forum').data('bgcolor', '#380606').hover(function(){_x000D_
    var $this = $(this);_x000D_
    var newBgc = $this.data('bgcolor');_x000D_
    $this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);_x000D_
  });_x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_

or

  $('.forum').hover(
    function(){
      var $this = $(this);
      $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
    },
    function(){
      var $this = $(this);
      $this.css('background-color', $this.data('bgcolor'));
    }
  );   

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('.forum').hover(_x000D_
    function(){_x000D_
      var $this = $(this);_x000D_
      $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');_x000D_
    },_x000D_
    function(){_x000D_
      var $this = $(this);_x000D_
      $this.css('background-color', $this.data('bgcolor'));_x000D_
    }_x000D_
  );    _x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
_x000D_
_x000D_

Start HTML5 video at a particular position when loading?

adjust video start and end time when using the video tag in html5;

http://www.yoursite.com/yourfolder/yourfile.mp4#t=5,15

where left of comma is start time in seconds, right of comma is end time in seconds. drop the comma and end time to effect the start time only.

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

Angular 2 http post params and body

And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

Where is SQLite database stored on disk?

There is no "standard place" for a sqlite database. The file's location is specified to the library, and may be in your home directory, in the invoking program's folder, or any other place.

If it helps, sqlite databases are, by convention, named with a .db file extension.

What programming language does facebook use?

might be surprised to know.. its PHP. read all about it here

What is the javascript filename naming convention?

One possible naming convention is to use something similar to the naming scheme jQuery uses. It's not universally adopted but it is pretty common.

product-name.plugin-ver.sion.filetype.js

where the product-name + plugin pair can also represent a namespace and a module. The version and filetype are usually optional.

filetype can be something relative to how the content of the file is. Often seen are:

  • min for minified files
  • custom for custom built or modified files

Examples:

  • jquery-1.4.2.min.js
  • jquery.plugin-0.1.js
  • myapp.invoice.js

Difference between margin and padding?

Padding is the space between you content and the border. Where as Margin is the space between the border and the other element.

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

[nodemon] Internal watch failed: watch /home/Document/nmmExpressServer/bin ENOSPC
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nodemon ./bin/www`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.

This is the error I got when running nodemon ./bin/www.

The solution was closing an Atom window that had a entire directory of folders open in the project window.

I don't know why, but I'm assuming Atom and nodemon use similar processes to watch files/folders.

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Write this in each "new activity" after you initialized your new intent->

Intent i = new Intent(this, yourClass.class);
startActivity(i);
finish();

how to get the attribute value of an xml node using java

try something like this :

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.

Case insensitive std::string.find()

I love the answers from Kiril V. Lyadvinsky and CC. but my problem was a little more specific than just case-insensitivity; I needed a lazy Unicode-supported command-line argument parser that could eliminate false-positives/negatives when dealing with alphanumeric string searches that could have special characters in the base string used to format alphanum keywords I was searching against, e.g., Wolfjäger shouldn't match jäger but <jäger> should.

It's basically just Kiril/CC's answer with extra handling for alphanumeric exact-length matches.

/* Undefined behavior when a non-alpha-num substring parameter is used. */
bool find_alphanum_string_CI(const std::wstring& baseString, const std::wstring& subString)
{
    /* Fail fast if the base string was smaller than what we're looking for */
    if (subString.length() > baseString.length()) 
        return false;

    auto it = std::search(
        baseString.begin(), baseString.end(), subString.begin(), subString.end(),
        [](char ch1, char ch2)
        {
            return std::toupper(ch1) == std::toupper(ch2);
        }
    );

    if(it == baseString.end())
        return false;

    size_t match_start_offset = it - baseString.begin();

    std::wstring match_start = baseString.substr(match_start_offset, std::wstring::npos);

    /* Typical special characters and whitespace to split the substring up. */
    size_t match_end_pos = match_start.find_first_of(L" ,<.>;:/?\'\"[{]}=+-_)(*&^%$#@!~`");

    /* Pass fast if the remainder of the base string where
       the match started is the same length as the substring. */
    if (match_end_pos == std::wstring::npos && match_start.length() == subString.length()) 
        return true;

    std::wstring extracted_match = match_start.substr(0, match_end_pos);

    return (extracted_match.length() == subString.length());
}

Why do you create a View in a database?

Here are two common reasons:

You can use it for security. Grant no permissions on the main table and create views that limits column or row access and grant permissions to users to see the view.

You can use use it for convenience. Join together some tables that you use together all the time in the view. This can make queries consistent and easier.

Laravel where on relationship object

I created a custom query scope in BaseModel (my all models extends this class):

/**
 * Add a relationship exists condition (BelongsTo).
 *
 * @param  Builder        $query
 * @param  string|Model   $relation   Relation string name or you can try pass directly model and method will try guess relationship
 * @param  mixed          $modelOrKey
 * @return Builder|static
 */
public function scopeWhereHasRelated(Builder $query, $relation, $modelOrKey = null)
{
    if ($relation instanceof Model && $modelOrKey === null) {
        $modelOrKey = $relation;
        $relation   = Str::camel(class_basename($relation));
    }

    return $query->whereHas($relation, static function (Builder $query) use ($modelOrKey) {
        return $query->whereKey($modelOrKey instanceof Model ? $modelOrKey->getKey() : $modelOrKey);
    });
}

You can use it in many contexts for example:

Event::whereHasRelated('participants', 1)->isNotEmpty(); // where has participant with id = 1 

Furthermore, you can try to omit relationship name and pass just model:

$participant = Participant::find(1);
Event::whereHasRelated($participant)->first(); // guess relationship based on class name and get id from model instance

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Best way to find if an item is in a JavaScript array?

A robust way to check if an object is an array in javascript is detailed here:

Here are two functions from the xa.js framework which I attach to a utils = {} ‘container’. These should help you properly detect arrays.

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     }
     if (utils.type(obj) === 'array') {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};

If you then want to check if an object is in an array, I would also include this code:

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

And finally this in_array function:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

How to make div go behind another div?

http://jsfiddle.net/f2znvn4f/


HTML

<div class="box-left-mini">
    <div class="front"><span>this is in front</span></div>
    <div class="behind_container">
        <div class="behind">behind</div>        
    </div>
</div>

CSS

.box-left-mini{
    float:left;
    background-image:url(website-content/hotcampaign.png);
    width:292px;
    height:141px;
}

.box-left-mini .front {
    display: block;
    z-index: 5;
    position: relative;
}
.box-left-mini .front span {
    background: #fff
}

.box-left-mini .behind_container {
    background-color: #ff0;
    position: relative;
    top: -18px;
}
.box-left-mini .behind {
    display: block;
    z-index: 3;
}

The reason you're getting so many different answers is because you've not explained what you want to do exactly. All the answers you get with code will be programmatically correct, but it's all down to what you want to achieve

Ripple effect on Android Lollipop CardView

Add the following to your xml:

android:clickable="true"
android:focusable="true"
android:background="?android:attr/selectableItemBackground"

And add to your adapter (if it's your case)

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val attrs = intArrayOf(R.attr.selectableItemBackground)
            val typedArray = holder.itemView.context.obtainStyledAttributes(attrs)
            val selectableItemBackground = typedArray.getResourceId(0, 0)
            typedArray.recycle()

            holder.itemView.isClickable = true
            holder.itemView.isFocusable = true
            holder.itemView.foreground = holder.itemView.context.getDrawable(selectableItemBackground)
        }
    }

Is background-color:none valid CSS?

.class {
    background-color:none;
}

This is not a valid property. W3C validator will display following error:

Value Error : background-color none is not a background-color value : none

transparent may have been selected as better term instead of 0 or none values during the development of specification of CSS.

How to check if a column exists before adding it to an existing table in PL/SQL?

Or, you can ignore the error:

declare
    column_exists exception;
    pragma exception_init (column_exists , -01430);
begin
    execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)';
    exception when column_exists then null;
end;
/

In Python script, how do I set PYTHONPATH?

You don't set PYTHONPATH, you add entries to sys.path. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.

sys.path.append('/path/to/whatever')

In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

You can also add directories using site.addsitedir, and that method will also take into account .pth files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH.)

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.

To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.

Edit: I've copied the steps below - kudos to the original author of the link above.

  1. Log on to the computer as an Administrator (or Any user with administrator privileges)
  2. Open "SQL Server Configuration Manager"
  3. Click "SQL Server Services" on the left pane
  4. Stop "SQL Server" and "SQL Server Agent" instance on the right pane if it is running
  5. Run the SQL Express in single-user mode by right clicking on "SQL Server" instance -> Properties (on the right pane of SQL Server Configuration Manager).
  6. Click Advanced Tab, and look for "Startup Parameters". Change the "Startup Parameters" so that the new value will be -m; (without the <>) example: from: -dc:\Program Files\Microsoft SQL.............(til end of string) to: -m;-dc:\Program Files\Microsoft SQL.............(til end of string)
  7. Start the SQL Server
  8. Open your MS SQL Server Management Studio and log on to the SQL server with "Windows Authentication" as the authentication mode. Since we have the SQL Server running on single user mode, and you are logged on to the computer with Administrator privileges, you will have a "sysadmin" access to the database.
  9. Expand the "Security" node on MS SQL Server Management Studio on the left pane
  10. Expand the "Logins" node
  11. Double-click the 'sa' login
  12. Change the password by entering a complex password if "Enforce password policy" is ticked, otherwise, just enter any password.
  13. Make sure that "sa" Account is "enabled" by clicking on Status on the left pane. Set the radio box under "Login" to "Enabled"
  14. Click "OK"
  15. Back on the main window of MS SQL Server Management Studio, verify if SQL Server Authentication is used by right clicking on the top most node in the left pane (usually ".\SQLEXPRESS (SQL Server )") and choosing properties.
  16. Click "Security" in the left pane and ensure that "SQL Server and Windows Authentication mode" is the one selected under "Server authentication"
  17. Click "OK"
  18. Disconnect from MS SQL Server Management Studio
  19. Open "Sql Server Configuration Manager" again and stop the SQL Server instance.
  20. Right-click on SQL Server instance and click on "Advanced" tab. Again look for "Startup Parameters" and remove the "-m;" that you added earlier.
  21. Click "OK" and start the SQL Server Instance again
  22. You should now be able to log on as "sa" using the new password that you have set in step 12.

Fragment transaction animation: slide in and slide out

slide_in_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="0%p"
        android:toYDelta="100%p" />
</set>

slide_in_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="100%p"
        android:toYDelta="0%p" />
</set>

slide_out_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="-100%"
        android:toYDelta="0"
        />
</set>

slide_out_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="0%p"
        android:toYDelta="-100%p"
        />
</set>

direction = down

            activity.getSupportFragmentManager()
                    .beginTransaction()
                    .setCustomAnimations(R.anim.slide_out_down, R.anim.slide_in_down)
                    .replace(R.id.container, new CardFrontFragment())
                    .commit();

direction = up

           activity.getSupportFragmentManager()
                    .beginTransaction()
                    .setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_up)
                    .replace(R.id.container, new CardFrontFragment())
                    .commit();

How do I center a window onscreen in C#?

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

Creating a BLOB from a Base64 string in JavaScript

For all copy-paste lovers out there like me, here is a cooked download function which works on Chrome, Firefox and Edge:

window.saveFile = function (bytesBase64, mimeType, fileName) {
var fileUrl = "data:" + mimeType + ";base64," + bytesBase64;
fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
        var link = window.document.createElement("a");
        link.href = window.URL.createObjectURL(blob, { type: mimeType });
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

How to add external fonts to android application

To implement you need use Typeface go through with sample below

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
   if (view instanceof TextView) 
   {
      TextView textView = (TextView) view;
      textView.setTypeface(typeface);
      }
   }
}

How to get a single value from FormGroup

You can do by the following ways

this.your_form.getRawValue()['formcontrolname]
this.your_form.value['formcontrolname]

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

How to convert .pfx file to keystore with private key?

jarsigner can use your pfx file as the keystore for signing your jar. Be sure that your pfx file has the private key and the cert chain when you export it. There is no need to convert to other formats. The trick is to obtain the Alias of your pfx file:

 keytool -list -storetype pkcs12 -keystore your_pfx_file -v | grep Alias

Once you have your alias, signing is easy

jarsigner.exe -storetype pkcs12 -keystore pfx_file jar_file "your alias"

The above two commands will prompt you for the password you specified at pfx export. If you want to have your password hang out in clear text use the -storepass switch before the -keystore switch

Once signed, admire your work:

jarsigner.exe -verify -verbose -certs  yourjarfile

Getting a File's MD5 Checksum in Java

Very fast & clean Java-method that doesn't rely on external libraries:

(Simply replace MD5 with SHA-1, SHA-256, SHA-384 or SHA-512 if you want those)

public String calcMD5() throws Exception{
        byte[] buffer = new byte[8192];
        MessageDigest md = MessageDigest.getInstance("MD5");

        DigestInputStream dis = new DigestInputStream(new FileInputStream(new File("Path to file")), md);
        try {
            while (dis.read(buffer) != -1);
        }finally{
            dis.close();
        }

        byte[] bytes = md.digest();

        // bytesToHex-method
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }

        return new String(hexChars);
}

iPhone UITextField - Change placeholder text color

For those using Monotouch (Xamarin.iOS), here's Adam's answer, translated to C#:

public class MyTextBox : UITextField
{
    public override void DrawPlaceholder(RectangleF rect)
    {
        UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
        new NSString(this.Placeholder).DrawString(rect, Font);
    }
}

return, return None, and no return at all?

In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)

GROUP BY having MAX date

There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.

How to select rows from a DataFrame based on column values

For selecting only specific columns out of multiple columns for a given value in Pandas:

select col_name1, col_name2 from table where column_name = some_value.

Options:

df.loc[df['column_name'] == some_value][[col_name1, col_name2]]

or

df.query['column_name' == 'some_value'][[col_name1, col_name2]]

How to debug in Android Studio using adb over WiFi

if adb command not found.

-----------------------------

Install homebrew

 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Install adb

brew install android-platform-tools

---------------------------

Connect the device now.

  • Enable USB debugging in the Android device
  • Enable Allow ADB debugging in charge only mode
  • Connect the device to the computer via a USB port.

Start using adb

adb devices

List of devices attached
DUM0219A21000314 device

the first item is device id.

adb -s <device id> tcpip 5555

adb -s DUM0219A21000314 tcpip 5555

restarting in TCP mode port: 5555

Find the local IP address of your Android device. You can find this information in the quick settings drop-down menu by pressing / long pressing the WiFi icon and then clicking on the WiFi network you are connected to.

adb connect <IP address>:5555
adb connect 192.168.2.2:5555

connected to 192.168.2.2:5555

Don't forget! Allow ADB debugging in charge only mode enabled before connecting the device

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Make Frequency Histogram for Factor Variables

It seems like you want barplot(prop.table(table(animals))):

enter image description here

However, this is not a histogram.

How can I display an image from a file in Jupyter Notebook?

This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)

from IPython.display import display
from PIL import Image


path="/path/to/image.jpg"
display(Image.open(path))

You may need to install PIL

in Anaconda this is done by typing

conda install pillow

How to select last two characters of a string

You can pass a negative index to .slice(). That will indicate an offset from the end of the set.

var member = "my name is Mate";

var last2 = member.slice(-2);

alert(last2); // "te"

What are database constraints?

Constraints are part of a database schema definition.

A constraint is usually associated with a table and is created with a CREATE CONSTRAINT or CREATE ASSERTION SQL statement.

They define certain properties that data in a database must comply with. They can apply to a column, a whole table, more than one table or an entire schema. A reliable database system ensures that constraints hold at all times (except possibly inside a transaction, for so called deferred constraints).

Common kinds of constraints are:

  • not null - each value in a column must not be NULL
  • unique - value(s) in specified column(s) must be unique for each row in a table
  • primary key - value(s) in specified column(s) must be unique for each row in a table and not be NULL; normally each table in a database should have a primary key - it is used to identify individual records
  • foreign key - value(s) in specified column(s) must reference an existing record in another table (via it's primary key or some other unique constraint)
  • check - an expression is specified, which must evaluate to true for constraint to be satisfied

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

How to make an image center (vertically & horizontally) inside a bigger div

another way is to create a table with valign, of course. This would work regardless of you knowing the div's height or not.

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

but you should always stick to just css whenever possible.

How to create user for a db in postgresql?

Create the user with a password :

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

Then grant the user rights on a specific database :

http://www.postgresql.org/docs/current/static/sql-grant.html

Example :

grant all privileges on database db_name to someuser;

how to set the default value to the drop down list control?

Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:

lstDepartment.ClearSelection();

foreach (var item in lstDepartment.Items) 
{
  if (item.Value == otherDropDownList.SelectedValue)
  {
    item.Selected = true;
  }
}

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

Read remote file with node.js (http.get)

function(url,callback){
    request(url).on('data',(data) => {
        try{
            var json = JSON.parse(data);    
        }
        catch(error){
            callback("");
        }
        callback(json);
    })
}

You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .

Win32Exception (0x80004005): The wait operation timed out

We encountered this error after an upgrade from 2008 to 2014 SQL Server where our some of our previous connection strings for local development had a Data Source=./ like this

        <add name="MyLocalDatabase" connectionString="Data Source=./;Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

Changing that from ./ to either (local) or localhost fixed the problem.

<add name="MyLocalDatabase" connectionString="Data Source=(local);Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

PRINT statement in T-SQL

I recently ran into this, and it ended up being because I had a convert statement on a null variable. Since that was causing errors, the entire print statement was rendering as null, and not printing at all.

Example - This will fail:

declare @myID int=null
print 'First Statement: ' + convert(varchar(4), @myID)

Example - This will print:

declare @myID int=null
print 'Second Statement: ' +  coalesce(Convert(varchar(4), @myID),'@myID is null')

Sorting dictionary keys in python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

How do I install a module globally using npm?

If you want to install a npm module globally, make sure to use the new -g flag, for example:

npm install forever -g

The general recommendations concerning npm module installation since 1.0rc (taken from blog.nodejs.org):

  • If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
  • If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.

I just recently used this recommendations and it went down pretty smoothly. I installed forever globally (since it is a command line tool) and all my application modules locally.

However, if you want to use some modules globally (i.e. express or mongodb), take this advice (also taken from blog.nodejs.org):

Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:

  • Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
  • Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.

The first option is the best in my opinion. Simple, clear, explicit. The second is really handy if you are going to re-use the same library in a bunch of different projects. (More on npm link in a future installment.)

I did not test one of those variations, but they seem to be pretty straightforward.

How to disable an input type=text?

If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly attribute (or disabled, if you want to remove it from the form submission as well) to the <input>, like this:

<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />

How to modify PATH for Homebrew?

Just run the following line in your favorite terminal application:

echo export PATH="/usr/local/bin:$PATH" >> ~/.bash_profile

Restart your terminal and run

brew doctor

the issue should be resolved

How to make zsh run as a login shell on Mac OS X (in iTerm)?

The command to change the shell at startup is chsh -s <path_to_shell>. The default shells in mac OS X are installed inside the bin directory so if you want to change to the default zsh then you would use the following

chsh -s /bin/zsh

If you're using different version of zsh then you might have to add that version to /etc/shells to avoid the nonstandard shell message. For example if you want home-brew's version of zsh then you have to add /usr/local/bin/zsh to the aforementioned file which you can do in one command sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" and then run

chsh -s /usr/local/bin/zsh

Or if you want to do the whole thing in one command just copy and paste this if you have zsh already installed

sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" && chsh -s /usr/local/bin/zsh

How do you change the text in the Titlebar in Windows Forms?

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

how to fix Cannot call sendRedirect() after the response has been committed?

you have already forwarded the response in catch block:

RequestDispatcher dd = request.getRequestDispatcher("error.jsp");

dd.forward(request, response);

so, you can not again call the :

response.sendRedirect("usertaskpage.jsp");

because it is already forwarded (committed).

So what you can do is: keep a string to assign where you need to forward the response.

    String page = "";
    try {

    } catch (Exception e) {
      page = "error.jsp";
    } finally {
      page = "usertaskpage.jsp";
    }

RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);

Android Stop Emulator from Command Line

To automate this, you can use any script or app that can send a string to a socket. I personally like nc (netcat) under cygwin. As I said before, I use it like this:

$ echo kill | nc -w 2 localhost 5554

(that means to send "kill" string to the port 5554 on localhost, and terminate netcat after 2 seconds.)

How to add anything in <head> through jquery/javascript?

jQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

If you do not wrap your component then you can write it as mentioned below method.

Instead of:

return(
  <Comp1 />
  <Comp2 />
     );

you can write this:

return[(
 <Comp1 />
),
(
<Comp2 />
) ];

How do I run a VBScript in 32-bit mode on a 64-bit machine?

If you have control over running the cscript executable then run the X:\windows\syswow64\cscript.exe version which is the 32bit implementation.

Delete all but the most recent X files in bash

I made this into a bash shell script. Usage: keep NUM DIR where NUM is the number of files to keep and DIR is the directory to scrub.

#!/bin/bash
# Keep last N files by date.
# Usage: keep NUMBER DIRECTORY
echo ""
if [ $# -lt 2 ]; then
    echo "Usage: $0 NUMFILES DIR"
    echo "Keep last N newest files."
    exit 1
fi
if [ ! -e $2 ]; then
    echo "ERROR: directory '$1' does not exist"
    exit 1
fi
if [ ! -d $2 ]; then
    echo "ERROR: '$1' is not a directory"
    exit 1
fi
pushd $2 > /dev/null
ls -tp | grep -v '/' | tail -n +"$1" | xargs -I {} rm -- {}
popd > /dev/null
echo "Done. Kept $1 most recent files in $2."
ls $2|wc -l

How do I style (css) radio buttons and labels?

The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.

Getting the Label Near the Radio Button

I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory):

  • Use <br />s to split the options apart and some CSS to vertically align them:
<style type='text/css'>
    .input input
    {
        width: 20px;
    }
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

Applying a Style to the Currently Selected Label + Radio Button

Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this:

<style type='text/css'>
    .input label.focused
    {
        background-color: #EEEEEE;
        font-style: italic;
    }
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
    $(document).ready(function() {
        $('.input :radio').focus(updateSelectedStyle);
        $('.input :radio').blur(updateSelectedStyle);
        $('.input :radio').change(updateSelectedStyle);
    })

    function updateSelectedStyle() {
        $('.input :radio').removeClass('focused').next().removeClass('focused');
        $('.input :radio:checked').addClass('focused').next().addClass('focused');
    }
</script>

The focus and blur hooks are needed to make this work in IE.

"std::endl" vs "\n"

I've always had a habit of just using std::endl because it is easy for me to see.

Stop a youtube video with jquery?

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

Add multiple items to a list

Code check:

This is offtopic here but the people over at CodeReview are more than happy to help you.

I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.

Lists:

As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List.

Lists are very straightforward to use but take a look at the related documentation anyway.

A very simple example to keep multiple bikes in a list:

List<Motorbike> bikes = new List<Motorbike>();

bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });

And to iterate over the list you can use the foreach statement:

foreach(var bike in bikes) {
     Console.WriteLine(bike.make);
}

I want to declare an empty array in java and then I want do update it but the code is not working

Your code compiles just fine. However, your array initialization line is wrong:

int array[]={};

What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.

Instead, you can either initialize the array right in your original line:

int array[] = { 5, 5, 5, 5 };

Or you can declare the size and then populate it:

int array[] = new int[4];
// ...while loop

If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

You can use the following code (For example if one was to want to copy cell data from Sheet2 to Sheet1).

Sub Copy
Worksheets("Sheet1").Activate                    
Worksheets("Sheet1").Range(Cells(i, 6), Cells(i, FullPathLastColumn)).Copy_
Destination:=Worksheets("Sheet2").Cells(Path2Row, Path2EndColumn + 1)
End Sub

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

Call Stored Procedure within Create Trigger in SQL Server

I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.

ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
    AFTER INSERT
AS
        -- This is your primary key.  I assume INT, but initialize
        -- to minimum value for the type you are using.
        DECLARE @rAgent_ID INT = 0

        -- Looping variable.
        DECLARE @i INT = 0

        -- Count of rows affected for looping over
        DECLARE @count INT

        -- These are your old variables.
        DECLARE @rAgent_Name NVARCHAR(50)
        DECLARE @rAgent_Email NVARCHAR(50)
        DECLARE @rAgent_IP NVARCHAR(50)
        DECLARE @hotelID INT
        DECLARE @retval INT

    BEGIN 
        SET NOCOUNT ON ;

        -- Get count of affected rows
        SELECT  @Count = Count(rAgent_ID)
        FROM    inserted

        -- Loop over rows affected
        WHILE @i < @count
            BEGIN
                -- Get the next rAgent_ID
                SELECT TOP 1
                        @rAgent_ID = rAgent_ID
                FROM    inserted
                WHERE   rAgent_ID > @rAgent_ID
                ORDER BY rAgent_ID ASC

                -- Populate values for the current row
                SELECT  @rAgent_Name = rAgent_Name,
                        @rAgent_Email = rAgent_Email,
                        @rAgent_IP = rAgent_IP,
                        @hotelID = hotelID
                FROM    Inserted
                WHERE   rAgent_ID = @rAgent_ID

                -- Run your stored procedure
                EXEC insert2Newsletter '', '', @rAgent_Name, @rAgent_Email,
                    @rAgent_IP, @hotelID, 'RA', @retval 

                -- Set up next iteration
                SET @i = @i + 1
            END
    END 
GO

I sure hope this helps you out. Cheers!

anchor jumping by using javascript

Because when you do

window.location.href = "#"+anchor;

You load a new page, you can do:

<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>

<script>

    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }

</script>

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

Make sure you are using the correct syntax.

We should use the sendMessage() method after listening it.

Here is a simple example of contentScript.js It sendRequest to app.js.

contentScript.js

chrome.extension.sendRequest({
    title: 'giveSomeTitle', params: paramsToSend
  }, function(result) { 
    // Do Some action
});

app.js

chrome.extension.onRequest.addListener( function(message, sender, 
 sendResponse) {
  if(message.title === 'giveSomeTitle'){
    // Do some action with message.params
    sendResponse(true);
  }
});

How can I make Jenkins CI with Git trigger on pushes to master?

Continuous Integration with Jenkins, after code is pushed to repository from Git command/ GUI:

  1. Create a job in Jenkins with only job name and select type of the project freestyle. Click OK. The next page doesn't add anything - just click Save.
  2. Go to the your local Git repository where you have the source code and navigate to the .git/hooks folder.
  3. The hooks folder contains the few files. Check for the "post-commit". If not present, create a file, "post-commit" without a file extension:

    C:\work\test\\.git\hooks\post-commit
    
  4. Edit the "post-commit" file with the below command. Make sure it is present in your local source code hooks folder.

    curl -u userName:apiToken -X POST http://localhost:8080/jenkins/job/jobName/build?token=apiToken
    

    Example:

    curl -u admin:f1c55b3a07bb2b69b9dd549e96898384 -X POST http://localhost:8080/jenkins/job/Gitcommittest/build?token=f1c55b3a07bb2b69b9dd549e96898384
    

    5.

    userName: Jenkins user name

    jobName: Job name of the build

    apiToken: To get your API token, go to your Jenkins user page (top right in the interface). It is available in the "Configure" menu on the left of the page: "Show API token"

  5. Make changes in your source code and commit the code to repository.

  6. Your job, http://localhost:8080/jenkins/job/Gitcommittest/, should be building.

Are string.Equals() and == operator really same?

In addition to Jon Skeet's answer, I'd like to explain why most of the time when using == you actually get the answer true on different string instances with the same value:

string a = "Hell";
string b = "Hello";
a = a + "o";
Console.WriteLine(a == b);

As you can see, a and b must be different string instances, but because strings are immutable, the runtime uses so called string interning to let both a and b reference the same string in memory. The == operator for objects checks reference, and since both a and b reference the same instance, the result is true. When you change either one of them, a new string instance is created, which is why string interning is possible.

By the way, Jon Skeet's answer is not complete. Indeed, x == y is false but that is only because he is comparing objects and objects compare by reference. If you'd write (string)x == (string)y, it will return true again. So strings have their ==-operator overloaded, which calls String.Equals underneath.

Sorting Python list based on the length of the string

The easiest way to do this is:

list.sort(key = lambda x:len(x))

Assert that a WebElement is not present using Selenium WebDriver with java

It's easier to do this:

driver.findElements(By.linkText("myLinkText")).size() < 1

How to call a shell script from python code?

Use the subprocess module as mentioned above.

I use it like this:

subprocess.call(["notepad"])

Parallel.ForEach vs Task.Factory.StartNew

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

In Eclipse goto Run->Run Configuration find the Name of the class you have been running, select it, click the Target tab then in "Additional Emulator Command Line Options" add:

-Xms512M -Xmx1524M

then click apply.

Setting transparent images background in IrfanView

You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.

You just need to re-open the image with IrfanView after changing the view color to white.

To change the viewing color in Irfanview go to:

Options > Properties/Settings > Viewing > Main window color

jquery .html() vs .append()

if by .add you mean .append, then the result is the same if #myDiv is empty.

is the performance the same? dont know.

.html(x) ends up doing the same thing as .empty().append(x)

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

int a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

The system cannot find the file specified. in Visual Studio

This is because you have not compiled it. Click 'Project > compile'. Then, either click 'start debugging', or 'start without debugging'.

How to prevent vim from creating (and leaving) temporary files?

I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.

set undofile
set undolevels=1000         " How many undos
set undoreload=10000        " number of lines to save for undo

set backup                        " enable backups
set swapfile                      " enable swaps
set undodir=$HOME/.vim/tmp/undo     " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap   " swap files

" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
    call mkdir(expand(&undodir), "p")
endif
if !isdirectory(expand(&backupdir))
    call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
    call mkdir(expand(&directory), "p")
endif

What are the minimum margins most printers can handle?

As a general rule of thumb, I use 1 cm margins when producing pdfs. I work in the geospatial industry and produce pdf maps that reference a specific geographic scale. Therefore, I do not have the option to 'fit document to printable area,' because this would make the reference scale inaccurate. You must also realize that when you fit to printable area, you are fitting your already existing margins inside the printer margins, so you end up with double margins. Make your margins the right size and your documents will print perfectly. Many modern printers can print with margins less than 3 mm, so 1 cm as a general rule should be sufficient. However, if it is a high profile job, get the specs of the printer you will be printing with and ensure that your margins are adequate. All you need is the brand and model number and you can find spec sheets through a google search.

Maven2: Best practice for Enterprise Project (EAR file)

What helped me a lot was to run the Maven archetype:generate goal and select from one of the archetypes, some of which seem to be updated regularly (in particular JBoss seems to be well maintained).

mvn archetype:generate

Hundreds of archetypes appeared in a numbered list from which to select (519 as of now!). The goal, still running, prompted me to make a selection by entering a number or entering a search string e.g.:

513: remote -> org.xwiki.commons:xwiki-commons-component-archetype
514: remote -> org.xwiki.rendering:xwiki-rendering-archetype-macro
515: remote -> org.zkoss:zk-archetype-component
516: remote -> org.zkoss:zk-archetype-webapp
517: remote -> ru.circumflex:circumflex-archetype (-)
518: remote -> se.vgregion.javg.maven.archetypes:javg-minimal-archetype (-)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains):

I entered the search string "ear," which reduced the list to only 8 items (as of today):

Choose archetype:
1: remote -> org.codehaus.mojo.archetypes:ear-j2ee14 (-)
2: remote -> org.codehaus.mojo.archetypes:ear-javaee6 (-)
3: remote -> org.codehaus.mojo.archetypes:ear-jee5 (-)
4: remote -> org.hibernate:hibernate-search-quickstart (-)
5: remote -> org.jboss.spec.archetypes:jboss-javaee6-ear-webapp 
6: remote -> org.jboss.spec.archetypes:jboss-javaee6-webapp-ear-archetype
7: remote -> org.jboss.spec.archetypes:jboss-javaee6-webapp-ear-archetype-blank
8: remote -> org.ow2.weblab.tools.maven:weblab-archetype-searcher

I selected "org.jboss.spec.archetypes:jboss-javaee6-ear-webapp" (by entering the selection "5" in this example).

Next, the goal asked me to enter the groupId, artifactId, package names, etc., and it then generated the following well-documented example application:

[pgarner@localhost Foo]$ tree
.
|-- Foo-ear
|   `-- pom.xml
|-- Foo-ejb
|   |-- pom.xml
|   `-- src
|       |-- main
|       |   |-- java
|       |   |   `-- com
|       |   |       `-- foo
|       |   |           |-- controller
|       |   |           |   `-- MemberRegistration.java
|       |   |           |-- data
|       |   |           |   `-- MemberListProducer.java
|       |   |           |-- model
|       |   |           |   `-- Member.java
|       |   |           `-- util
|       |   |               `-- Resources.java
|       |   `-- resources
|       |       |-- import.sql
|       |       `-- META-INF
|       |           |-- beans.xml
|       |           `-- persistence.xml
|       `-- test
|           |-- java
|           |   `-- com
|           |       `-- foo
|           |           `-- test
|           |               `-- MemberRegistrationTest.java
|           `-- resources
|-- Foo-web
|   |-- pom.xml
|   `-- src
|       `-- main
|           |-- java
|           |   `-- com
|           |       `-- foo
|           |           `-- rest
|           |               |-- JaxRsActivator.java
|           |               `-- MemberResourceRESTService.java
|           `-- webapp
|               |-- index.html
|               |-- index.xhtml
|               |-- resources
|               |   |-- css
|               |   |   `-- screen.css
|               |   `-- gfx
|               |       |-- banner.png
|               |       `-- logo.png
|               `-- WEB-INF
|                   |-- beans.xml
|                   |-- faces-config.xml
|                   `-- templates
|                       `-- default.xhtml
|-- pom.xml
`-- README.md

32 directories, 23 files

After reading the four POM files, which were well-commented, I had pretty much all the information I needed.

./pom.xml
./Foo-ear/pom.xml
./Foo-ejb/pom.xml
./Foo-web/pom.xml

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Why do python lists have pop() but not push()

Because it appends an element to a list? Push is usually used when referring to stacks.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How to access the elements of a 2D array?

Look carefully how many brackets does your array have. I met an example when function returned answer with extra bracket, like that:

>>>approx
array([[[1192,  391]],
       [[1191,  409]],
       [[1209,  438]],
       [[1191,  409]]])

And this didn't work

>>> approx[1,1]
IndexError: index 1 is out of bounds for axis 1 with size 1

This could open the brackets:

>>> approx[:,0]
array([[1192,  391],
       [1191,  409],
       [1209,  438],
       [1191,  409]])

Now it is possible to use an ordinary element access notation:

>>> approx[:,0][1,1]
409

List<T> OrderBy Alphabetical Order

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

Do you (really) write exception safe code?

Some of us prefer languages like Java which force us to declare all the exceptions thrown by methods, instead of making them invisible as in C++ and C#.

When done properly, exceptions are superior to error return codes, if for no other reason than you don't have to propagate failures up the call chain manually.

That being said, low-level API library programming should probably avoid exception handling, and stick to error return codes.

It's been my experience that it's difficult to write clean exception handling code in C++. I end up using new(nothrow) a lot.

C# ListView Column Width Auto

There is another useful method called AutoResizeColumn which allows you to auto size a specific column with the required parameter.

You can call it like this:

listview1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
listview1.AutoResizeColumn(4, ColumnHeaderAutoResizeStyle.HeaderSize);

C# List of objects, how do I get the sum of a property

Here is example code you could run to make such test:

var f = 10000000;
var p = new int[f];

for(int i = 0; i < f; ++i)
{
    p[i] = i % 2;
}

var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);

int x = 0;
time = DateTime.Now;
foreach(var item in p){
   x += item;
}
Console.WriteLine(DateTime.Now - time);

x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
   x += p[i];
}
Console.WriteLine(DateTime.Now - time);

The same example for complex object is:

void Main()
{
    var f = 10000000;
    var p = new Test[f];

    for(int i = 0; i < f; ++i)
    {
        p[i] = new Test();
        p[i].Property = i % 2;
    }

    var time = DateTime.Now;
    p.Sum(k => k.Property);
    Console.WriteLine(DateTime.Now - time);

    int x = 0;
    time = DateTime.Now;
    foreach(var item in p){
        x += item.Property;
    }
    Console.WriteLine(DateTime.Now - time);

    x = 0;
    time = DateTime.Now;
    for(int i = 0, j = f; i < j; ++i){
        x += p[i].Property;
    }
    Console.WriteLine(DateTime.Now - time);
}

class Test
{
    public int Property { get; set; }
}

My results with compiler optimizations off are:

00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)

and for second test are:

00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()

it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.

How to get html table td cell value by JavaScript?

This is my solution

var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
    console.log("My contents is \"" + cells[i].innerHTML + "\"");
}

Generating a random password in php

My answer is similar to some of the above, but I removed vowels, numbers 1 and 0, letters i,j, I, l, O,o, Q, q, X,x,Y,y,W,w. The reason is: the first ones are easy to mix up (like l and 1, depending on the font) and the rest (starting with Q) is because they don't exist in my language, so they might be a bit odd for super-end users. The string of characters is still long enough. Also, I know it would be ideal to use some special signs, but they also don't get along with some end-users.

function generatePassword($length = 8) {

$chars = '23456789bcdfhkmnprstvzBCDFHJKLMNPRSTVZ';
$shuffled = str_shuffle($chars);
$result = mb_substr($shuffled, 0, $length);

return $result;
}

Also, in this way, we avoid repeating the same letters and digits (match case not included)

How to check if user input is not an int value

Maybe you can try this:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

Function or sub to add new row and data to table

This should help you.

Dim Ws As Worksheet
Set Ws = Sheets("Sheet-Name")
Dim tbl As ListObject
Set tbl = Ws.ListObjects("Table-Name")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add

With newrow

        .Range(1, Ws.Range("Table-Name[Table-Column-Name]").Column) = "Your Data"

End With

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

Difference between git pull and git pull --rebase

git pull = git fetch + git merge against tracking upstream branch

git pull --rebase = git fetch + git rebase against tracking upstream branch

If you want to know how git merge and git rebase differ, read this.

Py_Initialize fails - unable to load the file system codec

In my cases, for windows, if you have multiple python versions installed, if PYTHONPATH is pointing to one version the other ones didn't work. I found that if you just remove PYTHONPATH, they all work fine

Get IP address of an interface on Linux

In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.

Can't use WAMP , port 80 is used by IIS 7.5

Yes, you can just change the port to to any number. For instance change Listen 80 to Listen 81 in the httpd.conf file. Now try with http://localhost:81 and it will respond on port 81!!

Responsive table handling in Twitter Bootstrap

Bootstrap 3 now has Responsive tables out of the box. Hooray! :)

You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive

Add a <div class="table-responsive"> surrounding your table and you should be good to go:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

To make it work on all layouts you can do this:

.table-responsive
{
    overflow-x: auto;
}

C# Creating an array of arrays

This loops vertically but might work for you.

int rtn = 0;    
foreach(int[] L in lists){
    for(int i = 0; i<L.Length;i++){
          rtn = L[i];
      //Do something with rtn
    }
}

running multiple bash commands with subprocess

Join commands with "&&".

os.system('echo a > outputa.txt && echo b > outputb.txt')

Counting number of words in a file

I would change your approach a bit. First, I would use a BufferedReader to read the file file in line-by-line using readLine(). Then split each line on whitespace using String.split("\\s") and use the size of the resulting array to see how many words are on that line. To get the number of characters you could either look at the size of each line or of each split word (depending of if you want to count whitespace as characters).

How do I find out if first character of a string is a number?

I just came across this question and thought on contributing with a solution that does not use regex.

In my case I use a helper method:

public boolean notNumber(String input){
    boolean notNumber = false;
    try {
        // must not start with a number
        @SuppressWarnings("unused")
        double checker = Double.valueOf(input.substring(0,1));
    }
    catch (Exception e) {
        notNumber = true;           
    }
    return notNumber;
}

Probably an overkill, but I try to avoid regex whenever I can.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

WPF C# button style

Here's my attempt. Looks more similar to the OP's sample and provides settable properties for icon (FrameworkElement), title (string) and subtitle (string). The output looks like this:

enter image description here

Here's XAML:

<Button x:Class="Controls.FancyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Width="300" Height="80"
          BorderBrush="{x:Null}" BorderThickness="0">
  <Button.Effect>
    <DropShadowEffect BlurRadius="12" Color="Gray" Direction="270" Opacity=".8" ShadowDepth="3" />
  </Button.Effect>

  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Grid Width="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualWidth}"
        Height="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualHeight}">

        <Border x:Name="MainBorder" CornerRadius="3" Grid.ColumnSpan="2" Margin="0,0,4,4" BorderBrush="Black" BorderThickness="1">
          <Border.Background>
            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
              <GradientStop Color="#FF5E5E5E" Offset="0" />
              <GradientStop Color="#FF040404" Offset="1" />
            </LinearGradientBrush>
          </Border.Background>

          <Grid >
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1.2*"/>
              <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>

            <Border CornerRadius="2" Margin="0" BorderBrush="LightGray" BorderThickness="0,1,0,0" Grid.ColumnSpan="2" Grid.RowSpan="2" />

            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="0" HorizontalAlignment="Right" Stroke="#0C0C0C" Grid.RowSpan="2" />
            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="1" HorizontalAlignment="Left" Grid.RowSpan="2">
              <Line.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <GradientStop Color="#4D4D4D" Offset="0" />
                  <GradientStop Color="#2C2C2C" Offset="1" />
                </LinearGradientBrush>
              </Line.Stroke>
            </Line>

            <ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2">
              <ContentControl.Content>
                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Image">
                  <Binding.FallbackValue>
                    <Path Data="M0,0 L30,15 L0,30Z">
                      <Path.Effect>
                        <DropShadowEffect Direction="50" ShadowDepth="2" />
                      </Path.Effect>
                      <Path.Fill>
                        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                          <GradientStop Color="#4B86B2" Offset="0" />
                          <GradientStop Color="#477FA8" Offset="1" />
                        </LinearGradientBrush>
                      </Path.Fill>
                    </Path>
                  </Binding.FallbackValue>
                </Binding>
              </ContentControl.Content>
            </ContentControl>


            <Grid Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>

              <TextBlock x:Name="Title" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title, FallbackValue='Watch Now'}" Grid.Column="1" VerticalAlignment="Bottom" FontFamily="Calibri" FontWeight="Bold" FontSize="28" Foreground="White" Margin="20,0,0,0" />
              <TextBlock x:Name="SubTitle" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SubTitle, FallbackValue='Duration: 50 min'}" Grid.Column="1" Grid.Row="1" VerticalAlignment="top" FontFamily="Calibri" FontSize="14" Foreground="White" Margin="20,0,0,0" />
            </Grid>
          </Grid>
        </Border>
      </Grid>

      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter TargetName="Title" Property="TextDecorations" Value="Underline" />
          <Setter TargetName="SubTitle" Property="TextDecorations" Value="Underline" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="MainBorder" Property="Background">
            <Setter.Value>
              <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Color="#FF5E5E5E" Offset="0" />
                <GradientStop Color="#FFA4A4A4" Offset="1" />
              </LinearGradientBrush>
            </Setter.Value>
          </Setter>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

Here's the code-behind:

using System.Windows;
using System.Windows.Controls;

namespace Controls
{
  public partial class FancyButton : Button
  {
    public FancyButton()
    {
      InitializeComponent();
    }

    public string Title
    {
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("Title", FrameworkPropertyMetadataOptions.AffectsRender));

    public string SubTitle
    {
      get { return (string)GetValue(SubTitleProperty); }
      set { SetValue(SubTitleProperty, value); }
    }

    public static readonly DependencyProperty SubTitleProperty =
        DependencyProperty.Register("SubTitle", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("SubTitle", FrameworkPropertyMetadataOptions.AffectsRender));

    public FrameworkElement Image
    {
      get { return (FrameworkElement)GetValue(ImageProperty); }
      set { SetValue(ImageProperty, value); }
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Image", typeof(FrameworkElement), typeof(FancyButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
  }
}

Here is how to use it:

<controls:FancyButton Grid.Row="1" HorizontalAlignment="Right" Margin="3" Title="Watch Now" SubTitle="Duration: 50 min">
  <controls:FancyButton.Image>
    <Path Data="M0,0 L30,15 L0,30Z">
      <Path.Effect>
        <DropShadowEffect Direction="50" ShadowDepth="2" />
      </Path.Effect>
      <Path.Fill>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Color="#4B86B2" Offset="0" />
          <GradientStop Color="#477FA8" Offset="1" />
        </LinearGradientBrush>
      </Path.Fill>
    </Path>
  </controls:FancyButton.Image>
</controls:FancyButton>

Fatal error: Call to undefined function mysql_connect()

A solution could be to use adapter functions like these to start using mysqli instead of mysql over your entire application:

if (!function_exists('mysql_connect')) {
    function mysql_connect($host = '', $user = '', $password = '', $database = '', $port = 0, $socket = '') {
        return mysqli_connect($host, $user, $password, $database, $port, $socket);
    }
}


if (!function_exists('mysql_select_db')) {
    function mysql_select_db($link, $dbname) {
        mysqli_select_db($link, $dbname);
    }
}

Bootstrap dropdown not working

FYI: If you have bootstrap.js, you should not add bootstrap-dropdown.js.

I'm unsure of the result with bootstrap.min.js.

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

The difference between sys.stdout.write and print?

In Python 2, if you need to pass around a function, then you can assign os.sys.stdout.write to a variable. You cannot do this (in the REPL) with print.

>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>>

That works as expected.

>>> cmd=print
  File "<stdin>", line 1
    cmd=print
            ^
SyntaxError: invalid syntax

That does not work. print is a magical function.

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

In my case this will work successfully. navigate your local repo and enter this command.

sudo chmod 666 /var/run/docker.sock

Initializing an Array of Structs in C#

Firstly, do you really have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.

Other than that, I'd just create a constructor taking the two bits of data:

class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}

Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.)

Python Script to convert Image into Byte array

This works for me

# Convert image to bytes
import PIL.Image as Image
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
return im_bytes

jQuery add image inside of div tag

var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
                var imgsrc = jQuery('.MulImage')[i];
                var CurrentImgSrc = imgsrc.src;
                img = jQuery('<img class="dynamic" style="width:100%;">');
                img.attr('src', CurrentImgSrc);
                jQuery('.YourDivClass').append(img);

            }

Is there a limit on how much JSON can hold?

There is no fixed limit on how large a JSON data block is or any of the fields.

There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See this question for example.

Redirect stdout to a file in Python?

You need a terminal multiplexer like either tmux or GNU screen

I'm surprised that a small comment by Ryan Amos' to the original question is the only mention of a solution far preferable to all the others on offer, no matter how clever the python trickery may be and how many upvotes they've received. Further to Ryan's comment, tmux is a nice alternative to GNU screen.

But the principle is the same: if you ever find yourself wanting to leave a terminal job running while you log-out, head to the cafe for a sandwich, pop to the bathroom, go home (etc) and then later, reconnect to your terminal session from anywhere or any computer as though you'd never been away, terminal multiplexers are the answer. Think of them as VNC or remote desktop for terminal sessions. Anything else is a workaround. As a bonus, when the boss and/or partner comes in and you inadvertently ctrl-w / cmd-w your terminal window instead of your browser window with its dodgy content, you won't have lost the last 18 hours-worth of processing!

Key hash for Android-Facebook app

  • download openSSL for windows in here you can find 64bit and 32bit here

  • extract the downloaded file

  • create folder name openSSL in C drive
  • copy all the extracted items in to openSSL folder (bin,include,lib,openssl.cnf)
  • get android debug keystore, default location will be

C:\Users\username\.android\debug.keystore

  • now get your command prompt and paste this code

keytool -exportcert -alias androiddebugkey -keystore C:\Users\username.android\debug.keystore | "C:\openSSL\bin\openssl" sha1 -binary | "C:\openSSL\bin\openssl" base64

  • hit enter and you will get the 28 digit keycode

Consistency of hashCode() on a Java string

If you're worried about changes and possibly incompatibly VMs, just copy the existing hashcode implementation into your own utility class, and use that to generate your hashcodes .

How do I run a single test using Jest?

From the command line, use the --testNamePattern or -t flag:

jest -t 'fix-order-test'

This will only run tests that match the test name pattern you provide. It's in the Jest documentation.

Another way is to run tests in watch mode, jest --watch, and then press P to filter the tests by typing the test file name or T to run a single test name.


If you have an it inside of a describe block, you have to run

jest -t '<describeString> <itString>'

A Simple AJAX with JSP example

I have used jQuery AJAX to make AJAX requests.

Check the following code:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#call').click(function ()
            {
                $.ajax({
                    type: "post",
                    url: "testme", //this is my servlet
                    data: "input=" +$('#ip').val()+"&output="+$('#op').val(),
                    success: function(msg){      
                            $('#output').append(msg);
                    }
                });
            });

        });
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    input:<input id="ip" type="text" name="" value="" /><br></br>
    output:<input id="op" type="text" name="" value="" /><br></br>
    <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
    <div id="output"></div>
</body>

How to get request URL in Spring Boot RestController

You may try adding an additional argument of type HttpServletRequest to the getUrlValue() method:

@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
    String test = request.getRequestURI();
    return test;
}

xpath find if node exists

Try the following expression: boolean(path-to-node)