Programs & Examples On #Server error

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.

"This SqlTransaction has completed; it is no longer usable."... configuration error?

I had this recently after refactoring in a new connection manager. A new routine accepted a transaction so it could be run as part of a batch, problem was with a using block:

public IEnumerable<T> Query<T>(IDbTransaction transaction, string command, dynamic param = null)
{
  using (transaction.Connection)
  {
    using (transaction)
    {
      return transaction.Connection.Query<T>(command, new DynamicParameters(param), transaction, commandType: CommandType.StoredProcedure);
    }
  }
}

It looks as though the outer using was closing the underlying connection thus any attempts to commit or rollback the transaction threw up the message "This SqlTransaction has completed; it is no longer usable."

I removed the usings added a covering test and the problem went away.

public IEnumerable<T> Query<T>(IDbTransaction transaction, string command, dynamic param = null)
{
  return transaction.Connection.Query<T>(command, new DynamicParameters(param), transaction, commandType: CommandType.StoredProcedure);
}

Check for anything that might be closing the connection while inside the context of a transaction.

How can I export the schema of a database in PostgreSQL?

For Linux: (data excluded)

  • pg_dump -s -t tablename databasename > dump.sql (For a specific table in database)

  • pg_dump -s databasename > dump.sql (For the entire database)

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

The problem you're having is the NSAutoresizingMaskLayoutConstraints should not be in there. This is the old system of springs and struts. To get rid of it, run this method on each view that you're wanting to constrain:

[view setTranslatesAutoresizingMaskIntoConstraints:NO];

Jquery-How to grey out the background while showing the loading icon over it

Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.

If the gif is displayed but not animating, see reference links at very bottom of this answer.

Displaying the gif + overlay, however, is easier than you might think.

All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.

So, when the button is pressed, just unhide those two divs. That's it!

jsFiddle Demo

_x000D_
_x000D_
$("#button").click(function() {_x000D_
    $('#myOverlay').show();_x000D_
    $('#loadingGIF').show();_x000D_
    setTimeout(function(){_x000D_
   $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    },2500);_x000D_
});_x000D_
/*  Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
 $('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Update:

You might enjoy playing with the new backdrop-filter:blur(_px) css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)

References:

http://www.paulirish.com/2007/animated-gif-not-animating/

Animated GIF while loading page does not animate

https://wordpress.org/support/topic/animated-gif-not-working

http://forums.mozillazine.org/viewtopic.php?p=987829

How can I get onclick event on webview in android?

Hamidreza's solution almost worked for me.

I noticed from experimentation that a simple tap usually has 2-5 action move events. Checking the time between action down and up was simpler and behaved more like what I expected.

private class CheckForClickTouchLister implements View.OnTouchListener {
    private final static long MAX_TOUCH_DURATION = 100;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                m_DownTime = event.getEventTime(); //init time

                break;

            case MotionEvent.ACTION_UP:
                if(event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION)
                    //On click action

                break;

            default:
                break; //No-Op

        }
        return false;
    }

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

Update 24.3.2016

I have found this guide from VP https://knowhow.visual-paradigm.com/technical-support/running-vp-in-android-studio/ created on September 8, 2015.

Good to know - it is possible to integrate VP into Android studio (in my case 1.5.1) now. Do not forget to backup your Android Studio settings (you can find them in Users%userName/.AndroidStudioX.X on Windows) ahead of installation.

I was trying to make it work, but created vp project did not contain any diagrams. Maybe someone else will have more luck.


I was using this manual http://www.visual-paradigm.com/support/documents/vpuserguide/2381/2385/66578_creatingauml.html to make Visual Paradigm working in Android studio, but action in 2. did not invoke dialogue in 3. So I Have asked Visual Paradigm support for help and they replied that Android Studio integration is not supported right now.

Reply from Visual paradigm reply from Apr 17 2015:

Thank you for your inquiry and I'm very sorry that at the moment we only support integrate with the standard IntelliJ IDEA, but not integrate with the Android Studio. We may consider to support it in our future release, and I'll keep you post once there any update on this topics. Feel free to contact me for any questions and wish you have a good day!

This post was deleted, so I will try to make it more clear.

As such I am considering previous answers as misleading and not useful. Therefore I thing that it is important for others to know that, before they lose their time trying to make it working.

ASP.NET MVC 404 Error Handling

In IIS, you can specify a redirect to "certain" page based on error code. In you example, you can configure 404 - > Your customized 404 error page.

Get the key corresponding to the minimum value within a dictionary

Use min with an iterator (for python 3 use items instead of iteritems); instead of lambda use the itemgetter from operator, which is faster than lambda.

from operator import itemgetter
min_key, _ = min(d.iteritems(), key=itemgetter(1))

RuntimeError on windows trying python multiprocessing

In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.

Programmatically go back to the previous fragment in the backstack

To elaborate on the other answers provided, this is my solution (placed in an Activity):

@Override
public void onBackPressed(){
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        Log.i("MainActivity", "popping backstack");
        fm.popBackStack();
    } else {
        Log.i("MainActivity", "nothing on backstack, calling super");
        super.onBackPressed();  
    }
}

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

Pattern matching using a wildcard

You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)

PHP 7 simpleXML

Because Google led me here, on Ubuntu 20.04 this works in 2020:

sudo apt install php7.4-xml

If on Apache2, remember to restart (probably not necessary):

sudo systemctl restart apache2

How to get the list of all database users

Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.

Run Sql Profiler. Attach it to your database of course.

Then right click in the GUI (in SSMS) and click "Refresh".
And then go see what Profiler "catches".

I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".

Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.

But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.

SELECT
u.name AS [Name],
'Server[@Name=' + quotename(CAST(
        serverproperty(N'Servername')
       AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/User[@Name=' + quotename(u.name,'''') + ']' AS [Urn],
u.create_date AS [CreateDate],
u.principal_id AS [ID],
CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
WHERE
(u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
ORDER BY
[Name] ASC

What is the use of the init() usage in JavaScript?

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

How to save an activity state using save instance state?

There are basically two ways to implement this change.

  1. using onSaveInstanceState() and onRestoreInstanceState().
  2. In manifest android:configChanges="orientation|screenSize".

I really do not recommend to use second method. Since in one of my experience it was causing half of the device screen black while rotating from portrait to landscape and vice versa.

Using first method mentioned above , we can persist data when orientation is changed or any config change happens. I know a way in which you can store any type of data inside savedInstance state object.

Example: Consider a case if you want to persist Json object. create a model class with getters and setters .

class MyModel extends Serializable{
JSONObject obj;

setJsonObject(JsonObject obj)
{
this.obj=obj;
}

JSONObject getJsonObject()
return this.obj;
} 
}

Now in your activity in onCreate and onSaveInstanceState method do the following. It will look something like this:

@override
onCreate(Bundle savedInstaceState){
MyModel data= (MyModel)savedInstaceState.getSerializable("yourkey")
JSONObject obj=data.getJsonObject();
//Here you have retained JSONObject and can use.
}


@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Obj is some json object 
MyModel dataToSave= new MyModel();
dataToSave.setJsonObject(obj);
oustate.putSerializable("yourkey",dataToSave); 

}

jquery mobile background image

Just add !important tag to all css elements in Paolo's answer! Works fine for me JQM+phonegap

EXAMPLE:

body {
    background: url(../images/background.jpg) !important;

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}

You can use this if you are using nullable DateFields.

Bootstrap close responsive menu "on click"

I think you are all over engineering..

    $('.navbar-collapse ul li a').click(function(){ 
            $('.navbar-toggle:visible').click();
    });

EDIT: To take care of sub menus, make sure their toggle anchor has the dropdown-toggle class on it.

    $(function () { 
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function () { 
                    $('.navbar-toggle:visible').click(); 
            }); 
    });

EDIT 2: Add support for phone touch.

    $(function () {
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').bind('click touchstart', function () {
                    $('.navbar-toggle:visible').click();
            });
    });

How to get the date from the DatePicker widget in Android?

If you are using Kotlin, you can define an extension function for DatePicker:

fun DatePicker.getDate(): Date {
    val calendar = Calendar.getInstance()
    calendar.set(year, month, dayOfMonth)
    return calendar.time
}

Then, it's just: datePicker.getDate(). As if it had always existed.

Float a div in top right corner without overlapping sibling header

This worked for me:

h1 {
    display: inline;
    overflow: hidden;
}
div {
    position: relative;
    float: right;
}

It's similar to the approach of the media object, by Stubbornella.

Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)

Scaling an image to fit on canvas

You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :

var hRatio = canvas.width / img.width    ;
var vRatio = canvas.height / img.height  ;
var ratio  = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);

i also suppose you want to center the image, so the code would be :

function drawImageScaled(img, ctx) {
   var canvas = ctx.canvas ;
   var hRatio = canvas.width  / img.width    ;
   var vRatio =  canvas.height / img.height  ;
   var ratio  = Math.min ( hRatio, vRatio );
   var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
   var centerShift_y = ( canvas.height - img.height*ratio ) / 2;  
   ctx.clearRect(0,0,canvas.width, canvas.height);
   ctx.drawImage(img, 0,0, img.width, img.height,
                      centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);  
}

you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Add this code to the beginning:

    Application.ScreenUpdating = False
     With ThisWorkbook
      Dim ws As Worksheet
       For Each ws In Worksheets: ws.Visible = True: Next ws
     End With

Add this code to the end:

    With ThisWorkbook
     Dim ws As Worksheet
      For Each ws In Worksheets: ws.Visible = False: Next ws
    End With
     Application.ScreenUpdating = True

Adjust Code at the end if you want more than the first sheet to be active and visible. Such as the following:

     Dim ws As Worksheet
      For Each ws In Worksheets
       If ws.Name = "_DataRecords" Then

         Else: ws.Visible = False
       End If
      Next ws

To ensure the new sheet is the one renamed, adjust your code similar to the following:

     Sheets(Me.cmbxSheetCopy.value).Copy After:=Sheets(Sheets.Count)
     Sheets(Me.cmbxSheetCopy.value & " (2)").Select
     Sheets(Me.cmbxSheetCopy.value & " (2)").Name = txtbxNewSheetName.value

This code is from my user form that allows me to copy a particular sheet (chosen from a dropdown box) with the formatting and formula's that I want to a new sheet and then rename new sheet with the user Input. Note that every time a sheet is copied it is automatically given the old sheet name with the designation of " (2)". Example "OldSheet" becomes "OldSheet (2)" after the copy and before the renaming. So you must select the Copied sheet with the programs naming before renaming.

How do I check if an integer is even or odd?

// C#
bool isEven = ((i % 2) == 0);

Add empty columns to a dataframe with specified names from a vector

The below works for me

dataframe[,"newName"] <- NA

Make sure to add "" for new name string.

How do I find the MySQL my.cnf location

Another option is to use the whereis command.

E.g. whereis my.cnf

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

How to use CMAKE_INSTALL_PREFIX

There are two ways to use this variable:

  • passing it as a command line argument just like Job mentioned:

    cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..

  • assigning value to it in CMakeLists.txt:

    SET(CMAKE_INSTALL_PREFIX < install_path >)

    But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

Select multiple images from android gallery

I got null from the Cursor. Then found a solution to convert the Uri into Bitmap that works perfectly.

Here is the solution that works for me:

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
{

    if (resultCode == Activity.RESULT_OK) {

        if (requestCode == YOUR_REQUEST_CODE) {

            if (data != null) {

                if (data.getData() != null) {

                    Uri contentURI = data.getData();
                    ex_one.setImageURI(contentURI);

                    Log.d(TAG, "onActivityResult: " + contentURI.toString());
                    try {

                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), contentURI);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {

                    if (data.getClipData() != null) {
                        ClipData mClipData = data.getClipData();
                        ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                        for (int i = 0; i < mClipData.getItemCount(); i++) {

                            ClipData.Item item = mClipData.getItemAt(i);
                            Uri uri = item.getUri();
                            try {
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                }

            }

        }

    }

}

Insert data into hive table

You can insert new data into table by two ways.

  1. Load the data of a file into table using load command.

    LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename.
    
  2. You can insert new data into table by using select query.

    INSERT INTO table tablename1 select columnlist FROM secondtable;
    

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

The inflate exception is not actually the problem but really comes from another deeper issue in your layout that is then wrapped in an InflateException. A common issue is an out of memory exception when trying to inflate an ImageView loading a drawable resource. If one of these resources has a high pixel resolution it would take a lot of memory causing then an inflate exception.

So basically verify that the pixel resolution in all your image drawables is just the minimum necessary for your layout.

Adding a 'share by email' link to website

<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>

Instructions

First, insert these lines wherever you want within your newsletter code. Then:

  1. Change "INSERT URL" to whatever website holds the shared content.
  2. Change "INSERT TITLE" to the title of the article.
  3. Change "INSERT SUMMARY" to a short summary of the article.
  4. Change "INSERT IMAGE URL" to an image that will be shared with the rest of the content.
  5. Change "INSERT DOMAIN NAME" to your domain name.
  6. Change "INSERT PUBLISHERID" to your publisher ID (if you have an account, if not, remove "[INSERT PUBLISHERID]" or sign up!)

If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.

expand/collapse table rows with JQuery

The easiest way to achieve this, without changing the HTML table-based structure, is to use a class-name on the tr elements containing a header, such as .header, to give:

<table border="0">
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr class="header">
    <td colspan="2">Header</td>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

And the jQuery:

// bind a click-handler to the 'tr' elements with the 'header' class-name:
$('tr.header').click(function(){
    /* get all the subsequent 'tr' elements until the next 'tr.header',
       set the 'display' property to 'none' (if they're visible), to 'table-row'
       if they're not: */
    $(this).nextUntil('tr.header').css('display', function(i,v){
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

In the linked demo I've used CSS to hide the tr elements that don't have the header class-name; in practice though (despite the relative rarity of users with JavaScript disabled) I'd suggest using JavaScript to add the relevant class-names, hiding and showing as appropriate:

// hide all 'tr' elements, then filter them to find...
$('tr').hide().filter(function () {
    // only those 'tr' elements that have 'td' elements with a 'colspan' attribute:
    return $(this).find('td[colspan]').length;
    // add the 'header' class to those found 'tr' elements
}).addClass('header')
    // set the display of those elements to 'table-row':
  .css('display', 'table-row')
    // bind the click-handler (as above)
  .click(function () {
    $(this).nextUntil('tr.header').css('display', function (i, v) {
        return this.style.display === 'table-row' ? 'none' : 'table-row';
    });
});

JS Fiddle demo.

References:

Displaying one div on top of another

Here is the jsFiddle

#backdrop{
    border: 2px solid red;
    width: 400px;
    height: 200px;
    position: absolute;
}

#curtain {
    border: 1px solid blue;
    width: 400px;
    height: 200px;
    position: absolute;
}

