Programs & Examples On #Vacuum

In SQLite and PosgreSQL, the VACUUM command rebuilds the entire database.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket"/var/pgsql_socket/.s.PGSQL.5432"?

I kept on getting the above error and none of the above solutions worked for me. Finally the following solution solved my problem on Mac OS X

Install postgres using brew

brew install postgres

Install brew services

brew tap homebrew/services

To start postgres as a background service

brew services start postgresql

To stop postgres manually

brew services stop postgresql

We can also use brew services to restart Postgres

brew services restart postgresql

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I sovled this errors by modifying the Database charset.Old Database charset is cp1252 and i conver to utf-8

Can not connect to local PostgreSQL

I tried most of the solutions to this problem but couldn't get any to work.

I ran lsof -P | grep ':5432' | awk '{print $2}' which showed the PID of the process running. However I couldn't kill it with kill -9 <pid>.

When I ran pkill postgresql the process finally stopped. Hope this helps.

Clearing content of text file using C#

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

Using an if statement to check if a div is empty

Try this:

$(document).ready(function() {
    if ($('#leftmenu').html() === "") {
        $('#menuTitleWrapper').remove();
        $('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
        $('#PageContent').css({'top' : '30px', 'position' : 'relative'});
    }
});

It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application because .js-Files aren't something a user wants to read but something that should get executed.

How to disable Django's CSRF validation?

If you want disable it in Global, you can write a custom middleware, like this

from django.utils.deprecation import MiddlewareMixin

class DisableCsrfCheck(MiddlewareMixin):

    def process_request(self, req):
        attr = '_dont_enforce_csrf_checks'
        if not getattr(req, attr, False):
            setattr(req, attr, True)

then add this class youappname.middlewarefilename.DisableCsrfCheck to MIDDLEWARE_CLASSES lists, before django.middleware.csrf.CsrfViewMiddleware

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

Making TextView scrollable on Android

I struggled with this for over a week and finally figured out how to make this work!

My issue was that everything would scroll as a 'block'. The text itself was scrolling, but as a chunk rather than line by line. This obviously didn't work for me, because it would cut off lines at the bottom. All of the previous solutions did not work for me, so I crafted my own.

Here is the easiest solution by far:

Make a class file called: 'PerfectScrollableTextView' inside a package, then copy and paste this code in:

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

public class PerfectScrollableTextView extends TextView {

    public PerfectScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context) {
        super(context);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

Finally change your 'TextView' in XML:

From: <TextView

To: <com.your_app_goes_here.PerfectScrollableTextView

printf formatting (%d versus %u)

%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

Check if a file exists or not in Windows PowerShell?

cls

$exactadminfile = "C:\temp\files\admin" #First folder to check the file

$userfile = "C:\temp\files\user" #Second folder to check the file

$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations

foreach ($filename in $filenames) {
  if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
    Write-Warning "$filename absent from both locations"
  } else {
    Write-Host " $filename  File is there in one or both Locations" #if file exists there at both locations or at least in one location
  }
}

"Initializing" variables in python?

Python treats comma on the left hand side of equal sign ( = ) as an input splitter, Very useful for functions that return a tuple.

e.g,

x,y = (5,2)

What you want to do is:

grade_1 = grade_2 = grade_3 = average = 0.0

though that might not be the most clear way to write it.

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

How to connect to SQL Server database from JavaScript in the browser?

This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.

Split Java String by New Line

String lines[] =String.split( System.lineSeparator())

Windows batch script to move files

Create a file called MoveFiles.bat with the syntax

move c:\Sourcefoldernam\*.* e:\destinationFolder

then schedule a task to run that MoveFiles.bat every 10 hours.

Can I use DIV class and ID together in CSS?

Yes, why not? Then CSS that applies to class "x" AND CSS that applies to ID "y" applies to the div.

Can Python test the membership of multiple values in a list?

Here's how I did it:

A = ['a','b','c']
B = ['c']
logic = [(x in B) for x in A]
if True in logic:
    do something

What are the differences among grep, awk & sed?

Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.

Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.

Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.

Make XAMPP / Apache serve file outside of htdocs folder

Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:


Virtual Hosts

  1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf.
  2. Un-comment ~line 19 (NameVirtualHost *:80).
  3. Add your virtual host (~line 36):

    <VirtualHost *:80>
        DocumentRoot C:\Projects\transitCalculator\trunk
        ServerName transitcalculator.localhost
        <Directory C:\Projects\transitCalculator\trunk>
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>
    
  4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts).

  5. Add

    127.0.0.1 transitcalculator.localhost #transitCalculator
    

    to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).

  6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).
  7. Restart Apache.

Now you can access that directory by browsing to http://transitcalculator.localhost/.


Make an Alias

  1. Starting ~line 200 of your http.conf file, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.

  2. Find the <IfModule alias_module></IfModule> section (~line 300) and add

    Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
    

    (or whatever is relevant to your desires) below the Alias comment block, inside the module tags.


Change your document root

  1. Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).

  2. Edit ~line 203 to match your new location (in this case C:/Projects).


Notes:

  • You have to use forward slashes "/" instead of back slashes "\".
  • Don't include the trailing "/" at the end.
  • restart your server.

Structs in Javascript

Following Markus's answer, in newer versions of JS (ES6 I think) you can create a 'struct' factory more simply using Arrow Functions and Rest Parameter like so:

const Struct = (...keys) => ((...v) => keys.reduce((o, k, i) => {o[k] = v[i]; return o} , {}))
const Item = Struct('id', 'speaker', 'country')
var myItems = [
    Item(1, 'john', 'au'),
    Item(2, 'mary', 'us')
];

console.log(myItems);
console.log(myItems[0].id);
console.log(myItems[0].speaker);
console.log(myItems[0].country);

The result of running this is:

[ { id: 1, speaker: 'john', country: 'au' },
  { id: 2, speaker: 'mary', country: 'us' } ]
1
john
au

You can make it look similar to Python's namedtuple:

const NamedStruct = (name, ...keys) => ((...v) => keys.reduce((o, k, i) => {o[k] = v[i]; return o} , {_name: name}))
const Item = NamedStruct('Item', 'id', 'speaker', 'country')
var myItems = [
    Item(1, 'john', 'au'),
    Item(2, 'mary', 'us')
];

console.log(myItems);
console.log(myItems[0].id);
console.log(myItems[0].speaker);
console.log(myItems[0].country);

And the results:

[ { _name: 'Item', id: 1, speaker: 'john', country: 'au' },
  { _name: 'Item', id: 2, speaker: 'mary', country: 'us' } ]
1
john
au

How to get HttpContext.Current in ASP.NET Core?

As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.

HttpContext.Current was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.

HttpContext property

You can access the current HTTP context via the HttpContext property on any controller. The closest thing to your original code sample would be to pass HttpContext into the method you are calling:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        MyMethod(HttpContext);

        // Other code
    }
}

public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
    var host = $"{context.Request.Scheme}://{context.Request.Host}";

    // Other code
}

HttpContext parameter in middleware

If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext is passed into your Invoke method automatically:

public Task Invoke(HttpContext context)
{
    // Do something with the current HTTP context...
}

HTTP context accessor

Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

Request this interface in your constructor:

public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

You can then access the current HTTP context in a safe way:

var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...

IHttpContextAccessor isn't always added to the service container by default, so register it in ConfigureServices just to be safe:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    // if < .NET Core 2.2 use this
    //services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Other code...
}

FileProvider - IllegalArgumentException: Failed to find configured root

I was getting this error Failed to find configured root that contains...

The following work around resolves my issue

res/xml/file_paths.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
        <external-path name="media" path="." />
</paths>

AndroidManifest.xml

<provider
      android:name="android.support.v4.content.FileProvider"
      android:authorities="[PACKAGE_NAME]"
      android:exported="false"
      android:grantUriPermissions="true">
         <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths">
         </meta-data>
</provider>

ActivityClass.java

void shareImage() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,"com.slappstudio.pencilsketchphotomaker", selectedFilePath));
        startActivity(Intent.createChooser(intent,getString(R.string.string_share_with)));
    }

IF formula to compare a date with current date and return result

I think this will cover any possible scenario for what is in O10:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),IF(TODAY()-O10<>1,CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," days"),CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," day")),IF(O10=TODAY(),"Due Today","Overdue")))

For Dates that are before Today, it will tell you how many days the item is due in. If O10 = Today then it will say "Due Today". Anything past Today and it will read overdue. Lastly, if it is blank, the cell will also appear blank. Let me know what you think!

Kotlin - Property initialization using "by lazy" vs. "lateinit"

lateinit vs lazy

  1. lateinit

    i) Use it with mutable variable[var]

     lateinit var name: String       //Allowed
     lateinit val name: String       //Not Allowed
    

ii) Allowed with only non-nullable data types

    lateinit var name: String       //Allowed
    lateinit var name: String?      //Not Allowed

iii) It is a promise to compiler that the value will be initialized in future.

NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.

  1. lazy

    i) Lazy initialization was designed to prevent unnecessary initialization of objects.

ii) Your variable will not be initialized unless you use it.

iii) It is initialized only once. Next time when you use it, you get the value from cache memory.

iv) It is thread safe(It is initialized in the thread where it is used for the first time. Other threads use the same value stored in the cache).

v) The variable can only be val.

vi) The variable can only be non-nullable.

Progress Bar with HTML and CSS

Using setInterval.

_x000D_
_x000D_
var totalelem = document.getElementById("total");_x000D_
var progresselem = document.getElementById("progress");_x000D_
var interval = setInterval(function(){_x000D_
    if(progresselem.clientWidth>=totalelem.clientWidth)_x000D_
    {_x000D_
        clearInterval(interval);_x000D_
        return;_x000D_
    }_x000D_
    progresselem.style.width = progresselem.offsetWidth+1+"px";_x000D_
},10)
_x000D_
.outer_x000D_
{_x000D_
    width: 200px;_x000D_
    height: 15px;_x000D_
    background: red;_x000D_
}_x000D_
.inner_x000D_
{_x000D_
    width: 0px;_x000D_
    height: 15px;_x000D_
    background: green;_x000D_
}
_x000D_
<div id="total" class="outer">_x000D_
    <div id="progress" class="inner"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using CSS Transtitions.

