Programs & Examples On #Ora 02291

CSS vertical alignment text inside li

Simple solution for vertical align middle... for me it works like a charm

ul{display:table; text-align:center; margin:0 auto;}
li{display:inline-block; text-align:center;}
li.items_inside_li{display:inline-block; vertical-align:middle;}

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I think the problem is with the datatype of the data you are passing Caused by: java.sql.SQLException: Invalid column type: 1111 check the datatypes you pass with the actual column datatypes may be there can be some mismatch or some constraint violation with null

How to convert int to NSString?

NSString *string = [NSString stringWithFormat:@"%d", theinteger];

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

How can I listen to the form submit event in javascript?

With jQuery:

$('form').submit(function () {
    // Validate here

    if (pass)
        return true;
    else
        return false;
});

sudo in php exec()

I think you can bring specific access to user and command with visudo something like this:

nobody ALL = NOPASSWD: /path/to/osascript myscript.scpt

and with php:

@exec("sudo /path/to/osascript myscript.scpt ");

supposing nobody user is running apache.

Is there a numpy builtin to reject outliers from a list

For a set of images (each image has 3 dimensions), where I wanted to reject outliers for each pixel I used:

mean = np.mean(imgs, axis=0)
std = np.std(imgs, axis=0)
mask = np.greater(0.5 * std + 1, np.abs(imgs - mean))
masked = np.multiply(imgs, mask)

Then it is possible to compute the mean:

masked_mean = np.divide(np.sum(masked, axis=0), np.sum(mask, axis=0))

(I use it for Background Subtraction)

#1071 - Specified key was too long; max key length is 1000 bytes

As @Devart says, the total length of your index is too long.

The short answer is that you shouldn't be indexing such long VARCHAR columns anyway, because the index will be very bulky and inefficient.

The best practice is to use prefix indexes so you're only indexing a left substring of the data. Most of your data will be a lot shorter than 255 characters anyway.

You can declare a prefix length per column as you define the index. For example:

...
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
...

But what's the best prefix length for a given column? Here's a method to find out:

SELECT
 ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10,
 ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20,
 ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50,
 ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100
FROM `pds_core_menu_items`;

It tells you the proportion of rows that have no more than a given string length in the menu_link column. You might see output like this:

+---------------+---------------+---------------+----------------+
| pct_length_10 | pct_length_20 | pct_length_50 | pct_length_100 |
+---------------+---------------+---------------+----------------+
|         21.78 |         80.20 |        100.00 |         100.00 |
+---------------+---------------+---------------+----------------+

This tells you that 80% of your strings are less than 20 characters, and all of your strings are less than 50 characters. So there's no need to index more than a prefix length of 50, and certainly no need to index the full length of 255 characters.

PS: The INT(1) and INT(32) data types indicates another misunderstanding about MySQL. The numeric argument has no effect related to storage or the range of values allowed for the column. INT is always 4 bytes, and it always allows values from -2147483648 to 2147483647. The numeric argument is about padding values during display, which has no effect unless you use the ZEROFILL option.

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

If you're using this purely to reference the function in the onclick attribute, this seems like a very bad idea. Inline events are a bad idea in general.

I would suggest the following:

function addEvent(elm, evType, fn, useCapture) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
}

handler = function(){
   showHref(el);
}

showHref = function(el) {
   alert(el.href);
}

var el = document.getElementById('linkid');

addEvent(el, 'click', handler);

If you want to call the same function from other javascript code, simulating a click to call the function is not the best way. Consider:

function doOnClick() {
   showHref(document.getElementById('linkid'));
}

What is the best way to do a substring in a batch file?

Nicely explained above!

For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the % with a !

So:

SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!

How to show first commit by 'git log'?

git log --format="%h" | tail -1 gives you the commit hash (ie 0dd89fb), which you can feed into other commands, by doing something like

git diff `git log --format="%h" --after="1 day"| tail -1`..HEAD to view all the commits in the last day.

"error: assignment to expression with array type error" when I assign a struct field (C)

You are facing issue in

 s1.name="Paolo";

because, in the LHS, you're using an array type, which is not assignable.

To elaborate, from C11, chapter §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

and, regarding the modifiable lvalue, from chapter §6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, [...]

You need to use strcpy() to copy into the array.

That said, data s1 = {"Paolo", "Rossi", 19}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

How do you check if a selector matches something in jQuery?

As the other commenters are suggesting the most efficient way to do it seems to be:

if ($(selector).length ) {
    // Do something
}

If you absolutely must have an exists() function - which will be slower- you can do:

jQuery.fn.exists = function(){return this.length>0;}

Then in your code you can use

if ($(selector).exists()) {
    // Do something
}

As answered here

Does Hibernate create tables in the database automatically

If property hibernate.ddl-auto = update, then it will not create the tables automatically. To create tables automatically, you need to set the property to hibernate.ddl-auto = create

The list of option which is used in the spring boot are

  • validate: validate the schema, makes no changes to the database.

  • update: update the schema.

  • create: creates the schema, destroying previous data.

  • create-drop: drop the schema at the end of the session

  • none: is all other cases

So for the first time you can set it to create and then next time on-wards you should set it to update.

How to automatically redirect HTTP to HTTPS on Apache servers?

for me this worked

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

How do I use the includes method in lodash to check if an object is in the collection?

You could use find to solve your problem

https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}


find(data, item)
// > true

How to clear the interpreter console?

Quickest and easiest way without a doubt is Ctrl+L.

This is the same for OS X on the terminal.

How to create a JQuery Clock / Timer

################## JQuery (use API) #################   
 $(document).ready(function(){
         function getdate(){
                var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();
             if(s<10){
                 s = "0"+s;
             }
             if (m < 10) {
                m = "0" + m;
            }
            $("h1").text(h+" : "+m+" : "+s);
             setTimeout(function(){getdate()}, 500);
            }

        $("button").click(getdate);
    });

################## HTML ###################
<button>start clock</button>
<h1></h1>

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

How to query all the GraphQL type fields without writing a long query?

I guess the only way to do this is by utilizing reusable fragments:

fragment UserFragment on Users {
    id
    username
    count
} 

FetchUsers {
    users(id: "2") {
        ...UserFragment
    }
}

How to connect SQLite with Java?

You need to have a SQLite JDBC driver in your classpath.

Taro L. Saito (xerial) forked the Zentus project and now maintains it under the name sqlite-jdbc. It bundles the native drivers for major platforms so you don't need to configure them separately.

console.log not working in Angular2 Component (Typescript)

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.

How to run mvim (MacVim) from Terminal?

If you have homeBrew installed, this is all you have to do:

brew install macvim
brew linkapps

Then type mvim in your terminal to run MacVim.

"CAUTION: provisional headers are shown" in Chrome debugger

I encountered this issue, and I managed to identify a specific cause, which isn't mentioned above either in answers or the question.

I am running a full js stack, angular front end and node back end on SSL, and the API is on a different domain running on port 8081, so I am doing CORS requests and withCredentials as I am dropping a session cookie from the API

So specifically my scenario was: POST request, withCredentials to port 8081 caused the "CAUTION: provisional headers are shown" message in the inspector and also of course blocked the request all together.

My solution was to set up apache to proxy pass the request from the usual SSL port of 443 to the node SSL port of 8081 (node has to be on a higher port as it cannot be ran as root in prod). So I guess Chrome doesn't like SSL requests to unconventional SSL ports, but perhaps their error message could be more specific.

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

I've made an XCode 4 project template that lets you make a universal framework as easily as making a regular library.

HighCharts Hide Series Name from the Legend

If you don't want to show the series names in the legend you can disable them by setting showInLegend:false.

example:

series: [{
   showInLegend: false,             
   name: "<b><?php echo $title; ?></b>",
   data: [<?php echo $yaxis; ?>],
}]

You get other options here.

How to evaluate http response codes from bash/shell script?

With netcat and awk you can handle the server response manually:

if netcat 127.0.0.1 8080 <<EOF | awk 'NR==1{if ($2 == "500") exit 0; exit 1;}'; then
GET / HTTP/1.1
Host: www.example.com

EOF

    apache2ctl restart;
fi

How to export query result to csv in Oracle SQL Developer?

Version I am using

alt text

Update 5th May 2012

Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:

Method 1

Add the comment /*csv*/ to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)

enter image description here

That's it.

Method 2

Run a query

alt text

Right click and select unload.

Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out

alt text

Revised screen shot for SQL Developer Version 3.0.04

enter image description here

From the format drop down select CSV

alt text

And follow the rest of the on screen instructions.

Quickly create a large file on a Linux system

The GPL mkfile is just a (ba)sh script wrapper around dd; BSD's mkfile just memsets a buffer with non-zero and writes it repeatedly. I would not expect the former to out-perform dd. The latter might edge out dd if=/dev/zero slightly since it omits the reads, but anything that does significantly better is probably just creating a sparse file.

Absent a system call that actually allocates space for a file without writing data (and Linux and BSD lack this, probably Solaris as well) you might get a small improvement in performance by using ftrunc(2)/truncate(1) to extend the file to the desired size, mmap the file into memory, then write non-zero data to the first bytes of every disk block (use fgetconf to find the disk block size).