Use Z-index to move the one you want on top.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

I got the same error as I didn't save the script before executing it. Check to see if you have saved it!

Modular multiplicative inverse function in Python

Python 3.8+

y = pow(x, -1, p)

Python 3.7 and earlier

Maybe someone will find this useful (from wikibooks):

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

Link and execute external JavaScript file hosted on GitHub

I found the error was shown due to the comments at the beginning of file , You can solve this issue , by simply creating your own file without comment and push to git, it shows no error

For proof you can try these two file with same code of easy pagination :

without comment

with comment

Jenkins / Hudson environment variables

I have Jenkins 1.639 installed on SLES 11 SP3 via zypper (the package manager). Installation configured jenkins as a service

 # service jenkins
 Usage: /etc/init.d/jenkins {start|stop|status|try-restart|restart|force-reload|reload|probe}

Although /etc/init.d/jenkins sources /etc/sysconfig/jenkins, any env variables set there are not inherited by the jenkins process because it is started in a separate login shell with a new environment like this:

startproc -n 0 -s -e -l /var/log/jenkins.rc -p /var/run/jenkins.pid -t 1 /bin/su -l -s /bin/bash -c '/usr/java/default/bin/java -Djava.awt.headless=true -DJENKINS_HOME=/var/lib/jenkins -jar /usr/lib/jenkins/jenkins.war --javaHome=/usr/java/default --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war --httpPort=8080 --ajp13Port=8009 --debug=9 --handlerCountMax=100 --handlerCountMaxIdle=20 &' jenkins

The way I managed to set env vars for the jenkins process is via .bashrc in its home directory - /var/lib/jenkins. I had to create /var/lib/jenkins/.bashrc as it did not exist before.

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Actually you can use both - you can develop an app with amazon servers ec2. Then push it (with git) to heroku for free for awhile (use heroku free tier to serve it to the public) and test it like so. It is very cost effective in comparison to rent a server, but you will have to talk with a more restrictive heroku api which is something you should think about. Source: this method was adopted for one of my online classes "Startup engineering from Coursera/Stanford by Balaji S. Srinivasan and Vijay S. Pande

Added a scheme so my explanation will be easier to understand

Fast way to get the min/max values among properties of object

You could try:

const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5

Android ImageButton with a selected state?

Try this:

 <item
   android:state_focused="true"
   android:state_enabled="true"
   android:drawable="@drawable/map_toolbar_details_selected" />

Also for colors i had success with

<selector
        xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:state_selected="true"

            android:color="@color/primary_color" />
        <item
            android:color="@color/secondary_color" />
</selector>

How do I search for an object by its ObjectId in the mongo console?

In MongoDB Stitch functions it can be done using BSON like below:

Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:

var id = "5bb9e9f84186b222c8901149";  
BSON.ObjectId(id);

What is the problem with shadowing names defined in outer scopes?

A good workaround in some cases may be to move the variables and code to another function:

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

Another "Up Tick" for AR..., but if you don't have to use interop I would avoid it altogether. This product is actually quite interesting: http://www.clearoffice.com/ and it provides a very intuitive, fully managed, api for manipulation excel files and seems to be free. (at least for the time being) SpreadSheetGear is also excellent but pricey.

my two cents.

How to "wait" a Thread in Android

You can try this one it is short :)

SystemClock.sleep(7000);

It will sleep for 7 sec look at documentation

Strange out of memory issue while loading an image to a Bitmap object

To fix OutOfMemory you should do something like that please try this code

public Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
                Bitmap bitmap = null;
                InputStream in = null;
                options.inSampleSize=4;
                try {
                    in = OpenHttpConnection(URL);
                    Log.e("In====>", in+"");
                    bitmap = BitmapFactory.decodeStream(in, null, options);
                    Log.e("URL====>", bitmap+"");

                    in.close();
                } catch (IOException e1) {
                }
                return bitmap;
            }

and

try {
                    BitmapFactory.Options bmOptions;
                    bmOptions = new BitmapFactory.Options();
                    bmOptions.inSampleSize = 1;
                    if(studentImage != null){
                        galleryThumbnail= loadBitmap(IMAGE_URL+studentImage, bmOptions);    
                    }

                    galleryThumbnail=getResizedBitmap(galleryThumbnail, imgEditStudentPhoto.getHeight(), imgEditStudentPhoto.getWidth());
                    Log.e("Image_Url==>",IMAGE_URL+studentImage+"");

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

SQL Count for each date

You can use:

Select
     count(created_date) as counted_leads,
     created_date as count_date
from
     table
group by
     created_date

error: strcpy was not declared in this scope

This error sometimes occurs in a situation like this:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

static void init_random(uint32_t initseed=0)
{
    if (initseed==0)
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec);
    }
    else
        seed=initseed;
#if !defined(CYGWIN) && !defined(__INTERIX)
    //seed=42
    //SG_SPRINT("initializing random number generator with %d (seed size %d)\n", seed, RNG_SEED_SIZE)
    initstate(seed, CMath::rand_state, RNG_SEED_SIZE);
#endif
}

If the following code lines not run in the run-time:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

you will face with an error in your code like something as follows; because initstate is placed in the stdlib.h file and it's not included:

In file included from ../../shogun/features/SubsetStack.h:14:0, 
                 from ../../shogun/features/Features.h:21, 
                 from ../../shogun/ui/SGInterface.h:7, 
                 from MatlabInterface.h:15, 
                 from matlabInterface.cpp:7: 
../../shogun/mathematics/Math.h: In static member function 'static void shogun::CMath::init_random(uint32_t)': 
../../shogun/mathematics/Math.h:459:52: error: 'initstate' was not declared in this scope

How to set zoom level in google map

Here is a function I use:

var map =  new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(52.2, 5),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: 7
        });

function zoomTo(level) {
        google.maps.event.addListener(map, 'zoom_changed', function () {
            zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
                if (this.getZoom() > level && this.initialZoom == true) {
                    this.setZoom(level);
                    this.initialZoom = false;
                }
                google.maps.event.removeListener(zoomChangeBoundsListener);
            });
        });
    }

List of tuples to dictionary

Just call dict() on the list of tuples directly

>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}

Load a bitmap image into Windows Forms using open file dialog

You should try to:

  • Create the picturebox visually in form (it's easier)
  • Set Dock property of picturebox to Fill (if you want image to fill form)
  • Set SizeMode of picturebox to StretchImage

Finally:

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Title = "Open Image";
    dlg.Filter = "bmp files (*.bmp)|*.bmp";
    if (dlg.ShowDialog() == DialogResult.OK)
    {                     
        PictureBox1.Image = Image.FromFile(dlg.Filename);
    }
    dlg.Dispose();
}

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

Bad Request - Invalid Hostname IIS7

Did you check the binding is IIS? (inetmgr.exe) It may not be registered to accept all hostnames on 8080.

For example, if you set it up for mysite.com:8080 and hit it at localhost:8080, IIS will get the request but not have a hostname binding to match so it rejects.