_x000D_
_x000D_
function loading()_x000D_
{_x000D_
    document.getElementById("progress").style.width="200px";_x000D_
}
_x000D_
.outer_x000D_
{_x000D_
    width: 200px;_x000D_
    height: 15px;_x000D_
    background: red;_x000D_
}_x000D_
.inner_x000D_
{_x000D_
    width: 0px;_x000D_
    height: 15px;_x000D_
    background: green;_x000D_
    -webkit-transition:width 3s linear;_x000D_
    transition: width 3s linear;_x000D_
}
_x000D_
<div id="total" class="outer">_x000D_
    <div id="progress" class="inner"></div>_x000D_
</div>_x000D_
<button id="load" onclick="loading()">Load</button>
_x000D_
_x000D_
_x000D_

How to change date format using jQuery?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

curr_year = curr_year.toString().substr(2,2);

document.write(curr_date+"-"+curr_month+"-"+curr_year);

You can change this as your need..

How can I use external JARs in an Android project?

Goto Current Project

RightClick->Properties->Java Build Path->Add Jar Files into Libraries -> Click OK

Then it is added into the Referenced Libraries File in your Current Project .

Pipe output and capture exit status in Bash

Dumb solution: Connecting them through a named pipe (mkfifo). Then the command can be run second.

 mkfifo pipe
 tee out.txt < pipe &
 command > pipe
 echo $?

Use different Python version with virtualenv

End of 2020:

The most seamless experience for using virtualenv (added benefit: with any possible python version) would be to use pyenv and its (bundled) pyenv-virtualenv plugin (cf https://realpython.com/intro-to-pyenv/#virtual-environments-and-pyenv)

Usage: pyenv virtualenv <python_version> <environment_name>

Installation:

cf https://github.com/pyenv/pyenv-installer

That being said, nowadays the best possible alternative instead of using virtualenv (and pip) would be Poetry (along with pyenv indicated above, to handle different python versions).

Another option, because it's supported directly by the PyPA (the org behind pip and the PyPI) and has restarted releasing since the end of May (didn't release since late 2018 prior to that...) would be Pipenv

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

Rails and PostgreSQL: Role postgres does not exist

I ended up here after attempting to follow Ryan Bate's tutorial on deploying to AWS EC2 with rubber. Here is what happened for me: We created a new app using "

rails new blog -d postgresql

Obviosuly this creates a new app with pg as the database, but the database was not made yet. With sqlite, you just run rake db:migrate, however with pg you need to create the pg database first. Ryan did not do this step. The command is rake db:create:all, then we can run rake db:migrate

The second part is changing the database.yml file. The default for the username when the file is generated is 'appname'. However, chances are your role for postgresql admin is something different (at least it was for me). I changed it to my name (see above advice about creating a role name) and I was good to go.

Hope this helps.

How to sum up elements of a C++ vector?

The easiest way is to use std:accumulate of a vector<int> A:

#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);

Javascript string/integer comparisons

The alert() wants to display a string, so it will interpret "2">"10" as a string.

Use the following:

var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);

var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

How to recognize vehicle license / number plate (ANPR) from an image?

EDIT: I wrote a Python script for this.

As your objective is blurring (for privacy protection), you basically need a high recall detector as a first step. Here's how to go about doing this. The included code hints use OpenCV with Python.

  1. Convert to Grayscale.
  2. Apply Gaussian Blur.

    img = cv2.imread('input.jpg',1)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_gray = cv2.GaussianBlur(img_gray, (5,5), 0)  
    

Let the input image be the following.

enter image description here

  1. Apply Sobel Filter to detect vertical edges.
  2. Threshold the resultant image using strict threshold or OTSU's binarization.

    cv2.Sobel(image, -1, 1, 0)
    cv2.threshold() 
    
  3. Apply a Morphological Closing operation using suitable structuring element. (I used 16x4 as structuring element)

    se = cv2.getStructuringElement(cv2.MORPH_RECT,(16,4))
    cv2.morphologyEx(image, cv2.MORPH_CLOSE, se)  
    

Resultant Image after Step 5.

enter image description here

  1. Find external contours of this image.

    cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
    
  2. For each contour, find the minAreaRect() bounding it.

  3. Select rectangles based on aspect ratio, minimum and maximum area, and angle with the horizontal. (I used 2.2 <= Aspect Ratio <= 8, 500 <= Area <=15000, and angle <= 45 degrees)

All minAreaRect()s are shown in orange and the one which satisfies our criteria is in green.

enter image description here

  1. There may be false positives after this step, to filter it, use edge density. Edge Density is defined as the number of white pixels/total number of pixels in a rectangle. Set a threshold for edge density. (I used 0.5)

enter image description here

  1. Blur the detected regions.

enter image description here

You can apply other filters you deem suitable to increase recall and precision. The detection can also be trained using HOG+SVM to increase precision.

Moving from position A to position B slowly with animation

Use jquery animate and give it a long duration say 2000

$("#Friends").animate({ 
        top: "-=30px",
      }, duration );

The -= means that the animation will be relative to the current top position.

Note that the Friends element must have position set to relative in the css:

#Friends{position:relative;}

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

Sleep function in ORACLE

You can use DBMS_PIPE.SEND_MESSAGE with a message that is too large for the pipe, for example for a 5 second delay write XXX to a pipe that can only accept one byte using a 5 second timeout as below

dbms_pipe.pack_message('XXX');<br>
dummy:=dbms_pipe.send_message('TEST_PIPE', 5, 1);

But then that requires a grant for DBMS_PIPE so perhaps no better.

Wrapping a react-router Link in an html button

Update for React Router version 6:

The various answers here are like a timeline of react-router's evolution

Using the latest hooks from react-router v6, this can now be done easily with the useNavigate hook.

import { useNavigate } from 'react-router-dom'      

function MyLinkButton() {
  const navigate = useNavigate()
  return (
      <button onClick={() => navigate("/home")}>
        Go Home
      </button>
  );
}

Splitting a string into chunks of a certain size

Using regular expressions and Linq:

List<string> groups = (from Match m in Regex.Matches(str, @"\d{4}")
                       select m.Value).ToList();

I find this to be more readable, but it's just a personal opinion. It can also be a one-liner : ).

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

Unrecognized escape sequence for path string containing backslashes

var foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

Delete a row in Excel VBA

Chris Nielsen's solution is simple and will work well. A slightly shorter option would be...

ws.Rows(Rand).Delete

...note there is no need to specify a Shift when deleting a row as, by definition, it's not possible to shift left

Incidentally, my preferred method for deleting rows is to use...

ws.Rows(Rand) = ""

...in the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink's comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range("A1:Z10").Sort Key1:=Range("A1"), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel...but you can always reduce the 2007/2010 equivalent code

Couple more points...if your list is not already sorted by a column and you wish to retain the order, you can stick the row number 'Rand' in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That's to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code's performance in the same way that deleting single rows does

How to remove decimal values from a value of type 'double' in Java

    public class RemoveDecimalPoint{

         public static void main(String []args){
            System.out.println(""+ removePoint(250022005.60));
         }
 
       public static String  removePoint(double number) {        
            long x = (long) number;
            return x+"";
        }

    }

How to execute my SQL query in CodeIgniter

If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:

$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");

Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

Remember that with the binding redirection

oldVersion="0.0.0.0-6.0.0.0"

You are saying that the old versions of the dll are between version 0.0.0.0 and version 6.0.0.0.

Change background position with jQuery

You guys are complicating things. You can simple do this from CSS.

#carousel li { background-position:0px 0px; }
#carousel li:hover { background-position:100px 0px; }

How can I remove duplicate rows?

I would mention this approach as well as it can be helpful, and works in all SQL servers: Pretty often there is only one - two duplicates, and Ids and count of duplicates are known. In this case:

SET ROWCOUNT 1 -- or set to number of rows to be deleted
delete from myTable where RowId = DuplicatedID
SET ROWCOUNT 0

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="check1" type="checkbox" checked="" name="copyNewAddrToBilling">
    </body>
    <script language="javascript">
        document.getElementById("check1").checked = true;
        document.getElementById("check1").checked = false;
    </script>
</html>

I have added the language attribute to the script element, but it is unnecessary because all browsers use this as a default, but it leaves no doubt what this example is showing.

If you want to use javascript to access elements, it has a very limited set of GetElement* functions. So you are going to need to get into the habit of giving every element a UNIQUE id attribute.

How to add a filter class in Spring Boot?

You need 2 main things : - Add @ServletComponentScan to your Main Class - you may add a package named filter inside it you create a Filter Class that has the following :

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {

 // whatever field you have

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;

 // whatever implementation you want

        try {
            chain.doFilter(req, res);
        } catch(Exception e) {
            e.printStackTrace();
        }

}

public void init(FilterConfig filterConfig) {}

public void destroy() {}
}

Android Design Support Library expandable Floating Action Button(FAB) menu

  • First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.

  • Create the menu layouts as per your need and number.

  • Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.

Please check the below code for the reference and for more info checkout my project from github

Checkout project from Github

<android.support.constraint.ConstraintLayout
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.app.fabmenu.MainActivity">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/baseFloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:clickable="true"
                android:onClick="@{FabHandler::onBaseFabClick}"
                android:tint="@android:color/white"
                app:fabSize="normal"
                app:layout_constraintBottom_toBottomOf="@+id/activity_main"
                app:layout_constraintRight_toRightOf="@+id/activity_main"
                app:srcCompat="@drawable/ic_add_black_24dp" />

            <LinearLayout
                android:id="@+id/shareLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="12dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/createLayout"
                app:layout_constraintLeft_toLeftOf="@+id/createLayout"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/shareLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Share"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />


                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/shareFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onShareFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_share_black_24dp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/createLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="24dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/baseFloatingActionButton"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/createLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Create"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/createFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onCreateFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_create_black_24dp" />

            </LinearLayout>

        </android.support.constraint.ConstraintLayout>