Matrix Transpose in Python

a=[]
def showmatrix (a,m,n):
    for i in range (m):
        for j in range (n):
            k=int(input("enter the number")
            a.append(k)      
print (a[i][j]),

print('\t')


def showtranspose(a,m,n):
    for j in range(n):
        for i in range(m):
            print(a[i][j]),
        print('\t')

a=((89,45,50),(130,120,40),(69,79,57),(78,4,8))
print("given matrix of order 4x3 is :")
showmatrix(a,4,3)


print("Transpose matrix is:")
showtranspose(a,4,3)

How to check if an item is selected from an HTML drop down list?

I believe this is the most simple in all aspects unless you call the validate function be other means. With no/null/empty value to your first option is easier to validate. You could also eliminate the first option and start with the most popular card type.

<form name="myForm">
<select id="cardtype" name="cards">
<option value="">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />

<input type="submit" name="submit" class="button" value="SUBMIT" onmouseover="validate()"></form>

<script>
function validate() {
 if (document.myform.cards.value == "") {
    alert("Please select a card type");
    document.myForm.cards.focus();
}
</script>

What is Domain Driven Design?

As in TDD & BDD you/ team focus the most on test and behavior of the system than code implementation.

Similar way when system analyst, product owner, development team and ofcourse the code - entities/ classes, variables, functions, user interfaces processes communicate using the same language, its called Domain Driven Design

DDD is a thought process. When modeling a design of software you need to keep business domain/process in the center of attention rather than data structures, data flows, technology, internal and external dependencies.

There are many approaches to model systerm using DDD

  • event sourcing (using events as a single source of truth)
  • relational databases
  • graph databases
  • using functional languages

Domain object:

In very naive words, an object which

  • has name based on business process/flow
  • has complete control on its internal state i.e exposes methods to manipulate state.
  • always fulfill all business invariants/business rules in context of its use.
  • follows single responsibility principle

Can I check if Bootstrap Modal Shown / Hidden?

I try like this with function then calling if needed a this function. Has been worked for me.

function modal_fix() {
var a = $(".modal"),
    b = $("body");
a.on("shown.bs.modal", function () {
    b.hasClass("modal-open") || b.addClass("modal-open");
});
}

Change default date time format on a single database in SQL Server

In order to avoid dealing with these very boring issues, I advise you to always parse your data with the standard and unique SQL/ISO date format which is YYYY-MM-DD. Your queries will then work internationally, no matter what the date parameters are on your main server or on the querying clients (where local date settings might be different than main server settings)!

How do I use a custom Serializer with Jackson?

Use @JsonValue:

public class User {
    int id;
    String name;

    @JsonValue
    public int getId() {
        return id;
    }
}

@JsonValue only works on methods so you must add the getId method. You should be able to skip your custom serializer altogether.

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

I encountered exact the same problem with maven thrift plugin. Here's my solution which requires no need to mess up your pom.xml:

  1. Use command line maven utility mvn

    mvn eclipse:eclipse

    to create a eclipse project

  2. Import the project in eclipse. Remember to use

    File > Import > General > Existing Projects into Workspace

    to add the project into your workspace.

This should fix the problem.

Error in plot.new() : figure margins too large, Scatter plot

Just run graphics.off() before plotting your data. This instruction solved my error. So, it's harmless to try it before taking a more complex solution.

How do I increment a DOS variable in a FOR /F loop?

I would like to add that in case in you create local variables within the loop, they need to be expanded using the bang(!) notation as well. Extending the example at https://stackoverflow.com/a/2919699 above, if we want to create counter-based output filenames

set TEXT_T="myfile.txt"

set /a c=1

setlocal ENABLEDELAYEDEXPANSION

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
    set /a c=c+1
    set OUTPUT_FILE_NAME=output_!c!.txt
    echo Output file is !OUTPUT_FILE_NAME!
    echo %%i, !c!
)

endlocal

JQuery .hasClass for multiple values in an if statement

Here is a slight variation on answer offered by jfriend00:

$.fn.hasAnyClass = function() {
    var classes = arguments[0].split(" ");
    for (var i = 0; i < classes.length; i++) {
        if (this.hasClass(classes[i])) {
            return true;
        }
    }
    return false;
}

Allows use of same syntax as .addClass() and .removeClass(). e.g., .hasAnyClass('m320 m768') Needs bulletproofing, of course, as it assumes at least one argument.

How do you convert a jQuery object into a string?

Just use .get(0) to grab the native element, and get its outerHTML property:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);

How can I change the thickness of my <hr> tag

I added opacity to the line, so it seems thinner:

<hr style="opacity: 0.25">

Passing an array as an argument to a function in C

When passing an array as a parameter, this

void arraytest(int a[])

means exactly the same as

void arraytest(int *a)

so you are modifying the values in main.

For historical reasons, arrays are not first class citizens and cannot be passed by value.

Set Label Text with JQuery

You can try:

<label id ="label_id"></label>
 $("#label_id").html('value');

ActionController::InvalidAuthenticityToken

I have checked the <%= csrf_meta_tags %> are present and clearing cookies in browser worked for me.

How to make php display \t \n as tab and new line instead of characters

"\n" = new line
'\n' = \n
"\t" = tab
'\t' = \t

How to retrieve a module's path?

you can just import your module then hit its name and you'll get its full path

>>> import os
>>> os
<module 'os' from 'C:\\Users\\Hassan Ashraf\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\os.py'>
>>>

callback to handle completion of pipe

Streams are EventEmitters so you can listen to certain events. As you said there is a finish event for request (previously end).

 var stream = request(...).pipe(...);
 stream.on('finish', function () { ... });

For more information about which events are available you can check the stream documentation page.

How to set image to fit width of the page using jsPDF?

A better solution is to set the doc width/height using the aspect ratio of your image.

_x000D_
_x000D_
var ExportModule = {_x000D_
  // Member method to convert pixels to mm._x000D_
  pxTomm: function(px) {_x000D_
    return Math.floor(px / $('#my_mm').height());_x000D_
  },_x000D_
  ExportToPDF: function() {_x000D_
    var myCanvas = document.getElementById("exportToPDF");_x000D_
_x000D_
    html2canvas(myCanvas, {_x000D_
      onrendered: function(canvas) {_x000D_
        var imgData = canvas.toDataURL(_x000D_
          'image/jpeg', 1.0);_x000D_
        //Get the original size of canvas/image_x000D_
        var img_w = canvas.width;_x000D_
        var img_h = canvas.height;_x000D_
_x000D_
        //Convert to mm_x000D_
        var doc_w = ExportModule.pxTomm(img_w);_x000D_
        var doc_h = ExportModule.pxTomm(img_h);_x000D_
        //Set doc size_x000D_
        var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);_x000D_
_x000D_
        //set image height similar to doc size_x000D_
        doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);_x000D_
        var currentTime = new Date();_x000D_
        doc.save('Dashboard_' + currentTime + '.pdf');_x000D_
_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
}
_x000D_
<script src="Scripts/html2canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/jsPDF.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/addimage.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>_x000D_
<div id="my_mm" style="height: 1mm; display: none"></div>_x000D_
_x000D_
<div id="exportToPDF">_x000D_
  Your html here._x000D_
</div>_x000D_
_x000D_
<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
_x000D_
_x000D_
_x000D_

Force “landscape” orientation mode

It is now possible with the HTML5 webapp manifest. See below.


Original answer:

You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.

You can detect the device orientation with CSS3 media queries like this:

@media screen and (orientation:portrait) {
    // CSS applied when the device is in portrait mode
}

@media screen and (orientation:landscape) {
    // CSS applied when the device is in landscape mode
}

Or by binding a JavaScript orientation change event like this:

document.addEventListener("orientationchange", function(event){
    switch(window.orientation) 
    {  
        case -90: case 90:
            /* Device is in landscape mode */
            break; 
        default:
            /* Device is in portrait mode */
    }
});

Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.

As explained on html5rocks.com, you can now force the orientation mode using a manifest.json file.

You need to include those line into the json file:

{
    "display":      "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
    "orientation":  "landscape", /* Could be "landscape" or "portrait" */
    ...
}

And you need to include the manifest into your html file like this:

<link rel="manifest" href="manifest.json">

Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.

Temporary tables in stored procedures

For short: No


Explanation:

According to the official docs: https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver15

If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb is made up of the table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, table_name specified for a local temporary name cannot exceed 116 characters.

What is the Angular equivalent to an AngularJS $watch?

Here is another approach using getter and setter functions for the model.

@Component({
  selector: 'input-language',
  template: `
  …
  <input 
    type="text" 
    placeholder="Language" 
    [(ngModel)]="query" 
  />
  `,
})
export class InputLanguageComponent {

  set query(value) {
    this._query = value;
    console.log('query set to :', value)
  }

  get query() {
    return this._query;
  }
}

How do I connect to a MySQL Database in Python?

As a db driver, there is also oursql. Some of the reasons listed on that link, which say why oursql is better:

  • oursql has real parameterization, sending the SQL and data to MySQL completely separately.
  • oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
  • oursql can both insert rows lazily and fetch rows lazily.
  • oursql has unicode support on by default.
  • oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
  • oursql runs natively on python 3.x.

So how to connect to mysql with oursql?

Very similar to mysqldb:

import oursql

db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
    print row[0]

The tutorial in the documentation is pretty decent.

And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.

jQuery toggle animation

$('.login').toggle(
    function(){
        $('#panel').animate({
            height: "150", 
            padding:"20px 0",
            backgroundColor:'#000000',
            opacity:.8
        }, 500);
        $('#otherdiv').animate({
            //otherdiv properties here
        }, 500);
    },
    function(){
        $('#panel').animate({
            height: "0", 
            padding:"0px 0",
            opacity:.2
        }, 500);     
        $('#otherdiv').animate({
            //otherdiv properties here
        }, 500);
});

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Go to windows -> Preferences -> Java -> Installed JREs

may be jre is already added enter image description here

click on Add -> Standard VM -> Next -> Directory

and browse for the JDK in my case path was C:\Program Files\Java\jdk1.8.0_111

then Click on finish.

you will see window like thisenter image description here

select JDK -> Apply -> Ok

And You are done.

c++ Read from .csv file

Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.

This is what your code sees

0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M

Try this

0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M


while(file.good())
{

    getline(file, ID, ',');
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero) ; \\ diff
    cout << "Sexo: " <<  genero;\\diff


}

ScriptManager.RegisterStartupScript code not working - why?

Off the top of my head:

  • Use GetType() instead of typeof(Page) in order to bind the script to your actual page class instead of the base class,
  • Pass a key constant instead of Page.UniqueID, which is not that meaningful since it's supposed to be used by named controls,
  • End your Javascript statement with a semicolon,
  • Register the script during the PreRender phase:

protected void Page_PreRender(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "YourUniqueScriptKey", 
        "alert('This pops up');", true);
}

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Copy every nth line from one sheet to another