Outside of that, you should check the IIS logs (C:\inetpub\logs\wmsvc#) on the server and see if you are seeing your request. Then you'll know if its a problem on your client or on the server itself.

How do I position one image on top of another in HTML?

Ok, after some time, here's what I landed on:

_x000D_
_x000D_
.parent {_x000D_
  position: relative;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.image1 {_x000D_
  position: relative;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  border: 1px red solid;_x000D_
}_x000D_
.image2 {_x000D_
  position: absolute;_x000D_
  top: 30px;_x000D_
  left: 30px;_x000D_
  border: 1px green solid;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <img class="image1" src="https://placehold.it/50" />_x000D_
  <img class="image2" src="https://placehold.it/100" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

As the simplest solution. That is:

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

Difference between binary semaphore and mutex

At a theoretical level, they are no different semantically. You can implement a mutex using semaphores or vice versa (see here for an example). In practice, the implementations are different and they offer slightly different services.

The practical difference (in terms of the system services surrounding them) is that the implementation of a mutex is aimed at being a more lightweight synchronisation mechanism. In oracle-speak, mutexes are known as latches and semaphores are known as waits.

At the lowest level, they use some sort of atomic test and set mechanism. This reads the current value of a memory location, computes some sort of conditional and writes out a value at that location in a single instruction that cannot be interrupted. This means that you can acquire a mutex and test to see if anyone else had it before you.

A typical mutex implementation has a process or thread executing the test-and-set instruction and evaluating whether anything else had set the mutex. A key point here is that there is no interaction with the scheduler, so we have no idea (and don't care) who has set the lock. Then we either give up our time slice and attempt it again when the task is re-scheduled or execute a spin-lock. A spin lock is an algorithm like:

Count down from 5000:
     i. Execute the test-and-set instruction
    ii. If the mutex is clear, we have acquired it in the previous instruction 
        so we can exit the loop
   iii. When we get to zero, give up our time slice.

When we have finished executing our protected code (known as a critical section) we just set the mutex value to zero or whatever means 'clear.' If multiple tasks are attempting to acquire the mutex then the next task that happens to be scheduled after the mutex is released will get access to the resource. Typically you would use mutexes to control a synchronised resource where exclusive access is only needed for very short periods of time, normally to make an update to a shared data structure.

A semaphore is a synchronised data structure (typically using a mutex) that has a count and some system call wrappers that interact with the scheduler in a bit more depth than the mutex libraries would. Semaphores are incremented and decremented and used to block tasks until something else is ready. See Producer/Consumer Problem for a simple example of this. Semaphores are initialised to some value - a binary semaphore is just a special case where the semaphore is initialised to 1. Posting to a semaphore has the effect of waking up a waiting process.

A basic semaphore algorithm looks like:

(somewhere in the program startup)
Initialise the semaphore to its start-up value.

Acquiring a semaphore
   i. (synchronised) Attempt to decrement the semaphore value
  ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.

Posting a semaphore
   i. (synchronised) Increment the semaphore value
  ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable.  
 iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.

In the case of a binary semaphore the main practical difference between the two is the nature of the system services surrounding the actual data structure.

EDIT: As evan has rightly pointed out, spinlocks will slow down a single processor machine. You would only use a spinlock on a multi-processor box because on a single processor the process holding the mutex will never reset it while another task is running. Spinlocks are only useful on multi-processor architectures.

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

Even if you remove the shared folder via net use * /del, on the server side there is still a connection up there.

In order to get around this problem which Microsoft created by design you should map the drive in a way to let windows think it's another share on another server. The simplest way to do that is to use DNS aliases or ip addresses. In your case, if your first mapping uses the ip address like \\IP\Share with your current credential, you should use something like \\ServerName\Share password /user:Domain\Username this should create a new share with the new credentials.

Microsoft call this behavior by design .. i call it just stupid design.

Merge / convert multiple PDF files into one PDF

Apache PDFBox http://pdfbox.apache.org/

PDFMerger This application will take a list of pdf documents and merge them, saving the result in a new document.

usage: java -jar pdfbox-app-x.y.z.jar PDFMerger "Source PDF files (2 ..n)" "Target PDF file"

Angular 2 How to redirect to 404 or other path if the path does not exist

My preferred option on 2.0.0 and up is to create a 404 route and also allow a ** route path to resolve to the same component. This allows you to log and display more information about the invalid route rather than a plain redirect which can act to hide the error.

Simple 404 example:

{ path '/', component: HomeComponent },
// All your other routes should come first    
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }

To display the incorrect route information add in import to router within NotFoundComponent:

import { Router } from '@angular/router';

Add it to the constructior of NotFoundComponent:

constructor(public router: Router) { }

Then you're ready to reference it from your HTML template e.g.

The page <span style="font-style: italic">{{router.url}}</span> was not found.

Reading a List from properties file and load with spring annotation @Value

Since Spring 3.0, you can add a line like

<bean id="conversionService" 
    class="org.springframework.context.support.ConversionServiceFactoryBean" />

to your applicationContext.xml (or where you configure things). As Dmitry Chornyi points out in a comment, Java based configuration looks like:

@Bean public ConversionService conversionService() {
    return new DefaultConversionService();
}

This activates the new configuration service which supports converting String to Collection types. If you do not activate this configuration service, Spring falls back on its legacy property editors as configuration services, which do not support this kind of conversion.

Converting to collections of other types works, too:

@Value("${my.list.of.ints}")
private List<Integer> myList

will work with a line like

 my.list.of.ints= 1, 2, 3, 4

No problems with whitespace there, the ConversionServiceFactoryBean takes care of it.

See http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#core-convert-Spring-config

In a Spring application, you typically configure a ConversionService instance per Spring container (or ApplicationContext). That ConversionService will be picked up by Spring and then used whenever a type conversion needs to be performed by the framework. [...] If no ConversionService is registered with Spring, the original PropertyEditor-based system is used.

Select 2 columns in one and combine them

None of the other answers worked for me but this did:

SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer

How to hide iOS status bar

You should add this value to plist: "View controller-based status bar appearance" and set it to "NO".

enter image description here

How can I make visible an invisible control with jquery? (hide and show not work)

You can't do this with jQuery, visible="false" in asp.net means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;" so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.

If you remove the visible attribute and add the style attribute you can then use jQuery to show it, like this:

$("#elementID").show();

Old Answer (before patrick's catch)

To change visibility, you need to use .css(), like this:

$("#elem").css('visibility', 'visible');

Unless you need to have the element occupy page space though, use display: none; instead of visibility: hidden; in your CSS, then just do:

$("#elem").show();

The .show() and .hide() functions deal with display instead of visibility, like most of the jQuery functions :)

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

how to change a selections options based on another select option selected?

Here is my simple solution using Jquery filters.

$('#publisher').on('change', function(e) {
   let selector = $(this).val();
   $("#site > option").hide();
   $("#site > option").filter(function(){return $(this).data('pub') == selector}).show();
});

JSFIDDLE

How can I check if a directory exists in a Bash shell script?

Check if the directory exists, else make one:

[ -d "$DIRECTORY" ] || mkdir $DIRECTORY

JUnit test for System.out.println()

Slightly off topic, but in case some people (like me, when I first found this thread) might be interested in capturing log output via SLF4J, commons-testing's JUnit @Rule might help:

public class FooTest {
    @Rule
    public final ExpectedLogs logs = new ExpectedLogs() {{
        captureFor(Foo.class, LogLevel.WARN);
    }};

    @Test
    public void barShouldLogWarning() {
        assertThat(logs.isEmpty(), is(true)); // Nothing captured yet.

        // Logic using the class you are capturing logs for:
        Foo foo = new Foo();
        assertThat(foo.bar(), is(not(nullValue())));

        // Assert content of the captured logs:
        assertThat(logs.isEmpty(), is(false));
        assertThat(logs.contains("Your warning message here"), is(true));
    }
}

Disclaimer:

  • I developed this library since I could not find any suitable solution for my own needs.
  • Only bindings for log4j, log4j2 and logback are available at the moment, but I am happy to add more.

Get first date of current month in java

First day of month of a date:

public static Date firstDayOfMonth(Date d) {
    
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(d);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    
    return calendar.getTime();  
}

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

I had a similar question and this answer in question HTML: table of forms? solved it for me. (Not sure if it is XHTML, but it works in an HTML5 browser.)

You can use css to give table layout to other elements.

.table { display: table; } 
.table>* { display: table-row; }
.table>*>* { display: table-cell; }

Then you use the following valid html.

<div class="table"> 
    <form>
        <div>snake<input type="hidden" name="cartitem" value="55"></div>
        <div><input name="count" value="4" /></div>
    </form>
</div>

Typescript: React event types

I have the following in a types.ts file for html input, select, and textarea:

export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>

Then import them:

import { InputChangeEventHandler } from '../types'

Then use them:


const updateName: InputChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}

Then apply the functions on your markup (replacing ... with other necessary props):

<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
  // ...
</select>

How can I quickly delete a line in VIM starting at the cursor position?

D or dd deletes and copies the line to the register. You can use Vx which only deletes the line and stays in the normal mode.

CSS text-overflow: ellipsis; not working?

Write these in your css rule.

display: block; /* or in-line block according to your requirement */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

Is there a MessageBox equivalent in WPF?

If you want to have your own nice looking wpf MessageBox: Create new Wpf Windows

here is xaml :

<Window x:Class="popup.MessageboxNew"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:popup"
        mc:Ignorable="d"
        Title="" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity="1"
        >
    <Window.Resources>

    </Window.Resources>
    <Border x:Name="MainBorder" Margin="10" CornerRadius="8" BorderThickness="0" BorderBrush="Black" Padding="0" >
        <Border.Effect>
            <DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="20" ShadowDepth="3" Opacity="0.6" />
        </Border.Effect>
        <Border.Triggers>
            <EventTrigger RoutedEvent="Window.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="ShadowDepth" From="0" To="3" Duration="0:0:1" AutoReverse="False" />
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="BlurRadius" From="0" To="20" Duration="0:0:1" AutoReverse="False" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Border.Triggers>
        <Grid Loaded="FrameworkElement_OnLoaded">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Border Name="Mask" CornerRadius="8" Background="White" />
            <Grid x:Name="Grid" Background="White">
                <Grid.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=Mask}"/>
                </Grid.OpacityMask>
                <StackPanel Name="StackPanel" >
                    <TextBox Style="{DynamicResource MaterialDesignTextBox}" Name="TitleBar" IsReadOnly="True" IsHitTestVisible="False" Padding="10" FontFamily="Segui" FontSize="14" 
                             Foreground="Black" FontWeight="Normal"
                             Background="Yellow" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="Auto" HorizontalContentAlignment="Center" BorderThickness="0"/>
                    <DockPanel Name="ContentHost" Margin="0,10,0,10" >
                        <TextBlock Margin="10" Name="Textbar"></TextBlock>
                    </DockPanel>
                    <DockPanel Name="ButtonHost" LastChildFill="False" HorizontalAlignment="Center" >
                        <Button Margin="10" Click="ButtonBase_OnClick" Width="70">Yes</Button>
                        <Button Name="noBtn" Margin="10" Click="cancel_Click" Width="70">No</Button>
                    </DockPanel>
                </StackPanel>
            </Grid>
        </Grid>
    </Border>
</Window>

for cs of this file :

public partial class MessageboxNew : Window
    {
        public MessageboxNew()
        {
            InitializeComponent();
            //second time show error solved
            if (Application.Current == null) new Application();
                    Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
        {
            this.MouseDown += delegate { DragMove(); };
        }
    }

then create a class to use this :

public class Mk_MessageBox
{
    public static bool? Show(string title, string text)
    {
        MessageboxNew msg = new MessageboxNew
        {
            TitleBar = {Text = title},
            Textbar = {Text = text}
        };
        msg.noBtn.Focus();
        return msg.ShowDialog();
    }
}

now you can create your message box like this:

var result = Mk_MessageBox.Show("Remove Alert", "This is gonna remove directory from host! Are you sure?");
            if (result == true)
            {
                // whatever
            }

copy this to App.xaml inside

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
            <!-- Accent and AppTheme setting -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />

            <!--two new guys-->
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.LightBlue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Green.xaml" />

            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

--------------IMAGE of Result-----------------

My Refrence : https://www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/

for logic how can i make my own messagebox

Where to find the complete definition of off_t type?

Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t defined on my machine" is "how is off_t defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.

In this case, off_t isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.

Unfortunately, off_t isn't very rigorously defined. All I could find to define it is on the page on sys/types.h:

blkcnt_t and off_t shall be signed integer types.

This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).


So, I think "where do I find the definition in my header files" isn't the best question. But, for completeness here's the answer:

On my machine (and most machines using glibc) you'll find the definition in bits/types.h (as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:

#include <stdio.h>
#include <sys/types.h>

int main(void) {
  off_t blah;

  return 0;
}

And then:

$ gcc -E sizes.c  | grep __off_t
typedef long int __off_t;
....

However, if you want to know the size of something, you can always use the sizeof() operator.

Edit: Just saw the part of your question about the __. This answer has a good discussion. The key point is that names starting with __ are reserved for the implementation (so you shouldn't start your own definitions with __).

Disable double-tap "zoom" option in browser on touch devices

* {
    -ms-touch-action: manipulation;
    touch-action: manipulation;
}

Disable double tap to zoom on touch screens. Internet explorer included.

cast class into another class or convert class to another

There are some great answers here, I just wanted to add a little bit of type checking here as we cannot assume that if properties exist with the same name, that they are of the same type. Here is my offering, which extends on the previous, very excellent answer as I had a few little glitches with it.

In this version I have allowed for the consumer to specify fields to be excluded, and also by default to exclude any database / model specific related properties.

    public static T Transform<T>(this object myobj, string excludeFields = null)
    {
        // Compose a list of unwanted members
        if (string.IsNullOrWhiteSpace(excludeFields))
            excludeFields = string.Empty;
        excludeFields = !string.IsNullOrEmpty(excludeFields) ? excludeFields + "," : excludeFields;
        excludeFields += $"{nameof(DBTable.ID)},{nameof(DBTable.InstanceID)},{nameof(AuditableBase.CreatedBy)},{nameof(AuditableBase.CreatedByID)},{nameof(AuditableBase.CreatedOn)}";

        var objectType = myobj.GetType();
        var targetType = typeof(T);
        var targetInstance = Activator.CreateInstance(targetType, false);

        // Find common members by name
        var sourceMembers = from source in objectType.GetMembers().ToList()
                                  where source.MemberType == MemberTypes.Property
                                  select source;
        var targetMembers = from source in targetType.GetMembers().ToList()
                                  where source.MemberType == MemberTypes.Property
                                  select source;
        var commonMembers = targetMembers.Where(memberInfo => sourceMembers.Select(c => c.Name)
            .ToList().Contains(memberInfo.Name)).ToList();

        // Remove unwanted members
        commonMembers.RemoveWhere(x => x.Name.InList(excludeFields));

        foreach (var memberInfo in commonMembers)
        {
            if (!((PropertyInfo)memberInfo).CanWrite) continue;

            var targetProperty = typeof(T).GetProperty(memberInfo.Name);
            if (targetProperty == null) continue;

            var sourceProperty = myobj.GetType().GetProperty(memberInfo.Name);
            if (sourceProperty == null) continue;

            // Check source and target types are the same
            if (sourceProperty.PropertyType.Name != targetProperty.PropertyType.Name) continue;

            var value = myobj.GetType().GetProperty(memberInfo.Name)?.GetValue(myobj, null);
            if (value == null) continue;

            // Set the value
            targetProperty.SetValue(targetInstance, value, null);
        }
        return (T)targetInstance;
    }

How does data binding work in AngularJS?

AngularJs supports Two way data-binding.
Means you can access data View -> Controller & Controller -> View

For Ex.

1)

// If $scope have some value in Controller. 
$scope.name = "Peter";

// HTML
<div> {{ name }} </div>

O/P

Peter

You can bind data in ng-model Like:-
2)