These are the animations-

Opening animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="0"
    android:fromYScale="0"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1"
    android:toYScale="1" />
<alpha
    android:duration="300"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

</set>

Closing animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="1"
    android:fromYScale="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="0.0"
    android:toYScale="0.0" />
<alpha
    android:duration="300"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />
</set>

Then in my Activity I've simply used the animations above to show and hide the FAB menu :

Show Fab Menu:

  private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;

}

Close Fab Menu:

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}

Here is the the Activity class -

package com.app.fabmenu;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;

import com.app.fabmenu.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    binding = DataBindingUtil.setContentView(this,    R.layout.activity_main);
    binding.setFabHandler(new FabHandler());

    getAnimations();


}

private void getAnimations() {

    fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);

    fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);

}

private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;


}

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}


public class FabHandler {

    public void onBaseFabClick(View view) {

        if (isFabMenuOpen)
            collapseFabMenu();
        else
            expandFabMenu();


    }

    public void onCreateFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();

    }

    public void onShareFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();

    }


}

@Override
public void onBackPressed() {

    if (isFabMenuOpen)
        collapseFabMenu();
    else
        super.onBackPressed();
}
}

Here are the screenshots

Floating Action Menu with Label Textview in new Cursive Font Family of Android

Floating Action Menu with Label Textview in new Roboto Font Family of Android

C99 stdint.h header and MS Visual Studio

Just define them yourself.

#ifdef _MSC_VER

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;

#else
#include <stdint.h>
#endif

How can I set the default value for an HTML <select> element?

I myself use it

<select selected=''>
    <option value=''></option>
    <option value='1'>ccc</option>
    <option value='2'>xxx</option>
    <option value='3'>zzz</option>
    <option value='4'>aaa</option>
    <option value='5'>qqq</option>
    <option value='6'>wwww</option>
</select>

Listing only directories in UNIX

You can use the tree command with its d switch to accomplish this.