If your original data is in column form with multiple columns and the first entry of your original data in C42, and you want your new (down-sampled) data to be in column form as well, but only every seventh row, then you will also need to subtract out the row number of the first entry, like so:

=OFFSET(C$42,(ROW(C42)-ROW(C$42))*7,0)

MySQL > Table doesn't exist. But it does (or it should)

It appears that the issue has to do (at least in mine and a few others) with invalid (corrupt?) innodb log files. Generally speaking, they simply need to be recreated.

Here are solutions, most of which require a restart of mysql.

  • Recreate your log files (Delete and restart mysql)
  • Resize your log files (MySql 5.6+ will regenerate the file for you)
  • If you are doing some type of a data migration, make sure you have correctly migrated the right file and given it permissions as others have already stated
  • Check permissions of your data and log files, that mysql is owner of both
  • If all else fails, you will likely have to recreate the database

How to do HTTP authentication in android?

I've not met that particular package before, but it says it's for client-side HTTP authentication, which I've been able to do on Android using the java.net APIs, like so:

Authenticator.setDefault(new Authenticator(){
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("myuser","mypass".toCharArray());
    }});
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
c.setUseCaches(false);
c.connect();

Obviously your getPasswordAuthentication() should probably do something more intelligent than returning a constant.

If you're trying to make a request with a body (e.g. POST) with authentication, beware of Android issue 4326. I've linked a suggested fix to the platform there, but there's a simple workaround if you only want Basic auth: don't bother with Authenticator, and instead do this:

c.setRequestProperty("Authorization", "basic " +
        Base64.encode("myuser:mypass".getBytes(), Base64.NO_WRAP));

Stretch image to fit full container width bootstrap

This will do the same as many of the other answers, but will make sides flush with the window, so there is no scroll bars.

<div class="container-fluid">
  <div class="row">
    <div class="col" style="padding: 0;">
       <img src="example.jpg" class="img-responsive" alt="Example">  
    </div>
  </div>
</div>

How to return 2 values from a Java method?

public class Mulretun
{
    public String name;;
    public String location;
    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]="siva";
        ar[1]="dallas";
        return ar; //returning two values at once
    }
    public static void main(String[] args)
    {
        Mulretun m=new Mulretun();
        String ar[] =m.getExample();
        int i;
        for(i=0;i<ar.length;i++)
        System.out.println("return values are: " + ar[i]);      

    }
}

o/p:
return values are: siva
return values are: dallas

How do you get the index of the current iteration of a foreach loop?

I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.

string[] names = { "one", "two", "three" };
var oddOrEvenByName = names
    .Select((name, index) => new KeyValuePair<string, int>(name, index % 2))
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.

What's wrong with using == to compare floats in Java?

As mentioned in other answers, doubles can have small deviations. And you could write your own method to compare them using an "acceptable" deviation. However ...

There is an apache class for comparing doubles: org.apache.commons.math3.util.Precision

It contains some interesting constants: SAFE_MIN and EPSILON, which are the maximum possible deviations of simple arithmetic operations.

It also provides the necessary methods to compare, equal or round doubles. (using ulps or absolute deviation)

Is there a "between" function in C#?

As @Hellfrost pointed out, it is literally nonsense to compare a number to two different numbers in "one operation", and I know of no C# operator that encapsulates this.

between = (0 < 5 && 5 < 10);

Is about the most-compact form I can think of.

You could make a somewhat "fluent"-looking method using extension (though, while amusing, I think it's overkill):

public static bool Between(this int x, int a, int b)
{
    return (a < x) && (x < b);
}

Use:

int x = 5;
bool b = x.Between(0,10);

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

We had this issue as the host server had been updated to use TLS V1.2 and we were connecting using standard SSL. This was an update made as part of pen testing of the sites. We saw the issue in code connection, but not browsers going to the wsdl. Below code resolved:

if (System.Net.ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls))
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Taken from here: How do I disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

What is a race condition?

There is an important technical difference between race conditions and data races. Most answers seem to make the assumption that these terms are equivalent, but they are not.

A data race occurs when 2 instructions access the same memory location, at least one of these accesses is a write and there is no happens before ordering among these accesses. Now what constitutes a happens before ordering is subject to a lot of debate, but in general ulock-lock pairs on the same lock variable and wait-signal pairs on the same condition variable induce a happens-before order.

A race condition is a semantic error. It is a flaw that occurs in the timing or the ordering of events that leads to erroneous program behavior.

Many race conditions can be (and in fact are) caused by data races, but this is not necessary. As a matter of fact, data races and race conditions are neither the necessary, nor the sufficient condition for one another. This blog post also explains the difference very well, with a simple bank transaction example. Here is another simple example that explains the difference.

Now that we nailed down the terminology, let us try to answer the original question.

Given that race conditions are semantic bugs, there is no general way of detecting them. This is because there is no way of having an automated oracle that can distinguish correct vs. incorrect program behavior in the general case. Race detection is an undecidable problem.

On the other hand, data races have a precise definition that does not necessarily relate to correctness, and therefore one can detect them. There are many flavors of data race detectors (static/dynamic data race detection, lockset-based data race detection, happens-before based data race detection, hybrid data race detection). A state of the art dynamic data race detector is ThreadSanitizer which works very well in practice.

Handling data races in general requires some programming discipline to induce happens-before edges between accesses to shared data (either during development, or once they are detected using the above mentioned tools). this can be done through locks, condition variables, semaphores, etc. However, one can also employ different programming paradigms like message passing (instead of shared memory) that avoid data races by construction.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

How to build jars from IntelliJ properly?

In case you are reading this answer because you are facing "resource file not found" error, try this:

  1. File -> Project Structure -> Artiface -> New, type is Other.
  2. Give it a nice name, and in the Output Layout, press Create Archive to create a new jar, and again, give it a nice name ;)
  3. Click on the jar you just added, add your compiled module output in the jar.
  4. Click on the jar again, in the lower pane, select your project path and add Manifest File then set correct Main Class and Class Path.
  5. Click Add Library Files, and select libraries you need (you can use Ctrl+A to select all).
  6. Build -> Build Artifact -> Clean & Build and see if the error is gone.

calculate the mean for each column of a matrix in R

For diversity: Another way is to converts a vector function to one that works with data frames by using plyr::colwise()

set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))

plyr::colwise(mean)(m)


#   X1   X2   X3   X4
# 1 47 64.4 44.8 67.8

Simple way to change the position of UIView?

Here is the Swift 3 answer for anyone looking since Swift 3 does not accept "Make".

aView.center = CGPoint(x: 200, Y: 200)

How to create a String with carriage returns?

It depends on what you mean by "multiple lines". Different operating systems use different line separators.

In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.

But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.

Passing a variable from one php include file to another: global vs. not

This is all you have to do:

In front.inc

global $name;
$name = 'james';

How to check if a string contains an element from a list in Python

extensionsToCheck = ('.pdf', '.doc', '.xls')

'test.doc'.endswith(extensionsToCheck)   # returns True

'test.jpg'.endswith(extensionsToCheck)   # returns False

Python CSV error: line contains NULL byte

data_initial = open("staff.csv", "rb")
data = csv.reader((line.replace('\0','') for line in data_initial), delimiter=",")

This works for me.

Table scroll with HTML and CSS

<div style="overflow:auto">
    <table id="table2"></table>