<input ng-model="name" />

<div> {{ name }} </div>

Here in above example whatever input user will give, It will be visible in <div> tag.

If want to bind input from html to controller:-
3)

<form name="myForm" ng-submit="registration()">
   <label> Name </lbel>
   <input ng-model="name" />
</form>

Here if you want to use input name in the controller then,

$scope.name = {};

$scope.registration = function() {
   console.log("You will get the name here ", $scope.name);
};

ng-model binds our view and render it in expression {{ }}.
ng-model is the data which is shown to the user in the view and with which the user interacts.
So it is easy to bind data in AngularJs.

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

You have to set "secondary okay" mode to let the mongo shell know that you're allowing reads from a secondary. This is to protect you and your applications from performing eventually consistent reads by accident. You can do this in the shell with:

rs.secondaryOk()

After that you can query normally from secondaries.

A note about "eventual consistency": under normal circumstances, replica set secondaries have all the same data as primaries within a second or less. Under very high load, data that you've written to the primary may take a while to replicate to the secondaries. This is known as "replica lag", and reading from a lagging secondary is known as an "eventually consistent" read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.

Edit: You only need to set secondaryOk when querying from secondaries, and only once per session.

ToList()-- does it create a new list?

I don't see anywhere in the documentation that ToList() is always guaranteed to return a new list. If an IEnumerable is a List, it may be more efficient to check for this and simply return the same List.

The worry is that sometimes you may want to be absolutely sure that the returned List is != to the original List. Because Microsoft doesn't document that ToList will return a new List, we can't be sure (unless someone found that documentation). It could also change in the future, even if it works now.

new List(IEnumerable enumerablestuff) is guaranteed to return a new List. I would use this instead.

How to specify multiple conditions in an if statement in javascript

just add them within the main bracket of the if statement like

if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
            PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

Logically this can be rewritten in a better way too! This has exactly the same meaning

if (Type == 2 && (PageCount == 0 || PageCount == '')) {

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

To diagnose this issue, place the line of code causing the TargetInvocationException inside the try block.

To troubleshoot this type of error, get the inner exception. It could be due to a number of different issues.

try
{
    // code causing TargetInvocationException
}
catch (Exception e)
{
    if (e.InnerException != null)
    {
    string err = e.InnerException.Message;
    }
}

How to change dataframe column names in pyspark?

If you want to change all columns names, try df.toDF(*cols)

Updating a date in Oracle SQL table

Just to add to Alex Poole's answer, here is how you do the date and time:

    TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss')

How can I align YouTube embedded video in the center in bootstrap

Using Bootstrap's built in .center-block class, which sets margin left and right to auto:

<iframe class="center-block" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>

Or using the built in .text-center class, which sets text-align: center:

<div class="text-center">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div>

CodeIgniter: How to use WHERE clause and OR clause

You can use this :

$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);

How to check for an empty object in an AngularJS view

You can use plain javascript Object class to achieve it, Object class has keys function which takes 1 argument as input as follows,

Object.keys(obj).length === 0

You can achieve it in 3 ways, 1) Current controller scope 2) Filter 3) $rootScope

1) First way is current controller scope,

$scope.isObjEmpty = function(obj){ return Object.keys(obj).length === 0; }

Then you can call the function from the view:

ng-show="!isObjEmpty(obj)" if you want to show and hide dom dynamically & ng-if="!isObjEmpty(obj)" if you want to remove or add dom dynamically.

2) The second way is a custom filter. Following code should work for the object & Array,

angular.module('angularApp')
    .filter('isEmpty', [function () {
        return function (obj) {
            if (obj == undefined || obj == null || obj == '')
                return true;
            if (angular.isObject(obj))
                return Object.keys(obj).length != 0;

            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    return false;
                }
            }
            return true;
        };
    }]);

    <div ng-hide="items | isEmpty"> Your content's goes here </div>

3) The third way is $rootScope, create a plain javascript function and add it in $rootScope server it will accessible default in all scopes and UI.

function isObjEmpty (obj){ return Object.keys(obj).length === 0; }

$rootScope.isObjEmpty = isObjEmpty ;

Permission denied on accessing host directory in Docker

In my situation the problem was different. I don't know why, but even if directory on host had chmod 777 run on it, inside docker it was visible as 755.

Running inside container sudo chmod 777 my_volume_dir fixed it.

Youtube autoplay not working on mobile devices with embedded HTML5 player

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512

How to change text color of cmd with windows batch script every 1 second

@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F 31 32 33 34 35 36 37 41 42 43 44 45 46 90 91 92 93 94 95 96 97 100 101 102 103 104 105 106 107 
for %%x in (%NUM%) do ( 
    for %%y in (%NUM%) do (
        color %%x%%y
cls
echo Himel Sarkar
        timeout 1 >nul
    )
)

pause

How to embed a .mov file in HTML?

Well, if you don't want to do the work yourself (object elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/

Get WooCommerce product categories from WordPress

Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:

$sub_cats = get_categories( $args2 );
    if($sub_cats) {
        foreach($sub_cats as $sub_category) {
            echo  $sub_category->name ;
        }

    }

with:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                }
            }

or if you also wish a counter for each subcategory, replace with this:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                    echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
                }
            }

How can I login to a website with Python?

import cookielib
import urllib
import urllib2

url = 'http://www.someserver.com/auth/login'
values = {'email-email' : '[email protected]',
          'password-clear' : 'Combination',
          'password-password' : 'mypassword' }

data = urllib.urlencode(values)
cookies = cookielib.CookieJar()

opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cookies))

response = opener.open(url, data)
the_page = response.read()
http_headers = response.info()
# The login cookies should be contained in the cookies variable

For more information visit: https://docs.python.org/2/library/urllib2.html

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I was seeing this issue when I was creating a bundle to react-native. Things I tried and didn't work:

  1. Increasing the node --max_old_space_size, intrestingly this worked locally for me but failed on jenkins and I'm still not sure what goes wrong with jenkins
  2. Some places mentioned to downgrade the version of node to 6.9.1 and that didn't work for me either. I would just like to put this here as it might work for you.

Thing that did work for me: I was importing a really big file in the code. The way I resolved it was by including it in the ignore list in .babelrc something like this:

{
    "presets": ["react-native"],
    "plugins": ["transform-inline-environment-variables"],
    "ignore": ["*.json","filepathToIgnore.ext"]
}

It was a .js file which did not really needed transpiling and adding it to the ignore list did help.

How can you undo the last git add?

You cannot undo the latest git add, but you can undo all adds since the last commit. git reset without a commit argument resets the index (unstages staged changes):

git reset

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

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

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


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

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

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


Which type of kernel image do I have to use?

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

ADDENDUM

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

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

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

Latex Remove Spaces Between Items in List

compactitem does the job.

\usepackage{paralist}

...

\begin{compactitem}[$\bullet$]
    \item Element 1
    \item Element 2
\end{compactitem}
\vspace{\baselineskip} % new line after list

Detect if range is empty

This just a slight addition to @TomM's answer/ A simple function to check if your Selection's cells are empty

Public Function CheckIfSelectionIsEmpty() As Boolean
   Dim emptySelection As Boolean:emptySelection=True
   Dim cell As Range
   For Each cell In Selection
       emptySelection = emptySelection And isEmpty(cell)
       If emptySelection = False Then
          Exit For
       End If
   Next
   CheckIfSelectionIsEmpty = emptySelection
End Function

How do I join two lists in Java?

I can't improve on the two-liner in the general case without introducing your own utility method, but if you do have lists of Strings and you're willing to assume those Strings don't contain commas, you can pull this long one-liner:

List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + ", " + listTwo.toString().subString(1, listTwo.length() - 1)).split(", ")));