% tree -d tstdir
tstdir
|-- d1
|   `-- d11
|       `-- d111
`-- d2
    `-- d21
        `-- d211

6 directories

see man tree for more info.

Unknown Column In Where Clause

Either:

SELECT u_name AS user_name
FROM   users
WHERE  u_name = "john";

or:

SELECT user_name
from
(
SELECT u_name AS user_name
FROM   users
)
WHERE  u_name = "john";

The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.

Android screen size HDPI, LDPI, MDPI

You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.

Extract from Android Developer Guide link above:

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).  
480dp: a tweener tablet like the Streak (480x800 mdpi).  
600dp: a 7” tablet (600x1024 mdpi).  
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

Trigger 404 in Spring-MVC controller?

Since Spring 3.0.2 you can return ResponseEntity<T> as a result of the controller's method:

@RequestMapping.....
public ResponseEntity<Object> handleCall() {
    if (isFound()) {
        // do what you want
        return new ResponseEntity<>(HttpStatus.OK);
    }
    else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

(ResponseEntity<T> is a more flexible than @ResponseBody annotation - see another question)

Sending and receiving data over a network using TcpClient

Be warned - this is a very old and cumbersome "solution".

By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.

On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.

Something like that I am using:

namespace System.Net.Sockets
{
    public class TcpConnection : IDisposable
    {
        public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
        public event EvHandler<TcpConnection> Drop = delegate { };

        private const int IntSize = 4;
        private const int BufferSize = 8 * 1024;

        private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
        private readonly TcpClient _tcpClient;
        private readonly object _droppedRoot = new object();
        private bool _dropped;
        private byte[] _incomingData = new byte[0];
        private Nullable<int> _objectDataLength;

        public TcpClient TcpClient { get { return _tcpClient; } }
        public bool Dropped { get { return _dropped; } }

        private void DropConnection()
        {
            lock (_droppedRoot)
            {
                if (Dropped)
                    return;

                _dropped = true;
            }

            _tcpClient.Close();
            _syncContext.Post(delegate { Drop(this); }, null);
        }

        public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
        public void SendData(PCmds pCmd, object[] datas)
        {
            datas.ThrowIfNull();
            SendDataInternal(new object[] { pCmd }.Append(datas));
        }
        private void SendDataInternal(object data)
        {
            if (Dropped)
                return;

            byte[] bytedata;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();

                try { bf.Serialize(ms, data); }
                catch { return; }

                bytedata = ms.ToArray();
            }

            try
            {
                lock (_tcpClient)
                {
                    TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
                    TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
                }
            }
            catch { DropConnection(); }
        }
        private void EndSend(IAsyncResult ar)
        {
            try { TcpClient.Client.EndSend(ar); }
            catch { }
        }

        public TcpConnection(TcpClient tcpClient)
        {
            _tcpClient = tcpClient;
            StartReceive();
        }

        private void StartReceive()
        {
            byte[] buffer = new byte[BufferSize];

            try
            {
                _tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
            }
            catch { DropConnection(); }
        }

        private void DataReceived(IAsyncResult ar)
        {
            if (Dropped)
                return;

            int dataRead;

            try { dataRead = TcpClient.Client.EndReceive(ar); }
            catch
            {
                DropConnection();
                return;
            }

            if (dataRead == 0)
            {
                DropConnection();
                return;
            }

            byte[] byteData = ar.AsyncState as byte[];
            _incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
            bool exitWhile = false;

            while (exitWhile)
            {
                exitWhile = true;

                if (_objectDataLength.HasValue)
                {
                    if (_incomingData.Length >= _objectDataLength.Value)
                    {
                        object data;
                        BinaryFormatter bf = new BinaryFormatter();

                        using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
                            try { data = bf.Deserialize(ms); }
                            catch
                            {
                                SendData(PCmds.Disconnect);
                                DropConnection();
                                return;
                            }

                        _syncContext.Post(delegate(object T)
                        {
                            try { DataArrive(this, new DataArrivedEventArgs(T)); }
                            catch { DropConnection(); }
                        }, data);

                        _incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
                        _objectDataLength = null;
                        exitWhile = false;
                    }
                }
                else
                    if (_incomingData.Length >= IntSize)
                    {
                        _objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
                        _incomingData = _incomingData.TrimLeft(IntSize);
                        exitWhile = false;
                    }
            }
            StartReceive();
        }


        public void Dispose() { DropConnection(); }
    }
}

That is just an example, you should edit it for your use.

jQuery AJAX form data serialize using PHP

I just had the same problem: You have to unserialize the data on the php side.

Add to the beginning of your php file (Attention this short version would replace all other post variables):

parse_str($_POST["data"], $_POST);

Convert array values from string to int?

Another technique is to type-hint (coerce) the incoming values to int type after exploding the string.

Note that these techniques will work as demonstrated in my demo link unless you have set php to use strict typing.

The following techniques should not be used to sanitize non-numeric strings; it assumes that all values will be numeric.

If float values are passed into these techniques, they will be truncated/floored to integers.

Code: (Demo)

$string = "1,2,3";
$array = explode(',', $string);
var_dump($array);

echo "\n---\n";
array_walk($array, function(int &$int){;});
var_dump($array);

echo "\n---\n";
var_dump(
    array_map(function(int $i){ return $i; }, explode(',', $string))
);

echo "\n---\n";
var_dump(
    array_map(fn(int $i) => $i, explode(',', $string)) // PHP 7.4 arrow function syntax
);

Output:

array(3) {
  [0]=> string(1) "1"
  [1]=> string(1) "2"
  [2]=> string(1) "3"
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

Convert a string date into datetime in Oracle

Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') and all I received was 2017-02-20 the time disappeared

My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') now the time doesn't disappear.

Error message "Linter pylint is not installed"

  1. Open a terminal (ctrl+~)
  2. Run the command pip install pylint

If that doesn't work: On the off chance you've configured a non-default Python path for your editor, you'll need to match that Python's install location with the pip executable you're calling from the terminal.

This is an issue because the Python extension's settings enable Pylint by default. If you'd rather turn off linting, you can instead change this setting from true to false in your user or workspace settings:

"python.linting.pylintEnabled": false

How to normalize a signal to zero mean and unit variance?

if your signal is in the matrix X, you make it zero-mean by removing the average:

X=X-mean(X(:));

and unit variance by dividing by the standard deviation:

X=X/std(X(:));

How to use table variable in a dynamic sql statement?

Your EXEC executes in a different context, therefore it is not aware of any variables that have been declared in your original context. You should be able to use a temp table instead of a table variable as shown in the simple demo below.

create table #t (id int)

declare @value nchar(1)
set @value = N'1'

declare @sql nvarchar(max)
set @sql = N'insert into #t (id) values (' + @value + N')'

exec (@sql)

select * from #t

drop table #t

Early exit from function?

if you are looking for a script to avoid submitting form when some errors found, this method should work

function verifyData(){
     if (document.MyForm.FormInput.value.length == "") {
          alert("Write something!");
     }
     else {
          document.MyForm.submit();
     }
}

change the Submit Button type to "button"

<input value="Save" type="button" onClick="verifyData()">

hope this help.

bash: npm: command not found?

I also come here for the same problem, The solution I found is to install npm and then restart the Visual Studio Code

Can You Get A Users Local LAN IP Address Via JavaScript?

Update

This solution would not longer work because browsers are fixing webrtc leak: for more info on that read this other question: RTCIceCandidate no longer returning IP


In addition to afourney's answer this code works in browsers that support WebRTC (Chrome and Firefox). I heard there is a movement going on to implement a feature that makes sites request the IP (like in case of user's geo-location or user-media) though it has yet to be implemented in either of those browsers.

Here is a modified version of the source code, reduced the lines, not making any stun requests since you only want Local IP not the Public IP:

window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;//compatibility for Firefox and chrome
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};      
pc.createDataChannel('');//create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop);// create offer and set local description
pc.onicecandidate = function(ice)
{
 if (ice && ice.candidate && ice.candidate.candidate)
 {
  var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
  console.log('my IP: ', myIP);   
  pc.onicecandidate = noop;
 }
};

We are creating a dummy peer connection for the remote peer to contact us. We generally exchange ice candidates with each other and reading the ice candidates we can tell the ip of the user.

You can find a demo at --> Demo

C: How to free nodes in the linked list?

Simply by iterating over the list:

struct node *n = head;
while(n){
   struct node *n1 = n;
   n = n->next;
   free(n1);
}

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Your dispatcher servlet does not where to dispatch the request. Issue is your controller bean is not created/working.

Even I faced the same problem. Then added the following under mvc-config.xml

<mvc:annotation-driven/>
<context:component-scan base-package="com.nsv.jsmbaba.teamapp.controller"/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix"><value>/WEB-INF/view/</value></property>
    <property name="suffix"><value>.jsp</value></property>
</bean>

Hope this helps

Proper MIME media type for PDF files

From Wikipedia Media type,

A media type is composed of a type, a subtype, and optional parameters. As an example, an HTML file might be designated text/html; charset=UTF-8.

Media type consists of top-level type name and sub-type name, which is further structured into so-called "trees".

top-level type name / subtype name [ ; parameters ]

top-level type name / [ tree. ] subtype name [ +suffix ] [ ; parameters ]

All media types should be registered using the IANA registration procedures. Currently the following trees are created: standard, vendor, personal or vanity, unregistered x.

Standard:

Media types in the standards tree do not use any tree facet (prefix).

type / media type name [+suffix]

Examples: "application/xhtml+xml", "image/png"

Vendor:

Vendor tree is used for media types associated with publicly available products. It uses vnd. facet.

type / vnd. media type name [+suffix] - used in the case of well-known producer

type / vnd. producer's name followed by media type name [+suffix] - producer's name must be approved by IANA

type / vnd. producer's name followed by product's name [+suffix] - producer's name must be approved by IANA

Personal or Vanity tree:

Personal or Vanity tree includes media types created experimentally or as part of products that are not distributed commercially. It uses prs. facet.

type / prs. media type name [+suffix]

Unregistered x. tree:

The "x." tree may be used for media types intended exclusively for use in private, local environments and only with the active agreement of the parties exchanging them. Types in this tree cannot be registered.

According to the previous version of RFC 6838 - obsoleted RFC 2048 (published in November 1996) it should rarely, if ever, be necessary to use unregistered experimental types, and as such use of both "x-" and "x." forms is discouraged. Previous versions of that RFC - RFC 1590 and RFC 1521 stated that the use of "x-" notation for the sub-type name may be used for unregistered and private sub-types, but this recommendation was obsoleted in November 1996.

type / x. media type name [+suffix]

So its clear that the standard type MIME type application/pdf is the appropriate one to use while you should avoid using the obsolete and unregistered x- media type as stated in RFC 2048 and RFC 6838.

Hexadecimal to Integer in Java

Why do you not use the java functionality for that:

If your numbers are small (smaller than yours) you could use: Integer.parseInt(hex, 16) to convert a Hex - String into an integer.

  String hex = "ff"
  int value = Integer.parseInt(hex, 16);  

For big numbers like yours, use public BigInteger(String val, int radix)

  BigInteger value = new BigInteger(hex, 16);

@See JavaDoc:

Margin between items in recycler view Android

Use CompatPadding in CardView Item

How to use UTF-8 in resource properties with ResourceBundle

Here's a Java 7 solution that uses Guava's excellent support library and the try-with-resources construct. It reads and writes properties files using UTF-8 for the simplest overall experience.

To read a properties file as UTF-8:

File file =  new File("/path/to/example.properties");

// Create an empty set of properties
Properties properties = new Properties();

if (file.exists()) {

  // Use a UTF-8 reader from Guava
  try (Reader reader = Files.newReader(file, Charsets.UTF_8)) {
    properties.load(reader);
  } catch (IOException e) {
    // Do something
  }
}

To write a properties file as UTF-8:

File file =  new File("/path/to/example.properties");

// Use a UTF-8 writer from Guava
try (Writer writer = Files.newWriter(file, Charsets.UTF_8)) {
  properties.store(writer, "Your title here");
  writer.flush();
} catch (IOException e) {
  // Do something
}

Can we rely on String.isEmpty for checking null condition on a String in Java?

You can't use String.isEmpty() if it is null. Best is to have your own method to check null or empty.

public static boolean isBlankOrNull(String str) {
    return (str == null || "".equals(str.trim()));
}

What is this CSS selector? [class*="span"]

.show-grid [class*="span"]

It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.

When to throw an exception?

My little guidelines are heavily influenced by the great book "Code complete":

  • Use exceptions to notify about things that should not be ignored.
  • Don't use exceptions if the error can be handled locally
  • Make sure the exceptions are at the same level of abstraction as the rest of your routine.
  • Exceptions should be reserved for what's truly exceptional.

How to do a Jquery Callback after form submit?

You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

  • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
  • grab all necessary values from the form
  • fire off an HTTP request
  • handle the response to the request

First, you'll have to cancel the form submit action like so:

$("#myform").submit(function(event) {
    // Cancels the form's submit action.
    event.preventDefault();
});

And then, grab the value of the data. Let's just assume you have one text box.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();
});

And then fire off a request. Let's just assume it's a POST request.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();

    // I like to use defers :)
    deferred = $.post("http://somewhere.com", { val: val });

    deferred.success(function () {
        // Do your stuff.
    });

    deferred.error(function () {
        // Handle any errors here.
    });
});

And this should about do it.

Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

$.post("http://somewhere.com", { val: val }, function () {
    // Start partying here.
}, function () {
    // Handle the bad news here.
});

Click outside menu to close in jquery

what about this?

    $(this).mouseleave(function(){  
        var thisUI = $(this);
        $('html').click(function(){
                thisUI.hide();
            $('html').unbind('click');
         });
     });

Extracting the last n characters from a string in R

I wrote some functions that can do all of these after failing my last exam on string manipulation in R programming. If you are coming from Excel, these functions will be similar to LEFT(), RIGHT(), and MID() functions.


# This counts from the left and then extract n characters

str_left <- function(string, n) {
  substr(string, 1, n)
}



# This counts from the right and then extract n characters

str_right <- function(string, n) {
  substr(string, nchar(string) - (n - 1), nchar(string))
}


# This extract characters from the middle

str_mid <- function(string, from = 2, to = 5){
  
  substr(string, from, to)
  }

Examples:

x <- "some text in a string"
str_left(x, 4)
[1] "some"

str_right(x, 6)
[1] "string"

str_mid(x, 6, 9)
[1] "text"

I'm getting Key error in python

Let us make it simple if you're using Python 3

mydict = {'a':'apple','b':'boy','c':'cat'}
check = 'c' in mydict
if check:
    print('c key is present')

If you need else condition

mydict = {'a':'apple','b':'boy','c':'cat'}
if 'c' in mydict:
    print('key present')
else:
    print('key not found')

For the dynamic key value, you can also handle through try-exception block

mydict = {'a':'apple','b':'boy','c':'cat'}
try:
    print(mydict['c'])
except KeyError:
    print('key value not found')mydict = {'a':'apple','b':'boy','c':'cat'}

My httpd.conf is empty

The /etc/apache2/httpd.conf is empty in Ubuntu, because the Apache configuration resides in /etc/apache2/apache2.conf!

“httpd.conf is for user options.” No it isn't, it's there for historic reasons.

Using Apache server, all user options should go into a new *.conf-file inside /etc/apache2/conf.d/. This method should be "update-safe", as httpd.conf or apache2.conf may get overwritten on the next server update.

Inside /etc/apache2/apache2.conf, you will find the following line, which includes those files:

# Include generic snippets of statements
Include conf.d/

As of Apache 2.4+ the user configuration directory is /etc/apache2/conf-available/. Use a2enconf FILENAME_WITHOUT_SUFFIX to enable the new configuration file or manually create a symlink in /etc/apache2/conf-enabled/. Be aware that as of Apache 2.4 the configuration files must have the suffix .conf (e.g. conf-available/my-settings.conf);

INFO: No Spring WebApplicationInitializer types detected on classpath

My silly reason was: Build Automatically was disabled!

How to convert JSON object to JavaScript array?

If you have a well-formed JSON string, you should be able to do

var as = JSON.parse(jstring);

I do this all the time when transfering arrays through AJAX.

How to open .SQLite files

I would suggest using R and the package RSQLite

#install.packages("RSQLite") #perhaps needed
library("RSQLite")

# connect to the sqlite file
sqlite    <- dbDriver("SQLite")
exampledb <- dbConnect(sqlite,"database.sqlite")

dbListTables(exampledb)

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

I've solved by going to Project Properties -> Debug, after enable SSL and use the address in your browser

enter image description here

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

How to extract URL parameters from a URL with Ruby or Rails?

Check out the addressable gem - a popular replacement for Ruby's URI module that makes query parsing easy:

require "addressable/uri"
uri = Addressable::URI.parse("http://www.example.com/something?param1=value1&param2=value2&param3=value3")
uri.query_values['param1']
=> 'value1'

(It also apparently handles param encoding/decoding, unlike URI)

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

How to get current page URL in MVC 3

Add this extension method to your code:

public static Uri UrlOriginal(this HttpRequestBase request)
{
  string hostHeader = request.Headers["host"];

  return new Uri(string.Format("{0}://{1}{2}",
     request.Url.Scheme, 
     hostHeader, 
     request.RawUrl));
}

And then you can execute it off the RequestContext.HttpContext.Request property.

There is a bug (can be side-stepped, see below) in Asp.Net that arises on machines that use ports other than port 80 for the local website (a big issue if internal web sites are published via load-balancing on virtual IP and ports are used internally for publishing rules) whereby Asp.Net will always add the port on the AbsoluteUri property - even if the original request does not use it.

This code ensures that the returned url is always equal to the Url the browser originally requested (including the port - as it would be included in the host header) before any load-balancing etc takes place.

At least, it does in our (rather convoluted!) environment :)

If there are any funky proxies in between that rewrite the host header, then this won't work either.

Update 30th July 2013

As mentioned by @KevinJones in comments below - the setting I mention in the next section has been documented here: http://msdn.microsoft.com/en-us/library/hh975440.aspx

Although I have to say I couldn't get it work when I tried it - but that could just be me making a typo or something.

Update 9th July 2012

I came across this a little while ago, and meant to update this answer, but never did. When an upvote just came in on this answer I thought I should do it now.

The 'bug' I mention in Asp.Net can be be controlled with an apparently undocumented appSettings value - called 'aspnet:UseHostHeaderForRequest' - i.e:

<appSettings>
  <add key="aspnet:UseHostHeaderForRequest" value="true" />
</appSettings>

I came across this while looking at HttpRequest.Url in ILSpy - indicated by the ---> on the left of the following copy/paste from that ILSpy view:

public Uri Url
{
  get
  {
    if (this._url == null && this._wr != null)
    {
      string text = this.QueryStringText;
      if (!string.IsNullOrEmpty(text))
      {
        text = "?" + HttpEncoder.CollapsePercentUFromStringInternal(text, 
          this.QueryStringEncoding);
      }
 ---> if (AppSettings.UseHostHeaderForRequestUrl)
      {
        string knownRequestHeader = this._wr.GetKnownRequestHeader(28);
        try
        {
          if (!string.IsNullOrEmpty(knownRequestHeader))
          {
            this._url = new Uri(string.Concat(new string[]
            {
              this._wr.GetProtocol(),
              "://",
              knownRequestHeader,
              this.Path,
              text 
            }));
          }
        }
        catch (UriFormatException)
        { }
     }
     if (this._url == null) { /* build from server name and port */
       ...

I personally haven't used it - it's undocumented and so therefore not guaranteed to stick around - however it might do the same thing that I mention above. To increase relevancy in search results - and to acknowledge somebody else who seeems to have discovered this - the 'aspnet:UseHostHeaderForRequest' setting has also been mentioned by Nick Aceves on Twitter

Swift alert view with OK and Cancel: which button tapped?

You can easily do this by using UIAlertController

let alertController = UIAlertController(
       title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
       title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well 
alertController.addAction(defaultAction)

present(alertController, animated: true, completion: nil)

.

Reference: iOS Show Alert

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How can I transform string to UTF-8 in C#?

@anothershrubery answer worked for me. I've made an enhancement using StringEntensions Class so I can easily convert any string at all in my program.

Method:

public static class StringExtensions
{
    public static string ToUTF8(this string text)
    {
        return Encoding.UTF8.GetString(Encoding.Default.GetBytes(text));
    }
}

Usage:

string myString = "Acción";
string strConverted = myString.ToUTF8();

Or simply:

string strConverted = "Acción".ToUTF8();

Using jQuery to center a DIV on the screen

Please use this:

$(window).resize(function(){
    $('.className').css({
        position:'absolute',
        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2
    });
});

// To initially run the function:
$(window).resize();

Install a module using pip for specific python version

For Python 3

sudo apt-get install python3-pip
sudo pip3 install beautifulsoup4

For Python 2

sudo apt-get install python2-pip
sudo pip2 install beautifulsoup4

On Debian/Ubuntu, pip is the command to use when installing packages for Python 2, while pip3 is the command to use when installing packages for Python 3.

Java optional parameters

In JDK>1.5 you can use it like this;

public class NewClass1 {

    public static void main(String[] args) {

        try {
            someMethod(18); // Age : 18
            someMethod(18, "John Doe"); // Age & Name : 18 & John Doe
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static void someMethod(int age, String... names) {

        if (names.length > 0) {
            if (names[0] != null) {
                System.out.println("Age & Name : " + age + " & " + names[0]);
            }
        } else {
            System.out.println("Age : " + age);
        }
    }
}

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Collection was modified; enumeration operation may not execute in ArrayList

Don't modify the list inside of a loop which iterates through the list.

Instead, use a for() or while() with an index, going backwards through the list. (This will let you delete things without getting an invalid index.)

var foo = new List<Bar>();

for(int i = foo.Count-1; i >= 0; --i)
{
  var item = foo[i];
  // do something with item
}

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

How to change mysql to mysqli?

The first thing to do would probably be to replace every mysql_* function call with its equivalent mysqli_*, at least if you are willing to use the procedural API -- which would be the easier way, considering you already have some code based on the MySQL API, which is a procedural one.

To help with that, the MySQLi Extension Function Summary is definitely something that will prove helpful.

For instance:

Note: For some functions, you may need to check the parameters carefully: Maybe there are some differences here and there -- but not that many, I'd say: both mysql and mysqli are based on the same library (libmysql ; at least for PHP <= 5.2)

For instance:

  • with mysql, you have to use the mysql_select_db once connected, to indicate on which database you want to do your queries
  • mysqli, on the other side, allows you to specify that database name as the fourth parameter to mysqli_connect.
  • Still, there is also a mysqli_select_db function that you can use, if you prefer.

Once you are done with that, try to execute the new version of your script... And check if everything works ; if not... Time for bug hunting ;-)

AttributeError: Module Pip has no attribute 'main'

To verify whether is your pip installation problem, try using easy_install to install an earlier version of pip:

easy_install pip==9.0.1

If this succeed, pip should be working now. Then you can go ahead to install any other version of pip you want with:

pip install pip==10....

Or you can just stay with version 9.0.1, as your project requires version >= 9.0.

Try building your project again.

Get push notification while App in foreground iOS

If the application is running in the foreground, iOS won't show a notification banner/alert. That's by design. You have to write some code to deal with the situation of your app receiving a notification while it is in the foreground. You should show the notification in the most appropriate way (for example, adding a badge number to a UITabBar icon, simulating a Notification Center banner, etc.).

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

There are certain tools that provide dependency injection through their library, for example in .net we have ninject Library .

If you are going further in java then spring provides this capabilities.

Loosly coupled objects can be made by introducing Interfaces in your code, thats what these sources do.

Say in your code you are writing

Myclass m = new Myclass();

now this statement in your method says that you are dependent on myclass this is called a tightly coupled. Now you provide some constructor injection , or property injection and instantiating object then it will become loosly coupled.

Bootstrap 3 modal responsive

I had the same problem, and a easy way i found to solve that was to make everything in the modal's body responsive(using boostrap classes) and my problem were solved.

There is already an open DataReader associated with this Command which must be closed first

For those finding this via Google;
I was getting this error because, as suggested by the error, I failed to close a SqlDataReader prior to creating another on the same SqlCommand, mistakenly assuming that it would be garbage collected when leaving the method it was created in.

I solved the issue by calling sqlDataReader.Close(); before creating the second reader.

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

How to convert string date to Timestamp in java?

You can convert String to Timestamp:

String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());

Pandas group-by and sum

If you want to keep the original columns Fruit and Name, use reset_index(). Otherwise Fruit and Name will become part of the index.

df.groupby(['Fruit','Name'])['Number'].sum().reset_index()

Fruit   Name       Number
Apples  Bob        16
Apples  Mike        9
Apples  Steve      10
Grapes  Bob        35
Grapes  Tom        87
Grapes  Tony       15
Oranges Bob        67
Oranges Mike       57
Oranges Tom        15
Oranges Tony        1

As seen in the other answers:

df.groupby(['Fruit','Name'])['Number'].sum()

               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

How do I make an HTML text box show a hint when empty?

I'm using a simple, one line javascript solution which works great. Here is an example both for textbox and for textarea:

    <textarea onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">Text</textarea>

    <input type="text" value="Text" onfocus="if (this.value == 'Text') { this.value = ''; }" onblur="if (this.value == '') { this.value = 'Text'; }">

only "downside" is to validate at $_POST or in Javascript validation before doing anything with the value of the field. Meaning, checking that the field's value isn't "Text".

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

Apache: client denied by server configuration

Here's my symfony 1.4 virtual host file on debian, which works fine.

  <Directory /var/www/sf_project/web/>
    Options All Indexes FollowSymLinks    
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>

If you wan't to restrict access to a specific ip range, e.g. localhost use this:

Allow from 127.0.0.0/8

The mod_authz_host is responsible for filtering ip ranges. You can look up detailed things in there.

But maybe the problem could be related to some kind of misconfiguration in your "apache2.conf".

On what OS is the apache running?

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

How to remove all .svn directories from my application directories

If you don't like to see a lot of

find: `./.svn': No such file or directory

