Programs & Examples On #Dev null

Position absolute and overflow hidden

You just make divs like this:

<div style="width:100px; height: 100px; border:1px solid; overflow:hidden; ">
    <br/>
    <div style="position:inherit; width: 200px; height:200px; background:yellow;">
        <br/>
        <div style="position:absolute; width: 500px; height:50px; background:Pink; z-index: 99;">
            <br/>
        </div>
    </div>
</div>

I hope this code will help you :)

How to select rows for a specific date, ignoring time in SQL Server

Something like this:

select 
  * 
from sales 
where salesDate >= '11/11/2010' 
  AND salesDate < (Convert(datetime, '11/11/2010') + 1)

Bootstrap - Removing padding or margin when screen size is smaller

The problem here is much more complex than removing the container padding since the grid structure relies on this padding when applying negative margins for the enclosed rows.

Removing the container padding in this case will cause an x-axis overflow caused by all the rows inside of this container class, this is one of the most stupid things about the Bootstrap Grid.

Logically it should be approached by

  1. Never using the .container class for anything other than rows
  2. Make a clone of the .container class that has no padding for use with non-grid html
  3. For removing the .container padding on mobile you can manually remove it with media queries then overflow-x: hidden; which is not very reliable but works in most cases.

If you are using LESS the end result will look like this

@media (max-width: @screen-md-max) {
    .container{
        padding: 0;
        overflow-x: hidden;
    }
}

Change the media query to whatever size you want to target.

Final thoughts, I would highly recommend using the Foundation Framework Grid as its way more advanced

String MinLength and MaxLength validation don't work (asp.net mvc)

They do now, with latest version of MVC (and jquery validate packages). mvc51-release-notes#Unobtrusive

Thanks to this answer for pointing it out!

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

How to force Selenium WebDriver to click on element which is not currently visible?

There is also another case when visible element will be recognized as not visible:

  • When the Element is CSS transformed
  • When Parent Element of the Element is CSS transformed

In order to check if element you wan't to interact with is CSS transformed, on CHROME do this:

  1. open inspector
  2. Find interesting element (or more likely its parent element, supposedly div element)
  3. Select 'Computed' tab
  4. if there is a parameter: webkit-transform: matrix( ... ) it means that the element is CSS transformed, and may not be recognized by selenium 2 as a visible element

Scroll to bottom of Div on page load (jQuery)

All the answers that I can see here, including the currently "accepted" one, is actually wrong in that they set:

scrollTop = scrollHeight

Whereas the correct approach is to set:

scrollTop = scrollHeight - clientHeight

In other words:

$('#div1').scrollTop($('#div1')[0].scrollHeight - $('#div1')[0].clientHeight);

Or animated:

$("#div1").animate({
  scrollTop: $('#div1')[0].scrollHeight - $('#div1')[0].clientHeight
}, 1000);

The type or namespace name 'System' could not be found

i had to upgrade from visual studio 2017 to 2019. no other proposed solution here helped me, i installed and configured, rebooted every one here plus many other options from ms site.

my root cause was probably due to the fact the git repository developer used 2019 and i tried to clone the original git repo into ma 2017.

How do I download a tarball from GitHub using cURL?

with a specific dir:

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

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Screen Size Class

-

  1. Hidden on all .d-none

  2. Hidden only on xs .d-none .d-sm-block

  3. Hidden only on sm .d-sm-none .d-md-block

  4. Hidden only on md .d-md-none .d-lg-block

  5. Hidden only on lg .d-lg-none .d-xl-block

  6. Hidden only on xl .d-xl-none

  7. Visible on all .d-block

  8. Visible only on xs .d-block .d-sm-none

  9. Visible only on sm .d-none .d-sm-block .d-md-none

  10. Visible only on md .d-none .d-md-block .d-lg-none

  11. Visible only on lg .d-none .d-lg-block .d-xl-none

  12. Visible only on xl .d-none .d-xl-block

Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements

What are the date formats available in SimpleDateFormat class?

Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {
   public static void main(String[] args) {
       Date now = new Date();

       //This is just Date's toString method and doesn't involve SimpleDateFormat
       System.out.println("toString(): " + now);  // dow mon dd hh:mm:ss zzz yyyy
       //Shows  "Mon Oct 08 08:17:06 EDT 2012"

       SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
       System.out.println("Format 1:   " + dateFormatter.format(now));
       // Shows  "Mon, 2012-10-8 at 8:17:6 AM EDT"

       dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
       System.out.println("Format 2:   " + dateFormatter.format(now));
       // Shows  "Mon 2012.10.08 at 08:17:06 AM EDT"

       dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
       System.out.println("Format 3:   " + dateFormatter.format(now));
       // Shows  "Monday, October 8, 2012"

       // SimpleDateFormat can be used to control the date/time display format:
       //   E (day of week): 3E or fewer (in text xxx), >3E (in full text)
       //   M (month): M (in number), MM (in number with leading zero)
       //              3M: (in text xxx), >3M: (in full text full)
       //   h (hour): h, hh (with leading zero)
       //   m (minute)
       //   s (second)
       //   a (AM/PM)
       //   H (hour in 0 to 23)
       //   z (time zone)
       //  (there may be more listed under the API - I didn't check)

   }

}

Good luck!

Error Code: 2013. Lost connection to MySQL server during query

I faced this same issue. I believe it happens when you have foreign keys to larger tables (which takes time).

I tried to run the create table statement again without the foreign key declarations and found it worked.

Then after creating the table, I added the foreign key constrains using ALTER TABLE query.

Hope this will help someone.

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

How to open html file?

CODE:

import codecs

path="D:\\Users\\html\\abc.html" 
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)

What's the difference between SHA and AES encryption?

SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.

AES Reference

Media Player called in state 0, error (-38,0)

I got this error when I was trying to get the current position (MediaPlayer.getCurrentPosition()) of media player when it wasn't in the prepared stated. I got around this by Keeping track of its state and only calling the getCurrentPosition() method after onPreparedListener is called.

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

It took a few tries, but I was able to get your jsFiddle to work (for Webkit only).

There's still an issue with the animation speed when the user re-enters the div.

Basically, just set the current rotation value to a variable, then do some calculations on that value (to convert to degrees), then set that value back to the element on mouse move and mouse enter.

Check out the jsFiddle: http://jsfiddle.net/4Vz63/46/

Check out this article for more information, including how to add cross-browser compatibility: http://css-tricks.com/get-value-of-css-rotation-through-javascript/

How to change a DIV padding without affecting the width/height ?

Solution is to wrap your padded div, with fixed width outer div

HTML

<div class="outer">
    <div class="inner">

        <!-- your content -->

    </div><!-- end .inner -->
</div><!-- end .outer -->

CSS

.outer, .inner {
    display: block;
}

.outer {
    /* specify fixed width */
    width: 300px;
    padding: 0;
}

.inner {
    /* specify padding, can be changed while remaining fixed width of .outer */
    padding: 5px;
}

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

As a picture is worth a thousand words..

When you find the IIS6 manager (I have found that searching for IIS may return 2 results) go to the SMTP server properties then 'Access' then press the relay button.

Then you can either select all or only allow certain ip's like 127.0.0.1

SMTP Relay

How do I find out if a column exists in a VB.Net DataRow

Another way to find out if a column exists is to check for Nothing the value returned from the Columns collection indexer when passing the column name to it:

If dataRow.Table.Columns("ColumnName") IsNot Nothing Then
    MsgBox("YAY")
End If

This approach might be preferred over the one that uses the Contains("ColumnName") method when the following code will subsequently need to get that DataColumn for further usage. For example, you may want to know which type has a value stored in the column:

Dim column = DataRow.Table.Columns("ColumnName")
If column IsNot Nothing Then
    Dim type = column.DataType
End If

In this case this approach saves you a call to the Contains("ColumnName") at the same time making your code a bit cleaner.

New line in Sql Query

use CHAR(10) for New Line in SQL
char(9) for Tab
and Char(13) for Carriage Return

node.js, socket.io with SSL

This is how I managed to set it up with express:

var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var server = https.createServer({
    key: fs.readFileSync('./test_key.key'),
    cert: fs.readFileSync('./test_cert.crt'),
    ca: fs.readFileSync('./test_ca.crt'),
    requestCert: false,
    rejectUnauthorized: false
},app);
server.listen(8080);

var io = require('socket.io').listen(server);

io.sockets.on('connection',function (socket) {
    ...
});

app.get("/", function(request, response){
    ...
})


I hope that this will save someone's time.

Update : for those using lets encrypt use this

var server = https.createServer({ 
                key: fs.readFileSync('privkey.pem'),
                cert: fs.readFileSync('fullchain.pem') 
             },app);

DataGridView changing cell background color

int rowscount = dataGridView1.Rows.Count;         

for (int i = 0; i < rowscount; i++)
{            
    if (!(dataGridView1.Rows[i].Cells[8].Value == null))
    {
        dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow;
    }
}

Append value to empty vector in R?

You have a few options:

  • c(vector, values)

  • append(vector, values)

  • vector[(length(vector) + 1):(length(vector) + length(values))] <- values