</div>

Try this code for overflow table it will work only on div tag

To add server using sp_addlinkedserver

I got it. It worked fine

Thank you for your help:

EXEC sp_addlinkedserver @server='Servername'

EXEC sp_addlinkedsrvlogin 'Servername', 'false', NULL, 'username', 'password@123'

Distinct() with lambda?

To Wrap things up . I think most of the people which came here like me want the simplest solution possible without using any libraries and with best possible performance.

(The accepted group by method for me i think is an overkill in terms of performance. )

Here is a simple extension method using the IEqualityComparer interface which works also for null values.

Usage:

var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();

Extension Method Code

public static class LinqExtensions
{
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
    {
        GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
        return items.Distinct(comparer);
    }   
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
    private Func<T, TKey> expr { get; set; }
    public GeneralPropertyComparer (Func<T, TKey> expr)
    {
        this.expr = expr;
    }
    public bool Equals(T left, T right)
    {
        var leftProp = expr.Invoke(left);
        var rightProp = expr.Invoke(right);
        if (leftProp == null && rightProp == null)
            return true;
        else if (leftProp == null ^ rightProp == null)
            return false;
        else
            return leftProp.Equals(rightProp);
    }
    public int GetHashCode(T obj)
    {
        var prop = expr.Invoke(obj);
        return (prop==null)? 0:prop.GetHashCode();
    }
}

PostgreSQL 'NOT IN' and subquery

When using NOT IN, you should also consider NOT EXISTS, which handles the null cases silently. See also PostgreSQL Wiki

SELECT mac, creation_date 
FROM logs lo
WHERE logs_type_id=11
AND NOT EXISTS (
  SELECT *
  FROM consols nx
  WHERE nx.mac = lo.mac
  );

Error renaming a column in MySQL

With MySQL 5.x you can use:

ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name DATATYPE NULL DEFAULT NULL;

Best way to verify string is empty or null

If you have to test more than one string in the same validation, you can do something like this:

import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class StringHelper {

  public static Boolean hasBlank(String ... strings) {

    Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();

    return Optional
      .ofNullable(strings)
      .map(Stream::of)
      .map(stream -> stream.anyMatch(isBlank))
      .orElse(false);
  }

}

So, you can use this like StringHelper.hasBlank("Hello", null, "", " ") or StringHelper.hasBlank("Hello") in a generic form.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Rather than doing string manipulation, you can use the HOUR, MINUTE, SECOND functions to break apart the time. You can then multiply by 60*60*1000, 60*1000, and 1000 respectively to get milliseconds.

Classes cannot be accessed from outside package

Let me guess