warnings, then use the -depth switch:

find . -depth -name .svn -exec rm -fr {} \;

How do I use a custom Serializer with Jackson?

If your only requirement in your custom serializer is to skip serializing the name field of User, mark it as transient. Jackson will not serialize or deserialize transient fields.

[ see also: Why does Java have transient fields? ]

How do I plot only a table in Matplotlib?

You can di this:

#axs[1].plot(clust_data[:,0],clust_data[:,1]) # Remove this if you don't need it
axs[1].axis("off")  # This will leave the table alone in the window 

Sql Server trigger insert values from new row into another table

When you are in the context of a trigger you have access to the logical table INSERTED which contains all the rows that have just been inserted to the table. You can build your insert to the other table based on a select from Inserted.

How to set 24-hours format for date on java?

Use HH instead of hh in formatter string

How To Include CSS and jQuery in my WordPress plugin?

You can use the following function to enqueue script or style from plugin.

function my_enqueued_assets() {
    wp_enqueue_script('my-js-file', plugin_dir_url(__FILE__) . '/js/script.js', '', time());
    wp_enqueue_style('my-css-file', plugin_dir_url(__FILE__) . '/css/style.css', '', time());
}
add_action('wp_enqueue_scripts', 'my_enqueued_assets');

Applying an ellipsis to multiline text