If you drop the generics, this should be JDK 1.4 compliant (though I haven't tested that). Also not recommended for production code ;-)

How do you get git to always pull from a specific branch?

Not wanting to edit my git config file I followed the info in @mipadi's post and used:

$ git pull origin master

Install specific branch from github using Npm

I'm using SSH to authenticate my GitHub account and have a couple dependencies in my project installed as follows:

"dependencies": {
  "<dependency name>": "git+ssh://[email protected]/<github username>/<repository name>.git#<release version | branch>"
}

How do I scroll to an element within an overflowed Div?

I write these 2 functions to make my life easier:

function scrollToTop(elem, parent, speed) {
    var scrollOffset = parent.scrollTop() + elem.offset().top;
    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

function scrollToCenter(elem, parent, speed) {
    var elOffset = elem.offset().top;
    var elHeight = elem.height();
    var parentViewTop = parent.offset().top;
    var parentHeight = parent.innerHeight();
    var offset;

    if (elHeight >= parentHeight) {
        offset = elOffset;
    } else {
        margin = (parentHeight - elHeight)/2;
        offset = elOffset - margin;
    }

    var scrollOffset = parent.scrollTop() + offset - parentViewTop;

    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

And use them:

scrollToTop($innerListItem, $parentDiv, 200);
// or
scrollToCenter($innerListItem, $parentDiv, 200);

Array Size (Length) in C#

What has been missed so far is what I suddenly was irritated about:

How do I know the amount of items inside the array? Is .Length equal .Count of a List?

The answer is: the amount of items of type X which have been put into an array of type X created with new X[number] you have to carry yourself!

Eg. using a counter: int countItemsInArray = 0 and countItemsInArray++ for every assignment to your array.

(The array just created with new X[number] has all space for number items (references) of type X already allocated, you can assign to any place inside as your first assignment, for example (if number = 100 and the variable name = a) a[50] = new X();.

I don't know whether C# specifies the initial value of each place inside an array upon creation, if it doesn't or the initial value you cannot compare to (because it might be a value you yourself have put into the array), you would have to track which places inside the array you already assigned to too if you don't assign sequentially starting from 0 (in which case all places smaller than countItemsInArray would be assigned to).)

In your question size of an array (length / number of items) depending on whether / is meant to stand for "alternative" or "divide by" the latter still has to be covered (the "number of items" I just gave as "amount of items" and others gave .Length which corresponds to the value of number in my code above):

C# has a sizeof operator (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/sizeof). It's safe to use for built-in types (such as int) (and only operates on types (not variables)). Thus the size of an array b of type int in bytes would be b.Length * sizeof(int).

(Due to all space of an array already being allocated on creation, like mentioned above, and sizeof only working on types, no code like sizeof(variable)/sizeof(type) would work or yield the amount of items without tracking.)

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;

Linux Script to check if process is running and act on the result

I adopted the @Jotne solution and works perfectly! For example for mongodb server in my NAS

#! /bin/bash

case "$(pidof mongod | wc -w)" in

0)  echo "Restarting mongod:"
    mongod --config mongodb.conf
    ;;
1)  echo "mongod already running"
    ;;
esac

How can I clear console

The easiest way for me without having to reinvent the wheel.

void Clear()
{
#if defined _WIN32
    system("cls");
    //clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
    system("clear");
    //std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences 
#elif defined (__APPLE__)
    system("clear");
#endif
}
  • On Windows you can use "conio.h" header and call clrscr function to avoid the use of system funtion.
#include <conio.h>
clrscr();
  • On Linux you can use ANSI Escape sequences to avoid use of system function. Check this reference ANSI Escape Sequences
    std::cout<< u8"\033[2J\033[1;1H"; 
  • On MacOS Investigating...

How do I list all tables in all databases in SQL Server in a single result set?

This is really handy, but I wanted a way to show all user objects, not just tables, so I adapted it to use sys.objects instead of sys.tables

SET NOCOUNT ON
DECLARE @AllTables table (DbName sysname,SchemaName sysname, ObjectType char(2), ObjectName sysname)
DECLARE
     @SearchDb nvarchar(200)
    ,@SearchSchema nvarchar(200)
    ,@SearchObject nvarchar(200)
    ,@SQL nvarchar(4000)
SET @SearchDb='%'
SET @SearchSchema='%'
SET @SearchObject='%Something%'
SET @SQL='select ''?'' as DbName, s.name as SchemaName, t.type as ObjectType, t.name as ObjectName 
from [?].sys.objects t inner join sys.schemas s on t.schema_id=s.schema_id 
WHERE t.type in (''FN'',''IF'',''U'',''V'',''P'',''TF'') 
AND ''?'' LIKE '''+@SearchDb+''' 
AND s.name LIKE '''+@SearchSchema+''' 
AND t.name LIKE '''+@SearchObject+''''

INSERT INTO @AllTables (DbName, SchemaName, ObjectType, ObjectName)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY DbName, SchemaName, ObjectType, ObjectName

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

use current date as default value for a column

CREATE TABLE Orders(
    O_Id int NOT NULL,
    OrderNo int NOT NULL,
    P_Id int,
    OrderDate date DEFAULT GETDATE() // you can set default constraints while creating the table
)

Set transparent background of an imageview on Android

Try to use the following code. It will help you in full or more.

  1. A .xml file designed to use this code to set background color:

    android:background="#000000"
    

    or

    android:background="#FFFFFF"
    

    Image is here

    Or you can set it programmatically as well.

  2. Also you can use this code programmatically:

    image.setBackgroundDrawable(getResources().getDrawable(
        R.drawable.llabackground));
    
  3. Also this code for setting the background color as well programmatically:

    image.setBackgroundColor(Color.parseColor("#FFFFFF"));
    
  4. This code for the same programmatically:

    image.setBackgroundColor(getResources().getColor(Color.WHITE));
    

The color depends on your choice of which color you want to use for transparent. Mostly use a white or #FFFFFF color.

Regarding R.drawable.llabackground: This line of code is for your style of the background, like something special or different for your purpose. You can also use this.

Eclipse count lines of code

The first thing to do is to determine your definition of "line of code" (LOC). In both your question

It counts a line with just one } as a line and he doesn't want that to count as "its not a line, its a style choice"

and in the answers, e.g.,

You can adjust the Lines of Code metrics by ignoring blank and comment-only lines or exclude Javadoc if you want

you can tell that people have different opinions as to what constitutes a line of code. In particular, people are often imprecise about whether they really want the number of lines of code or the number of statements. For example, if you have the following really long line filled with statements, what do you want to report, 1 LOC or hundreds of statements?

{ a = 1; b = 2; if (a==c) b++; /* etc. for another 1000 characters */ }

And when somebody asks you what you are calling a LOC, make sure you can answer, even if it is just "my definition of a LOC is Metrics2's definition". In general, for most commonly formatted code (unlike my example), the popular tools will give numbers fairly similar, so Metrics2, SonarQube, etc. should all be fine, as long as you use them consistently. In other words, don't count the LOC of some code using one tool and compare that value to a later version of that code that was measured with a different tool.

GitHub: How to make a fork of public repository private?

The answers are correct but don't mention how to sync code between the public repo and the fork.

Here is the full workflow (we've done this before open sourcing React Native):


First, duplicate the repo as others said (details here):

Create a new repo (let's call it private-repo) via the Github UI. Then:

git clone --bare https://github.com/exampleuser/public-repo.git
cd public-repo.git
git push --mirror https://github.com/yourname/private-repo.git
cd ..
rm -rf public-repo.git

Clone the private repo so you can work on it:

git clone https://github.com/yourname/private-repo.git
cd private-repo
make some changes
git commit
git push origin master

To pull new hotness from the public repo:

cd private-repo
git remote add public https://github.com/exampleuser/public-repo.git
git pull public master # Creates a merge commit
git push origin master

Awesome, your private repo now has the latest code from the public repo plus your changes.


Finally, to create a pull request private repo -> public repo:

Use the GitHub UI to create a fork of the public repo (the small "Fork" button at the top right of the public repo page). Then:

git clone https://github.com/yourname/the-fork.git
cd the-fork
git remote add private_repo_yourname https://github.com/yourname/private-repo.git
git checkout -b pull_request_yourname
git pull private_repo_yourname master
git push origin pull_request_yourname

Now you can create a pull request via the Github UI for public-repo, as described here.

Once project owners review your pull request, they can merge it.

Of course the whole process can be repeated (just leave out the steps where you add remotes).

ArrayList of String Arrays

Use a second ArrayList for the 3 strings, not a primitive array. Ie.
private List<List<String>> addresses = new ArrayList<List<String>>();

Then you can have:

ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");

addresses.add(singleAddress);

(I think some strange things can happen with type erasure here, but I don't think it should matter here)

If you're dead set on using a primitive array, only a minor change is required to get your example to work. As explained in other answers, the size of the array can not be included in the declaration. So changing:

private ArrayList<String[]> addresses = new ArrayList<String[3]>();

to

private ArrayList<String[]> addresses = new ArrayList<String[]>();

will work.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

svn: E155004: ..(path of resource).. is already locked

Just cleanup. Happened in JetBrains PhpStorm

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Ignore cells on Excel line graph

if the data is the result of a formula, then it will never be empty (even if you set it to ""), as having a formula is not the same as an empty cell

There are 2 methods, depending on how static the data is.

The easiest fix is to clear the cells that return empty strings, but that means you will have to fix things if data changes

the other fix involves a little editing of the formula, so instead of setting it equal to "", you set it equal to NA().
For example, if you have =IF(A1=0,"",B1/A1), you would change that to =IF(A1=0,NA(),B1/A1).
This will create the gaps you desire, and will also reflect updates to the data so you don't have to keep fixing it every time

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

java.lang.IllegalArgumentException: View not attached to window manager

Migh below code works for you, It works for me perfectly fine:

private void viewDialog() {
    try {
        Intent vpnIntent = new Intent(context, UtilityVpnService.class);
        context.startService(vpnIntent);
        final View Dialogview = View.inflate(getBaseContext(), R.layout.alert_open_internet, null);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_DIM_BEHIND,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
        windowManager.addView(Dialogview, params);

        Button btn_cancel = (Button) Dialogview.findViewById(R.id.btn_canceldialog_internetblocked);
        Button btn_okay = (Button) Dialogview.findViewById(R.id.btn_openmainactivity);
        RelativeLayout relativeLayout = (RelativeLayout) Dialogview.findViewById(R.id.rellayout_dialog);

            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (Dialogview != null) {
//                                ( (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                                    windowManager.removeView(Dialogview);
                                }
                            } catch (final IllegalArgumentException e) {
                                e.printStackTrace();
                                // Handle or log or ignore
                            } catch (final Exception e) {
                                e.printStackTrace();
                                // Handle or log or ignore
                            } finally {
                                try {
                                    if (windowManager != null && Dialogview != null) {
//                                    ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                                        windowManager.removeView(Dialogview);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            //    ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
//                        windowManager.removeView(Dialogview);


                        }
                    });
                }
            });
            btn_okay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //        ((WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE)).removeView(Dialogview);
                            try {
                                if (windowManager != null && Dialogview != null)
                                    windowManager.removeView(Dialogview);
                                Intent intent = new Intent(getBaseContext(), SplashActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


                                context.startActivity(intent);
                            } catch (Exception e) {
                                windowManager.removeView(Dialogview);
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });
        } catch (Exception e) {
            //` windowManager.removeView(Dialogview);
            e.printStackTrace();
        }
    }

Do not define your view globally if u call it from background service.

Presto SQL - Converting a date string to date format

You can also do something like this

date(cast('2016-03-22 15:19:34.0' as timestamp))

Import text file as single character string

Here's a variant of the solution from @JoshuaUlrich that uses the correct size instead of a hard-coded size:

fileName <- 'foo.txt'
readChar(fileName, file.info(fileName)$size)

Note that readChar allocates space for the number of bytes you specify, so readChar(fileName, .Machine$integer.max) does not work well...

Proper MIME type for OTF fonts

There are a number of font formats that one can set MIME types for, on both Apache and IIS servers. I've traditionally had luck with the following:

svg   as "image/svg+xml"                  (W3C: August 2011)
ttf   as "application/x-font-ttf"         (IANA: March 2013)
      or "application/x-font-truetype"
otf   as "application/x-font-opentype"    (IANA: March 2013)
woff  as "application/font-woff"          (IANA: January 2013)
woff2 as "application/font-woff2"         (W3C W./E.Draft: May 2014/March 2016)
eot   as "application/vnd.ms-fontobject"  (IANA: December 2005)
sfnt  as "application/font-sfnt"          (IANA: March 2013) 

According to the Internet Engineering Task Force who maintain the initial document regarding Multipurpose Internet Mail Extensions (MIME types) here: http://tools.ietf.org/html/rfc2045#section-5 ... it says in specifics:

"It is expected that additions to the larger set of supported types can generally be accomplished by the creation of new subtypes of these initial types. In the future, more top-level types may be defined only by a standards-track extension to this standard. If another top-level type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid a potential conflict with a future official name."

As it were, and over time, additional MIME types get added as standards are created and accepted, therefor we see examples of vendor specific MIME types such as vnd.ms-fontobject and the like.

UPDATE August 16, 2013: WOFF was formally registered at IANA on January 3, 2013 and Webkit has been updated on March 5, 2013 and browsers that are sourcing this update in their latest versions will start issuing warnings about the server MIME types with the old x-font-woff declaration. Since the warnings are only annoying I would recommend switching to the approved MIME type right away. In an ideal world, the warnings will resolve themselves in time.

UPDATE February 26, 2015: WOFF2 is now in the W3C Editor's Draft with the proposed mime-type. It should likely be submitted to IANA in the next year (possibly by end of 2016) following more recent progress timelines. As well SFNT, the scalable/spline container font format used in the backbone table reference of Google Web Fonts with their sfntly java library and is already registered as a mime type with IANA and could be added to this list as well dependent on individual need.

UPDATE October 4, 2017: We can follow the progression of the WOFF2 format here with a majority of modern browsers supporting the format successfully. As well, we can follow the IETF's "font" Top-Level Media Type request for comments (RFC) tracker and document regarding the latest set of proposed font types for approval.


For those wishing to embed the typeface in the proper order in your CSS please visit this article. But again, I've had luck with the following order:

@font-face {
    font-family: 'my-web-font';
    src: url('webfont.eot');
    src: url('webfont.eot?#iefix') format('embedded-opentype'),
         url('webfont.woff2') format('woff2'),
         url('webfont.woff') format('woff'),
         url('webfont.ttf') format('truetype'),
         url('webfont.svg#webfont') format('svg');
    font-weight: normal;
    font-style: normal;
}

For Subversion auto-properties, these can be listed as:

# Font formats
svg   = svn:mime-type=image/svg+xml
ttf   = svn:mime-type=application/x-font-ttf
otf   = svn:mime-type=application/x-font-opentype
woff  = svn:mime-type=application/font-woff
woff2 = svn:mime-type=application/font-woff2
eot   = svn:mime-type=application/vnd.ms-fontobject
sfnt  = svn:mime-type=application/font-sfnt

How to align footer (div) to the bottom of the page?

check this out, works on firefox and IE

<style>
    html, body
    {
        height: 100%;
    }
    .content
    {
        min-height: 100%;
    }
    .footer
    {
        position: relative;
        clear: both;
    }
</style>

<body>
<div class="content">Page content
</div>
<div class="footer">this is my footer
</div>
</body>

Best way to log POST data in Apache?

An easier option may be to log the POST data before it gets to the server. For web applications, I use Burp Proxy and set Firefox to use it as an HTTP/S proxy, and then I can watch (and mangle) data 'on the wire' in real time.

For making API requests without a browser, SoapUI is very useful and may show similar info. I would bet that you could probably configure SoapUI to connect through Burp as well (just a guess though).

Need to find element in selenium by css

Only using class names is not sufficient in your case.

  • By.cssSelector(".ban") has 15 matching nodes
  • By.cssSelector(".hot") has 11 matching nodes
  • By.cssSelector(".ban.hot") has 5 matching nodes

Therefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.

Option 1: Using list items' index (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes

Example:

driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));

Option 2: Using Selenium's FindElements, then index them. (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes
  • Not the native selector's way

Example:

// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];

Option 3: Using text (XPath only)

Limitations

  • Not for multilanguage sites
  • Only for XPath, not for Selenium's CssSelector

Example:

driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));

Option 4: Index the grouped selector (XPath only)

Limitations

  • Not stable enough if site's structure changes
  • Only for XPath, not CssSelector

Example:

driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));

Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)

Limitations

  • Only for XPath, not CssSelector
  • Low performance
  • Tricky XPath

Example:

driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));

Git Diff with Beyond Compare

I don't use extra wrapper .sh files. My environment is Windows XP, git 1.7.1 on cygwin, and Beyond Compare 3. Following is my .git/config file.

[diff]
    tool = bc3
[difftool]
    prompt = false
[difftool "bc3"]
    #use cygpath to transform cygwin path $LOCAL (something like /tmp/U5VvP1_abc) to windows path, because bc3 is a windows software
    cmd = \"c:/program files/beyond compare 3/bcomp.exe\" "$(cygpath -w $LOCAL)" "$REMOTE"