The first one is the standard approach. The second one gives you the option to append someplace other than the end. The last one is a bit contorted but has the advantage of modifying vector (though really, you could just as easily do vector <- c(vector, values).

Notice that in R you don't need to cycle through vectors. You can just operate on them in whole.

Also, this is fairly basic stuff, so you should go through some of the references.

Some more options based on OP feedback:

for(i in values) vector <- c(vector, i)

Finding Variable Type in JavaScript

In JavaScript everything is an object

console.log(type of({}))  //Object
console.log(type of([]))  //Object

To get Real type , use this

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

Hope this helps

How to set cache: false in jQuery.get call

Set cache: false in jQuery.get call using Below Method

use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond.

Or

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });

What is the difference between .*? and .* regular expressions?

It is the difference between greedy and non-greedy quantifiers.

Consider the input 101000000000100.

Using 1.*1, * is greedy - it will match all the way to the end, and then backtrack until it can match 1, leaving you with 1010000000001.
.*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1, eventually matching 101.

All quantifiers have a non-greedy mode: .*?, .+?, .{2,6}?, and even .??.

In your case, a similar pattern could be <([^>]*)> - matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than > in-between < and >).

See Quantifier Cheat Sheet.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

View JSON file in Browser

Right click on JSON file, select open, navigate to program you want open with(notepad). Consecutive opens automatically use notepad.

Codeigniter LIKE with wildcard(%)

I'm using

$this->db->query("SELECT * FROM film WHERE film.title LIKE '%$query%'"); for such purposes

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document , and fortunately it's solved easier:

Instead of

List<Document> docs = obj.get("documents");
Document doc = docs.get(0)

which gives error on second line, One can use

List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));

Difference between spring @Controller and @RestController annotation

@RestController annotated classes are the same as @Controller but the @ResponseBody on the handler methods are implied.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

This post is right from SAP on Sep 20, 2012.

In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.

If you want to download that version you can find it here.

Further, service packs etc. when released can be found here.


I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.

How to store an output of shell script to a variable in Unix?

You should probably re-write the script to return a value rather than output it. Instead of:

a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
   success) echo script succeeded;;
   Failed) echo script failed;;
esac

you would be able to do:

if script.sh > /dev/null; then
    echo script succeeded
else
    echo script failed
fi

It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0 instead of printing success, and exit 1 instead of printing Failed. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.

How do I concatenate two strings in Java?

The java 8 way:

StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);


StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);

Removing Spaces from a String in C?

#include<stdio.h>
#include<string.h>
main()
{
  int i=0,n;
  int j=0;
  char str[]="        Nar ayan singh              ";
  char *ptr,*ptr1;
  printf("sizeof str:%ld\n",strlen(str));
  while(str[i]==' ')
   {
     memcpy (str,str+1,strlen(str)+1);
   }
  printf("sizeof str:%ld\n",strlen(str));
  n=strlen(str);
  while(str[n]==' ' || str[n]=='\0')
    n--;
  str[n+1]='\0';
  printf("str:%s ",str);
  printf("sizeof str:%ld\n",strlen(str));
}

How to use GROUP BY to concatenate strings in MySQL?

Great answers. I also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows:

SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ') 
FROM table 
GROUP BY id;

Hope this helps someone else

Version of Apache installed on a Debian machine

For me apachectl -V did not work, but apachectl fullstatus gave me my version.

Fit background image to div

you also use this:

background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%; 

I don't know your div-values, but let's assume you've got those.

height: auto;
max-width: 600px;

Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.

Chris

Get the Id of current table row with Jquery

Create a class in css name it .buttoncontact, add the class attribute to your buttons

function ClickedRow() {
    $(document).on('click', '.buttoncontact', function () {
        var row = $(this).parents('tr').attr('id');
        var rowtext = $(this).closest('tr').text();
        alert(row);      
    });
}

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

Use dynamic (variable) string as regex pattern in JavaScript

Much easier way: use template literals.

var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false

Setting CSS pseudo-class rules from JavaScript

If you use REACT , There is something called radium. It is so useful here :

  • Add handlers to props if interactive styles are specified, e.g. onMouseEnter for :hover, wrapping existing handlers if necessary

  • If any of the handlers are triggered, e.g. by hovering, Radium calls setState to update a Radium-specific field on the components state object

  • On re-render, resolve any interactive styles that apply, e.g. :hover, by looking up the element's key or ref in the Radium-specific state

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

Revert to Eclipse default settings

  • Window > Preferences > Editors > Restore Defaults

  • Window > Preferences > Java > Editor > Syntax Coloring > Restore Defaults

  • Window > Preferences > JavaScript > Editor > Syntax Coloring > Restore Defaults

  • Window > Preferences > Web > CSS Files > Editor > Syntax Coloring > Restore Defaults

  • Window > Preferences > Web > HTML Files > Editor > Syntax Coloring > Restore Defaults

  • Window > Preferences > Web > JSP Files > Editor > Syntax Coloring > Restore Defaults

  • Window > Preferences > XML > DTD Files > Syntax Coloring > Restore Defaults

  • Window > Preferences > XML > XML Files > Editor > Syntax Coloring > Restore Defaults

  • Window > Preferences > XML > XSL > Syntax Coloring > Restore Defaults

  • Window > Preferences > Data Management > SQL Development > SQL Editor > Syntax Coloring > Restore Defaults

Import Python Script Into Another?

I highly recommend the reading of a lecture in SciPy-lectures organization:

https://scipy-lectures.org/intro/language/reusing_code.html

It explains all the commented doubts.

But, new paths can be easily added and avoiding duplication with the following code:

import sys
new_path = 'insert here the new path'

if new_path not in sys.path:
    sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script

How can I handle the warning of file_get_contents() function in PHP?

Here's how I handle that:

$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
    $error = error_get_last();
    $error = explode(': ', $error['message']);
    $error = trim($error[2]) . PHP_EOL;
    fprintf(STDERR, 'Error: '. $error);
    die();
}

Subtract two dates in Java

Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
            getParameter(date2));

long diff = d2.getTime() - d1.getTime();

System.out.println("Difference between  " + d1 + " and "+ d2+" is "
        + (diff / (1000 * 60 * 60 * 24)) + " days.");

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

A simple way is set android:usesCleartextTraffic="true" on you AndroidManifest.xml

android:usesCleartextTraffic="true"

Your AndroidManifest.xml look like

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.dww.drmanar">
   <application
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:usesCleartextTraffic="true"
       android:theme="@style/AppTheme"
       tools:targetApi="m">
       <activity
            android:name=".activity.SplashActivity"
            android:theme="@style/FullscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
       </activity>
    </application>
</manifest>

I hope this will help you.

How can I push a specific commit to a remote, and not previous commits?

The simplest way to accomplish this is to use two commands.

First, get the local directory into the state that you want. Then,

$ git push origin +HEAD^:someBranch

removes the last commit from someBranch in the remote only, not local. You can do this a few times in a row, or change +HEAD^ to reflect the number of commits that you want to batch remove from remote. Now you're back on your feet, and use

$ git push origin someBranch

as normal to update the remote.

Create a view with ORDER BY clause

Just use TOP 100 Percent in the Select:

     CREATE VIEW [schema].[VIEWNAME] (
         [COLUMN1],
         [COLUMN2],
         [COLUMN3],
         [COLUMN4])
     AS 
        SELECT TOP 100 PERCENT 
         alias.[COLUMN1],
         alias.[COLUMN2],
         alias.[COLUMN3],
         alias.[COLUMN4]
        FROM 
           [schema].[TABLENAME] AS alias
          ORDER BY alias.COLUMN1
     GO

jquery background-color change on focus and blur

Tested Code:

$("input").css("background","red");

Complete:

$('input:text').focus(function () {
    $(this).css({ 'background': 'Black' });
});

$('input:text').blur(function () {
    $(this).css({ 'background': 'red' });
});

Tested in version:

jquery-1.9.1.js
jquery-ui-1.10.3.js

How to set environment via `ng serve` in Angular 6

For Angular 2 - 5 refer the article Multiple Environment in angular

For Angular 6 use ng serve --configuration=dev

Note: Refer the same article for angular 6 as well. But wherever you find --env instead use --configuration. That's works well for angular 6.

Detecting which UIButton was pressed in a UITableView

create an nsmutable array and put all button in that array usint[array addObject:yourButton];

in the button press method