After many tries, I finally ended up with a mixed js / css to handle multiline and single line overflows.

CSS3 code:

.forcewrap { // single line ellipsis
  -ms-text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  overflow: hidden;
  -moz-binding: url( 'bindings.xml#ellipsis' );
  white-space: nowrap;
  display: block;
  max-width: 95%; // spare space for ellipsis
}

.forcewrap.multiline {
  line-height: 1.2em;  // my line spacing 
  max-height: 3.6em;   // 3 lines
  white-space: normal;
}

.manual-ellipsis:after {
  content: "\02026";      // '...'
  position: absolute;     // parent container must be position: relative
  right: 10px;            // typical padding around my text
  bottom: 10px;           // same reason as above
  padding-left: 5px;      // spare some space before ellipsis
  background-color: #fff; // hide text behind
}

and I simply check with js code for overflows on divs, like this:

function handleMultilineOverflow(div) {
    // get actual element that is overflowing, an anchor 'a' in my case
    var element = $(div).find('a'); 
    // don't know why but must get scrollHeight by jquery for anchors
    if ($(element).innerHeight() < $(element).prop('scrollHeight')) {
        $(element).addClass('manual-ellipsis');
    }
}

Usage example in html:

<div class="towrap">
  <h4>
    <a class="forcewrap multiline" href="/some/ref">Very long text</a>
  </h4>
</div>

Save PHP array to MySQL?

The best way, that I found to myself is save array as data string with separator characters

$array = array("value1", "value2", "value3", "...", "valuen");
$array_data = implode("array_separator", $array);

$query = "INSERT INTO my_tbl_name (id, array_data) VALUES(NULL,'" . $array_data . "');";

You can then search data, stored in your array with simple query

$query = "SELECT * FROM my_tbl_name WHERE array_data LIKE '%value3%'";

use explode() function to convert "array_data" string to array

$array = explode("array_separator", $array_data);

note that this is not working with multidimensional arrays and make sure that your "array_separator" is unique and had not exist in array values.

Be careful !!! if you just will take a form data and put in database, you will be in trap, becous the form data isn't SQL-safe ! you must handle your form value with mysql_real_escape_string or if you use MySQLi mysqli::real_escape_string or if value are integer or boolean cast (int) (boolean) on them

$number = (int)$_POST['number'];
$checked = (boolean) $_POST['checked'];

$name = mysql_real_escape_string($db_pt, $_POST['name']);
$email = mysqli_obj->real_escape_string($_POST['email']);

Button text toggle in jquery

Use an if/else statement.. or ternary if you understand it

$(".pushme").click(function () {
    var $el = $(this);
    $el.text($el.text() == "DON'T PUSH ME" ? "PUSH ME": "DON'T PUSH ME");
});

http://jsfiddle.net/dFZyv/

How to embed an autoplaying YouTube video in an iframe?

The flags, or parameters that you can use with IFRAME and OBJECT embeds are documented here; the details about which parameter works with what player are also clearly mentioned:

YouTube Embedded Players and Player Parameters

You will notice that autoplay is supported by all players (AS3, AS2 and HTML5).

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

in your Xcode:

  • Click on your active scheme name right next to the Stop button
  • Click on Edit Scheme....
  • in Run (Debug) select the Arguments tab
  • in Environment Variables click +
  • add variable: OS_ACTIVITY_MODE = disable

screenshot

Domain Account keeping locking out with correct password every few minutes

I think this highlights a serious deficiency in Windows. We have a (techincal) user account that we use for our system consisting of a windows service and websites, with the app pools configured to run as this user.

Our company has a security policy that after 5 bad passwords, it locks the account out.

Now finding out what locks out the account is practically impossible in a enterprise. When the account is locked out, the AD server should log from what process and what server caused the lock out.

I've looked into it and it (lock out tools) and it doesnt do this. only possible thing is a tool but you have to run it on the server and wait to see if any process is doing it. But in a enterprise with 1000s of servers thats impossible, you have to guess. Its crazy.

Powershell remoting with ip-address as target

On your machine* run 'Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ipaddress"

*Machine from where you are running PSSession

How to create a simple http proxy in node.js?

Here's a proxy server using request that handles redirects. Use it by hitting your proxy URL http://domain.com:3000/?url=[your_url]

var http = require('http');
var url = require('url');
var request = require('request');

http.createServer(onRequest).listen(3000);

function onRequest(req, res) {

    var queryData = url.parse(req.url, true).query;
    if (queryData.url) {
        request({
            url: queryData.url
        }).on('error', function(e) {
            res.end(e);
        }).pipe(res);
    }
    else {
        res.end("no url found");
    }
}

Manifest merger failed : uses-sdk:minSdkVersion 14

In the build.gradle file, It was by default compile 'com.android.support:support-v4:+' so when you build the gradle projecit would consider, com.android.support:support-v4:21.0.0-rc1 because of the recent L developer preview release.

Make changes in the following line and it will resolve the issue. Change

compile 'com.android.support:support-v4:+' 

to

compile 'com.android.support:support-v4:20.+'

Similarly when using v7-appcompat support library, make the change from

compile 'com.android.support:appcompat-v7:+'

to

compile 'com.android.support:appcompat-v7:20.+'.

C - gettimeofday for computing time?

Your curtime variable holds the number of seconds since the epoch. If you get one before and one after, the later one minus the earlier one is the elapsed time in seconds. You can subtract time_t values just fine.

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

export PATH=$PATH:/usr/local/mysql/bin/

should fix the issue for you as the system is not able to find the mysql_config file.

When is layoutSubviews called?

I had a similar question, but wasn't satisfied with the answer (or any I could find on the net), so I tried it in practice and here is what I got:

  • init does not cause layoutSubviews to be called (duh)
  • addSubview: causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target
  • view setFrame intelligently calls layoutSubviews on the view having its frame set only if the size parameter of the frame is different
  • scrolling a UIScrollView causes layoutSubviews to be called on the scrollView, and its superview
  • rotating a device only calls layoutSubview on the parent view (the responding viewControllers primary view)
  • Resizing a view will call layoutSubviews on its superview

My results - http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/

How to install Intellij IDEA on Ubuntu?

try simple way to install intellij idea

Install IntelliJ on Ubuntu using Ubuntu Make

You need to install Ubuntu Make first. If you are using Ubuntu 16.04, 18.04 or a higher version, you can install Ubuntu Make using the command below:

  1. sudo apt install ubuntu-make

Once you have Ubuntu Make installed, you can use the command below to install IntelliJ IDEA Community edition:

  1. umake ide idea

To install the IntelliJ IDEA Ultimate edition, use the command below:

  1. umake ide idea-ultimate

To remove IntelliJ IDEA installed via Ubuntu Make, use the command below for your respective versions:

  1. umake -r ide idea
  2. umake -r ide idea-ultimate

you may visit for more option.

https://itsfoss.com/install-intellij-ubuntu-linux/

Setting Inheritance and Propagation flags with set-acl and powershell

Here's the MSDN page describing the flags and what is the result of their various combinations.

Flag combinations => Propagation results
=========================================
No Flags => Target folder.
ObjectInherit => Target folder, child object (file), grandchild object (file).
ObjectInherit and NoPropagateInherit => Target folder, child object (file).
ObjectInherit and InheritOnly => Child object (file), grandchild object (file).
ObjectInherit, InheritOnly, and NoPropagateInherit => Child object (file).
ContainerInherit => Target folder, child folder, grandchild folder.
ContainerInherit, and NoPropagateInherit => Target folder, child folder.
ContainerInherit, and InheritOnly => Child folder, grandchild folder.
ContainerInherit, InheritOnly, and NoPropagateInherit => Child folder.
ContainerInherit, and ObjectInherit => Target folder, child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, and NoPropagateInherit => Target folder, child folder, child object (file).
ContainerInherit, ObjectInherit, and InheritOnly => Child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, NoPropagateInherit, InheritOnly => Child folder, child object (file).

To have it apply the permissions to the directory, as well as all child directories and files recursively, you'll want to use these flags:

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
PropagationFlags.None

So the specific code change you need to make for your example is:

$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

How can I get the max (or min) value in a vector?

Assuming cloud is int cloud[10] you can do it like this: int *p = max_element(cloud, cloud + 10);

How to execute a stored procedure within C# program

What I made, in my case I wanted to show procedure's result in dataGridView:

using (var command = new SqlCommand("ProcedureNameHere", connection) {
            // Set command type and add Parameters
            CommandType = CommandType.StoredProcedure,
            Parameters = { new SqlParameter("@parameterName",parameterValue) }
        }) 
        {
            // Execute command in Adapter and store to dataset
            var adapter = new SqlDataAdapter(command);
            var dataset = new DataSet();
            adapter.Fill(dataset);
            // Display results in DatagridView
            dataGridView1.DataSource = dataset.Tables[0];
        }

Calling ASP.NET MVC Action Methods from JavaScript

You can simply add this when you are using same controller to redirect

var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;

In Perl, how do I create a hash whose keys come from a given array?

There is a presupposition here, that the most efficient way to do a lot of "Does the array contain X?" checks is to convert the array to a hash. Efficiency depends on the scarce resource, often time but sometimes space and sometimes programmer effort. You are at least doubling the memory consumed by keeping a list and a hash of the list around simultaneously. Plus you're writing more original code that you'll need to test, document, etc.

As an alternative, look at the List::MoreUtils module, specifically the functions any(), none(), true() and false(). They all take a block as the conditional and a list as the argument, similar to map() and grep():