Your initial declaration of class PUBLICClass was not public, then you made it `Public', can you try to clean and rebuild your project ?

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

Another way to avoid this problem that may help others is build your .net web service to version 4.0 or higher if possible.

jQuery get an element by its data-id

You can always use an attribute selector. The selector itself would look something like:

a[data-item-id=stand-out]

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

MySQL ODBC 3.51 Driver is that special characters in the password aren't handled.

"Warning – You might have a serious headache with MySQL ODBC 3.51 if the password in your GRANT command contains special characters, such as ! @ # $ % ^ ?. MySQL ODBC 3.51 ODBC Driver does not support these special characters in the password box. The only error message you would receive is “Access denied” (using password: YES)" - from http://www.plaintutorials.com/install-and-create-mysql-odbc-connector-on-windows-7/

What's the UIScrollView contentInset property for?

Content insets solve the problem of having content that goes underneath other parts of the User Interface and yet still remains reachable using scroll bars. In other words, the purpose of the Content Inset is to make the interaction area smaller than its actual area.

Consider the case where we have three logical areas of the screen:

TOP BUTTONS

TEXT

BOTTOM TAB BAR

and we want the TEXT to never appear transparently underneath the TOP BUTTONS, but we want the Text to appear underneath the BOTTOM TAB BAR and yet still allow scrolling so we could update the text sitting transparently under the BOTTOM TAB BAR.

Then we would set the top origin to be below the TOP BUTTONS, and the height to include the bottom of BOTTOM TAB BAR. To gain access to the Text sitting underneath the BOTTOM TAB BAR content we would set the bottom inset to be the height of the BOTTOM TAB BAR.

Without the inset, the scroller would not let you scroll up the content enough to type into it. With the inset, it is as if the content had extra "BLANK CONTENT" the size of the content inset. Blank text has been "inset" into the real "content" -- that's how I remember the concept.

Unicode character as bullet for list-item in CSS

To add a star use the Unicode character 22C6.

I added a space to make a little gap between the li and the star. The code for space is A0.

li:before {
    content: '\22C6\A0';
}

await vs Task.Wait - Deadlock?

Wait and await - while similar conceptually - are actually completely different.

Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use "async all the way down"; that is, don't block on async code. On my blog, I go into the details of how blocking in asynchronous code causes deadlock.

await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

You also mentioned a "cooperative block", by which I assume you mean a task that you're Waiting on may execute on the waiting thread. There are situations where this can happen, but it's an optimization. There are many situations where it can't happen, like if the task is for another scheduler, or if it's already started or if it's a non-code task (such as in your code example: Wait cannot execute the Delay task inline because there's no code for it).

You may find my async / await intro helpful.

C++ equivalent of StringBuffer/StringBuilder?

I wanted to add something new because of the following:

At a first attemp I failed to beat

std::ostringstream 's operator<<

efficiency, but with more attemps I was able to make a StringBuilder that is faster in some cases.

Everytime I append a string I just store a reference to it somewhere and increase the counter of the total size.

The real way I finally implemented it (Horror!) is to use a opaque buffer(std::vector < char > ):

  • 1 byte header (2 bits to tell if following data is :moved string, string or byte[])
  • 6 bits to tell lenght of byte[]

for byte [ ]

  • I store directly bytes of short strings (for sequential memory access)

for moved strings (strings appended with std::move)

  • The pointer to a std::string object (we have ownership)
  • set a flag in the class if there are unused reserved bytes there

for strings

  • The pointer to a std::string object (no ownership)

There's also one small optimization, if last inserted string was mov'd in, it checks for free reserved but unused bytes and store further bytes in there instead of using the opaque buffer (this is to save some memory, it actually make it slightly slower, maybe depend also on the CPU, and it is rare to see strings with extra reserved space anyway)

This was finally slightly faster than std::ostringstream but it has few downsides:

  • I assumed fixed lenght char types (so 1,2 or 4 bytes, not good for UTF8), I'm not saying it will not work for UTF8, Just I don't checked it for laziness.
  • I used bad coding practise (opaque buffer, easy to make it not portable, I believe mine is portable by the way)
  • Lacks all features of ostringstream
  • If some referenced string is deleted before mergin all the strings: undefined behaviour.

conclusion? use std::ostringstream

It already fix the biggest bottleneck while ganing few % points in speed with mine implementation is not worth the downsides.

How do I import material design library to Android Studio?

build.gradle

implementation 'com.google.android.material:material:1.2.0-alpha02'

styles.xml

 <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

You need to use a Theme.AppCompat theme (or descendant) with this activity

In my case, i was inflating a view with ApplicationContext. When you use ApplicationContext, theme/style is not applied, so although there was Theme.Appcompat in my style, it was not applied and caused this exception. More details: Theme/Style is not applied when inflater used with ApplicationContext

How can I open the interactive matplotlib window in IPython notebook?

Starting with matplotlib 1.4.0 there is now an an interactive backend for use in the notebook

%matplotlib notebook

There are a few version of IPython which do not have that alias registered, the fall back is:

%matplotlib nbagg

If that does not work update you IPython.

To play with this, goto tmpnb.org

and paste

%matplotlib notebook

import pandas as pd
import numpy as np
import matplotlib

from matplotlib import pyplot as plt
import seaborn as sns

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
                  columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
df.plot(); plt.legend(loc='best')    

into a code cell (or just modify the existing python demo notebook)

Need to combine lots of files in a directory

If you like to do this for open files on Notepad++, you can use Combine plugin: http://www.scout-soft.com/combine/

Installing lxml module in python

For python 3 this worked for me

sudo apt-get install python3-lxml

How to include a PHP variable inside a MySQL statement

The text inside $type is substituted directly into the insert string, therefore MySQL gets this:

... VALUES(testing, 'john', 'whatever')

Notice that there are no quotes around testing, you need to put these in like so:

$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");

I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:

Convert comma separated string of ints to int array

I think is good enough. It's clear, it lazy so it will be fast (except maybe the first case when you split the string).

Problems after upgrading to Xcode 10: Build input file cannot be found

Not that I did anything wrong, but I ran into this issue for a completely different reason and kinda know what caused this.

I previously used finder and dragged a file into my project's directory/folder. I didn't drag into Xcode. To make Xcode include that file into the project, I had to drag it into Xcode myself later again.

But when I switched to a new branch which didn't have that file (nor it needed to), Xcode was giving me this error:

Build input file cannot be found: '/Users/honey/Documents/xp/xpios/powerup/Models Extensions/CGSize+Extension.swift'


I did clean build folder and delete my derived data, but it didn't work until I restarted my Xcode.

Change onClick attribute with javascript

You want to do this - set a function that will be executed to respond to the onclick event:

document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;

The things you are doing don't work because:

  1. The onclick event handler expects to have a function, here you are assigning a string

    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
    
  2. In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:

    document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
    

Django - Did you forget to register or load this tag?

You need to change:

{% endblock content %}

to

{% endblock %}

ComboBox: Adding Text and Value to an Item (no Binding Source)

I liked fab's answer but didn't want to use a dictionary for my situation so I substituted a list of tuples.

// set up your data
public static List<Tuple<string, string>> List = new List<Tuple<string, string>>
{
  new Tuple<string, string>("Item1", "Item2")
}

// bind to the combo box
comboBox.DataSource = new BindingSource(List, null);
comboBox.ValueMember = "Item1";
comboBox.DisplayMember = "Item2";

//Get selected value
string value = ((Tuple<string, string>)queryList.SelectedItem).Item1;

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

How to input a path with a white space?

If the file contains only parameter assignments, you can use the following loop in place of sourcing it:

# Instead of source file.txt
while IFS="=" read name value; do
    declare "$name=$value"
done < file.txt

This saves you having to quote anything in the file, and is also more secure, as you don't risk executing arbitrary code from file.txt.

How to present a simple alert message in java?

Assuming you already have a JFrame to call this from:

JOptionPane.showMessageDialog(frame, "thank you for using java");

See The Java Tutorials: How to Make Dialogs
See the JavaDoc

How to attach a file using mail command on Linux?

Example using uuencode:

uuencode surfing.jpeg surfing.jpeg | mail [email protected]

and reference article:

http://www.shelldorado.com/articles/mailattachments.html

Note:

you may apt install sharutils to have uuencode command

How do I grep recursively?

For a list of available flags:

grep --help 

Returns all matches for the regexp texthere in the current directory, with the corresponding line number:

grep -rn "texthere" .

Returns all matches for texthere, starting at the root directory, with the corresponding line number and ignoring case:

grep -rni "texthere" /

flags used here:

  • -r recursive
  • -n print line number with output
  • -i ignore case

Java JRE 64-bit download for Windows?

Might this be the download you are looking for?

  1. Go to the Java SE Downloads Page.
  2. Scroll down a tad look for the main table with the header of "Java Platform, Standard Edition"
  3. Click the JRE Download Button (JRE is the runtime component. JDK is the developer's kit).
  4. Select the appropriate download (all platforms and 32/64 bit downloads are listed)

Android Google Maps API V2 Zoom to Current Location

After you instansiated the map object (from the fragment) add this -

private void centerMapOnMyLocation() {

    map.setMyLocationEnabled(true);

    location = map.getMyLocation();

    if (location != null) {
        myLocation = new LatLng(location.getLatitude(),
                location.getLongitude());
    }
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
            Constants.MAP_ZOOM));
}

if you need any guidance just ask but it should be self explantory - just instansiate the myLocation object for a default one...

How to set the value for Radio Buttons When edit?

    Gender :<br>
    <input type="radio" name="g" value="male"  <?php echo ($g=='Male')?'checked':'' ?>>male <br>
    <input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
            <?php echo $errors['g'];?>

How to dynamically allocate memory space for a string and get that string from user?

This is a function snippet I wrote to scan the user input for a string and then store that string on an array of the same size as the user input. Note that I initialize j to the value of 2 to be able to store the '\0' character.

char* dynamicstring() {
    char *str = NULL;
    int i = 0, j = 2, c;
    str = (char*)malloc(sizeof(char));
    //error checking
    if (str == NULL) {
        printf("Error allocating memory\n");
        exit(EXIT_FAILURE);
    }

    while((c = getc(stdin)) && c != '\n')
    {
        str[i] = c;
        str = realloc(str,j*sizeof(char));
        //error checking
        if (str == NULL) {
            printf("Error allocating memory\n");
            free(str);
            exit(EXIT_FAILURE);
        }

        i++;
        j++;
    }
    str[i] = '\0';
    return str;
}

In main(), you can declare another char* variable to store the return value of dynamicstring() and then free that char* variable when you're done using it.

How to return a value from __init__ in Python?

__init__ doesn't return anything and should always return None.

Vertical rulers in Visual Studio Code

With Visual Studio Code 1.27.2:

  1. When I go to File > Preference > Settings, I get the following tab

    Screenshot

  2. I type rulers in Search settings and I get the following list of settings

    screenshot

  3. Clicking on the first Edit in settings.json, I can edit the user settings

    screenshot

  4. Clicking on the pen icon that appears to the left of the setting in Default user settings I can copy it on the user settings and edit it

With Visual Studio Code 1.38.1, the screenshot shown on the third point changes to the following one.

enter image description here

The panel for selecting the default user setting values isn't shown anymore.

Formatting "yesterday's" date in python

Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')

Read/Write 'Extended' file properties (C#)

  • After looking at a number of solutions on this thread and elsewhere the following code was put together. This is only to read a property.
  • I could not get the Shell32.FolderItem2.ExtendedProperty function to work, it is supposed to take a string value and return the correct value and type for that property... this was always null for me and developer reference resources were very thin.
  • The WindowsApiCodePack seems to have been abandoned by Microsoft which brings us the code below.

Use:

string propertyValue = GetExtendedFileProperty("c:\\temp\\FileNameYouWant.ext","PropertyYouWant");
  1. Will return you the value of the extended property you want as a string for the given file and property name.
  2. Only loops until it found the specified property - not until all properties are discovered like some sample code
  3. Will work on Windows versions like Windows server 2008 where you will get the error "Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'" if just trying to create the Shell32 Object normally.

    public static string GetExtendedFileProperty(string filePath, string propertyName)
    {
        string value = string.Empty;
        string baseFolder = Path.GetDirectoryName(filePath);
        string fileName = Path.GetFileName(filePath);
    
        //Method to load and execute the Shell object for Windows server 8 environment otherwise you get "Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'"
        Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
        Object shell = Activator.CreateInstance(shellAppType);
        Shell32.Folder shellFolder = (Shell32.Folder)shellAppType.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { baseFolder });
    
        //Parsename will find the specific file I'm looking for in the Shell32.Folder object
        Shell32.FolderItem folderitem = shellFolder.ParseName(fileName);
        if (folderitem != null)
        {
            for (int i = 0; i < short.MaxValue; i++)
            {
                //Get the property name for property index i
                string property = shellFolder.GetDetailsOf(null, i);
    
                //Will be empty when all possible properties has been looped through, break out of loop
                if (String.IsNullOrEmpty(property)) break;
    
                //Skip to next property if this is not the specified property
                if (property != propertyName) continue;    
    
                //Read value of property
                value = shellFolder.GetDetailsOf(folderitem, i);
            }
        }
        //returns string.Empty if no value was found for the specified property
        return value;
    }
    

Android Studio says "cannot resolve symbol" but project compiles

I have tried this but nothing worked for me:

  • Invalidate Caches / Restart
  • Changing the order of dependencies
  • Sync project with Gradle Files
  • Clean -> Rebuild Project

In my case, just do:

  • Delete all files in .idea/libraries folder
  • Rebuild Project

Finding the last index of an array

say your array is called arr

do

arr[arr.Length - 1]

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

You can use the following methods to specify C:\Program Files without a space in it for programs that can't handle spaces in file paths:

'Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~1\continuum_reports\" or
RepPath = C:\Program Files\Continuum_Reports  'si es para 64 bits.

' Path to Continuum Reports Subdirectory - Note use DOS equivalent (no spaces)
RepPath = "c:\progra~2\continuum_reports\" 'or
RepPath = C:\Program Files (x86)\Continuum_Reports  'si es para 32 bits.

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

alter table tablename drop (column1, column2, column3......);

What causes a SIGSEGV

The initial source cause can also be an out of memory.

How to insert date values into table

let suppose we create a table Transactions using SQl server management studio

txn_id int,

txn_type_id varchar(200),

Account_id int,

Amount int,

tDate date

);

with date datatype we can insert values in simple format: 'yyyy-mm-dd'

INSERT INTO transactions (txn_id,txn_type_id,Account_id,Amount,tDate)
VALUES (978, 'DBT', 103, 100, '2004-01-22');

Moreover we can have differet time formats like

DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MI:SS
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS 

WCF service startup error "This collection already contains an address with scheme http"

Summary,

Code solution: Here

Configuration solutions: Here

With the help of Mike Chaliy, I found some solutions on how to do this through code. Because this issue is going to affect pretty much all projects we deploy to a live environment I held out for a purely configuration solution. I eventually found one which details how to do it in .net 3.0 and .net 3.5.

Taken from the site, below is an example of how to alter your applications web config:

<system.serviceModel>
    <serviceHostingEnvironment>
        <baseAddressPrefixFilters>
            <add prefix="net.tcp://payroll.myorg.com:8000"/>
            <add prefix="http://shipping.myorg.com:9000"/>
        </baseAddressPrefixFilters>
    </serviceHostingEnvironment>
</system.serviceModel>

In the above example, net.tcp://payroll.myorg.com:8000 and http://shipping.myorg.com:9000 are the only base addresses, for their respective schemes, which will be allowed to be passed through. The baseAddressPrefixFilter does not support any wildcards .

The baseAddresses supplied by IIS may have addresses bound to other schemes not present in baseAddressPrefixFilter list. These addresses will not be filtered out.

Dns solution (untested): I think that if you created a new dns entry specific to your web application, added a new web site, and gave it a single host header matching the dns entry, you would mitigate this issue altogether, and would not have to write custom code or add prefixes to your web.config file.

The request was rejected because no multipart boundary was found in springboot

The "Postman - REST Client" is not suitable for doing post action with setting content-type.You can try to use "Advanced REST client" or others.

Additionally, headers was replace by consumes and produces since Spring 3.1 M2, see https://spring.io/blog/2011/06/13/spring-3-1-m2-spring-mvc-enhancements. And you can directly use produces = MediaType.MULTIPART_FORM_DATA_VALUE.

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

Why is there no xrange function in Python3?

xrange from Python 2 is a generator and implements iterator while range is just a function. In Python3 I don't know why was dropped off the xrange.

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

I had issue while inspecting the xml file in notepad++ and saving the file, though I had the top utf-8 xml tag as <?xml version="1.0" encoding="utf-8"?>

Got fixed by saving the file in notpad++ with Encoding(Tab) > Encode in UTF-8:selected (was Encode in UTF-8-BOM)

Getting the thread ID from a thread

You can use the deprecated AppDomain.GetCurrentThreadId to get the ID of the currently running thread. This method uses a PInvoke to the Win32 API method GetCurrentThreadID, and will return the Windows thread ID.

This method is marked as deprecated because the .NET Thread object does not correspond to a single Windows thread, and as such there is no stable ID which can be returned by Windows for a given .NET thread.

See configurator's answer for more reasons why this is the case.

delete vs delete[] operators in C++

The delete operator deallocates memory and calls the destructor for a single object created with new.

The delete [] operator deallocates memory and calls destructors for an array of objects created with new [].

Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined behavior.

MySQL Cannot drop index needed in a foreign key constraint

Because you have to have an index on a foreign key field you can just create a simple index on the field 'AID'

CREATE INDEX aid_index ON mytable (AID);

and only then drop the unique index 'AID'

ALTER TABLE mytable DROP INDEX AID;

How to get the parent dir location

os.pardir is a better way for ../ and more readable.

import os
print os.path.abspath(os.path.join(given_path, os.pardir))  

This will return the parent path of the given_path

Html.EditorFor Set Default Value

In the constructor method of your model class set the default value whatever you want. Then in your first action create an instance of the model and pass it to your view.

    public ActionResult VolunteersAdd()
    {
        VolunteerModel model = new VolunteerModel(); //to set the default values
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult VolunteersAdd(VolunteerModel model)
    {


        return View(model);
    }

Android Layout Right Align

The layout is extremely inefficient and bloated. You don't need that many LinearLayouts. In fact you don't need any LinearLayout at all.

Use only one RelativeLayout. Like this.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageButton android:background="@null"
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/back"
        android:padding="10dip"
        android:layout_alignParentLeft="true"/>
    <ImageButton android:background="@null"
        android:id="@+id/forward"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/forward"
        android:padding="10dip"
        android:layout_toRightOf="@id/back"/>
    <ImageButton android:background="@null"
        android:id="@+id/special"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/barcode"
        android:padding="10dip"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch

By adding #ifdef HAVE_CAMV4L around

#include <linux/videodev.h>

in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp and removing || defined (HAVE_CAMV4L2) from line 174 allowed me to compile.

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

How can I get city name from a latitude and longitude point?

Here is the latest sample of Google's geocode Web Service

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY

Simply change the YOUR_API_KEY to the API key you get from Google Geocoding API

P/S: Geocoding API is under Places NOT Maps ;)

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

Go to beginning of line without opening new line in VI

I just found 0(zero) and shift+0 works on vim.

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

Your target domain might refuse to send you information. This can work as a filter based on browser agent or any other header information. This is a defense against bots, crawlers or any unwanted applications.

Turn off constraints temporarily (MS SQL)

Disabling and Enabling All Foreign Keys

CREATE PROCEDURE pr_Disable_Triggers_v2
    @disable BIT = 1
AS
    DECLARE @sql VARCHAR(500)
        ,   @tableName VARCHAR(128)
        ,   @tableSchema VARCHAR(128)

    -- List of all tables
    DECLARE triggerCursor CURSOR FOR
        SELECT  t.TABLE_NAME AS TableName
            ,   t.TABLE_SCHEMA AS TableSchema
        FROM    INFORMATION_SCHEMA.TABLES t
        ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA

    OPEN    triggerCursor
    FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
    WHILE ( @@FETCH_STATUS = 0 )
    BEGIN

        SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
        IF @disable = 1
            SET @sql = @sql + ' DISABLE TRIGGER ALL'
        ELSE
            SET @sql = @sql + ' ENABLE TRIGGER ALL'

        PRINT 'Executing Statement - ' + @sql
        EXECUTE ( @sql )

        FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema

    END

    CLOSE triggerCursor
    DEALLOCATE triggerCursor

First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:

0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missing

Inside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.

see Disabling Constraints and Triggers from MSDN Magazine

How to add dividers and spaces between items in RecyclerView?

I have added a line in list item like below

<View
android:id="@+id/divider"
android:layout_width="match_parent"
android:layout_height="1px"
android:background="@color/dividerColor"/>

1px will draw the thin line.

If you want to hide the divider for the last row then divider.setVisiblity(View.GONE); on the onBindViewHolder for the last list Item.

Eclipse IDE for Java - Full Dark Theme

For a Visual Studio 2013 Dark Theme:

Combine this preferences file from eclipsecolorthemes.org (an .epf) with the built-in dark theme from Eclipse Luna. I was able to do so with the following steps:

  1. Window > General > Appearance > Theme: Dark.
  2. File > Import > General > Preferences > Browse: theme-25999.epf > Finish.

An example search for more VS Dark Themes on eclipsecolorthemes.org

Is unsigned integer subtraction defined behavior?

When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:

enter image description here

9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned, then modular arithmetic takes place.


Now look at the following operations storing the result as an unsigned int:

unsigned int five = 5, seven = 7;
unsigned int a = five - seven;      // a = (-2 % 2^32) = 4294967294 

int one = 1, six = 6;
unsigned int b = one - six;         // b = (-5 % 2^32) = 4294967291

When you want to make sure that the result is signed, then stored it into signed variable or cast it to signed. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs() function defined in stdlib.h:

int c = five - seven;       // c = -2
int d = abs(five - seven);  // d =  2

Be very careful, especially while writing conditions, because:

if (abs(five - seven) < seven)  // = if (2 < 7)
    // ...

if (five - seven < -1)          // = if (-2 < -1)
    // ...

if (one - six < 1)              // = if (-5 < 1)
    // ...

if ((int)(five - seven) < 1)    // = if (-2 < 1)
    // ...

but

if (five - seven < 1)   // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
    // ...

if (one - six < five)   // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
    // ...

Extract substring from a string

substring():

str.substring(startIndex, endIndex); 

Why is there no Constant feature in Java?

Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of const in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.

Wikipedia offers the following information on the subject:

Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.

EF 5 Enable-Migrations : No context type was found in the assembly

How to Update table and column in mvc using entity framework code first approach

1: tool > package manager console

2: select current project where context class exist

3: Enable migration using following command PM > enable-migrations

4: Add migration folder name using following command PM > add-migration MyMigrationName

4: Now update database following command PM > update-database

Remove a file from a Git repository without deleting it from the local filesystem

You can also remove files from the repository based on your .gitignore without deleting them from the local file system :

git rm --cached `git ls-files -i -X .gitignore`

Or, alternatively, on Windows Powershell:

git rm --cached $(git ls-files -i -X .gitignore)

Chrome Dev Tools - Modify javascript and reload

Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools

"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types

How it works:

  • You specify a directory where DevTools should save changes. When you make changes in DevTools, DevTools saves a copy of the modified file to your directory.
  • When you reload the page, DevTools serves the local, modified file, rather than the network resource.

To set up Local Overrides:

  1. Open the Sources panel.
  2. Open the Overrides tab.
  3. Click Setup Overrides.
  4. Select which directory you want to save your changes to.
  5. At the top of your viewport, click Allow to give DevTools read and write access to the directory.
  6. Make your changes."

UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides

Add items in array angular 4

Push object into your array. Try this:

export class FormComponent implements OnInit {
    name: string;
    empoloyeeID : number;
    empList: Array<{name: string, empoloyeeID: number}> = []; 
    constructor() {}
    ngOnInit() {}
    onEmpCreate(){
        console.log(this.name,this.empoloyeeID);
        this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
        this.name = "";
        this.empoloyeeID = 0;
    }
}

Function return value in PowerShell

As a workaround I've been returning the last object in the array that you get back from the function... It is not a great solution, but it's better than nothing:

someFunction {
   $a = "hello"
   "Function is running"
   return $a
}

$b = someFunction
$b = $b[($b.count - 1)]  # Or
$b = $b[-1]              # Simpler

All in all, a more one-lineish way of writing the same thing could be:

$b = (someFunction $someParameter $andAnotherOne)[-1]

Transparent scrollbar with css

Just set display:none; as an attribute in your stylesheet ;)
It's way better than loading pictures for nothing.

body::-webkit-scrollbar {
  width: 9px;
  height: 9px;
}

body::-webkit-scrollbar-button:start:decrement,
body::-webkit-scrollbar-button:end:increment {
  display: block;
  height: 0;
  background-color: transparent;
}

body::-webkit-scrollbar-track-piece {
  background-color: #ffffff;
  opacity: 0.2;

  /* Here */
  display: none;

  -webkit-border-radius: 0;
  -webkit-border-bottom-right-radius: 14px;
  -webkit-border-bottom-left-radius: 14px;
}

body::-webkit-scrollbar-thumb:vertical {
  height: 50px;
  background-color: #333333;
  -webkit-border-radius: 8px;
}

Create a new cmd.exe window from within another cmd.exe prompt

You can just type these 3 commands from command prompt:

  1. start

  2. start cmd

  3. start cmd.exe

Content Security Policy: The page's settings blocked the loading of a resource

I got around this by upgrading both the version of Angular that I was using (from v8 -> v9) and the version of TypeScript (from 3.5.3 -> latest).

getActionBar() returns null

One thing I wanted to add since I just ran into this, if you are trying to getActionBar() on an Activity that has a parent, it will return null. I am trying to refactor code where my Activity is contained inside an ActivityGroup, and it took a good few minutes for me to go "oh duh" after looking at the source of how an ActionBar gets created in source.

Ajax using https on an http page

http://example.com/ may resolve to a different VirtualHost than https://example.com/ (which, as the Host header is not sent, responds to the default for that IP), so the two are treated as separate domains and thus subject to crossdomain JS restrictions.

JSON callbacks may let you avoid this.

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

How to append elements at the end of ArrayList in Java?

import java.util.*;


public class matrixcecil {
    public static void main(String args[]){
        List<Integer> k1=new ArrayList<Integer>(10);
        k1.add(23);
        k1.add(10);
        k1.add(20);
        k1.add(24);
        int i=0;
        while(k1.size()<10){
            if(i==(k1.get(k1.size()-1))){

            }
             i=k1.get(k1.size()-1);
             k1.add(30);
             i++;
             break;
        }
        System.out.println(k1);
    }

}

I think this example will help you for better solution.

Dilemma: when to use Fragments vs Activities:

There's more to this than you realize, you have to remember than an activity that is launched does not implicitly destroy the calling activity. Sure, you can set it up such that your user clicks a button to go to a page, you start that page's activity and destroy the current one. This causes a lot of overhead. The best guide I can give you is:

** Start a new activity only if it makes sense to have the main activity and this one open at the same time (think of multiple windows).

A great example of when it makes sense to have multiple activities is Google Drive. The main activity provides a file explorer. When a file is opened, a new activity is launched to view that file. You can press the recent apps button which will allow you to go back to the browser without closing the opened document, then perhaps even open another document in parallel to the first.

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

SVN "Already Locked Error"

You need to cleanup your tortoise SVN by clicking on cleanup option you get after Right Clicking on windows where you want to UPDATE SVN. And after cleanup try updating SVN similarly by clicking UPDATE SVN option you get after right clicking.

This worked for me.

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

How to convert JSON to a Ruby hash

You can use the nice_hash gem: https://github.com/MarioRuiz/nice_hash

require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'

# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json

# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)

# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]

What is ADT? (Abstract Data Type)

Simply Abstract Data Type is nothing but a set of operation and set of data is used for storing some other data efficiently in the machine. There is no need of any perticular type declaration. It just require a implementation of ADT.

Visual Studio Code - Convert spaces to tabs

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

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

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

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

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

Auto detect mobile browser (via user-agent?)

Have you considered using css3 media queries? In most cases you can apply some css styles specifically for the targeted device without having to create a separate mobile version of the site.

@media screen and (max-width:1025px) {
   #content {
     width: 100%;
   }
}

You can set the width to whatever you want, but 1025 will catch the iPad landscape view.

You'll also want to add the following meta tag to your head:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Check out this article over at HTML5 Rocks for some good examples

Multi-Line Comments in Ruby?

=begin
(some code here)
=end

and

# This code
# on multiple lines
# is commented out

are both correct. The advantage of the first type of comment is editability—it's easier to uncomment because fewer characters are deleted. The advantage of the second type of comment is readability—reading the code line by line, it's much easier to tell that a particular line has been commented out. Your call but think about who's coming after you and how easy it is for them to read and maintain.

Difference between a View's Padding and Margin

Sometimes you can achieve the same result by playing only with padding OR margin. Example :

Say View X contains view Y (aka : View Y is inside View X).

-View Y with Margin=30 OR View X with Padding=30 will achieve the same result: View Y will have an offset of 30.

Ascending and Descending Number Order in java

You can sort the array first, and then loop through it twice, once in both directions:

Arrays.sort(arr); 
System.out.print("Numbers in Ascending Order:" ); 
for(int i = 0; i < arr.length; i++){ 
  System.out.print( " " + arr[i]); 
} 
System.out.print("Numbers in Descending Order: " ); 
for(int i = arr.length - 1; i >= 0; i--){ 
  System.out.print( " " + arr[i]); 
} 

How to append multiple values to a list in Python

You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

So you can use list.append() to append a single value, and list.extend() to append multiple values.

How to convert a Binary String to a base 10 integer in Java

Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.

public static String decimalToBinaryString(int value) {
    String str = "";
    while(value > 0) {
        if(value % 2 == 1) {
            str = "1"+str;
        } else {
            str = "0"+str;
        }
        value /= 2;
    }
    return str;
}

How to completely remove Python from a Windows machine?

Windows 7 64-bit, with both Python3.4 and Python2.7 installed at some point :)

I'm using Py.exe to route to Py2 or Py3 depending on the script's needs - but I previously improperly uninstalled Python27 before.

Py27 was removed manually from C:\python\Python27 (the folder Python27 was deleted by me previously)

Upon re-installing Python27, it gave the above error you specify.
It would always back out while trying to 'remove shortcuts' during the installation process.

I placed a copy of Python27 back in that original folder, at C:\Python\Python27, and re-ran the same failing Python27 installer. It was happy locating those items and removing them, and proceeded with the install.

This is not the answer that addresses registry key issues (others mention that) but it is somewhat of a workaround if you know of previous installations that were improperly removed.

You could have some insight to this by opening "regedit" and searching for "Python27" - a registry key appeared in my command-shell Cache pointing at c:\python\python27\ (which had been removed and was not present when searching in the registry upon finding it).

That may help point to previously improperly removed installations.

Good luck!

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

I faced this issue today, and I resolved it by doing the following steps:

1) manually inserting that troubling user providing value of mandatory fields into mysql.user

mysql> insert into user(Host, User, Password, ssl_type) 
   values ('localhost', 'jack', 'jack', 'ANY');

2)

mysql> select * from user where User = 'jack';
   1 row in set (0.00 sec)

3) A.

mysql> drop user jack;
Query OK, 0 rows affected (0.00 sec)

B. mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

C. mysql> create user 'jack' identified by 'jack';
Query OK, 0 rows affected (0.00 sec)

D. mysql> select Host, User, Password, ssl_type  from user where User = 'jack';
+-----------+-----------+-------------------------------------------+----------+
| Host      | User      | Password                                  | ssl_type |
+-----------+-----------+-------------------------------------------+----------+
| localhost | jack      | jack                                      | ANY      |
| %         | jack      | *45BB7035F11303D8F09B2877A00D2510DCE4D758 |          |
+-----------+-----------+-------------------------------------------+----------+
2 rows in set (0.00 sec)

4) A.

mysql> delete from user 
 where User = 'nyse_user' and 
       Host = 'localhost' and 
       Password ='nyse';
Query OK, 1 row affected (0.00 sec)

B.

mysql> select Host, User, Password, ssl_type  from user where User = 'jack';
+------+-----------+-------------------------------------------+----------+
| Host | User      | Password                                  | ssl_type |
+------+-----------+-------------------------------------------+----------+
| %    | jack      | *45BB7035F11303D8F09B2877A00D2510DCE4D758 |          |
+------+-----------+-------------------------------------------+----------+
1 row in set (0.00 sec)

Hope this helps.

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

position fixed header in html

body{
  margin:0;
  padding:0 0 0 0;
}
div#header{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  height:25;
}
@media screen{
 body>div#header{
   position: fixed;
 }
}
* html body{
  overflow:hidden;
} 
* html div#content{
  height:100%;
  overflow:auto;
}

AWS S3: how do I see how much disk space is using

In addition to Christopher's answer.

If you need to count total size of versioned bucket use:

aws s3api list-object-versions --bucket BUCKETNAME --output json --query "[sum(Versions[].Size)]"

It counts both Latest and Archived versions.

Failed to run sdkmanager --list with Java 9

Another solution possible to this error is check your Java version, maybe you can solve it downloading this jdk oracle-jdk-8, this was my mistake :P

Angular2 handling http response

in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).

It's nice because it can be used with all other Observable chained methods like .retry .map etc.

import {Observable} from 'rxjs/Rx';


  Http
  .put(...)
  .catch(err =>  { 
     notify('UI error handling');
     return Observable.throw(err); // observable needs to be returned or exception raised
  })
  .subscribe(data => ...) // handle success

from documentation:

Returns

(Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.

Volley - POST/GET parameters

In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().

If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example. It goes something like this

public class LoginRequest extends Request<String> {

    // ... other methods go here

    private Map<String, String> mParams;

    public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
        super(Method.POST, "http://test.url", errorListener);
        mListener = listener;
        mParams = new HashMap<String, String>();
        mParams.put("paramOne", param1);
        mParams.put("paramTwo", param2);

    }

    @Override
    public Map<String, String> getParams() {
        return mParams;
    }
}

Evan Charlton was kind enough to make a quick example project to show us how to use volley. https://github.com/evancharlton/folly/

What is REST call and how to send a REST call?

REST is just a software architecture style for exposing resources.

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.

A typical REST call to return information about customer 34456 could look like:

http://example.com/customer/34456

Have a look at the IBM tutorial for REST web services

How to find a Java Memory Leak

You really need to use a memory profiler that tracks allocations. Take a look at JProfiler - their "heap walker" feature is great, and they have integration with all of the major Java IDEs. It's not free, but it isn't that expensive either ($499 for a single license) - you will burn $500 worth of time pretty quickly struggling to find a leak with less sophisticated tools.

Convert string[] to int[] in one line of code using LINQ

EDIT: to convert to array

int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();

This should do the trick:

var asIntegers = arr.Select(s => int.Parse(s));

how to do bitwise exclusive or of two strings in python?

def strxor (s0, s1):
  l = [ chr ( ord (a) ^ ord (b) ) for a,b in zip (s0, s1) ]
  return ''.join (l)

(Based on Mark Byers answer.)

Mail multipart/alternative vs multipart/mixed

I hit this issue. This architecture (from Lain's answer) worked for me. Here is the solution in Python.

  • mixed
    • alternative
      • text
      • related
        • html
        • inline image
        • inline image
    • attachment
    • attachment

Here is the main email creation function:

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

Here is the full code for sending an email containing html/text/attachment:

import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE1 = 'client_secret.json'
location = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))
CLIENT_SECRET_FILE = os.path.join(location, CLIENT_SECRET_FILE1)
APPLICATION_NAME = 'Gmail API Python Send Email'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-email-send.json')
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    message1 = create_message_with_attachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    SendMessageInternal(service, "me", message1)

def SendMessageInternal(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        print 'Message Id: %s' % message['id']
        return message
    except errors.HttpError, error:
        print 'An error occurred: %s' % error
        return "error"

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}


def main():
    to = "[email protected]"
    sender = "[email protected]"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    attachment = "/path/to/file.pdf"
    SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachment)

if __name__ == '__main__':
    main()

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

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

One other thing. You may need to specify the -L option as well - eg

-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz

or you may end up with an error like

ld: cannot find -lbaz

How to clear react-native cache?

I had a similar problem, I tried to clear all the caches possible (tried almost all the solutions above) and the only thing that worked for me was to kill the expo app and to restart it.

Connection Strings for Entity Framework

Unfortunately, combining multiple entity contexts into a single named connection isn't possible. If you want to use named connection strings from a .config file to define your Entity Framework connections, they will each have to have a different name. By convention, that name is typically the name of the context:

<add name="ModEntity" connectionString="metadata=res://*/ModEntity.csdl|res://*/ModEntity.ssdl|res://*/ModEntity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
<add name="Entity" connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=SOMESERVER;Initial Catalog=SOMECATALOG;Persist Security Info=True;User ID=Entity;Password=Entity;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

However, if you end up with namespace conflicts, you can use any name you want and simply pass the correct name to the context when it is generated:

var context = new Entity("EntityV2");

Obviously, this strategy works best if you are using either a factory or dependency injection to produce your contexts.

Another option would be to produce each context's entire connection string programmatically, and then pass the whole string in to the constructor (not just the name).

// Get "Data Source=SomeServer..."
var innerConnectionString = GetInnerConnectionStringFromMachinConfig();
// Build the Entity Framework connection string.
var connectionString = CreateEntityConnectionString("Entity", innerConnectionString);
var context = new EntityContext(connectionString);

How about something like this:

Type contextType = typeof(test_Entities);
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
string entConnection = 
    string.Format(
        "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\"{1}\"",
        contextType.Name,
        innerConnectionString);
object objContext = Activator.CreateInstance(contextType, entConnection);
return objContext as test_Entities; 

... with the following in your machine.config:

<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

This way, you can use a single connection string for every context in every project on the machine.

Multiline for WPF TextBox

Here is a sample XAML that will allow TextBox to accept multiline text and it uses its own scrollbars:

<TextBox
Height="200"
Width="500"
TextWrapping="Wrap"
AcceptsReturn="True"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"/>

How do I prevent site scraping?

One way would be to serve the content as XML attributes, URL encoded strings, preformatted text with HTML encoded JSON, or data URIs, then transform it to HTML on the client. Here are a few sites which do this:

  • Skechers: XML

    <document 
     filename="" 
     height="" 
     width="" 
     title="SKECHERS" 
     linkType="" 
     linkUrl="" 
     imageMap="" 
     href=&quot;http://www.bobsfromskechers.com&quot; 
     alt=&quot;BOBS from Skechers&quot; 
     title=&quot;BOBS from Skechers&quot; 
    />
    
  • Chrome Web Store: JSON

    <script type="text/javascript" src="https://apis.google.com/js/plusone.js">{"lang": "en", "parsetags": "explicit"}</script>
    
  • Bing News: data URL

    <script type="text/javascript">
      //<![CDATA[
      (function()
        {
        var x;x=_ge('emb7');
        if(x)
          {
          x.src='data:image/jpeg;base64,/*...*/';
          } 
        }() )
    
  • Protopage: URL Encoded Strings

    unescape('Rolling%20Stone%20%3a%20Rock%20and%20Roll%20Daily')
    
  • TiddlyWiki : HTML Entities + preformatted JSON

       <pre>
       {&quot;tiddlers&quot;: 
        {
        &quot;GettingStarted&quot;: 
          {
          &quot;title&quot;: &quot;GettingStarted&quot;,
          &quot;text&quot;: &quot;Welcome to TiddlyWiki,
          }
        }
       }
       </pre>
    
  • Amazon: Lazy Loading

    amzn.copilot.jQuery=i;amzn.copilot.jQuery(document).ready(function(){d(b);f(c,function() {amzn.copilot.setup({serviceEndPoint:h.vipUrl,isContinuedSession:true})})})},f=function(i,h){var j=document.createElement("script");j.type="text/javascript";j.src=i;j.async=true;j.onload=h;a.appendChild(j)},d=function(h){var i=document.createElement("link");i.type="text/css";i.rel="stylesheet";i.href=h;a.appendChild(i)}})();
    amzn.copilot.checkCoPilotSession({jsUrl : 'http://z-ecx.images-amazon.com/images/G/01/browser-scripts/cs-copilot-customer-js/cs-copilot-customer-js-min-1875890922._V1_.js', cssUrl : 'http://z-ecx.images-amazon.com/images/G/01/browser-scripts/cs-copilot-customer-css/cs-copilot-customer-css-min-2367001420._V1_.css', vipUrl : 'https://copilot.amazon.com'
    
  • XMLCalabash: Namespaced XML + Custom MIME type + Custom File extension

       <p:declare-step type="pxp:zip">
            <p:input port="source" sequence="true" primary="true"/>
            <p:input port="manifest"/>
            <p:output port="result"/>
            <p:option name="href" required="true" cx:type="xsd:anyURI"/>
            <p:option name="compression-method" cx:type="stored|deflated"/>
            <p:option name="compression-level" cx:type="smallest|fastest|default|huffman|none"/>
            <p:option name="command" select="'update'" cx:type="update|freshen|create|delete"/>
       </p:declare-step>
    

If you view source on any of the above, you see that scraping will simply return metadata and navigation.

How to insert a new line in Linux shell script?

echo $'Create the snapshots\nSnapshot created\n'

Fixing the order of facets in ggplot

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

Then change the facet_grid(.~size) to facet_grid(.~size_f)

Then plot: enter image description here

The graphs are now in the correct order.

Is it possible to convert char[] to char* in C?

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:

int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
    buf[i] = (int*) malloc(N * sizeof(int));

and then you can reference buf[3][5] or whatever.

How to install a specific version of a ruby gem?

As others have noted, in general use the -v flag for the gem install command.

If you're developing a gem locally, after cutting a gem from your gemspec:

$ gem install gemname-version.gem

Assuming version 0.8, it would look like this:

$ gem install gemname-0.8.gem

python exception message capturing

The syntax is no longer supported in python 3. Use the following instead.

try:
    do_something()
except BaseException as e:
    logger.error('Failed to do something: ' + str(e))

How to configure postgresql for the first time?

This is my solution:

su root
su postgres
psql