[merge]
    tool = bc3
[mergetool]
    prompt = false
[mergetool "bc3"]
    #trustExitCode = true
    cmd = \"c:/program files/beyond compare 3/bcomp.exe\" "$LOCAL" "$REMOTE" "$BASE" "$MERGED"

Then, I use $ git difftool to compare and $ git mergetool to merge.

About trustExitCode: For a custom merge command, specify whether the exit code of the merge command can be used to determine whether the merge was successful. If this is not set to true then the merge target file timestamp is checked and the merge assumed to have been successful if the file has been updated, otherwise the user is prompted to indicate the success of the merge.

Generate insert script for selected records?

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLENAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''   -- where TableId = 5 or some value
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @TABLE_NAME VARCHAR(MAX),
        @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX),
        @FILTER VARCHAR(MAX) 

SET @TABLE_NAME=@TABLENAME

SELECT @FILTER=@FILTER_CONDITION

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END

Fixed footer in Bootstrap

You can do this by wrapping the page contents in a div with the following id styling applied:

<style>
#wrap {
   min-height: 100%;
   height: auto !important;
   height: 100%;
   margin: 0 auto -60px;
}
</style>

<div id="wrap">
    <!-- Your page content here... -->
</div>

Worked for me.

Excel: How to check if a cell is empty with VBA?

IsEmpty() would be the quickest way to check for that.

IsNull() would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.

Also, you can check the cell by:

count()

counta()

Len(range("BCell").Value) = 0

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Android transparent status bar and actionbar

I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.

Transparent Actionbar:

values/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="android:windowContentOverlay">@null</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="windowActionBarOverlay">false</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>


values-v21/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    ...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>

Now you can use these themes in your AndroidManifest.xml to specify which activities will have a transparent or colored ActionBar:

    <activity
            android:name=".MyTransparentActionbarActivity"
            android:theme="@style/AppTheme.ActionBar.Transparent"/>

    <activity
            android:name=".MyColoredActionbarActivity"
            android:theme="@style/AppTheme.ActionBar"/>

enter image description here enter image description here enter image description here enter image description here enter image description here

Note: in API>=21 to get the Actionbar transparent you need to get the Statusbar transparent too, otherwise will not respect your colour styles and will stay light-grey.



Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

But you'll notice a funky result: enter image description here

This happens because when the Statusbar is transparent the layout will use its height. To prevent this we just need to:

SOLUTION ONE:
Add this line android:fitsSystemWindows="true" in your layout view container of whatever you want to be placed bellow the Actionbar:

    ...
        <LinearLayout
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            ...
        </LinearLayout>
    ...

SOLUTION TWO:
Add a few lines to our previous method:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        View v = findViewById(R.id.bellow_actionbar);
        if (v != null) {
            int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
            TypedValue tv = new TypedValue();
            getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
            paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
        }

        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

Where R.id.bellow_actionbar will be the layout container view id of whatever we want to be placed bellow the Actionbar:

...
    <LinearLayout
            android:id="@+id/bellow_actionbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        ...
    </LinearLayout>
...

enter image description here

So this is it, it think I'm not forgetting something. In this example I didn't use a Toolbar but I think it'll have the same result. This is how I customize my Actionbar:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        View vg = getActionBarView();
        getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        if (vg != null) {
            getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            getSupportActionBar().setDisplayShowCustomEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayUseLogoEnabled(false);
        }
        setStatusBarTranslucent(true);
    }

Note: this is an abstract class that extends ActionBarActivity
Hope it helps!

Find file in directory from command line

locate <file_pattern>

*** find will certainly work, and can target specific directories. However, this command is slower than the locate command. On a Linux OS, each morning a database is constructed that contains a list of all directory and files, and the locate command efficiently searches this database, so if you want to do a search for files that weren't created today, this would be the fastest way to accomplish such a task.

What is the result of % in Python?

% is modulo. 3 % 2 = 1, 4 % 2 = 0

/ is (an integer in this case) division, so:

3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
1 + 4%2 - 1/4 + 6
1 + 0 - 0 + 6
7

UILabel with text of two different colors

For Xamarin users I have a static C# method where I pass in an array of strings, an array of UIColours and array of UIFonts (they will need to match in length). The attributed string is then passed back.

see:

public static NSMutableAttributedString GetFormattedText(string[] texts, UIColor[] colors, UIFont[] fonts) {

  NSMutableAttributedString attrString = new NSMutableAttributedString(string.Join("", texts));
  int position = 0;

  for (int i = 0; i < texts.Length; i++) {
    attrString.AddAttribute(new NSString("NSForegroundColorAttributeName"), colors[i], new NSRange(position, texts[i].Length));

    var fontAttribute = new UIStringAttributes {
      Font = fonts[I]
    };

    attrString.AddAttributes(fontAttribute, new NSRange(position, texts[i].Length));

    position += texts[i].Length;
  }

  return attrString;

}

T-SQL: Opposite to string concatenation - how to split string into multiple records

For the particular case of splitting strings into words I've come across another solution for SQL Server 2008.

with testTable AS
(
SELECT 1 AS Id, N'how now brown cow' AS txt UNION ALL
SELECT 2, N'she sells sea shells upon the sea shore' UNION ALL
SELECT 3, N'red lorry yellow lorry' UNION ALL
SELECT 4, N'the quick brown fox jumped over the lazy dog'
)

SELECT display_term, COUNT(*) As Cnt
 FROM testTable
CROSS APPLY sys.dm_fts_parser('"' + txt + '"', 1033, 0,0)
GROUP BY display_term
HAVING COUNT(*) > 1
ORDER BY Cnt DESC

Returns

display_term                   Cnt
------------------------------ -----------
the                            3
brown                          2
lorry                          2
sea                            2

How do I use raw_input in Python 3

A reliable way to address this is

from six.moves import input

six is a module which patches over many of the 2/3 common code base pain points.

Best way to check if a Data Table has a null value in it

You can null/blank/space Etc value using LinQ Use Following Query

   var BlankValueRows = (from dr1 in Dt.AsEnumerable()
                                  where dr1["Columnname"].ToString() == ""
                                  || dr1["Columnname"].ToString() == ""
                                   || dr1["Columnname"].ToString() == ""
                                  select Columnname);

Here Replace Columnname with table column name and "" your search item in above code we looking null value.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

It's quite weird. Every time I face this issue, have different solution. This time all of the previous fixes failed then I changed project output path from Bin to ..\Build\Bin. It failed. Reverted output path to the previous value , i.e., Bin fixed the issue.

Perform debounce in React.js

Avoid using event.persist() - you want to let React recycle the synthetic event. I think the cleanest way whether you use classes or hooks is to split the callback into two pieces:

  1. The callback with no debouncing
  2. Calls a debounced function with only the pieces of the event you need (so the synthetic event can be recycled)

Classes

handleMouseOver = throttle(target => {
  console.log(target);
}, 1000);

onMouseOver = e => {
  this.handleMouseOver(e.target);
};

<div onMouseOver={this.onMouseOver} />

Functions

const handleMouseOver = useRef(throttle(target => {
  console.log(target);
}, 1000));

function onMouseOver(e) {
  handleMouseOver.current(e.target);
}

<div onMouseOver={this.onMouseOver} />

Note that if your handleMouseOver function uses state from within the component, you should use useMemo instead of useRef and pass those as dependencies otherwise you will be working with stale data (does not apply to classes of course).

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

For fixing such an issue I have used below code

a.divide(b, 2, RoundingMode.HALF_EVEN)

2 is precision. Now problem was resolved.

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:

1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok

I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use

Difference between @click and v-on:click Vuejs

v-bind and v-on are two frequently used directives in vuejs html template. So they provided a shorthand notation for the both of them as follows:

You can replace v-on: with @

v-on:click='someFunction'

as:

@click='someFunction'

Another example:

v-on:keyup='someKeyUpFunction'

as:

@keyup='someKeyUpFunction'

Similarly, v-bind with :

v-bind:href='var1'

Can be written as:

:href='var1'

Hope it helps!

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

How to get SLF4J "Hello World" working with log4j?

Here a working example to use slf4j as façade with log4j in the backend:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>xxx</groupId>
    <artifactId>xxx</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.30</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.13.3</version>
        </dependency>
    </dependencies>
</project>

src/main/resources/log4j.properties

# Root logger option
log4j.rootLogger=DEBUG, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

src/main/java/Main.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    /**
     * Default private constructor.
     */
    private Main() {
    }

    /**
     * Main method.
     *
     * @param args Arguments passed to the execution of the application
     */
    public static void main(final String[] args) {
        logger.info("Message to log");
    }
}

How to check if string contains Latin characters only?

There is no jquery needed:

var matchedPosition = str.search(/[a-z]/i);
if(matchedPosition != -1) {
    alert('found');
}

Maven Error: Could not find or load main class

For me the problem was nothing to do with Maven but to do with how I was running the .jar. I wrote some code and packaged it as a .jar with Maven. I ran it with

java target/gs-maven-0.1.0.jar

and got the error in the OP. Actually you need the -jar option:

java -jar target/gs-maven-0.1.0.jar

Purpose of Activator.CreateInstance with example?

Well i can give you an example why to use something like that. Think of a game where you want to store your level and enemies in an XML file. When you parse this file, you might have an element like this.

<Enemy X="10" Y="100" Type="MyGame.OrcGuard"/>

what you can do now is, create dynamically the objects found in your level file.

foreach(XmlNode node in doc)
   var enemy = Activator.CreateInstance(null, node.Attributes["Type"]);

This is very useful, for building dynamic enviroments. Of course its also possible to use this for Plugin or addin scenarios and alot more.

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Dynamic Height Issue for UITableView Cells (Swift)

Try This:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

EDIT

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Swift 4

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Swift 4.2

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

Define above Both Methods.
It solves the problem.

PS: Top and bottom constraints is required for this to work.

Here is example

Instagram API: How to get all user media?

Use the next_url object to get the next 20 images.

In the JSON response there is an pagination array:

 "pagination":{
      "next_max_tag_id":"1411892342253728",
      "deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
      "next_max_id":"1411892342253728",
      "next_min_id":"1414849145899763",
      "min_tag_id":"1414849145899763",
      "next_url":"https:\/\/api.instagram.com\/v1\/tags\/lemonbarclub\/media\/recent?client_id=xxxxxxxxxxxxxxxxxx\u0026max_tag_id=1411892342253728"
 }

This is the information on specific API call and the object next_url shows the URL to get the next 20 pictures so just take that URL and call it for the next 20 pictures.

For more information about the Instagram API check out this blogpost: Getting Friendly With Instagram’s API

Sort array of objects by object fields

Downside of all answers here is that they use static field names, so I wrote an adjusted version in OOP style. Assumed you are using getter methods you could directly use this Class and use the field name as parameter. Probably someone find it useful.

class CustomSort{

    public $field = '';

    public function cmp($a, $b)
    {
        /**
         * field for order is in a class variable $field
         * using getter function with naming convention getVariable() we set first letter to uppercase
         * we use variable variable names - $a->{'varName'} would directly access a field
         */
        return strcmp($a->{'get'.ucfirst($this->field)}(), $b->{'get'.ucfirst($this->field)}());
    }

    public function sortObjectArrayByField($array, $field)
    {
        $this->field = $field;
        usort($array, array("Your\Namespace\CustomSort", "cmp"));;
        return $array;
    }
} 

Does C have a "foreach" loop construct?

Here's a simple one, single for loop:

#define FOREACH(type, array, size) do { \
        type it = array[0]; \
        for(int i = 0; i < size; i++, it = array[i])
#define ENDFOR  } while(0);

int array[] = { 1, 2, 3, 4, 5 };

FOREACH(int, array, 5)
{
    printf("element: %d. index: %d\n", it, i);
}
ENDFOR

Gives you access to the index should you want it (i) and the current item we're iterating over (it). Note you might have naming issues when nesting loops, you can make the item and index names be parameters to the macro.

Edit: Here's a modified version of the accepted answer foreach. Lets you specify the start index, the size so that it works on decayed arrays (pointers), no need for int* and changed count != size to i < size just in case the user accidentally modifies 'i' to be bigger than size and get stuck in an infinite loop.

#define FOREACH(item, array, start, size)\
    for(int i = start, keep = 1;\
        keep && i < size;\
        keep = !keep, i++)\
    for (item = array[i]; keep; keep = !keep)

int array[] = { 1, 2, 3, 4, 5 };
FOREACH(int x, array, 2, 5)
    printf("index: %d. element: %d\n", i, x);

Output:

index: 2. element: 3
index: 3. element: 4
index: 4. element: 5

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

If the error happens with error column "File" as SGEN, then the fix needs to be in a file sgen.exe.config, next to sgen.exe. For example, for VS 2015, create C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sgen.exe.config. Minimum file contents: <configuration><startup useLegacyV2RuntimeActivationPolicy="true"/></configuration>

Source: SGEN Mixed mode assembly

ASP.NET 2.0 - How to use app_offline.htm

Make sure that app_offline.htm is in the root of the virtual directory or website in IIS.

How do I create a folder in a GitHub repository?

You just create the required folders in your local repository. For example, you created the app and config directories.

You may create new files under these folders.

For Git rules:

  1. First we need to add files to the directory.
  2. Then commit those added files.

Git command to do commit:

  1. git add app/ config/
  2. git commit

Then give the commit message and save the commit.

Then push to your remote repository,

git push origin remote

How do I get textual contents from BLOB in Oracle SQL

You can use below SQL to read the BLOB Fields from table.

SELECT DBMS_LOB.SUBSTR(BLOB_FIELD_NAME) FROM TABLE_NAME;

Creating and appending text to txt file in VB.NET

While I realize this is an older thread, I noticed the if block above is out of place with using:

Following is corrected:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim filePath As String =
      String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
    Using writer As New StreamWriter(filePath, True)
        If File.Exists(filePath) Then
            writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
        Else
            writer.WriteLine("Start Error Log for today")
        End If
    End Using
End Sub

Error 1046 No database Selected, how to resolve?

  • Edit your SQL file using Notepad or Notepad++
  • add the following 2 line:

CREATE DATABASE NAME; USE NAME;

Capturing count from an SQL query

Use SqlCommand.ExecuteScalar() and cast it to an int:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

How can I stop float left?

You could modify .adm and add

.adm{
 clear:both;
}

That should make it move to a new line

PHP Warning: Unknown: failed to open stream

This also happens (and is particularly confounding) if you forgot that you created a Windows symlink to a different directory, and that other directory doesn't have appropriate permissions.

Multithreading in Bash

You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:

    ls *.cfg | xargs -P 4 -n 1 read_cfg.sh

The read_cfg.sh script takes just one parameters (as enforced by -n)

Simple function to sort an array of objects

How about this?

var people = [
{
    name: 'a75',
    item1: false,
    item2: false
},
{
    name: 'z32',
    item1: true,
    item2: false
},
{
    name: 'e77',
    item1: false,
    item2: false
}];

function sort_by_key(array, key)
{
 return array.sort(function(a, b)
 {
  var x = a[key]; var y = b[key];
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

people = sort_by_key(people, 'name');

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

How do I include a newline character in a string in Delphi?

The plattform agnostic way would be 'sLineBreak': http://www.freepascal.org/docs-html/rtl/system/slinebreak.html

Write('Hello' + sLineBreak + 'World!');

Browser detection

For browser compatibility you can use this code. This method returns browser name and version :

private string GetBrowserNameWithVersion
{
    var userAgent = Request.UserAgent;
    var browserWithVersion = "";
    if (userAgent.IndexOf("Edge") > -1)
    {
        //Edge
        browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Chrome") > -1)
    {
        //Chrome
        browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Safari") > -1)
    {
        //Safari
        browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Firefox") > -1)
    {
        //Firefox
        browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("rv") > -1)
    {
            //IE11
        browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("MSIE") > -1)
    {
        //IE6-10
        browserWithVersion = "Internet Explorer Browser  Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
    }
    else if (userAgent.IndexOf("Other") > -1)
    {
        //Other
        browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
    }

    return browserWithVersion;
}

jquery get all form elements: input, textarea & select

This is my favorite function and it works like a charm for me!

It returns an object with all for input, select and textarea data.

And it's trying to getting objects name by look for elements name else Id else class.

var All_Data = Get_All_Forms_Data();
console.log(All_Data);

Function:

function Get_All_Forms_Data(Element)
{
    Element = Element || '';
    var All_Page_Data = {};
    var All_Forms_Data_Temp = {};
    if(!Element)
    {
        Element = 'body';
    }

    $(Element).find('input,select,textarea').each(function(i){
        All_Forms_Data_Temp[i] = $(this);
    });

    $.each(All_Forms_Data_Temp,function(){
        var input = $(this);
        var Element_Name;
        var Element_Value;

        if((input.attr('type') == 'submit') || (input.attr('type') == 'button'))
        {
            return true;
        }

        if((input.attr('name') !== undefined) && (input.attr('name') != ''))
        {
            Element_Name = input.attr('name').trim();
        }
        else if((input.attr('id') !== undefined) && (input.attr('id') != ''))
        {
            Element_Name = input.attr('id').trim();
        }
        else if((input.attr('class') !== undefined) && (input.attr('class') != ''))
        {
            Element_Name = input.attr('class').trim();
        }

        if(input.val() !== undefined)
        {
            if(input.attr('type') == 'checkbox')
            {
                Element_Value = input.parent().find('input[name="'+Element_Name+'"]:checked').val();
            }
            else if((input.attr('type') == 'radio'))
            {
                Element_Value = $('input[name="'+Element_Name+'"]:checked',Element).val();
            }
            else
            {
                Element_Value = input.val();
            }
        }
        else if(input.text() != undefined)
        {
            Element_Value = input.text();
        }

        if(Element_Value === undefined)
        {
            Element_Value = '';
        }

        if(Element_Name !== undefined)
        {
            var Element_Array = new Array();
            if(Element_Name.indexOf(' ') !== -1)
            {
                Element_Array = Element_Name.split(/(\s+)/);
            }
            else
            {
                Element_Array.push(Element_Name);
            }

            $.each(Element_Array,function(index, Name)
            {
                Name = Name.trim();
                if(Name != '')
                {
                    All_Page_Data[Name] = Element_Value;
                }
            });
        }
    });
    return All_Page_Data;
}

Is there a naming convention for git repositories?

I'd go for purchase-rest-service. Reasons:

  1. What is "pur chase rests ervice"? Long, concatenated words are hard to understand. I know, I'm German. "Donaudampfschifffahrtskapitänspatentausfüllungsassistentenausschreibungsstellenbewerbung."

  2. "_" is harder to type than "-"

Loop through an array in JavaScript

You can use map, which is a functional programming technique that's also available in other languages like Python and Haskell.

[1,2,3,4].map( function(item) {
     alert(item);
})

The general syntax is:

array.map(func)

In general func would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.

The return value of array.map is another array, so you can use it like this:

var x = [1,2,3,4].map( function(item) {return item * 10;});

And now x is [10,20,30,40].

You don't have to write the function inline. It could be a separate function.

var item_processor = function(item) {
      // Do something complicated to an item
}

new_list = my_list.map(item_processor);

which would be sort-of equivalent to:

 for (item in my_list) {item_processor(item);}

Except you don't get the new_list.

How to switch to the new browser window, which opens after click on the button?

 main you can do :

 String mainTab = page.goToNewTab ();
 //do what you want
 page.backToMainPage(mainTab);  

 What you need to have in order to use the main   

        private static Set<String> windows;

            //get all open windows 
            //return current window
            public String initWindows() {
                windows = new HashSet<String>();
                driver.getWindowHandles().stream().forEach(n ->   windows.add(n));
                return driver.getWindowHandle();
            }

            public String getNewWindow() {
                List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
                        .collect(Collectors.toList());
                logger.info(newWindow.get(0));
                return newWindow.get(0);
            }


            public String goToNewTab() {
                String startWindow = driver.initWindows();
                driver.findElement(By.cssSelector("XX")).click();
                String newWindow = driver.getNewWindow();
                driver.switchTo().window(newWindow);
                return startWindow;
            }

            public void backToMainPage(String startWindow) {
                driver.close();
                driver.switchTo().window(startWindow);
            }

Check if a value exists in ArrayList

When Array List contains object of Primitive DataType.

Use this function:
arrayList.contains(value);

if list contains that value then it will return true else false.

When Array List contains object of UserDefined DataType.

Follow this below Link 

How to compare Objects attributes in an ArrayList?

I hope this solution will help you. Thanks

UICollectionView - Horizontal scroll, horizontal layout?

If you need to set the UICollectionView scrolling Direction Horizental and you need to set cell width and height static. Please set the collectionview estimate size Automatic into None .

View The ScreenShot

What is the difference between hg forget and hg remove?

From the documentation, you can apparently use either command to keep the file in the project history. Looks like you want remove, since it also deletes the file from the working directory.

From the Mercurial book at http://hgbook.red-bean.com/read/:

Removing a file does not affect its history. It is important to understand that removing a file has only two effects. It removes the current version of the file from the working directory. It stops Mercurial from tracking changes to the file, from the time of the next commit. Removing a file does not in any way alter the history of the file.

The man page hg(1) says this about forget:

Mark the specified files so they will no longer be tracked after the next commit. This only removes files from the current branch, not from the entire project history, and it does not delete them from the working directory.

And this about remove:

Schedule the indicated files for removal from the repository. This only removes files from the current branch, not from the entire project history.

How do I retrieve the number of columns in a Pandas data frame?

There are multiple option to get column number and column information such as:
let's check them.

local_df = pd.DataFrame(np.random.randint(1,12,size=(2,6)),columns =['a','b','c','d','e','f']) 1. local_df.shape[1] --> Shape attribute return tuple as (row & columns) (0,1).

  1. local_df.info() --> info Method will return detailed information about data frame and it's columns such column count, data type of columns, Not null value count, memory usage by Data Frame

  2. len(local_df.columns) --> columns attribute will return index object of data frame columns & len function will return total available columns.

  3. local_df.head(0) --> head method with parameter 0 will return 1st row of df which actually nothing but header.

Assuming number of columns are not more than 10. For loop fun: li_count =0 for x in local_df: li_count =li_count + 1 print(li_count)

How can I scroll to a specific location on the page using jquery?

Here is variant of @juraj-blahunka's lightweight approach. This function does not assume the container is the document and only scrolls if the item is out of view. Animation queuing is also disabled to avoid unnecessary bouncing.

$.fn.scrollToView = function () {
    return $.each(this, function () {
        if ($(this).position().top < 0 ||
            $(this).position().top + $(this).height() > $(this).parent().height()) {
            $(this).parent().animate({
                scrollTop: $(this).parent().scrollTop() + $(this).position().top
            }, {
                duration: 300,
                queue: false
            });
        }
    });
};

What is the use of a cursor in SQL Server?

Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.

However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ..., they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.

In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.

Stock ticker symbol lookup API

You can send an HTTP request to http://finance.yahoo.com requesting symbols, names, quotes, and all sorts of other data. Data is returned as a .CSV so you can request multiple symbols in one query.

So if you send:

http://finance.yahoo.com/d/quotes.csv?s=MSFT+F+ATT&f=sn

You'll get back something like:

"MSFT","Microsoft Corp"
"F","FORD MOTOR CO"
"ATT","AT&T"

Here is an article called Downloading Yahoo Data which includes the various tags used to request the data.

How do I restart a service on a remote machine in Windows?

You can use mmc:

  1. Start / Run. Type "mmc".
  2. File / Add/Remove Snap-in... Click "Add..."
  3. Find "Services" and click "Add"
  4. Select "Another computer:" and type the host name / IP address of the remote machine. Click Finish, Close, etc.

At that point you will be able to manage services as if they were on your local machine.

Disable a Button

The boolean value for NO in Swift is false.

button.isEnabled = false

should do it.

Here is the Swift documentation for UIControl's isEnabled property.

What is the purpose of the "role" attribute in HTML?

Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML via supporting specs like HTML-AAM. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.

http://www.w3.org/TR/wai-aria/

There are a few primary reasons to use roles in addition to your native semantic element.

Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.

In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.

<a href="#" role="button" aria-label="Delete item 1">Delete</a>
<!-- Note: href="#" is just a shorthand here, not a recommended technique. Use progressive enhancement when possible. -->

Screen readers users will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.

[role="button"] {
  /* style these as buttons w/o relying on a .button class */
}

[Update 7 years later: removed the * selector to make some commenters happy, since the old browser quirk that required universal selector on attribute selectors is unnecessary in 2020.]

Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.

For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <main>.

<main role="main">…</main>

This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary for main.

Reason #3. Update 7 years later (2020): As at least one commenter pointed out, this is now very useful for custom elements, and some spec work is underway to define the default accessibility role of a web component. Even if/once that API is standardized, there may be need to override the default role of a component.

Note/Reply

You also wrote:

I see some people make up their own. Is that allowed or a correct use of the role attribute?

That's an allowed use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.

<span role="foo link note bar">...</a>

Out of the list, only link and note are valid roles, and so the link role will be applied in the platform accessibility API because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)

Amazon Interview Question: Design an OO parking lot

public class ParkingLot 
{
    Vector<ParkingSpace> vacantParkingSpaces = null;
    Vector<ParkingSpace> fullParkingSpaces = null;

    int parkingSpaceCount = 0;

    boolean isFull;
    boolean isEmpty;

    ParkingSpace findNearestVacant(ParkingType type)
    {
        Iterator<ParkingSpace> itr = vacantParkingSpaces.iterator();

        while(itr.hasNext())
        {
            ParkingSpace parkingSpace = itr.next();

            if(parkingSpace.parkingType == type)
            {
                return parkingSpace;
            }
        }
        return null;
    }

    void parkVehicle(ParkingType type, Vehicle vehicle)
    {
        if(!isFull())
        {
            ParkingSpace parkingSpace = findNearestVacant(type);

            if(parkingSpace != null)
            {
                parkingSpace.vehicle = vehicle;
                parkingSpace.isVacant = false;

                vacantParkingSpaces.remove(parkingSpace);
                fullParkingSpaces.add(parkingSpace);

                if(fullParkingSpaces.size() == parkingSpaceCount)
                    isFull = true;

                isEmpty = false;
            }
        }
    }

    void releaseVehicle(Vehicle vehicle)
    {
        if(!isEmpty())
        {
            Iterator<ParkingSpace> itr = fullParkingSpaces.iterator();

            while(itr.hasNext())
            {
                ParkingSpace parkingSpace = itr.next();

                if(parkingSpace.vehicle.equals(vehicle))
                {
                    fullParkingSpaces.remove(parkingSpace);
                    vacantParkingSpaces.add(parkingSpace);

                    parkingSpace.isVacant = true;
                    parkingSpace.vehicle = null;

                    if(vacantParkingSpaces.size() == parkingSpaceCount)
                        isEmpty = true;

                    isFull = false;
                }
            }
        }
    }

    boolean isFull()
    {
        return isFull;
    }

    boolean isEmpty()
    {
        return isEmpty;
    }
}

public class ParkingSpace 
{
    boolean isVacant;
    Vehicle vehicle;
    ParkingType parkingType;
    int distance;
}

public class Vehicle 
{
    int num;
}

public enum ParkingType
{
    REGULAR,
    HANDICAPPED,
    COMPACT,
    MAX_PARKING_TYPE,
}

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Simple rules of bidirectional relationships:

1.For many-to-one bidirectional relationships, the many side is always the owning side of the relationship. Example: 1 Room has many Person (a Person belongs one Room only) -> owning side is Person

2.For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

3.For many-to-many bidirectional relationships, either side may be the owning side.

Hope can help you.

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

How to build query string with Javascript

This doesn't directly answer your question, but here's a generic function which will create a URL that contains query string parameters. The parameters (names and values) are safely escaped for inclusion in a URL.

function buildUrl(url, parameters){
  var qs = "";
  for(var key in parameters) {
    var value = parameters[key];
    qs += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&";
  }
  if (qs.length > 0){
    qs = qs.substring(0, qs.length-1); //chop off last "&"
    url = url + "?" + qs;
  }
  return url;
}

// example:
var url = "http://example.com/";

var parameters = {
  name: "George Washington",
  dob: "17320222"
};

console.log(buildUrl(url, parameters));
// => http://www.example.com/?name=George%20Washington&dob=17320222

How to set the action for a UIBarButtonItem in Swift

As of Swift 2.2, there is a special syntax for compiler-time checked selectors. It uses the syntax: #selector(methodName).

Swift 3 and later:

var b = UIBarButtonItem(
    title: "Continue",
    style: .plain,
    target: self,
    action: #selector(sayHello(sender:))
)

func sayHello(sender: UIBarButtonItem) {
}

If you are unsure what the method name should look like, there is a special version of the copy command that is very helpful. Put your cursor somewhere in the base method name (e.g. sayHello) and press Shift+Control+Option+C. That puts the ‘Symbol Name’ on your keyboard to be pasted. If you also hold Command it will copy the ‘Qualified Symbol Name’ which will include the type as well.

Swift 2.3:

var b = UIBarButtonItem(
    title: "Continue",
    style: .Plain,
    target: self,
    action: #selector(sayHello(_:))
)

func sayHello(sender: UIBarButtonItem) {
}

This is because the first parameter name is not required in Swift 2.3 when making a method call.

You can learn more about the syntax on swift.org here: https://swift.org/blog/swift-2-2-new-features/#compile-time-checked-selectors

ReactJS map through Object

Use Object.entries() function.

Object.entries(object) return:

[
    [key, value],
    [key, value],
    ...
]

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

{Object.entries(subjects).map(([key, subject], i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subject.name}</span>
    </li>
))}

Any good boolean expression simplifiers out there?

I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).

Also in Logic Friday the expression A | B just returns 3 entries in truth table; I expected 4.

Python Script Uploading files via FTP

Use ftplib, you can write it like this:

import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb')                  # file to send
session.storbinary('STOR kitten.jpg', file)     # send the file
file.close()                                    # close file and FTP
session.quit()

Use ftplib.FTP_TLS instead if you FTP host requires TLS.


To retrieve it, you can use urllib.retrieve:

import urllib 

urllib.urlretrieve('ftp://server/path/to/file', 'file')

EDIT:

To find out the current directory, use FTP.pwd():

FTP.pwd(): Return the pathname of the current directory on the server.

To change the directory, use FTP.cwd(pathname):

FTP.cwd(pathname): Set the current directory on the server.

count number of lines in terminal output

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

Converting unix time into date-time via excel

TLDR

=(A1/86400)+25569

...and the format of the cell should be date.

If it doesn't work for you

  • If you get a number you forgot to format the output cell as a date.
  • If you get ##### you probably don't have a real Unix time. Check your timestamps in https://www.epochconverter.com/. Try to divide your input by 10, 100, 1000 or 10000**
  • You work with timestamps outside Excel's (very extended) limits.
  • You didn't replace A1 with the cell containing the timestamp ;-p

Explanation

Unix system represent a point in time as a number. Specifically the number of seconds* since a zero-time called the Unix epoch which is 1/1/1970 00:00 UTC/GMT. This number of seconds is called "Unix timestamp" or "Unix time" or "POSIX time" or just "timestamp" and sometimes (confusingly) "Unix epoch".

In the case of Excel they chose a different zero-time and step (because who wouldn't like variety in technical details?). So Excel counts days since 24 hours before 1/1/0000 UTC/GMT. So 25569 corresponds to 1/1/1970 00:00 UTC/GMT and 25570 to 2/1/1970 00:00.

Now please note that we have 86400 seconds per day (24 hours x60 minutes each x60 seconds) and you can understand what this formula does: A1/86400 converts seconds to days and +25569 adjusts for the offset between what is time-zero for Unix and what is time-zero for Excel.

By the way DATE(1970,1,1) will helpfully return 25569 for you in case you forget all this so a more "self-documenting" way to write our formula is:

=A1/(24*60*60) + DATE(1970,1,1)

P.S.: All these were already present in other answers and comments just not laid out as I like them and I don't feel it's OK to edit the hell out of another answer.


*: that's almost correct because you should not count leap seconds

**: E.g. in the case of this question the number was number of milliseconds since the the Unix epoch.

Oracle 12c Installation failed to access the temporary location

Looking at Oracle's support site, it could be one of two things (may be #2 in your case, but including both).

Problem 1:

  1. Enable administrative share for C$ (Please check with your System Admin to do this or See Microsoft document http://support.microsoft.com/kb/314984)

  2. Check that it is ok:

    • net use \\c$ should work
    • the current user (i.e. user in administrator group) should have all privileges on the default share
  3. Retry the installation

  4. Remove the administrative share again

Problem 2: Remove the OracleRemExecService before doing the Oracle Client 12c Release 1 32-bit or 64-bit installation on the same Microsoft Windows x64 (64-bit) after installing the Oracle 64-bit or 32-bit software .

  • Go to the Windows 'Services'
  • Stop OracleRemExecServiceV2

( This service is having a intelligence .Once someone tries to stop it this service gets deleted. This is due to the fact ,that this service is not running from the Oracle Home like other oracle services ,but from temp . For example : C:\Users\AppData\Local\Temp\oraremservi... )

  • Then try to install the Oracle 12c 32-bit or 64-bit on the same Microsoft Windows x64 (64-bit)

How to deploy a React App on Apache web server

Ultimately was able to figure it out , i just hope it will help someone like me.
Following is how the web pack config file should look like check the dist dir and output file specified. I was missing the way to specify the path of dist directory

const webpack = require('webpack');
const path = require('path');
var config = {
    entry: './main.js',

    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'index.js',
    },

    devServer: {
        inline: true,
        port: 8080
    },
    resolveLoader: {
        modules: [path.join(__dirname, 'node_modules')]
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
}

module.exports = config;

Then the package json file

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack --progress",
    "production": "webpack -p --progress"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "webpack": "^2.2.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.20",
    "babel-loader": "^6.0.1",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-react": "^6.0.15",
    "babel-preset-stage-0": "^6.0.15",
    "express": "^4.13.3",
    "webpack": "^1.9.6",
    "webpack-devserver": "0.0.6"
  }
}

Notice the script section and production section, production section is what gives you the final deployable index.js file ( name can be anything )

Rest fot the things will depend upon your code and components

Execute following sequence of commands

npm install

this should get you all the dependency (node modules)

then

npm run production

this should get you the final index.js file which will contain all the code bundled

Once done place index.html and index.js files under www/html or the web app root directory and that's all.

Django error - matching query does not exist

your line raising the error is here:

comment = Comment.objects.get(pk=comment_id)

you try to access a non-existing comment.

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.

Ok up to here I suppose you are aware of this.

Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.

Other users go to addresses from their history, (same if data have been deleted since it may happens).

DataTable: How to get item value with row name and column name? (VB)

Try:

DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()

(This is C# code. Change this to VB equivalent)

How to display pandas DataFrame of floats using a format string for columns?

You can also set locale to your region and set float_format to use a currency format. This will automatically set $ sign for currency in USA.

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

pd.set_option("float_format", locale.currency)

df = pd.DataFrame(
    [123.4567, 234.5678, 345.6789, 456.7890],
    index=["foo", "bar", "baz", "quux"],
    columns=["cost"],
)
print(df)

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

Change New Google Recaptcha (v2) Width

.g-recaptcha{
    -moz-transform:scale(1.1);
    -ms-transform:scale(1.1); 
    -o-transform:scale(1.1); 
    -moz-transform-origin:0; 
    -ms-transform-origin:0;
    -o-transform-origin:0;
    -webkit-transform:scale(1.1);
    transform:scale(1.1);
    -webkit-transform-origin:0 0;
    transform-origin:0;
    filter: progid:DXImageTransform.Microsoft.Matrix(M11=1.1,M12=0,M21=0,M22=1.1,SizingMethod='auto expand');
}

How can I get the current page's full URL on a Windows/IIS server?

Use this class to get the URL works.

class VirtualDirectory
{
    var $protocol;
    var $site;
    var $thisfile;
    var $real_directories;
    var $num_of_real_directories;
    var $virtual_directories = array();
    var $num_of_virtual_directories = array();
    var $baseURL;
    var $thisURL;

    function VirtualDirectory()
    {
        $this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
        $this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];
        $this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);
        $this->real_directories = $this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['PHP_SELF'])));
        $this->num_of_real_directories = count($this->real_directories);
        $this->virtual_directories = array_diff($this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['REQUEST_URI']))),$this->real_directories);
        $this->num_of_virtual_directories = count($this->virtual_directories);
        $this->baseURL = $this->site . "/" . implode("/", $this->real_directories) . "/";
        $this->thisURL = $this->baseURL . implode("/", $this->virtual_directories) . "/";
    }

    function cleanUp($array)
    {
        $cleaned_array = array();
        foreach($array as $key => $value)
        {
            $qpos = strpos($value, "?");
            if($qpos !== false)
            {
                break;
            }
            if($key != "" && $value != "")
            {
                $cleaned_array[] = $value;
            }
        }
        return $cleaned_array;
    }
}

$virdir = new VirtualDirectory();
echo $virdir->thisURL;