print "At least one value undefined" if any { !defined($_) } @list;

I ran a quick test, loading in half of /usr/share/dict/words to an array (25000 words), then looking for eleven words selected from across the whole dictionary (every 5000th word) in the array, using both the array-to-hash method and the any() function from List::MoreUtils.

On Perl 5.8.8 built from source, the array-to-hash method runs almost 1100x faster than the any() method (1300x faster under Ubuntu 6.06's packaged Perl 5.8.7.)

That's not the full story however - the array-to-hash conversion takes about 0.04 seconds which in this case kills the time efficiency of array-to-hash method to 1.5x-2x faster than the any() method. Still good, but not nearly as stellar.

My gut feeling is that the array-to-hash method is going to beat any() in most cases, but I'd feel a whole lot better if I had some more solid metrics (lots of test cases, decent statistical analyses, maybe some big-O algorithmic analysis of each method, etc.) Depending on your needs, List::MoreUtils may be a better solution; it's certainly more flexible and requires less coding. Remember, premature optimization is a sin... :)

Download & Install Xcode version without Premium Developer Account

I am able to download it using apple's download website today. https://developer.apple.com/download/

I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.

How do a LDAP search/authenticate against this LDAP in Java

try {
    LdapContext ctx = new InitialLdapContext(env, null);
    ctx.setRequestControls(null);
    NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
    while (namingEnum.hasMore ()) {
        SearchResult result = (SearchResult) namingEnum.next ();    
        Attributes attrs = result.getAttributes ();
        System.out.println(attrs.get("cn"));

    } 
    namingEnum.close();
} catch (Exception e) {
    e.printStackTrace();
}

private SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    //String[] attrIDs = {"objectGUID"};
    //searchControls.setReturningAttributes(attrIDs);
    return searchControls;
}

Node: log in a file instead of the console

I often use many arguments to console.log() and console.error(), so my solution would be:

var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('log.txt', { flags: 'a' });
  // Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;

console.log = function () {
  logFile.write(util.format.apply(null, arguments) + '\n');
  logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;

What's the difference between & and && in MATLAB?

&& and || take scalar inputs and short-circuit always. | and & take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.

See these doc pages for more information.

How can I map True/False to 1/0 in a Pandas DataFrame?

Just multiply your Dataframe by 1 (int)

[1]: data = pd.DataFrame([[True, False, True], [False, False, True]])
[2]: print data
          0      1     2
     0   True  False  True
     1   False False  True

[3]: print data*1
         0  1  2
     0   1  0  1
     1   0  0  1

C# equivalent to Java's charAt()?

Console.WriteLine allows the user to specify a position in a string.

See sample:

string str = "Tigger"; Console.WriteLine( str[0] ); //returns "T"; Console.WriteLine( str[2] ); //returns "g";

There you go!

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

Nginx reverse proxy causing 504 Gateway Timeout

Increasing the timeout will not likely solve your issue since, as you say, the actual target web server is responding just fine.

I had this same issue and I found it had to do with not using a keep-alive on the connection. I can't actually answer why this is but, in clearing the connection header I solved this issue and the request was proxied just fine:

server {
    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_pass http://localhost:5000;
    }
}

Have a look at this posts which explains it in more detail: nginx close upstream connection after request Keep-alive header clarification http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive

fatal error: Python.h: No such file or directory

Sure python-dev or libpython-all-dev are the first thing to (apt )install, but if that doesn't help as was my case, I advice you to install the foreign Function Interface packages by sudo apt-get install libffi-dev and sudo pip install cffi.

This should help out especially if you see the error as/from c/_cffi_backend.c:2:20: fatal error: Python.h: No such file or directory.

Show div #id on click with jQuery

The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").show("slow");
        });

    });

An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

To make the div hide again, once the #music element is clicked, simply use toggle():

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").toggle();
        });
    });

JS Fiddle demo.

And for fading:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
        });
    });

JS Fiddle demo.

How do I improve ASP.NET MVC application performance?

If you are running your ASP.NET MVC application on Microsoft Azure (IaaS or PaaS), then do the following at least at before the first deployment.

  • Scan your code with static code analyzer for any type of code debt, duplication, complexity and for security.
  • Always enable the Application Insight, and monitor the performance, browsers, and analytics frequently to find the real-time issues in the application.
  • Implement Azure Redis Cache for static and less frequent change data like Images, assets, common layouts etc.
  • Always rely on APM (Application Performance Management) tools provided by Azure.
  • See application map frequently to investigate the communication performance between internal parts of the application.
  • Monitor Database/VM performance too.
  • Use Load Balancer (Horizontal Scale) if required and within the budget.
  • If your application has the target audience all over the globe, then use Azure Trafic Manager to automatically handle the incoming request and divert it to the most available application instance.
  • Try to automate the performance monitoring by writing the alerts based on low performance.

Remove an entire column from a data.frame in R

With this you can remove the column and store variable into another variable.

df = subset(data, select = -c(genome) )

git remove merge commit from history

Do git rebase -i <sha before the branches diverged> this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more. The reason that your rebase wasn't working was that you weren't going back far enough.

WARNING: You are rewriting history doing this. Doing this with changes that have been pushed to a remote repo will cause issues. I recommend only doing this with commits that are local.

Attach Authorization header for all axios requests

Try to make new instance like i did below

var common_axios = axios.create({
    baseURL: 'https://sample.com'
});

// Set default headers to common_axios ( as Instance )
common_axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// Check your Header
console.log(common_axios.defaults.headers);

How to Use it

common_axios.get(url).......
common_axios.post(url).......

Force browser to refresh css, javascript, etc

General solution

Pressing Ctrl + F5 (or Ctrl + Shift + R) to force a cache reload. I believe Macs use Cmd + Shift + R.

PHP

In PHP, you can disable the cache by setting the expiration date to a time in the past with headers:

header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Chrome

Chrome's cache can be disabled by opening the developer tools with F12, clicking on the gear icon in the lower right corner and selecting Disable cache in the settings dialog, like this:

enter image description here
Image taken from this answer.

Firefox

Type about:config into the URL bar then find the entry titled network.http.use-cache. Set this to false.

'Property does not exist on type 'never'

This seems to be similar to this issue: False "Property does not exist on type 'never'" when changing value inside callback with strictNullChecks, which is closed as a duplicate of this issue (discussion): Trade-offs in Control Flow Analysis.

That discussion is pretty long, if you can't find a good solution there you can try this:

if (instance == null) {
    console.log('Instance is null or undefined');
} else {
    console.log(instance!.name); // ok now
}

Set colspan dynamically with jquery

You'd need to remove the blank table cell element entirely, and change the colspan attribute on another cell in the row to encompass the released space, e.g.:

refToCellToRemove.remove();
refTocellToExpand.colspan = 4;

Note that setting it via setAttribute (which would otherwise be correct) will not work properly on IE.

Beware: IE does some very strange table layout things when you muck about with colspans dynamically. If you can avoid it, I would.

Python Socket Receive Large Amount of Data