-

 (void)buttonPressedAction:(id)sender
{
    UIButton *button = (UIButton *)sender;

for(int i=0;i<[yourArray count];i++){

if([buton isEqual:[yourArray objectAtIndex:i]]){

//here write wat u need to do

}
}

Check if a variable exists in a list in Bash

IMHO easiest solution is to prepend and append the original string with a space and check against a regex with [[ ]]

haystack='foo bar'
needle='bar'

if [[ " $haystack " =~ .*\ $needle\ .* ]]; then
    ...
fi

this will not be false positive on values with values containing the needle as a substring, e.g. with a haystack foo barbaz.

(The concept is shamelessly stolen form JQuery's hasClass()-Method)

Python, creating objects

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

The correct way to read a data file into an array

I like...

@data = `cat /var/tmp/somefile`;

It's not as glamorous as others, but, it works all the same. And...

$todays_data = '/var/tmp/somefile' ;
open INFILE, "$todays_data" ; 
@data = <INFILE> ; 
close INFILE ;

Cheers.

Create Elasticsearch curl query for not null and not empty("")

A null value and an empty string both result in no value being indexed, in which case you can use the exists filter

curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1'  -d '
{
   "query" : {
      "constant_score" : {
         "filter" : {
            "exists" : {
               "field" : "myfield"
            }
         }
      }
   }
}
'

Or in combination with (eg) a full text search on the title field:

curl -XGET 'http://127.0.0.1:9200/test/test/_search?pretty=1'  -d '
{
   "query" : {
      "filtered" : {
         "filter" : {
            "exists" : {
               "field" : "myfield"
            }
         },
         "query" : {
            "match" : {
               "title" : "search keywords"
            }
         }
      }
   }
}
'

How can I make an svg scale with its parent container?

You'll want to do a transform as such:

with JavaScript:

document.getElementById(yourtarget).setAttribute("transform", "scale(2.0)");

With CSS:

#yourtarget {
  transform:scale(2.0);
  -webkit-transform:scale(2.0);
}

Wrap your SVG Page in a Group tag as such and target it to manipulate the whole page:

<svg>
  <g id="yourtarget">
    your svg page
  </g>
</svg>

Note: Scale 1.0 is 100%

Where does Git store files?

I also couldn't find my git repository. I am using Windows 8 and created my repository (by mistake) under C:\Program Files (x86)\Git. I could see the repository folder in bash but not in cmd or Windows Explorer.

Then I remembered about Windows's "Virtual Store" feature. My repository folder was actually created under C:\Users\<username>\AppData\Local\VirtualStore\Program Files (x86)\Git\<myrepo> and in there was my .git folder!

What does href expression <a href="javascript:;"></a> do?

basically instead of using the link to move pages (or anchors), using this method launches a javascript function(s)

<script>
function doSomething() {
  alert("hello")
}
</script>
<a href="javascript:doSomething();">click me</a>

clicking the link will fire the alert.

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

declare @T1 table(ID int, ReceivedDate datetime, [type] varchar(10))
declare @T2 table(ID int, ReceivedDate datetime, [type] varchar(10))

insert into @T1 values(1, '20010101', '1')
insert into @T1 values(2, '20010102', '1')
insert into @T1 values(3, '20010103', '1')

insert into @T2 values(10, '20010101', '2')
insert into @T2 values(20, '20010102', '2')
insert into @T2 values(30, '20010103', '2')

;with cte1 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T1
  where [type] = '1'
),
cte2 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T2
  where [type] = '2'
)
select *
from cte1
where rn <= 2
union all
select *
from cte2
where rn <= 2

How to display a gif fullscreen for a webpage background?

IMG Method

If you want the image to be a stand alone element, use this CSS:

#selector {
    width:100%;
    height:100%;
}

With this HTML:

<img src='folder/image.gif' id='selector'/>

Fiddle

Please note that the img tag would have to be inside the body tag ONLY. If it were inside anything else, it may not fill the entire screen based on the other elements properties. This method will also not work if the page is taller than the image. It will leave white space. This is where the background method comes in

Background Image Method

If you want it to be the background image of you page, you can use this CSS:

body {
    background-image:url('folder/image.gif');
    background-size:100%;
    background-repeat: repeat-y;
    background-attachment: fixed;
    height:100%;
    width:100%;
}

Fiddle

Or the shorthand version:

body {
    background:url('folder/image.gif') repeat-y 100% 100% fixed;
    height:100%;
    width:100%;
}

Fiddle

Laravel 5 – Remove Public from URL

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteRule ^(.*)$ public/$1 [L]
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Activate the mod_rewrite module with

sudo a2enmod rewrite

and restart the apache

sudo service apache2 restart

To use mod_rewrite from within .htaccess files (which is a very common use case), edit the default VirtualHost with

sudo nano /etc/apache2/sites-available/000-default.conf

Below "DocumentRoot /var/www/html" add the following lines:

<Directory "/var/www/html">
AllowOverride All
</Directory>

Restart the server again:

sudo service apache2 restart

How to delete an element from a Slice in Golang

I take the below approach to remove the item in slice. This helps in readability for others. And also immutable.

func remove(items []string, item string) []string {
    newitems := []string{}

    for _, i := range items {
        if i != item {
            newitems = append(newitems, i)
        }
    }

    return newitems
}

Change the Arrow buttons in Slick slider

If you are using sass you can simply set below mentioned variables,

$slick-font-family:FontAwesome;
$slick-prev-character: "\f053";
$slick-next-character: "\f054";

These will change the font family used by slick's theme css and also the unicode for prev and next button.

Other sass variables which can be configured are given in Slick Github page

Cross-Origin Request Blocked

You have to placed this code in application.rb

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}

How to make a background 20% transparent on Android

I know, that's a very old question.

If you want use a color value, you can also use the short version of that with #ARGB. Where A is the value for the alpha channel.

In case of a white color there are the following transparency values:

#FFFF  -     0%
#EFFF  -   6,7%
#DFFF  -  13,3%
#CFFF  -  20,0%
#BFFF  -  26,7%
#AFFF  -  33,3%
#9FFF  -  40,0%
#FFF8  -  46,7%
#7FFF  -  53,3%
#6FFF  -  60,0%
#5FFF  -  66,7%
#4FFF  -  73,3%
#3FFF  -  80,0%
#2FFF  -  86,7%
#1FFF  -  93,3%
#0FFF  - 100,0%

So you can for TextView add the following line for 20% transparency:

<TextView
    android:background="#CFFF"
    ... />

How do you add a timer to a C# console application

In C# 5.0+ and .NET Framework 4.5+ you can use async/await:

async void RunMethodEvery(Action method, double seconds)
{
    while (true)
    {
        await Task.Delay(TimeSpan.FromSeconds(seconds));
        method();
    }
 }

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

CSS: Change image src on img:hover

Fiddle

Agree with AshisKumar's answer,
there is a way to change image url on mouse over by using jQuery functionality as below:

$(function() {
  $("img")
    .mouseover(function() { 
        var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
        $(this).attr("src", url1); //URL @the time of mouse over on image
    })
    .mouseout(function() {
        var src = $(this).attr("src").replace("over", "");
        $(this).attr("src", url2); //default URL
    });
 });

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Expression ___ has changed after it was checked

Can't you use ngOnInit because you just changing the member variable message?

If you want to access a reference to a child component @ViewChild(ChildComponent), you indeed need to wait for it with ngAfterViewInit.

A dirty fix is to call the updateMessage() in the next event loop with e.g. setTimeout.

ngAfterViewInit() {
  setTimeout(() => {
    this.updateMessage();
  }, 1);
}

How do I render a shadow?

    viewStyle : {
    backgroundColor: '#F8F8F8',
    justifyContent: 'center',
    alignItems: 'center',
    height: 60,
    paddingTop: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    marginBottom: 10,
    elevation: 2,
    position: 'relative'
},

Use marginBottom: 10

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

How do I specify unique constraint for multiple columns in MySQL?

If you want to avoid duplicates in future. Create another column say id2.

UPDATE tablename SET id2 = id;

Now add the unique on two columns:

alter table tablename add unique index(columnname, id2);

How to use org.apache.commons package?

You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.

For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.

If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.

For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.

If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.

Allow multi-line in EditText view in Android?

This is how I applied the code snippet below and it's working fine. Hope, this would help somebody.

<EditText 
    android:id="@+id/EditText02"
    android:gravity="top|left" 
    android:inputType="textMultiLine"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:lines="5" 
    android:scrollHorizontally="false" 
/>

Cheers! ...Thanks.

Why is lock(this) {...} bad?

Because if people can get at your object instance (ie: your this) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on this internally, so this may cause problems (possibly a deadlock)

In addition to this, it's also bad practice, because it's locking "too much"

For example, you might have a member variable of List<int>, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.

How to check if an email address exists without sending an email?

Some issues:

  1. I'm sure some SMTP servers will let you know immediately if an address you give them does not exist, but some won't as a privacy measure. They'll just accept whatever addresses you give them and silently ignore the ones that don't exist.
  2. As the article says, if you do this too often with some servers, they will blacklist you.
  3. For some SMTP servers (like gmail), you need to use SSL in order to do anything. This is only true when using gmail's SMTP server to send email.

PostgreSQL database service

Your server running on port 5432 but in the properties, the port is set to 5433.

You must go to pgAdmin, click on database version, ex: PostgresSQL 10 and edit properties.

A new window appears and you need to change the port to 5432 [this is default port].

Ubuntu, how do you remove all Python 3 but not 2

EDIT: As pointed out in recent comments, this solution may BREAK your system.

You most likely don't want to remove python3.

Please refer to the other answers for possible solutions.

Outdated answer (not recommended)

sudo apt-get remove 'python3.*'

How to Git stash pop specific stash in 1.8.3?

First check the list:-

git stash list

copy the index you wanted to pop from the stash list

git stash pop stash@{index_number}

eg.:

git stash pop stash@{1}

Laravel Update Query

Try doing it like this.

User::where('email', $userEmail)
       ->update([
           'member_type' => $plan
        ]);

label or @html.Label ASP.net MVC 4

The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.

With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.

jQuery toggle CSS?

I would use the toggleClass function in jQuery and define the CSS to the class e.g.

/* start of css */
#user_button.active {
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    -webkit-border-bottom-right-radius: 5px; /* user-agent specific */
    -webkit-border-bottom-left-radius: 5px;
    -moz-border-radius-bottomright: 5px;
    -moz-border-radius-bottomleft: 5px; /* etc... */
}
/* start of js */
$('#user_button').click(function() {
    $('#user_options').toggle();
    $(this).toggleClass('active');
    return false;
})

ASP.NET MVC passing an ID in an ActionLink to the controller

In MVC 4 you can link from one view to another controller passing the Id or Primary Key via

@Html.ActionLink("Select", "Create", "StudentApplication", new { id=item.PersonId }, null) 

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

Imagine you have a numpy array of integers (it works with other types but you need some slight modification). You can do this:

a = np.array([0, 3, 5])
a_str = ','.join(str(x) for x in a) # '0,3,5'
a2 = np.array([int(x) for x in a_str.split(',')]) # np.array([0, 3, 5])

If you have an array of float, be sure to replace int by float in the last line.

You can also use the __repr__() method, which will have the advantage to work for multi-dimensional arrays:

from numpy import array
numpy.set_printoptions(threshold=numpy.nan)
a = array([[0,3,5],[2,3,4]])
a_str = a.__repr__() # 'array([[0, 3, 5],\n       [2, 3, 4]])'
a2 = eval(a_str) # array([[0, 3, 5],
                 #        [2, 3, 4]])

'Source code does not match the bytecode' when debugging on a device

There's an open issue for this in Google's IssueTracker.

The potential solutions given in the issue (as of the date of this post) are:

  • Click Build -> Clean
  • Disable Instant Run, in Settings -> Build, Execution, Deployment

Simple IEnumerator use (with example)

public IEnumerable<string> Appender(IEnumerable<string> strings)
{
  List<string> myList = new List<string>();
  foreach(string str in strings)
  {
      myList.Add(str + "roxxors");
  }
  return myList;
}

or

public IEnumerable<string> Appender(IEnumerable<string> strings)
{
  foreach(string str in strings)
  {
      yield return str + "roxxors";
  }
}

using the yield construct, or simply

var newCollection = strings.Select(str => str + "roxxors"); //(*)

or

var newCollection = from str in strings select str + "roxxors"; //(**)

where the two latter use LINQ and (**) is just syntactic sugar for (*).

Regex to get the words after matching string

Here's a quick Perl script to get what you need. It needs some whitespace chomping.

#!/bin/perl

$sample = <<END;
Subject:
  Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
  Account Name:       ChamaraKer
  Account Domain:     JIC
  Logon ID:       0x1fffb

Object:
  Object Server:  Security
  Object Type:    File
  Object Name:    D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
  Handle ID:  0x11dc
END

my @sample_lines = split /\n/, $sample;
my $path;

foreach my $line (@sample_lines) {
  ($path) = $line =~ m/Object Name:([^s]+)/g;
  if($path) {
    print $path . "\n";
  }
}

Difference between & and && in Java?

& is bitwise AND operator comparing bits of each operand.
For example,

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100


&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

I encountered a similar error with while attempting to play an audio file. At first, it was working, then it stopped working when I started using ChangeDetector's markForCheck method in the same function to trigger a re-render when a promise resolves (I had an issue with view rendering).

When I changed the markForCheck to detectChanges it started working again. I really can't explain what happened, I just thought of dropping this here, perhaps it would help someone.

JavaScript - cannot set property of undefined

d = {} is an empty object right now.

And d[a] is also an empty object.

It does not have any key values. So you should initialize the key values to this.

d[a] = {
greetings:'',
data:''
}

Str_replace for multiple items

For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:

print str_replace(
    array("search1","search2"),
    array("replace1", "replace2"),
    "search1 search2"
);

// Output: replace1 replace2

Git push hangs when pushing to Github?

Try creating a script like ~/sshv.sh that will show you what ssh is up to:

#!/bin/bash
ssh -vvv "$@"

Allow execution of the ~/sshv.sh file for the owner of the file:

chmod u+x ~/sshv.sh

Then invoke your git push with:

GIT_SSH=~/sshv.sh git push ...

In my case, this helped me figure out that I was using ssh shared connections that needed to be closed, so I killed those ssh processes and it started working.

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

How to count the number of files in a directory using Python

I solved this problem while calculating the number of files in a google drive directory through Google Colab by directing myself into the directory folder by

import os                                                                                                
%cd /content/drive/My Drive/  
print(len([x for x in os.listdir('folder_name/']))  

Normal user can try

 import os                                                                                                     
 cd Desktop/Maheep/                                                     
 print(len([x for x in os.listdir('folder_name/']))  

How do I build an import library (.lib) AND a DLL in Visual C++?

OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.

#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif

Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:

BARNABY_API int add(){
}

This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.

Android - Pulling SQlite database android device

It is always better if things are automated.That's why I wrote simple python script for copying db file from device using ADB. It saves a lot of development time if you're doing it frequently.

Works only with debuggable apps if device is Not rooted.

Here is link to the gist.

Run it as : python copyandroiddbfile.py

import sys
import subprocess
import re

#/
# Created by @nieldeokar on 25/05/2018.
#/

# 1. Python script which will copy database file of debuggable apps from the android device to your computer using ADB.
# 2. This script ask for PackageName and DatabaseName at runtime.
# 3. You can make it static by passing -d at as command line argument while running script and setting defaults in following way.
# 4. Edit script and change the values of varialbe packageName and dbName to debuggable app package name and database name then
# run script as : python Copydbfileandroid.py -d 

useDefaults = False


def checkIfPackageInstalled(strSelectedDevice) :

    packageName = 'com.nileshdeokar.healthapp.debug'
    dbName = 'healthapp.db'


    if not useDefaults : 
        print('Please enter package name : ')
        packageName = raw_input()

    packageString = 'package:'+packageName

    try:
        adbCheckIfPackageInstalledOutput = subprocess.check_output('adb -s ' + strSelectedDevice + ' shell pm list packages | grep -x '+ packageString, shell=True)
    except subprocess.CalledProcessError as e:
                print "Package not found"
                return


    if packageString.strip() == adbCheckIfPackageInstalledOutput.strip() : 
        if not useDefaults : 
            print('Please enter db name : ')
            dbName = raw_input()

        adbCopyDbString = 'adb -s '+strSelectedDevice + ' -d shell \"run-as '+packageName+' cat /data/data/'+packageName+'/databases/'+ dbName +'\" > '+dbName

        try:
            copyDbOp = subprocess.check_output(adbCopyDbString,shell=True)
        except subprocess.CalledProcessError as e:
                return

        if "is not debuggable" in copyDbOp :
            print packageString + 'is nto debuggable'

        if copyDbOp.strip() == "":
            print 'Successfully copied '+dbName + ' in current directory'

    else :
        print 'Package is not installed on the device'



defaultString = "-d"
if len(sys.argv[1:]) > 0 and sys.argv[1] == defaultString :
        useDefaults = True

listDevicesOutput = subprocess.check_output("adb devices", shell=True)
listDevicesOutput = listDevicesOutput.replace("List of devices attached"," ").replace("\n","").replace("\t","").replace("\n\n","")

numberofDevices = len(re.findall(r'device+', listDevicesOutput))

connectedDevicesArray = listDevicesOutput.split("device")   
del connectedDevicesArray[-1] 


strSelectedDevice = ''
if(numberofDevices > 1) :
    print('Please select the device : \n'),

    for idx, device in enumerate(connectedDevicesArray):
        print idx+1,device

    selectedDevice = raw_input()

    if selectedDevice.isdigit() :
        intSelected = int(selectedDevice)
        if 1 <= intSelected <= len(connectedDevicesArray) :
            print 'Selected device is : ',connectedDevicesArray[intSelected-1]
            checkIfPackageInstalled(connectedDevicesArray[intSelected-1])
        else :
            print 'Please select in range'
    else : 
        print 'Not valid input'

elif numberofDevices == 1 :
    checkIfPackageInstalled(connectedDevicesArray[0])
elif numberofDevices == 0 :
    print("No device is attached")

Determining image file size + dimensions via Javascript?

Check the uploaded image size using Javascript

<script type="text/javascript">
    function check(){
      var imgpath=document.getElementById('imgfile');
      if (!imgpath.value==""){
        var img=imgpath.files[0].size;
        var imgsize=img/1024; 
        alert(imgsize);
      }
    }
</script>

Html code

<form method="post" enctype="multipart/form-data" onsubmit="return check();">
<input type="file" name="imgfile" id="imgfile"><br><input type="submit">
</form>

How to wrap text using CSS?

The better option if you cannot control user input, it is to establish the css property, overflow:hidden, so if the string is superior to the width, it will not deform the design.

Edited:

I like the answer: "word-wrap: break-word", and for those browsers that do not support it, for example, IE6 or IE7, I would use my solution.

Difference between Relative path and absolute path in javascript

Imagine you have a window open on http://www.foo.com/bar/page.html In all of them (HTML, Javascript and CSS):

opened_url = http://www.foo.com/bar/page.html
base_path = http://www.foo.com/bar/
home_path = http://www.foo.com/
/kitten.png = Home_path/kitten.png
kitten.png = Base_path/kitten.png

In HTML and Javascript, the base_path is based on the opened window. In big javascript projects you need a BASEPATH or root variable to store the base_path occasionally. (like this)

In CSS the opened url is the address of which your .css is stored or loaded, its not the same like javascript with current opened window in this case.

And for being more secure in absolute paths it is recommended to use // instead of http:// for possible future migrations to https://. In your own example, use it this way:

<img src="//www.foo.com/images/kitten.png">

How to use the DropDownList's SelectedIndexChanged event

The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..

    <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
        AutoPostBack="True" AppendDataBoundItems="true">
    <asp:DropDownList ID="DropDownList2" runat="server"
        onselectedindexchanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList> 


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList2

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList3
}

CSS Font Border?

UPDATE

Here's a SCSS mixin to generate the stroke: http://codepen.io/pixelass/pen/gbGZYL

/// Stroke font-character
/// @param  {Integer} $stroke - Stroke width
/// @param  {Color}   $color  - Stroke color
/// @return {List}            - text-shadow list
@function stroke($stroke, $color) {
  $shadow: ();
  $from: $stroke*-1;
  @for $i from $from through $stroke {
   @for $j from $from through $stroke {
      $shadow: append($shadow, $i*1px $j*1px 0 $color, comma);
    }
  }
  @return $shadow;
}
/// Stroke font-character
/// @param  {Integer} $stroke - Stroke width
/// @param  {Color}   $color  - Stroke color
/// @return {Style}           - text-shadow
@mixin stroke($stroke, $color) {
  text-shadow: stroke($stroke, $color);
}

enter image description here

YES old question.. with accepted (and good) answers..

BUT...In case anybody ever needs this and hates typing code...

THIS is a 2px black border with CrossBrowser support (not IE) I needed this for @fontface fonts so it needed to be cleaner than previous seen answers... I takes every side pixelwise to make sure there are (almost) no gaps for "fuzzy" (handrawn or similar) fonts. Subpixels (0.5px) could be added but I don't need it.

Long code for just the border??? ...YES!!!

text-shadow: 1px 1px 0 #000,
    -1px 1px 0 #000,
    1px -1px 0 #000,
    -1px -1px 0 #000,
    0px 1px 0 #000,
    0px -1px 0 #000,
    -1px 0px 0 #000,
    1px 0px 0 #000,
    2px 2px 0 #000,
    -2px 2px 0 #000,
    2px -2px 0 #000,
    -2px -2px 0 #000,
    0px 2px 0 #000,
    0px -2px 0 #000,
    -2px 0px 0 #000,
    2px 0px 0 #000,
    1px 2px 0 #000,
    -1px 2px 0 #000,
    1px -2px 0 #000,
    -1px -2px 0 #000,
    2px 1px 0 #000,
    -2px 1px 0 #000,
    2px -1px 0 #000,
    -2px -1px 0 #000;

Convert object to JSON in Android

Might be better choice:

@Override
public String toString() {
    return new GsonBuilder().create().toJson(this, Producto.class);
}

Is it possible to change the location of packages for NuGet?

Just updating with Nuget 2.8.3. To change the location of installed packages , I enabled package restore from right clicking solution. Edited NuGet.Config and added these lines :

  <config>
    <add key="repositorypath" value="..\Core\Packages" />
  </config>

Then rebuilt the solution, it downloaded all packages to my desired folder and updated references automatically.

Stopping Excel Macro executution when pressing Esc won't work

Sometimes, the right set of keys (Pause, Break or ScrLk) are not available on the keyboard (mostly happens with laptop users) and pressing Esc 2, 3 or multiple times doesn't halt the macro too.

I got stuck too and eventually found the solution in accessibility feature of Windows after which I tried all the researched options and 3 of them worked for me in 3 different scenarios.

Step #01: If your keyboard does not have a specific key, please do not worry and open the 'OnScreen Keyboard' from Windows Utilities by pressing Win + U.

Step #02: Now, try any of the below option and of them will definitely work depending on your system architecture i.e. OS and Office version

  • Ctrl + Pause
  • Ctrl + ScrLk
  • Esc + Esc (Press twice consecutively)

You will be put into break mode using the above key combinations as the macro suspends execution immediately finishing the current task. For eg. if it is pulling the data from web then it will halt immediately before execting any next command but after pulling the data, following which one can press F5 or F8 to continue the debugging.

Find column whose name contains a specific string

Just iterate over DataFrame.columns, now this is an example in which you will end up with a list of column names that match:

import pandas as pd

data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)

spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)

Output:

['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']

Explanation:

  1. df.columns returns a list of column names
  2. [col for col in df.columns if 'spike' in col] iterates over the list df.columns with the variable col and adds it to the resulting list if col contains 'spike'. This syntax is list comprehension.

If you only want the resulting data set with the columns that match you can do this:

df2 = df.filter(regex='spike')
print(df2)

Output:

   spike-2  spiked-in
0        1          7
1        2          8
2        3          9

What, why or when it is better to choose cshtml vs aspx?

While the syntax is certainly different between Razor (.cshtml/.vbhtml) and WebForms (.aspx/.ascx), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).

This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.

Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

If you use pip version of tensorflow, it means it's already compiled and you are just installing it. Basically you install tensorflow-gpu, but when you download it from repository and trying to build, you should build it with CPU AVX support. If you ignore it, you will get the warning every time when you run on cpu.

How to add content to html body using JS?

Working demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
var divg = document.createElement("div");
divg.appendChild(document.createTextNode("New DIV"));
document.body.appendChild(divg);
};
</script>
</head>
<body>

</body>
</html>

How can I check file size in Python?

#Get file size , print it , process it...
#Os.stat will provide the file size in (.st_size) property. 
#The file size will be shown in bytes.

import os

fsize=os.stat('filepath')
print('size:' + fsize.st_size.__str__())

#check if the file size is less than 10 MB

if fsize.st_size < 10000000:
    process it ....

Python: How to use RegEx in an if statement?

The REPL makes it easy to learn APIs. Just run python, create an object and then ask for help:

$ python
>>> import re
>>> help(re.compile(r''))

at the command line shows, among other things:

search(...)

search(string[, pos[, endpos]]) --> match object or None. Scan through string looking for a match, and return a corresponding MatchObject instance. Return None if no position in the string matches.

so you can do

regex = re.compile(regex_txt, re.IGNORECASE)

match = regex.search(content)  # From your file reading code.
if match is not None:
  # use match

Incidentally,

regex_txt = "facebook.com"

has a . which matches any character, so re.compile("facebook.com").search("facebookkcom") is not None is true because . matches any character. Maybe

regex_txt = r"(?i)facebook\.com"

The \. matches a literal "." character instead of treating . as a special regular expression operator.

The r"..." bit means that the regular expression compiler gets the escape in \. instead of the python parser interpreting it.

The (?i) makes the regex case-insensitive like re.IGNORECASE but self-contained.

How to swap two variables in JavaScript

You could use a temporary swap variable or XOR.

a = a ^ b
b = a ^ b
a = a ^ b

This is just a basic logical concept and works in every language that supports XOR operation.

edit: see the Comments. Forgot to tell that this works for sure only with integer. Assumed the integer variables from question's thread

Opening database file from within SQLite command-line shell

You can simply specify the database file name in the command line:

bash-3.2 # sqlite3 UserDb.sqlite
SQLite version 3.16.2 2017-01-06 16:32:41
Enter ".help" for usage hints.

sqlite> .databases
main: /db/UserDb.sqlite

sqlite> .tables
accountLevelSettings  genres               syncedThumbs
collectionActivity    recordingFilter      thumbs
contentStatus         syncedContentStatus 

sqlite> select count(*) from genres;
10

Moreover, you can execute your query from the command line:

bash-3.2 # sqlite3 UserDb.sqlite 'select count(*) from genres'
10

You could attach another database file from the SQLite shell:

sqlite> attach database 'RelDb.sqlite' as RelDb;

sqlite> .databases
main: /db/UserDb.sqlite
RelDb: /db/RelDb_1.sqlite

sqlite> .tables
RelDb.collectionRelationship  contentStatus               
RelDb.contentRelationship     genres                      
RelDb.leagueRelationship      recordingFilter             
RelDb.localizedString         syncedContentStatus         
accountLevelSettings          syncedThumbs                
collectionActivity            thumbs                      

The tables from this 2nd database will be accessible via prefix of the database:

sqlite> select count(*) from RelDb.localizedString;
2442

But who knows how to specify multiple database files from the command line to execute the query from the command line?

In DB2 Display a table's definition

you can use the below command to see the complete characteristics of DB

db2look -d <DB NAme>-u walid -e -o

you can use the below command to see the complete characteristics of Schema

 db2look -d <DB NAme> -u walid -z <Schema Name> -e -o

you can use the below command to see the complete characteristics of table

db2look -d <DB NAme> -u walid -z <Schema Name> -t <Table Name>-e -o

you can also visit the below link for more details. https://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=%2Fcom.ibm.db2.udb.admin.doc%2Fdoc%2Fr0002051.htm

Collection that allows only unique items in .NET?

From the HashSet<T> page on MSDN:

The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

(emphasis mine)

How to clear File Input

By Setting $("ID").val(null), worked for me

How to save an activity state using save instance state?

Note that it is NOT safe to use onSaveInstanceState and onRestoreInstanceState for persistent data, according to the documentation on Activity states in http://developer.android.com/reference/android/app/Activity.html.

The document states (in the 'Activity Lifecycle' section):

Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the later is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

In other words, put your save/restore code for persistent data in onPause() and onResume()!

EDIT: For further clarification, here's the onSaveInstanceState() documentation:

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

Unable to create migrations after upgrading to ASP.NET Core 2.0

If you want to avoid those IDesignTimeDbContextFactory thing: Just make sure that you don't use any Seed method in your startup. I was using a static seed method in my startup and it was causing this error for me.

Disable hover effects on mobile browsers

Try this easy 2019 jquery solution, although its been around a while;

  1. add this plugin to head:

    src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"

  2. add this to js:

    $("*").on("touchend", function(e) { $(this).focus(); }); //applies to all elements

  3. some suggested variations to this are:

    $(":input, :checkbox,").on("touchend", function(e) {(this).focus);}); //specify elements
    
    $("*").on("click, touchend", function(e) { $(this).focus(); });  //include click event`
    
    css: body { cursor: pointer; } //touch anywhere to end a focus`
    

Notes

  • place plugin before bootstrap.js, if applicable, to avoid affecting tooltips
  • only tested on iphone XR ios 12.1.12, and ipad 3 ios 9.3.5, using Safari or Chrome.

References:

https://code.jquery.com/ui/

https://api.jquery.com/category/selectors/jquery-selector-extensions/

JSHint and jQuery: '$' is not defined

If you're using an IntelliJ editor such as WebStorm, PyCharm, RubyMine, or IntelliJ IDEA:

In the Environments section of File/Settings/JavaScript/Code Quality Tools/JSHint, click on the jQuery checkbox.

How can I get a specific parameter from location.search?

My favorite way for getting URL params is this approach:

var parseQueryString = function() {

    var str = window.location.search;
    var objURL = {};

    str.replace(
        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){
            objURL[ $1 ] = $3;
        }
    );
    return objURL;
};

//Example how to use it: 
var params = parseQueryString();
alert(params["foo"]); 

Java Reflection: How to get the name of a variable?

All you need to do is make an array of fields and then set it to the class you want like shown below.

Field fld[] = (class name).class.getDeclaredFields();   
for(Field x : fld)
{System.out.println(x);}

For example if you did

Field fld[] = Integer.class.getDeclaredFields();
          for(Field x : fld)
          {System.out.println(x);}

you would get

public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
static final char[] java.lang.Integer.digits
static final char[] java.lang.Integer.DigitTens
static final char[] java.lang.Integer.DigitOnes
static final int[] java.lang.Integer.sizeTable
private static java.lang.String java.lang.Integer.integerCacheHighPropValue
private final int java.lang.Integer.value
public static final int java.lang.Integer.SIZE
private static final long java.lang.Integer.serialVersionUID

Transposing a 2D-array in JavaScript

reverseValues(values) {
        let maxLength = values.reduce((acc, val) => Math.max(val.length, acc), 0);
        return [...Array(maxLength)].map((val, index) => values.map((v) => v[index]));
}

Parsing query strings on Android

On Android, I tried using @diyism answer but I encountered the space character issue raised by @rpetrich, for example: I fill out a form where username = "us+us" and password = "pw pw" causing a URL string to look like:

http://somewhere?username=us%2Bus&password=pw+pw

However, @diyism code returns "us+us" and "pw+pw", i.e. it doesn't detect the space character. If the URL was rewritten with %20 the space character gets identified:

http://somewhere?username=us%2Bus&password=pw%20pw

This leads to the following fix:

Uri uri = Uri.parse(url_string.replace("+", "%20"));
uri.getQueryParameter("para1");

How can I view an old version of a file with Git?

To quickly see the differences with older revisions of a file:

git show -1 filename.txt > to compare against the last revision of file

git show -2 filename.txt > to compare against the 2nd last revision

git show -3 fielname.txt > to compare against the last 3rd last revision

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

.Net System.Mail.Message adding multiple "To" addresses

I wasn't able to replicate your bug:

var message = new MailMessage();

message.To.Add("[email protected]");
message.To.Add("[email protected]");

message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";

var client = new SmtpClient("localhost", 25);
client.Send(message);

Dumping the contents of the To: MailAddressCollection:

MailAddressCollection (2 items)
DisplayName User Host Address

user example.com [email protected]
user2 example.com [email protected]

And the resulting e-mail as caught by smtp4dev:

Received: from mycomputername (mycomputername [127.0.0.1])
     by localhost (Eric Daugherty's C# Email Server)
     3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

Test

Are you sure there's not some other issue going on with your code or SMTP server?

SQLite add Primary Key

I tried to add the primary key afterwards by changing the sqlite_master table directly. This trick seems to work. It is a hack solution of course.

In short: create a regular (unique) index on the table, then make the schema writable and change the name of the index to the form reserved by sqlite to identify a primary key index, (i.e. sqlite_autoindex_XXX_1, where XXX is the table name) and set the sql string to NULL. At last change the table definition itself. One pittfal: sqlite does not see the index name change until the database is reopened. This seems like a bug, but not a severe one (even without reopening the database, you can still use it).

Suppose the table looks like:

CREATE TABLE tab1(i INTEGER, j INTEGER, t TEXT);

Then I did the following:

BEGIN;
CREATE INDEX pk_tab1 ON tab1(i,j);
pragma writable_schema=1;
UPDATE sqlite_master SET name='sqlite_autoindex_tab1_1',sql=null WHERE name='pk_tab1';
UPDATE sqlite_master SET sql='CREATE TABLE tab1(i integer,j integer,t text,primary key(i,j))' WHERE name='tab1';
COMMIT;

Some tests (in sqlite shell):

sqlite> explain query plan select * from tab1 order by i,j;
0|0|0|SCAN TABLE tab1 USING INDEX sqlite_autoindex_tab1_1
sqlite> drop index sqlite_autoindex_tab1_1;
Error: index associated with UNIQUE or PRIMARY KEY constraint cannot be dropped    

Select rows which are not present in other table

A.) The command is NOT EXISTS, you're missing the 'S'.

B.) Use NOT IN instead

SELECT ip 
  FROM login_log 
  WHERE ip NOT IN (
    SELECT ip
    FROM ip_location
  )
;

Convert absolute path into relative path given a current directory using Bash

A slight improvement on kasku's and Pini's answers, which plays nicer with spaces and allows passing relative paths:

#!/bin/bash
# both $1 and $2 are paths
# returns $2 relative to $1
absolute=`readlink -f "$2"`
current=`readlink -f "$1"`
# Perl is magic
# Quoting horror.... spaces cause problems, that's why we need the extra " in here:
relative=$(perl -MFile::Spec -e "print File::Spec->abs2rel(q($absolute),q($current))")

echo $relative

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I encounter some issue in my project.

enter image description here

In child table, there isn't any record Id equals 1 and 11

mage

I inserted DEAL_ITEM_THIRD_PARTY_PO table which Id equals 1 and 11 then I can create FK

How to clamp an integer to some range?

See numpy.clip:

index = numpy.clip(index, 0, len(my_list) - 1)

Jquery click not working with ipad

actually , this has turned out to be couple of javascript changes in the code. calling of javascript method with ; at the end. placing script tags in body instead of head. and interestingly even change the text displayed (please "click") to something that is not an event. so Please rate etc.

turned debugger on safari, it didnot give much information or even errors at times.

Django URL Redirect

If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:

(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),  

You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:

(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),  

This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

Should I use Java's String.format() if performance is important?

The answer to this depends very much on how your specific Java compiler optimizes the bytecode it generates. Strings are immutable and, theoretically, each "+" operation can create a new one. But, your compiler almost certainly optimizes away interim steps in building long strings. It's entirely possible that both lines of code above generate the exact same bytecode.

The only real way to know is to test the code iteratively in your current environment. Write a QD app that concatenates strings both ways iteratively and see how they time out against each other.

Remove querystring from URL

(() => {
        'use strict';
        const needle = 'SortOrder|Page'; // example
        if ( needle === '' || needle === '{{1}}' ) { 
            return; 
        }           
        const needles = needle.split(/\s*\|\s*/);
        const querystripper = ev => {
                    if (ev) { window.removeEventListener(ev.type, querystripper, true);}
                    try {
                          const url = new URL(location.href);
                          const params = new URLSearchParams(url.search.slice(1));
                          for (const needleremover of needles) {
                                if (params.has(needleremover)) {
                                url.searchParams.delete(needleremover);
                                    window.location.href = url;
                            }
                          }     
                    } catch (ex) { }
        };          
        if (document.readyState === 'loading') {
                 window.addEventListener('DOMContentLoaded', querystripper, true);
        } else {
                 querystripper();
        }
})();

That's how I did it, also has RegEx support.

how to set ul/li bullet point color?

A couple ways this can be done:

This will make it a square

ul
{
  list-style-type: square;
}

This will make it green

li
{
  color: #0F0;
}

This will prevent the text from being green

li p
{
  color: #000;
}

However that will require that all text within lists be in paragraphs so that the color is not overridden.

A better way is to make an image of a green square and use:

ul
{
  list-style: url(green-square.png);
}

how to open *.sdf files?

In addition to the methods described by @ctacke, you can also open SQL Server Compact Edition databases with SQL Server Management Studio. You'll need SQL Server 2008 to open SQL CE 3.5 databases.

How to click or tap on a TextView text

This may not be quite what you are looking for but this is what worked for what I'm doing. All of this is after my onCreate:

boilingpointK = (TextView) findViewById(R.id.boilingpointK);

boilingpointK.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if ("Boiling Point K".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("2792");
        else if ("2792".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("Boiling Point K");
    }
});

Django DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

How do I automatically update a timestamp in PostgreSQL

Updating timestamp, only if the values changed

Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
      NEW.modified = now(); 
      RETURN NEW;
   ELSE
      RETURN OLD;
   END IF;
END;
$$ language 'plpgsql';

How to open link in new tab on html?

target="_blank" attribute will do the job. Just don't forget to add rel="noopener noreferrer" to solve the potential vulnerability. More on that here: https://dev.to/ben/the-targetblank-vulnerability-by-example

<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">Searcher</a>

Invalid argument supplied for foreach()

There seems also to be a relation to the environment:

I had that "invalid argument supplied foreach()" error only in the dev environment, but not in prod (I am working on the server, not localhost).

Despite the error a var_dump indicated that the array was well there (in both cases app and dev).

The if (is_array($array)) around the foreach ($array as $subarray) solved the problem.

Sorry, that I cannot explain the cause, but as it took me a while to figure a solution I thought of better sharing this as an observation.

How to split data into 3 sets (train, validation and test)?

It is very convenient to use train_test_split without performing reindexing after dividing to several sets and not writing some additional code. Best answer above does not mention that by separating two times using train_test_split not changing partition sizes won`t give initially intended partition:

x_train, x_remain = train_test_split(x, test_size=(val_size + test_size))

Then the portion of validation and test sets in the x_remain change and could be counted as

new_test_size = np.around(test_size / (val_size + test_size), 2)
# To preserve (new_test_size + new_val_size) = 1.0 
new_val_size = 1.0 - new_test_size

x_val, x_test = train_test_split(x_remain, test_size=new_test_size)

In this occasion all initial partitions are saved.

ASP.NET MVC Ajax Error handling

After googling I write a simple Exception handing based on MVC Action Filter:

public class HandleExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    filterContext.Exception.Message,
                    filterContext.Exception.StackTrace
                }
            };
            filterContext.ExceptionHandled = true;
        }
        else
        {
            base.OnException(filterContext);
        }
    }
}

and write in global.ascx:

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

and then write this script on the layout or Master page:

<script type="text/javascript">
      $(document).ajaxError(function (e, jqxhr, settings, exception) {
                       e.stopPropagation();
                       if (jqxhr != null)
                           alert(jqxhr.responseText);
                     });
</script>

Finally you should turn on custom error. and then enjoy it :)

Fitting a density curve to a histogram in R

I had the same problem but Dirk's solution didn't seem to work. I was getting this warning messege every time

"prob" is not a graphical parameter

I read through ?hist and found about freq: a logical vector set TRUE by default.

the code that worked for me is

hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)

Assigning strings to arrays of characters

Note that you can still do:

s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '\0';

How can I use threading in Python?

Here is multi threading with a simple example which will be helpful. You can run it and understand easily how multi threading is working in Python. I used a lock for preventing access to other threads until the previous threads finished their work. By the use of this line of code,

tLock = threading.BoundedSemaphore(value=4)

you can allow a number of processes at a time and keep hold to the rest of the threads which will run later or after finished previous processes.

import threading
import time

#tLock = threading.Lock()
tLock = threading.BoundedSemaphore(value=4)
def timer(name, delay, repeat):
    print  "\r\nTimer: ", name, " Started"
    tLock.acquire()
    print "\r\n", name, " has the acquired the lock"
    while repeat > 0:
        time.sleep(delay)
        print "\r\n", name, ": ", str(time.ctime(time.time()))
        repeat -= 1

    print "\r\n", name, " is releaseing the lock"
    tLock.release()
    print "\r\nTimer: ", name, " Completed"

def Main():
    t1 = threading.Thread(target=timer, args=("Timer1", 2, 5))
    t2 = threading.Thread(target=timer, args=("Timer2", 3, 5))
    t3 = threading.Thread(target=timer, args=("Timer3", 4, 5))
    t4 = threading.Thread(target=timer, args=("Timer4", 5, 5))
    t5 = threading.Thread(target=timer, args=("Timer5", 0.1, 5))

    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t5.start()

    print "\r\nMain Complete"

if __name__ == "__main__":
    Main()

MySQL - How to select data by string length

select * from table order by length(column);

Documentation on the length() function, as well as all the other string functions, is available here.

Untrack files from git temporarily

Not an answer to the original question. But this might help someone.

To see the changes you have done (know which files are marked as --assume-unchanged)

git ls-files -v

The resulted list of files will have a prefix with one character (ex : H or h) If it is a lowercase (i.e. h) then the file was marked --assume-unchanged

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

My issue was that my method was missing the @RequestBody annotation. After adding the annotation I no longer received the 404 exception.

How to terminate the script in JavaScript?

If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and first two lines executed.

I think, this is the best way to stop the script. If there's any other way then please comment me. I also want to know another best and simple way. BTW, I didn't get exit or die inbuilt function in Javascript like PHP for terminate the script. If anyone know then please let me know.

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');

Singletons vs. Application Context in Android?

Application is not the same as the Singleton.The reasons are:

  1. Application's method(such as onCreate) is called in the ui thread;
  2. singleton's method can be called in any thread;
  3. In the method "onCreate" of Application,you can instantiate Handler;
  4. If the singleton is executed in none-ui thread,you could not instantiate Handler;
  5. Application has the ability to manage the life cycle of the activities in the app.It has the method "registerActivityLifecycleCallbacks".But the singletons has not the ability.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

In my case reference of System.Web.MVC was missing from my project. But after adding references issue was same so i checked properties of my Bin folder it was ReadOnly. Just after making it writable,everything working fine.

Redirect to new Page in AngularJS using $location

Try entering the url inside the function

$location.url('http://www.google.com')

How to create my json string by using C#?

To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.

The below code demonstrates the use of JSON in an ASP.NET environment:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace JSONFromCS
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e1)
        {
            List<Employee> eList = new List<Employee>();
            Employee e = new Employee();
            e.Name = "Minal";
            e.Age = 24;

            eList.Add(e);

            e = new Employee();
            e.Name = "Santosh";
            e.Age = 24;

            eList.Add(e);

            string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);

            string script = "var employeeList = {\"Employee\": " + ans+"};";
            script += "for(i = 0;i<employeeList.Employee.length;i++)";
            script += "{";
            script += "alert ('Name : ='+employeeList.Employee[i].Name+' 
            Age : = '+employeeList.Employee[i].Age);";
            script += "}";

            ClientScriptManager cs = Page.ClientScript;
            cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
        }
    }
    public class Employee
    {
        public string Name;
        public int Age;
    }
}  

After running this program, you will get two alerts

In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:

{ "Maths" : [ {"Name"     : "Minal",        // First element
                             "Marks"     : 84,
                             "age"       : 23 },
                             {
                             "Name"      : "Santosh",    // Second element
                             "Marks"     : 91,
                             "age"       : 24 }
                           ],                       
              "Science" :  [ 
                             {
                             "Name"      : "Sahoo",     // First Element
                             "Marks"     : 74,
                             "age"       : 27 }, 
                             {                           
                             "Name"      : "Santosh",    // Second Element
                             "Marks"     : 78,
                             "age"       : 41 }
                           ] 
            } 

Syntax:

  • {} - acts as 'containers'

  • [] - holds arrays

  • : - Names and values are separated by a colon

  • , - Array elements are separated by commas

This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.

You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.

In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.

The following code demonstrates how to use that class to convert into JSON in C#3.5.

JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);   

So, try to create a List of arrays with Questions and then serialize this list into JSON

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

C non-blocking keyboard input

As already stated, you can use sigaction to trap ctrl-c, or select to trap any standard input.

Note however that with the latter method you also need to set the TTY so that it's in character-at-a-time rather than line-at-a-time mode. The latter is the default - if you type in a line of text it doesn't get sent to the running program's stdin until you press enter.

You'd need to use the tcsetattr() function to turn off ICANON mode, and probably also disable ECHO too. From memory, you also have to set the terminal back into ICANON mode when the program exits!

Just for completeness, here's some code I've just knocked up (nb: no error checking!) which sets up a Unix TTY and emulates the DOS <conio.h> functions kbhit() and getch():

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;

    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));

    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv);
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}

int main(int argc, char *argv[])
{
    set_conio_terminal_mode();

    while (!kbhit()) {
        /* do some work */
    }
    (void)getch(); /* consume the character */
}

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Its already answered above. I will summarise the steps to check above.

run git remote -v in project dir. If the output shows remote url starting with https://abc then you may need username password everytime.

So to change the remote url run git remote set-url origin {ssh remote url address starts with mostly [email protected]:}.

Now run git remote -v to verify the changed remote url.

Refer : https://help.github.com/articles/changing-a-remote-s-url/

How to create war files

Use the following command outside the WEB-INF folder. This should create your war file and is the quickest method I know.

(You will need JDK 1.7+ installed and environment variables that point to the bin directory of your JDK.)

jar -cvf projectname.war *

Reference Link

Validating input using java.util.Scanner

One idea:

try {
    int i = Integer.parseInt(myString);
    if (i < 0) {
        // Error, negative input
    }
} catch (NumberFormatException e) {
    // Error, not a number.
}

There is also, in commons-lang library the CharUtils class that provides the methods isAsciiNumeric() to check that a character is a number, and isAsciiAlpha() to check that the character is a letter...

There is no argument given that corresponds to the required formal parameter - .NET Error

In the constructor of

 public class ErrorEventArg : EventArgs

You have to add "base" as follows:

    public ErrorEventArg(string errorMsg, string lastQuery) : base (string errorMsg, string lastQuery)
    {
        ErrorMsg = errorMsg;
        LastQuery = lastQuery;
    }

That solved it for me

Fastest way to convert string to integer in PHP

I've just set up a quick benchmarking exercise:

Function             time to run 1 million iterations
--------------------------------------------
(int) "123":                0.55029
intval("123"):              1.0115  (183%)

(int) "0":                  0.42461
intval("0"):                0.95683 (225%)

(int) int:                  0.1502
intval(int):                0.65716 (438%)

(int) array("a", "b"):      0.91264
intval(array("a", "b")):    1.47681 (162%)

(int) "hello":              0.42208
intval("hello"):            0.93678 (222%)

On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.

I'd be interested to know why though.


Update: I've run the tests again, this time with coercion (0 + $var)

| INPUT ($x)      |  (int) $x  |intval($x) |  0 + $x   |
|-----------------|------------|-----------|-----------|
| "123"           |   0.51541  |  0.96924  |  0.33828  |
| "0"             |   0.42723  |  0.97418  |  0.31353  |
| 123             |   0.15011  |  0.61690  |  0.15452  |
| array("a", "b") |   0.8893   |  1.45109  |  err!     |
| "hello"         |   0.42618  |  0.88803  |  0.1691   |
|-----------------|------------|-----------|-----------|

Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:

$x = "11";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11)

$x = "0x11";
(int) $x;      // int(0)
intval($x);    // int(0)
$x + 0;        // int(17) !

$x = "011";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11) (not 9)

Tested using PHP 5.3.1

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

If the DLL and the .NET projects are in the same solution and you want to compile and run both every time, you can right click the properties of the .NET project, Build events, then add something like the following to Post-build event command line:

copy $(SolutionDir)Debug\MyOwn.dll .

It's basically a DOS line, and you can tweak based on where your DLL is being built to.

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

Constructor in an Interface?

Here´s an example using this Technic. In this specifik example the code is making a call to Firebase using a mock MyCompletionListener that is an interface masked as an abstract class, an interface with a constructor

private interface Listener {
    void onComplete(databaseError, databaseReference);
}

public abstract class MyCompletionListener implements Listener{
    String id;
    String name;
    public MyCompletionListener(String id, String name) {
        this.id = id;
        this.name = name;
    }
}

private void removeUserPresenceOnCurrentItem() {
    mFirebase.removeValue(child("some_key"), new MyCompletionListener(UUID.randomUUID().toString(), "removeUserPresenceOnCurrentItem") {
        @Override
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

        }
    });
    }
}

@Override
public void removeValue(DatabaseReference ref, final MyCompletionListener var1) {
    CompletionListener cListener = new CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if (var1 != null){
                        System.out.println("Im back and my id is: " var1.is + " and my name is: " var1.name);
                        var1.onComplete(databaseError, databaseReference);
                    }
                }
            };
    ref.removeValue(cListener);
}

How many files can I put in a directory?

It really depends on the filesystem used, and also some flags.

For example, ext3 can have many thousands of files; but after a couple of thousands, it used to be very slow. Mostly when listing a directory, but also when opening a single file. A few years ago, it gained the 'htree' option, that dramatically shortened the time needed to get an inode given a filename.

Personally, I use subdirectories to keep most levels under a thousand or so items. In your case, I'd create 256 directories, with the two last hex digits of the ID. Use the last and not the first digits, so you get the load balanced.

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

I'm new in ASP.NET MVC. I faced the same problem, the following is my workable in my Erorr.vbhtml (it work if you only need to log the error using Elmah log)

@ModelType System.Web.Mvc.HandleErrorInfo

    @Code
        ViewData("Title") = "Error"
        Dim item As HandleErrorInfo = CType(Model, HandleErrorInfo)
        //To log error with Elmah
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(New Elmah.Error(Model.Exception, HttpContext.Current))
    End Code

<h2>
    Sorry, an error occurred while processing your request.<br />

    @item.ActionName<br />
    @item.ControllerName<br />
    @item.Exception.Message
</h2> 

It is simply!

Finding blocking/locking queries in MS SQL (mssql)

You may find this query useful:

SELECT * 
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName' 
AND blocking_session_id <> 0

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Overlay a background-image with an rgba background-color

Yes, there is a way to do this. You could use a pseudo-element after to position a block on top of your background image. Something like this: http://jsfiddle.net/Pevara/N2U6B/

The css for the :after looks like this:

#the-div:hover:after {
    content: ' ';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0,0,0,.5);
}

edit:
When you want to apply this to a non-empty element, and just get the overlay on the background, you can do so by applying a positive z-index to the element, and a negative one to the :after. Something like this:

#the-div {
    ...
    z-index: 1;
}
#the-div:hover:after {
    ...
    z-index: -1;
}

And the updated fiddle: http://jsfiddle.net/N2U6B/255/

Difference between TCP and UDP?

One of the differences is in short

UDP : Send message and dont look back if it reached destination, Connectionless protocol
TCP : Send message and guarantee to reach destination, Connection-oriented protocol

Can I limit the length of an array in JavaScript?

You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.

You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).

You should convert the shortened array back to a string with .join(",") and then use it for the new cookie instead of using old_cookie which is not shortened.

You may also not be using .splice() correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice() here.

get size of json object

you dont need to change your JSON format.

replace:

console.log(data.phones.length);

with:

console.log( Object.keys( data.phones ).length ) ;

How to update values in a specific row in a Python Pandas DataFrame?

There are probably a few ways to do this, but one approach would be to merge the two dataframes together on the filename/m column, then populate the column 'n' from the right dataframe if a match was found. The n_x, n_y in the code refer to the left/right dataframes in the merge.

In[100] : df = pd.merge(df1, df2, how='left', on=['filename','m'])

In[101] : df
Out[101]: 
    filename   m   n_x  n_y
0  test0.dat  12  None  NaN
1  test2.dat  13  None   16

In[102] : df['n'] = df['n_y'].fillna(df['n_x'])

In[103] : df = df.drop(['n_x','n_y'], axis=1)

In[104] : df
Out[104]: 
    filename   m     n
0  test0.dat  12  None
1  test2.dat  13    16

SELECT * FROM multiple tables. MySQL

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

Android : difference between invisible and gone?

INVISIBLE:

This view is invisible, but it still takes up space for layout purposes.

GONE:

This view is invisible, and it doesn't take any space for layout purposes.

Solr vs. ElasticSearch

I have created a table of major differences between elasticsearch and Solr and splunk, you can use it as 2016 update: enter image description here

Java - JPA - @Version annotation

Every time an entity is updated in the database the version field will be increased by one. Every operation that updates the entity in the database will have appended WHERE version = VERSION_THAT_WAS_LOADED_FROM_DATABASE to its query.

In checking affected rows of your operation the jpa framework can make sure there was no concurrent modification between loading and persisting your entity because the query would not find your entity in the database when it's version number has been increased between load and persist.

Set focus on textbox in WPF

Another possible solution is to use FocusBehavior provided by free DevExpress MVVM Framework:

<TextBox Text="This control is focused on startup">
    <dxmvvm:Interaction.Behaviors>
        <dxmvvm:FocusBehavior/>
    </dxmvvm:Interaction.Behaviors>
</TextBox>

It allows you to focus a control when it's loaded, when a certain event is raised or a property is changed.

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';

JBoss debugging in Eclipse

What @VonC says is correct, but you can put the commands to set debug directly into VM arguments on jBoss Launch.

To do that, open jBoss server inside Eclipse, go to Open launch configuration and put this in VM arguments textbox: vm args

How to code a BAT file to always run as admin mode?

You use runas to launch a program as a specific user:

runas /user:Administrator Example1Server.exe

Charts for Android

SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.

SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.

Some useful links can be found below:

enter image description here

Disclosure: I am the tech lead on the SciChart project!

How to get these two divs side-by-side?

Using the style

.child_div_1 {
    float:left
}

SQL Server : fetching records between two dates?

Your question didnt ask how to use BETWEEN correctly, rather asked for help with the unexpectedly truncated results...

As mentioned/hinting at in the other answers, the problem is that you have time segments in addition to the dates.

In my experience, using date diff is worth the extra wear/tear on the keyboard. It allows you to express exactly what you want, and you are covered.

select * 
from xxx 
where datediff(d, '2012-10-26', dates) >=0
and  datediff(d, dates,'2012-10-27') >=0

using datediff, if the first date is before the second date, you get a positive number. There are several ways to write the above, for instance always having the field first, then the constant. Just flipping the operator. Its a matter of personal preference.

you can be explicit about whether you want to be inclusive or exclusive of the endpoints by dropping one or both equal signs.

BETWEEN will work in your case, because the endpoints are both assumed to be midnight (ie DATEs). If your endpoints were also DATETIME, using BETWEEN may require even more casting. In my mind DATEDIFF was put in our lives to insulate us from those issues.

How to ignore SSL certificate errors in Apache HttpClient 4.0

Just for the record, there is a much simpler way to accomplish the same with HttpClient 4.1

    SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() {

        public boolean isTrusted(
                final X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy...
            return true;
        }

    });

python: urllib2 how to send cookie with urlopen request

Maybe using cookielib.CookieJar can help you. For instance when posting to a page containing a form:

import urllib2
import urllib
from cookielib import CookieJar

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

EDIT:

After Piotr's comment I'll elaborate a bit. From the docs:

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

So whatever requests you make with your CookieJar instance, all cookies will be handled automagically. Kinda like your browser does :)

I can only speak from my own experience and my 99% use-case for cookies is to receive a cookie and then need to send it with all subsequent requests in that session. The code above handles just that, and it does so transparently.