Disclaimer: There are very rare cases in which you really need to do this. If possible use an existing application layer protocol or define your own eg. precede each message with a fixed length integer indicating the length of data that follows or terminate each message with a '\n' character. (Adam Rosenfield's answer does a really good job at explaining that)

With that said, there is a way to read all of the data available on a socket. However, it is a bad idea to rely on this kind of communication as it introduces the risk of loosing data. Use this solution with extreme caution and only after reading the explanation below.

def recvall(sock):
    BUFF_SIZE = 4096
    data = bytearray()
    while True:
        packet = sock.recv(BUFF_SIZE)
        if not packet:  # Important!!
            break
        data.extend(packet)
    return data

Now the if not packet: line is absolutely critical! Many answers here suggested using a condition like if len(packet) < BUFF_SIZE: which is broken and will most likely cause you to close your connection prematurely and loose data. It wrongly assumes that one send on one end of a TCP socket corresponds to one receive of sent number of bytes on the other end. It does not. There is a very good chance that sock.recv(BUFF_SIZE) will return a chunk smaller than BUFF_SIZE even if there's still data waiting to be received. There is a good explanation of the issue here and here.

By using the above solution you are still risking data loss if the other end of the connection is writing data slower than you are reading. You may just simply consume all data on your end and exit when more is on the way. There are ways around it that require the use of concurrent programming, but that's another topic of its own.

How can I select from list of values in SQL Server

Available only on SQL Server 2008 and over is row-constructor in this form:
You could use

SELECT DISTINCT * FROM (VALUES (1), (1), (1), (2), (5), (1), (6)) AS X(a)

Many wrote about, among them:

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

Undefined reference to static class member

Aaa.h

class Aaa {

protected:

    static Aaa *defaultAaa;

};

Aaa.cpp

// You must define an actual variable in your program for the static members of the classes

static Aaa *Aaa::defaultAaa;

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

How to change fonts in matplotlib (python)?

import pylab as plb
plb.rcParams['font.size'] = 12

or

import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12

How can I change all input values to uppercase using Jquery?

$('#id-submit').click(function () {
    $("input").val(function(i,val) {
        return val.toUpperCase();
    });
});

FIDDLE

Best way to resolve file path too long exception

As the cause of the error is obvious, here's some information that should help you solve the problem:

See this MS article about Naming Files, Paths, and Namespaces

Here's a quote from the link:

Maximum Path Length Limitation In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

And a few workarounds (taken from the comments):

There are ways to solve the various problems. The basic idea of the solutions listed below is always the same: Reduce the path-length in order to have path-length + name-length < MAX_PATH. You may:

  • Share a subfolder
  • Use the commandline to assign a drive letter by means of SUBST
  • Use AddConnection under VB to assign a drive letter to a path

How to convert an object to a byte array in C#

This worked for me:

byte[] bfoo = (byte[])foo;

foo is an Object that I'm 100% certain that is a byte array.

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Upload Progress Bar in PHP

You would need to use Javascript to create a progress bar. A simple Google search led me to this article: WebAppers Simple Javascript Progress Bar with CSS.

Dojo File Upload Progress Bar Widget is another option using the Dojo Javascript framework.

EDIT: Assuming your uploading a large number of images (such as a photo album), and POSTing them to your PHP script, you could use javascript to read the results back from the post and update the progress bar based on the number of images uploaded / total number of images. This has the side effect of only updating after each post has completed. Check out here for some info on how to post with JS.

How to set up a Web API controller for multipart/form-data

This is what solved my problem
Add the following line to WebApiConfig.cs

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

How to construct a set out of list items in python?

The most direct solution is this:

s = set(filelist)

The issue in your original code is that the values weren't being assigned to the set. Here's the fixed-up version of your code:

s = set()
for filename in filelist:
    s.add(filename)
print(s)

How to sort List<Integer>?

Ascending order:

 Collections.sort(lList); 

Descending order:

Collections.sort(lList, Collections.reverseOrder()); 

How do I convert a string to a number in PHP?

You can use:

(int)(your value);

Or you can use:

intval(string)

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

Android Facebook integration with invalid key hash

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "www.icognix.infomedia",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("YourKeyHash: ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        Log.d("YourKeyHash: ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (PackageManager.NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

Npm Please try using this command again as root/administrator

I don't know which steps worked for me. But these are my steps to get rid of this error:

  1. Updated Node.js
  2. Ran npm cache clean command in Command prompt ( With some element of doubt for cache presence)
  3. Ran react-native init in command prompt as Administrator (on Windows OS), hoping works well with sudo react-native init on Mac OS

How to trim a string to N chars in Javascript?

    let trimString = function (string, length) {
      return string.length > length ? 
             string.substring(0, length) + '...' :
             string;
    };

Use Case,

let string = 'How to trim a string to N chars in Javascript';

trimString(string, 20);

//How to trim a string...

Detect if an element is visible with jQuery

There's no need, just use fadeToggle() on the element:

$('#testElement').fadeToggle('fast');

Here's a demo.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

How to make a new line or tab in <string> XML (eclipse/android)?

Use \t to add tab and \n for new line, here is a simple example below.

<string name="list_with_tab_tag">\tbanana\torange\tblueberry\tmango</string>
<string name="sentence_with_new_line_tag">This is the first sentence\nThis is the second scentence\nThis is the third sentence</string>

How to echo print statements while executing a sql script

For mysql you can add \p to the commands to have them print out while they run in the script:

SELECT COUNT(*) FROM `mysql`.`user`
\p;

Run it in the MySQL client:

mysql> source example.sql
--------------
SELECT COUNT(*) FROM `mysql`.`user`
--------------

+----------+
| COUNT(*) |
+----------+
|       24 |
+----------+
1 row in set (0.00 sec)

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

Add this to you PageLoad and it will solve your problem:

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.lblbtndoc1);

How to Display Selected Item in Bootstrap Button Dropdown Title

I had to put some the displayed javascripts above inside the "document.ready" code. Otherwise they didn't work. Probably obvious for many, but not for me. So if you're testing look at that option.

<script type="text/javascript">
$(document).ready(function(){
//rest of the javascript code here
});
</script>

DropdownList DataSource

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.

  1. DataSource - Name of the dataset or datatable or your datasource
  2. DataValueField - These field will be hidden
  3. DataTextField - These field will be displayed on the dropdwon.

you can use following code to bind a dropdownlist to a datasource as a datatable:

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

    SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt=new DataTable();
    da.Fill(dt);

    DropDownList1.DataTextField = "QUIZ_Name";
    DropDownList1.DataValueField = "QUIZ_ID"

    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();

if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string strQUIZ_ID=DropDownList1.SelectedValue;
    string strQUIZ_Name=DropDownList1.SelectedItem.Text;
    // Your code..............
}

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

how to implement regions/code collapse in javascript

Thats easy!

Mark the section you want to collapse and,

Ctrl+M+H

And to expand use '+' mark on its left.

MySQL select where column is not empty

If there are spaces in the phone2 field from inadvertant data entry, you can ignore those records with the IFNULL and TRIM functions:

SELECT phone, phone2
FROM jewishyellow.users
WHERE phone LIKE '813%'
    AND TRIM(IFNULL(phone2,'')) <> '';

How to export a Hive table into a CSV file?

In case you are doing it from Windows you can use Python script hivehoney to extract table data to local CSV file.

It will:

  • Login to bastion host.
  • pbrun.
  • kinit.
  • beeline (with your query).
  • Save echo from beeline to a file on Windows.

Execute it like this:

set PROXY_HOST=your_bastion_host

set SERVICE_USER=you_func_user

set LINUX_USER=your_SOID

set LINUX_PWD=your_pwd

python hh.py --query_file=query.sql

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

You should save all the files. For example html, css, component.ts, module, model files. Open each file and press ctrl-S. This worked for me

How to read a file byte by byte in Python and how to print a bytelist as a binary?

The code you've shown will read 8 bytes. You could use

with open(filename, 'rb') as f:
   while 1:
      byte_s = f.read(1)
      if not byte_s:
         break
      byte = byte_s[0]
      ...

Combining the results of two SQL queries as separate columns

You can use a CROSS JOIN:

SELECT *
FROM (  SELECT SUM(Fdays) AS fDaysSum 
        FROM tblFieldDays 
        WHERE tblFieldDays.NameCode=35 
        AND tblFieldDays.WeekEnding=1) A -- use you real query here
CROSS JOIN (SELECT SUM(CHdays) AS hrsSum 
            FROM tblChargeHours 
            WHERE tblChargeHours.NameCode=35 
            AND tblChargeHours.WeekEnding=1) B -- use you real query here

How to output an Excel *.xls file from classic ASP

There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.

How to simulate a button click using code?

there is a better way.

View.performClick();

http://developer.android.com/reference/android/view/View.html#performClick()

this should answer all your problems. every View inherits this function, including Button, Spinner, etc.

Just to clarify, View does not have a static performClick() method. You must call performClick() on an instance of View. For example, you can't just call

View.performClick();

Instead, do something like:

View myView = findViewById(R.id.myview);
myView.performClick();

Is there a performance difference between a for loop and a for-each loop?

From Item 46 in Effective Java by Joshua Bloch :

The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

How to pass object with NSNotificationCenter

Swift 5.1 Custom Object/Type

// MARK: - NotificationName
// Extending notification name to avoid string errors.
extension Notification.Name {
    static let yourNotificationName = Notification.Name("yourNotificationName")
}


// MARK: - CustomObject
class YourCustomObject {
    // Any stuffs you would like to set in your custom object as always.
    init() {}
}

// MARK: - Notification Sender Class
class NotificatioSenderClass {

     // Just grab the content of this function and put it to your function responsible for triggering a notification.
    func postNotification(){
        // Note: - This is the important part pass your object instance as object parameter.
        let yourObjectInstance = YourCustomObject()
        NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
    }
}

// MARK: -Notification  Receiver class
class NotificationReceiverClass: UIViewController {
    // MARK: - ViewController Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        // Register your notification listener
        NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
    }

    // MARK: - Helpers
    @objc private func didReceiveNotificationWithCustomObject(notification: Notification){
        // Important: - Grab your custom object here by casting the notification object.
        guard let yourPassedObject = notification.object as? YourCustomObject else {return}
        // That's it now you can use your custom object
        //
        //

    }
      // MARK: - Deinit
  deinit {
      // Save your memory by releasing notification listener
      NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
    }




}

How do I unlock a SQLite database?

My lock was caused by the system crashing and not by a hanging process. To resolve this I simply renamed the file then copied it back to it's original name and location.

Using a linux shell that would be...

mv mydata.db temp.db
cp temp.db mydata.db

The remote server returned an error: (403) Forbidden

In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.

[System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
$req.UserAgent = "BlackHole"
$req.UseDefaultCredentials = $true

What is the difference between atan and atan2 in C++?

Consider a right angled triangle. We label the hypotenuse r, the horizontal side y and the vertical side x. The angle of interest α is the angle between x and r.

C++ atan2(y, x) will give us the value of angle α in radians. atan is used if we only know or are interested in y/x not y and x individually. So if p = y/x then to get α we'd use atan(p).

You cannot use atan2 to determine the quadrant, you can use atan2 only if you already know which quadrant your in! In particular positive x and y imply the first quadrant, positive y and negative x, the second and so on. atan or atan2 themselves simply return a positive or a negative number, nothing more.

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.)

How to list the files inside a JAR file?

public static ArrayList<String> listItems(String path) throws Exception{
    InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(path);
    byte[] b = new byte[in.available()];
    in.read(b);
    String data = new String(b);
    String[] s = data.split("\n");
    List<String> a = Arrays.asList(s);
    ArrayList<String> m = new ArrayList<>(a);
    return m;
}

How do I create 7-Zip archives with .NET?

 string zipfile = @"E:\Folderx\NPPES.zip";
 string folder = @"E:\TargetFolderx";

 ExtractFile(zipfile,folder);
public void ExtractFile(string source, string destination)
        {
            // If the directory doesn't exist, create it.
            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            //string zPath = ConfigurationManager.AppSettings["FileExtactorEXE"];
          //  string zPath = Properties.Settings.Default.FileExtactorEXE; ;

            string zPath=@"C:\Program Files\7-Zip\7zG.exe";

            try
            {
                ProcessStartInfo pro = new ProcessStartInfo();
                pro.WindowStyle = ProcessWindowStyle.Hidden;
                pro.FileName = zPath;
                pro.Arguments = "x \"" + source + "\" -o" + destination;
                Process x = Process.Start(pro);
                x.WaitForExit();
            }
            catch (System.Exception Ex) { }
        }

Just Install 7 zip from source and pass the parameter to the method.

Thanks. Please like the answer.

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE