Programs & Examples On #Mouse

A mouse is a pointing device that functions by detecting two-dimensional motion relative to its supporting surface.

How can I detect when the mouse leaves the window?

See mouseover and mouseout.

_x000D_
_x000D_
var demo = document.getElementById('demo');_x000D_
document.addEventListener("mouseout", function(e){demo.innerHTML="";});_x000D_
document.addEventListener("mouseover", function(e){demo.innerHTML="";});
_x000D_
div { font-size:80vmin; position:absolute;_x000D_
      left:50%; top:50%; transform:translate(-50%,-50%); }
_x000D_
<div id='demo'></div>
_x000D_
_x000D_
_x000D_

Change background color on mouseover and remove it after mouseout

After lot of struggle finally got it working. ( Perfectly tested)

The below example will also support the fact that color of already clicked button should not be changes

JQuery Code

var flag = 0; // Flag is to check if you are hovering on already clicked item

$("a").click(function() {
    $('a').removeClass("YourColorClass");
    $(this).addClass("YourColorClass");
    flag=1;
}); 

$("a").mouseover(function() {
    if ($(this).hasClass("YourColorClass")) {
        flag=1;
    }
    else{
        $(this).addClass("YourColorClass");
    };
});

$("a").mouseout(function() {
    if (flag == 0) {
        $(this).removeClass("YourColorClass");
    }
    else{
        flag = 0;
    }
});

Get Mouse Position

Try looking at the java.awt.Robot class. It allows you to move the mouse programatically.

Copying text outside of Vim with set mouse=a enabled

I accidently explained how to switch off set mouse=a, when I reread the question and found out that the OP did not want to switch it off in the first place. Anyway for anyone searching how to switch off the mouse (set mouse=) centrally, I leave a reference to my answer here: https://unix.stackexchange.com/a/506723/194822

Controlling mouse with Python

Another alternative would be mouse library, I personally use it as it is relatively simple and cross-platform.

Here is how you can use it:

import mouse
# move 100 right and 100 down with a duration of 0.5 seconds
mouse.move(100, 100, absolute=False, duration=0.5)
# left click
mouse.click('left')
# right click
mouse.click('right')

Here is the source: How to Control your Mouse in Python

JavaScript: Check if mouse button down?

Regarding Pax' solution: it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.

The correct code should be like that:

var mouseDown = 0;
document.body.onmousedown = function() { 
  ++mouseDown;
}
document.body.onmouseup = function() {
  --mouseDown;
}

With the test like this:

if(mouseDown){
  // crikey! isn't she a beauty?
}

If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:

// let's pretend that a mouse doesn't have more than 9 buttons
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
    mouseDownCount = 0;
document.body.onmousedown = function(evt) { 
  ++mouseDown[evt.button];
  ++mouseDownCount;
}
document.body.onmouseup = function(evt) {
  --mouseDown[evt.button];
  --mouseDownCount;
}

Now you can check what buttons were pressed exactly:

if(mouseDownCount){
  // alright, let's lift the little bugger up!
  for(var i = 0; i < mouseDown.length; ++i){
    if(mouseDown[i]){
      // we found it right there!
    }
  }
}

Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:

  • 0 for "nothing is pressed"
  • 1 for left
  • 2 for right
  • 4 for middle
  • and any combination of above, e.g., 5 for left + middle

So adjust your code accordingly! I leave it as an exercise.

And remember: IE uses a global event object called … "event".

Incidentally IE has a feature useful in your case: when other browsers send "button" only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:

// for IE only!
document.body.onmousemove = function(){
  if(event.button){
    // aha! we caught a feisty little sheila!
  }
};

Of course you get nothing if she plays dead and not moving.

Relevant links:

Update #1: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.

How to disable mouse right click on a web page?

You can do so with Javascript and/or an HTML attribute (which is really a Javascript event handler anyway) as described here: http://www.codeproject.com/KB/aspnet/Disabling_the_right_click.aspx

<script language="javascript">
document.onmousedown=disableclick;
status="Right Click Disabled";
Function disableclick(event)
{
  if(event.button==2)
   {
     alert(status);
     return false;    
   }
}
</script>

and

<body oncontextmenu="return false">
...
</body>

Determine which element the mouse pointer is on top of in JavaScript

<!-- One simple solution to your problem could be like this: -->

<div>
<input type="text" id="fname" onmousemove="javascript: alert(this.id);" />
<!-- OR -->
<input type="text" id="fname" onclick="javascript: alert(this.id);" />
</div>
<!-- Both mousemove over the field & click on the field displays "fname"-->
<!-- Works fantastic in IE, FireFox, Chrome, Opera. -->
<!-- I didn't test it for Safari. -->

How to get mouse position in jQuery without mouse-events?

use window.event - it contains last event and as any event contains pageX, pageY etc. Works for Chrome, Safari, IE but not FF.

Move the mouse pointer to a specific position?

You cannot move the mousepointer with javascript.

Just think about the implications for a second, if you could ;)

  1. User thinks: "hey I'd like to click this link"
  2. Javascript moves mousecursor to another link
  3. User clicks wrong link and inadvertently downloads malware that formats his c-drive and eats his candy

Java Mouse Event Right Click

I've seen

anEvent.isPopupTrigger() 

be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)

Change the mouse cursor on mouse over to anchor-like style

If you want to do this in jQuery instead of CSS, you basically follow the same process.

Assuming you have some <div id="target"></div>, you can use the following code:

$("#target").hover(function() {
    $(this).css('cursor','pointer');
}, function() {
    $(this).css('cursor','auto');
});

and that should do it.

How exactly to use Notification.Builder

It works even in API 8 you can use this code:

 Notification n = 
   new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe), 
System.currentTimeMillis());

PendingIntent i=PendingIntent.getActivity(this, 0,
             new Intent(this, NotifyActivity.class),
                               0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;

// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr = 
   (NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);

Or I suggest to follow an excellent tutorial about this

What should be the values of GOPATH and GOROOT?

I had to append

export GOROOT=/usr/local/Cellar/go/1.10.1/libexec

to my ~/.bash_profile on Mac OS X

PHP to search within txt file and echo the whole line

one way...

$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];

though it would probably be better to read it line by line with fopen() and fread() and use strpos()

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

Fatal Error :1:1: Content is not allowed in prolog

The real solution that I found for this issue was by disabling any XML Format post processors. I have added a post processor called "jp@gc - XML Format Post Processor" and started noticing the error "Fatal Error :1:1: Content is not allowed in prolog"

By disabling the post processor had stopped throwing those errors.

Push an associative item into an array in JavaScript

JavaScript has associative arrays.

Here is a working snippet.

_x000D_
_x000D_
<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>
_x000D_
_x000D_
_x000D_

They are simply called objects.

how to convert rgb color to int in java

int color = (A & 0xff) << 24 | (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);

ASP.NET Core configuration for .NET Core console application

Install these packages:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

Code:

static void Main(string[] args)
    {
        var environmentName = Environment.GetEnvironmentVariable("ENVIRONMENT");
        Console.WriteLine("ENVIRONMENT: " + environmentName);

        var builder = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", false)
           .AddJsonFile($"appsettings.{environmentName}.json", true)
           .AddEnvironmentVariables();

        IConfigurationRoot configuration = builder.Build();
        var mySettingsConfig = configuration.Get<MySettingsConfig>();

        Console.WriteLine("URL: " + mySettingsConfig.Url);
        Console.WriteLine("NAME: " + mySettingsConfig.Name);

        Console.ReadKey();
    }

MySettingsConfig Class:

public class MySettingsConfig
{
    public string Url { get; set; }
    public string Name { get; set; }
}

Your appsettings can be as simple as this: enter image description here

Also, set the appsettings files to Content / Copy if newer: content

MemoryStream - Cannot access a closed Stream

In my case (admittedly very arcane and not likely to be reproduced often), this was causing the problem (this code is related to PDF generation using iTextSharp):

PdfPTable tblDuckbilledPlatypi = new PdfPTable(3);
float[] DuckbilledPlatypiRowWidths = new float[] { 42f, 76f };
tblDuckbilledPlatypi.SetWidths(DuckbilledPlatypiRowWidths);

The declaration of a 3-celled/columned table, and then setting only two vals for the width was what caused the problem, apparently. Once I changed "PdfPTable(3)" to "PdfPTable(2)" the problem went the way of the convection oven.

SDK Location not found Android Studio + Gradle

creating local.properties file in the root directory solved my issue I somehow lost this file after pulling from GitHub

this is how my local.properties file looks like now:

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Sat Feb 06 11:53:03 EST 2016

sdk.dir=/Users/****/Library/Android/sdk

TSQL select into Temp table from dynamic sql

DECLARE @count_ser_temp int;
DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'TableTemporal'

EXECUTE ('CREATE VIEW vTemp AS
    SELECT *
    FROM ' + @TableTemporal)
SELECT TOP 1 * INTO #servicios_temp  FROM vTemp

DROP VIEW vTemp

-- Contar la cantidad de registros de la tabla temporal
SELECT @count_ser_temp = COUNT(*) FROM #servicios_temp;

-- Recorro los registros de la tabla temporal 
WHILE @count_ser_temp > 0
 BEGIN
 END
END

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

Replace get with jsonp:

 $http.jsonp('http://mywebservice').success(function ( data ) {
    alert(data);
    });
}

Magento How to debug blank white screen

My solution: Activating the plugin via System -> Config > Advanced > Advanced

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

How to test for $null array in PowerShell

It's an array, so you're looking for Count to test for contents.

I'd recommend

$foo.count -gt 0

The "why" of this is related to how PSH handles comparison of collection objects

Java - using System.getProperty("user.dir") to get the home directory

"user.dir" is the current working directory, not the home directory It is all described here.

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Also, by using \\ instead of File.separator, you will lose portability with *nix system which uses / for file separator.

How can I change image tintColor in iOS and WatchKit

let navHeight = self.navigationController?.navigationBar.frame.height;
let menuBtn = UIButton(type: .custom)
menuBtn.frame = CGRect(x: 0, y: 0, width: 45, height: navHeight!)     
menuBtn.setImage(UIImage(named:"image_name")!.withRenderingMode(.alwaysTemplate), for: .normal)        
menuBtn.tintColor = .black

SQL Server Profiler - How to filter trace to only display events from one database?

In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.

Assuming you have the Tuning template selected, to filter:

  • Click the "Events Selection" tab
  • Click the "Column Filters" button
  • Check Show all Columns (Right Side Down)
  • Select "DatabaseName", click the plus next to Like in the right-hand pane, and type your database name.

I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.

How to convert object to Dictionary<TKey, TValue> in C#?

Assuming key can only be a string but value can be anything try this

public static Dictionary<TKey, TValue> MyMethod<TKey, TValue>(object obj)
{
    if (obj is Dictionary<TKey, TValue> stringDictionary)
    {
        return stringDictionary;
    }

    if (obj is IDictionary baseDictionary)
    {
        var dictionary = new Dictionary<TKey, TValue>();
        foreach (DictionaryEntry keyValue in baseDictionary)
        {
            if (!(keyValue.Value is TValue))
            {
                // value is not TKey. perhaps throw an exception
                return null;
            }
            if (!(keyValue.Key is TKey))
            {
                // value is not TValue. perhaps throw an exception
                return null;
            }

            dictionary.Add((TKey)keyValue.Key, (TValue)keyValue.Value);
        }
        return dictionary;
    }
    // object is not a dictionary. perhaps throw an exception
    return null;
}

Proper way to empty a C-String

It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.

This will also work:

buffer[0] = '\0';

If you want to zero the entire contents of the string, you can do it this way:

memset(buffer,0,strlen(buffer));

but this will only work for zeroing up to the first NULL character.

If the string is a static array, you can use:

memset(buffer,0,sizeof(buffer));

How to iterate for loop in reverse order in swift?

Swift 4 onwards

for i in stride(from: 5, to: 0, by: -1) {
    print(i)
}
//prints 5, 4, 3, 2, 1

for i in stride(from: 5, through: 0, by: -1) {
    print(i)
}
//prints 5, 4, 3, 2, 1, 0

Subtract two variables in Bash

Try this Bash syntax instead of trying to use an external program expr:

count=$((FIRSTV-SECONDV))

BTW, the correct syntax of using expr is:

count=$(expr $FIRSTV - $SECONDV)

But keep in mind using expr is going to be slower than the internal Bash syntax I provided above.

JQuery DatePicker ReadOnly

Sorry, but Eduardos solution did not work for me. At the end, I realized that disabled datepicker is just a read-only textbox. So you should make it read only and destroy the datepicker. Field will be sent to server upon submit.

Here is a bit generalized code that takes multiple textboxes and makes them read only. It will strip off the datepickers as well.

fields.attr("readonly", "readonly");
fields.each(function(idx, fld) {
    if($(fld).hasClass('hasDatepicker'))
    {
        $(fld).datepicker("destroy");
    }
});

extract digits in a simple way from a python string

If you're doing some sort of math with the numbers you might also want to know the units. Given your input restrictions (that the input string contains unit and value only), this should correctly return both (you'll just need to figure out how to convert units into common units for your math).

def unit_value(str):
    m = re.match(r'([^\d]*)(\d*\.?\d+)([^\d]*)', str)
    if m:
        g = m.groups()
        return ' '.join((g[0], g[2])).strip(), float(g[1])
    else:
        return int(str)

Get the first N elements of an array?

You can use array_slice as:

$sliced_array = array_slice($array,0,$N);

How do format a phone number as a String in Java?

You can implement your own method to do that for you, I recommend you to use something such as this. Using DecimalFormat and MessageFormat. With this method you can use pretty much whatever you want (String,Integer,Float,Double) and the output will be always right.

import java.text.DecimalFormat;
import java.text.MessageFormat;

/**
 * Created by Yamil Garcia Hernandez on 25/4/16.
 */

public class test {
    // Constants
    public static final DecimalFormat phoneFormatD = new DecimalFormat("0000000000");
    public static final MessageFormat phoneFormatM = new MessageFormat("({0}) {1}-{2}");

    // Example Method on a Main Class
    public static void main(String... args) {
        try {
            System.out.println(formatPhoneNumber("8091231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("18091231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("451231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("11231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("1231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber(""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber(8091231234f));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // Magic
    public static String formatPhoneNumber(Object phone) throws Exception {

        double p = 0;

        if (phone instanceof String)
            p = Double.valueOf((String) phone);

        if (phone instanceof Integer)
            p = (Integer) phone;

        if (phone instanceof Float)
            p = (Float) phone;

        if (phone instanceof Double)
            p = (Double) phone;

        if (p == 0 || String.valueOf(p) == "" || String.valueOf(p).length() < 7)
            throw new Exception("Paramenter is no valid");

        String fot = phoneFormatD.format(p);

        String extra = fot.length() > 10 ? fot.substring(0, fot.length() - 10) : "";
        fot = fot.length() > 10 ? fot.substring(fot.length() - 10, fot.length()) : fot;

        String[] arr = {
                (fot.charAt(0) != '0') ? fot.substring(0, 3) : (fot.charAt(1) != '0') ? fot.substring(1, 3) : fot.substring(2, 3),
                fot.substring(3, 6),
                fot.substring(6)
        };
        String r = phoneFormatM.format(arr);
        r = (r.contains("(0)")) ? r.replace("(0) ", "") : r;
        r = (extra != "") ? ("+" + extra + " " + r) : r;
        return (r);
    }
}

Result will be

(809) 123-1234
+1 (809) 123-1234
(45) 123-1234
(1) 123-1234
123-1234
023-1234
java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.lang.Double.valueOf(Double.java:502)
    at test.formatPhoneNumber(test.java:66)
    at test.main(test.java:45)
java.lang.Exception: Paramenter is no valid
    at test.formatPhoneNumber(test.java:78)
    at test.main(test.java:50)
(809) 123-1232

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

How to check if an environment variable exists and get its value?

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script's point of view, a variable is a variable.

You can check if a variable is defined:

if [ -z "$a" ]
then
    echo "not defined"
else 
    echo "defined"
fi

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

XMLHttpRequest cannot load an URL with jQuery

I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi.

My change was only in web.config file and is working.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol> 

Thanks for you solution @Rytis!

How to select an item in a ListView programmatically?

Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.

  1. The simple solution is to set the focus to the ListView first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load event, or immediately after you set the Selected property:

    myListView.Select();
    

    The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).

  2. To fix that, you will need to set the HideSelection property of the ListView control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.

    When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.

    You can set this property either at design time, or through code:

    myListView.HideSelection = false;
    

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

In my case ( XCode 7 and iOS 9 ), I use UINavigationController "hidden", so Ihave to add UINavigationControllerDelegate to present camera or roll and it work like it is supposed to! And pickerControllerDelegate.self doesn't display error either!

How can I get a first element from a sorted list?

If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)), you can use do it in linear time using min:

<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

That looks gnarly at first, but looking at your previous questions, you have a List<String>. In short: min works on it.

For the long answer: all that super and extends stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)

Producer Extends, Consumer Super

It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)

jQuery OR Selector?

I have written an incredibly simple (5 lines of code) plugin for exactly this functionality:

http://byrichardpowell.github.com/jquery-or/

It allows you to effectively say "get this element, or if that element doesnt exist, use this element". For example:

$( '#doesntExist' ).or( '#exists' );

Whilst the accepted answer provides similar functionality to this, if both selectors (before & after the comma) exist, both selectors will be returned.

I hope it proves helpful to anyone who might land on this page via google.

How to show alert message in mvc 4 controller?

TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])

Parse date without timezone javascript

simple solution

const handler1 = {
  construct(target, args) {
    let newDate = new target(...args);
    var tzDifference = newDate.getTimezoneOffset();
    return new target(newDate.getTime() + tzDifference * 60 * 1000);
  }
};

Date = new Proxy(Date, handler1);

How to Install Sublime Text 3 using Homebrew

As per latest updates, caskroom packages have moved to homebrew. So try following commands:

brew tap homebrew/cask
brew cask install sublime-text

These 2 terminal commands will be enough for installing sublime.

Can't find AVD or SDK manager in Eclipse

Try to reinstall ADT plugin on Eclipse. Check out this: Installing the Eclipse Plugin

Include of non-modular header inside framework module

I solved it removing Modules folder from the framework.

  • Browse to your framework location which is present in the App Project using finder

  • Go inside Test.framework folder (In the above case it will be CoreLibrary.framework) & Delete Modules folder.

  • Clean and Re Build the app, it will solve the problem.

What is the best IDE to develop Android apps in?

you can use Juno, i just find it. it's fastest than Helios that i worked with that. you can try it.

How to export DataTable to Excel

Excel Interop:

This method prevents Dates getting flipped from dd-mm-yyyy to mm-dd-yyyy

public bool DataTableToExcelFile(DataTable dt, string targetFile)
{
    const bool dontSave = false;
    bool success = true;

    //Exit if there is no rows to export
    if (dt.Rows.Count == 0) return false;

    object misValue = System.Reflection.Missing.Value;
    List<int> dateColIndex = new List<int>();
    Excel.Application excelApp = new Excel.Application();
    Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(misValue);
    Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets("sheet1");

    //Iterate through the DataTable and populate the Excel work sheet
    try {
        for (int i = -1; i <= dt.Rows.Count - 1; i++) {
            for (int j = 0; j <= dt.Columns.Count - 1; j++) {
                if (i < 0) {
                    //Take special care with Date columns
                    if (dt.Columns(j).DataType is typeof(DateTime)) {
                        excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "d-MMM-yyyy;@";
                        dateColIndex.Add(j);
                    } 
                    //else if ... Feel free to add more Formats

                    else {
                        //Otherwise Format the column as text
                        excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "@";
                    }
                    excelWorkSheet.Cells(1, j + 1) = dt.Columns(j).Caption;
                } 
                else if (dateColIndex.IndexOf(j) > -1) {
                    excelWorkSheet.Cells(i + 2, j + 1) = Convert.ToDateTime(dt.Rows(i).ItemArray(j)).ToString("d-MMM-yyyy");
                } 
                else {
                    excelWorkSheet.Cells(i + 2, j + 1) = dt.Rows(i).ItemArray(j).ToString();
                }
            }
        }

        //Add Autofilters to the Excel work sheet  
        excelWorkSheet.Cells.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);
        //Autofit columns for neatness
        excelWorkSheet.Columns.AutoFit();
        if (File.Exists(exportFile)) File.Delete(exportFile);
        excelWorkSheet.SaveAs(exportFile);
    } catch {
        success = false;
    } finally {
        //Do this irrespective of whether there was an exception or not. 
        excelWorkBook.Close(dontSave);
        excelApp.Quit();
        releaseObject(excelWorkSheet);
        releaseObject(excelWorkBook);
        releaseObject(excelApp);
    }
    return success;
}

If you dont care about Dates being flipped, then use see link that shows how to populate all the cells in the Excel spreadsheet in one line of code:

Excel Interop - Efficiency and performance

CSV:

public string DataTableToCSV(DataTable dt, bool includeHeader, string rowFilter, string sortFilter, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
    dt.DefaultView.RowFilter = rowFilter;
    dt.DefaultView.Sort = sortFilter;
    DataView dv = dt.DefaultView;
    string csv = DataTableToCSV(dv.ToTable, includeHeader, useCommaDelimiter, truncateTimesFromDates);
    //reset the Filtering
    dt.DefaultView.RowFilter = string.Empty;
    return csv;
}

public string DataTableToCsv(DataTable dt, bool includeHeader, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
    StringBuilder sb = new StringBuilder();
    string delimter = Constants.vbTab;
    if (useCommaDelimiter)
        delimter = ",";

    if (includeHeader) {
        foreach (DataColumn dc in dt.Columns) {
            sb.AppendFormat("{0}" + Constants.vbTab, dc.ColumnName);
        }

        //remove the last Tab
        sb.Remove(sb.ToString.Length - 1, 1);
        sb.Append(Environment.NewLine);
    }

    foreach (DataRow dr in dt.Rows) {
        foreach (DataColumn dc in dt.Columns) {
            if (Information.IsDate(dr(dc.ColumnName).ToString()) & dr(dc.ColumnName).ToString().Contains(".") == false & truncateTimesFromDates) {
                sb.AppendFormat("{0}" + delimter, Convert.ToDateTime(dr(dc.ColumnName).ToString()).Date.ToShortDateString());
            } else {
                sb.AppendFormat("{0}" + delimter, CheckDBNull(dr(dc.ColumnName).ToString().Replace(",", "")));
            }
        }
        //remove the last Tab
        sb.Remove(sb.ToString.Length - 1, 1);
        sb.Append(Environment.NewLine);
    }
    return sb.ToString;
}

public enum enumObjectType
{
    StrType = 0,
    IntType = 1,
    DblType = 2
}

public object CheckDBNull(object obj, enumObjectType ObjectType = enumObjectType.StrType)
{
    object objReturn = null;
    objReturn = obj;
    if (ObjectType == enumObjectType.StrType & Information.IsDBNull(obj)) {
        objReturn = "";
    } else if (ObjectType == enumObjectType.IntType & Information.IsDBNull(obj)) {
        objReturn = 0;
    } else if (ObjectType == enumObjectType.DblType & Information.IsDBNull(obj)) {
        objReturn = 0.0;
    }
    return objReturn;
}

Delete/Reset all entries in Core Data?

There seems to be two approaches:

Say you have a typical singleton for your core data stack.

import CoreData
public let core = Core.shared
public final class Core {
    static let shared = Core()
    var container: NSPersistentContainer!
    private init() {
        container = NSPersistentContainer(name: "stuff")
        //deleteSql()
        container.loadPersistentStores { storeDescription, error in
            if let error = error { print("Error loading... \(error)") }
        }
        //deleteAll()
    }
    
    func saveContext() { // typical save helper
        if container.viewContext.hasChanges {
            do { try container.viewContext.save()
            } catch { print("Error saving... \(error)") }
        }
    }
    

then ...

    func deleteSql() {
        let url = FileManager.default.urls(
           for: .applicationSupportDirectory,
           in: .userDomainMask)[0].appendingPathComponent( "stuff.sqlite" )
        
        guard FileManager.default.fileExists(atPath: url.path) else {
            print("nothing to delete!")
            return
        }
        
        do {
            try container.persistentStoreCoordinator.destroyPersistentStore(
                at: url, ofType: "sqlite", options: nil)
            print("totally scorched the sql file. you DO now have to LOAD again")
        }
        catch {
            print("there was no sql file there!")
        }
    }
    
    func deleteAll() { // courtesy @Politta
        for e in container.persistentStoreCoordinator.managedObjectModel.entities {
            let r = NSBatchDeleteRequest(
              fetchRequest: NSFetchRequest(entityName: e.name ?? ""))
            let _ = try? container.viewContext.execute(r)
        }
        saveContext()
        print("conventionally deleted everything from within core data. carry on")
    }
}

.

1. scorch the sql file

Courtesy the excellent @J.Doe answer. You completely destroy the sql file.

You must to do this

  • before loading core data, ie, after creating the container, but
  • before actually loading the stores.)

(Notice the example line of code "//deleteSql()" is just before initialization.)

2. delete everything one by one within core data

Courtesy the excellent @Politta answer. You could do this at any time once core data is up and running.

(Notice the example line of code "//deleteAll()" is after initialization.)

Approach one is probably more useful during development. Approach two is probably more useful in production (in the relatively unusual case that for some reason you need to wipe everything).

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

How does C#'s random number generator work?

You can use Random.Next(int maxValue):

Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.

var r = new Random();
// print random integer >= 0 and  < 100
Console.WriteLine(r.Next(100));

For this case however you could use Random.Next(int minValue, int maxValue), like this:

// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);

Send form data with jquery ajax json

You can use serialize() like this:

$.ajax({
  cache: false,
  url: 'test.php',
  data: $('form').serialize(),
  datatype: 'json',
  success: function(data) {

  }
});

How to return the current timestamp with Moment.js?

Try to use it this way:

let current_time = moment().format("HH:mm")

Java 8 lambdas, Function.identity() or t->t

From the JDK source:

static <T> Function<T, T> identity() {
    return t -> t;
}

So, no, as long as it is syntactically correct.

How can I read inputs as numbers?

def dbz():
    try:
        r = raw_input("Enter number:")
        if r.isdigit():
            i = int(raw_input("Enter divident:"))
            d = int(r)/i
            print "O/p is -:",d
        else:
            print "Not a number"
    except Exception ,e:
        print "Program halted incorrect data entered",type(e)
dbz()

Or 

num = input("Enter Number:")#"input" will accept only numbers

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"

example of adding (compile 'io.reactivex:rxjava:1.1.0'):

hit refresh

If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}

QByteArray to QString

You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

Using OR operator in a jquery if statement

The logical OR '||' automatically short circuits if it meets a true condition once.

false || false || true || false = true, stops at second condition.

On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.

false && true && true && true = false, stops at first condition.

How to implement common bash idioms in Python?

I just discovered how to combine the best parts of bash and ipython. Up to now this seems more comfortable to me than using subprocess and so on. You can easily copy big parts of existing bash scripts and e.g. add error handling in the python way :) And here is my result:

#!/usr/bin/env ipython3

# *** How to have the most comfort scripting experience of your life ***
# ######################################################################
#
# … by using ipython for scripting combined with subcommands from bash!
#
# 1. echo "#!/usr/bin/env ipython3" > scriptname.ipy    # creates new ipy-file
#
# 2. chmod +x scriptname.ipy                            # make in executable
#
# 3. starting with line 2, write normal python or do some of
#    the ! magic of ipython, so that you can use unix commands
#    within python and even assign their output to a variable via
#    var = !cmd1 | cmd2 | cmd3                          # enjoy ;)
#
# 4. run via ./scriptname.ipy - if it fails with recognizing % and !
#    but parses raw python fine, please check again for the .ipy suffix

# ugly example, please go and find more in the wild
files = !ls *.* | grep "y"
for file in files:
  !echo $file | grep "p"
# sorry for this nonsense example ;)

See IPython docs on system shell commands and using it as a system shell.

Edit and Continue: "Changes are not allowed when..."

This problem is due to Intellitrace setting

If Intellitrace is enabled make sure Intellitrace event only is checked

Otherwise this will not allow edit and continue..

If you will click on Intellitrace options you will see the warnings.

Handling MySQL datetimes and timestamps in Java

The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp. A few resources include:

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

How to store Java Date to Mysql datetime...?

http://www.velocityreviews.com/forums/t599436-the-best-practice-to-deal-with-datetime-in-mysql-using-jdbc.html

EDIT:

As others have indicated, the suggestion of using strings may lead to issues.

How to define a default value for "input type=text" without using attribute 'value'?

Here is the question: Is it possible that I can set the default value without using attribute 'value'?

Nope: value is the only way to set the default attribute.

Why don't you want to use it?

How to try convert a string to a Guid

use code like this:

new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")

instead of "9D2B0228-4D0D-4C23-8B49-01A698857709" you can set your string value

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

Java List.contains(Object with field value equal to x)

This is how to do it using Java 8+ :

boolean isJohnAlive = list.stream().anyMatch(o -> o.getName().equals("John"));

How to add header row to a pandas DataFrame

To fix your code you can simply change [Cov] to Cov.values, the first parameter of pd.DataFrame will become a multi-dimensional numpy array:

Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')

But the smartest solution still is use pd.read_excel with header=None and names=columns_list.

Is it good practice to make the constructor throw an exception?

It is bad practice to throw Exception, as that requires anyone who calls your constructor to catch Exception which is a bad practice.

It is a good idea to have a constructor (or any method) throw an exception, generally speaking IllegalArgumentException, which is unchecked, and thus the compiler doesn't force you to catch it.

You should throw checked exceptions (things that extend from Exception, but not RuntimeException) if you want the caller to catch it.

Detect Route Change with react-router

You can make use of history.listen() function when trying to detect the route change. Considering you are using react-router v4, wrap your component with withRouter HOC to get access to the history prop.

history.listen() returns an unlisten function. You'd use this to unregister from listening.

You can configure your routes like

index.js

ReactDOM.render(
      <BrowserRouter>
            <AppContainer>
                   <Route exact path="/" Component={...} />
                   <Route exact path="/Home" Component={...} />
           </AppContainer>
        </BrowserRouter>,
  document.getElementById('root')
);

and then in AppContainer.js

class App extends Component {
  
  componentWillMount() {
    this.unlisten = this.props.history.listen((location, action) => {
      console.log("on route change");
    });
  }
  componentWillUnmount() {
      this.unlisten();
  }
  render() {
     return (
         <div>{this.props.children}</div>
      );
  }
}
export default withRouter(App);

From the history docs:

You can listen for changes to the current location using history.listen:

history.listen((location, action) => {
      console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

The location object implements a subset of the window.location interface, including:

**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment

Locations may also have the following properties:

location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory and createMemoryHistory)

location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)

The action is one of PUSH, REPLACE, or POP depending on how the user got to the current URL.

When you are using react-router v3 you can make use of history.listen() from history package as mentioned above or you can also make use browserHistory.listen()

You can configure and use your routes like

import {browserHistory} from 'react-router';

class App extends React.Component {

    componentDidMount() {
          this.unlisten = browserHistory.listen( location =>  {
                console.log('route changes');
                
           });
      
    }
    componentWillUnmount() {
        this.unlisten();
     
    }
    render() {
        return (
               <Route path="/" onChange={yourHandler} component={AppContainer}>
                   <IndexRoute component={StaticContainer}  />
                   <Route path="/a" component={ContainerA}  />
                   <Route path="/b" component={ContainerB}  />
            </Route>
        )
    }
} 

Make a number a percentage

((portion/total) * 100).toFixed(2) + '%'

How to find numbers from a string?

This a variant of brettdj's & pstraton post.

This will return a true Value and not give you the #NUM! error. And \D is shorthand for anything but digits. The rest is much like the others only with this minor fix.

Function StripChar(Txt As String) As Variant
With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "\D"
    StripChar = Val(.Replace(Txt, " "))
End With
End Function

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

Get the date (a day before current time) in Bash

#!/bin/bash
OFFSET=1;
eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
month=12
fi
set `cal $month $year`
xday=${$#}
day=`expr $xday + $day`
fi
echo $year-$month-$day

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

Lua - Current time in milliseconds

I use LuaSocket to get more precision.

require "socket"
print("Milliseconds: " .. socket.gettime()*1000)

This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).

.gitignore and "The following untracked working tree files would be overwritten by checkout"

This could be a permission issue,

change the ownership,

sudo chown -v -R usr-name:group-name folder-name

return in for loop or outside loop

Some people argue that a method should have a single point of exit (e.g., only one return). Personally, I think that trying to stick to that rule produces code that's harder to read. In your example, as soon as you find what you were looking for, return it immediately, it's clear and it's efficient.

Quoting the C2 wiki:

The original significance of having a single entry and single exit for a function is that it was part of the original definition of StructuredProgramming as opposed to undisciplined goto SpaghettiCode, and allowed a clean mathematical analysis on that basis.

Now that structured programming has long since won the day, no one particularly cares about that anymore, and the rest of the page is largely about best practices and aesthetics and such, not about mathematical analysis of structured programming constructs.

Leaflet changing Marker color

Ahh an event listener and change the icon through setIcon() method:

createdMarker.on("dblclick", function(evt) {

        var myIcon = L.icon({
            iconUrl: 'res/marker-icon-red.png',
            shadowUrl: 'res/marker-shadow.png'
        });
        this.setIcon(myIcon);
});

How to add a char/int to an char array in C?

The error is due the fact that you are passing a wrong to strcat(). Look at strcat()'s prototype:

   char *strcat(char *dest, const char *src);

But you pass char as the second argument, which is obviously wrong.

Use snprintf() instead.

char str[1024] = "Hello World";
char tmp = '.';
size_t len = strlen(str);

snprintf(str + len, sizeof str - len, "%c", tmp);

As commented by OP:

That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array

In that case, snprintf() can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf() is that it's more flexible to concatenate various types of data into a char buffer.

For example to concatenate a string, char and an int:

char str[1024];
ch tmp = '.';
int i = 5;

// Fill str here

snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
 CASE 
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

Setting the Textbox read only property to true using JavaScript

You can try

document.getElementById("textboxid").readOnly = true;

How can I wait for a thread to finish with .NET?

Add

t1.Join();    // Wait until thread t1 finishes

after you start it, but that won't accomplish much as it's essentialy the same result as running on the main thread!

I can highly recommended reading Joe Albahari's Threading in C# free e-book, if you want to gain an understanding of threading in .NET.

Calling Python in PHP

You can run a python script via php, and outputs on browser.

Basically you have to call the python script this way:

$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
 echo fread($pid, 256);
 flush();
 ob_flush();
 usleep(100000);
}
pclose($pid);

Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.

For full codes working, visit How to execute python script from php and show output on browser

How to make a simple rounded button in Storyboard?

As other answer have suggested to perform most of this work in code only one answer actually provided a way to view your changes in the storyboard IB Interface. My answer goes beyond that answer by allowing you to change the cornerRadius of the view, button, image, etc.

Please take a look at the following code. To use this code create a new swift file called RoundedView or whatever you would like to call it then go to your storyboard and change the class to either "RoundedView", "RoundedImageView" or "RoundedButton".

import UIKit

@IBDesignable class RoundedImage: UIImageView
{
    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var rounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.1 {
        didSet {
            updateCornerRadius()
        }
    }

    func updateCornerRadius() {
        layer.cornerRadius = rounded ? cornerRadius : 0
        layer.masksToBounds = rounded ? true : false
    }
}

@IBDesignable class RoundedView: UIView
{
    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var rounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.1 {
        didSet {
            updateCornerRadius()
        }
    }

    func updateCornerRadius() {
        layer.cornerRadius = rounded ? cornerRadius : 0
        layer.masksToBounds = rounded ? true : false
    }
}

@IBDesignable class RoundedButton: UIButton
{
    override func layoutSubviews() {
        super.layoutSubviews()

        updateCornerRadius()
    }

    @IBInspectable var rounded: Bool = false {
        didSet {
            updateCornerRadius()
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.1 {
        didSet {
            updateCornerRadius()
        }
    }

    func updateCornerRadius() {
        layer.cornerRadius = rounded ? cornerRadius : 0
        layer.masksToBounds = rounded ? true : false
    }
}

Installing MySQL Python on Mac OS X

On Mojave, I ran into errors with finding the SSL libraries, here's what finally worked without having to modify mysql_config:

sudo pip install MySQL-Python --global-option=build_ext --global-option="-I/usr/local/opt/openssl/include" --global-option="-L/usr/local/opt/openssl/lib"

Hopefully that will save someone a few hours of heartache

How to deal with SQL column names that look like SQL keywords?

The following will work perfectly:

SELECT DISTINCT table.from AS a FROM table

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

Disable/enable an input with jQuery?

Approach 4 (this is extension of wild coder answer)

_x000D_
_x000D_
txtName.disabled=1     // 0 for enable
_x000D_
<input id="txtName">
_x000D_
_x000D_
_x000D_

SQL Server convert select a column and convert it to a string

ALTER PROCEDURE [dbo].[spConvertir_CampoACadena]( @nomb_tabla   varchar(30),
                          @campo_tabla  varchar(30),
                          @delimitador  varchar(5),
                          @respuesta    varchar(max) OUTPUT
)
AS
DECLARE @query      varchar(1000),
    @cadena     varchar(500)
BEGIN
  SET @query = 'SELECT @cadena  = COALESCE(@cadena + '''+ @delimitador +''', '+ '''''' +') + '+ @campo_tabla + ' FROM '+@nomb_tabla
  --select @query
  EXEC(@query)
  SET @respuesta = @cadena  
END

C# - Making a Process.Start wait until the process has start-up

public static class WinApi
{

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    public static class Windows
    {
        public const int NORMAL = 1;
        public const int HIDE = 0;
        public const int RESTORE = 9;
        public const int SHOW = 5;
        public const int MAXIMIXED = 3;
    }

}

App

String process_name = "notepad"
Process process;
process = Process.Start( process_name );

while (!WinApi.ShowWindow(process.MainWindowHandle, WinApi.Windows.NORMAL))
{
    Thread.Sleep(100);
    process.Refresh();
}

// Done!
// Continue your code here ...

How to add headers to a multicolumn listbox in an Excel userform using VBA

I was looking at this problem just now and found this solution. If your RowSource points to a range of cells, the column headings in a multi-column listbox are taken from the cells immediately above the RowSource.

Using the example pictured here, inside the listbox, the words Symbol and Name appear as title headings. When I changed the word Name in cell AB1, then opened the form in the VBE again, the column headings changed.

Screenshot displaying a named range and the column headings outside the range.

The example came from a workbook in VBA For Modelers by S. Christian Albright, and I was trying to figure out how he got the column headings in his listbox :)

What's the use of session.flush() in Hibernate

I would just like to club all the answers given above and also relate Flush() method with Session.save() so as to give more importance

Hibernate save() can be used to save entity to database. We can invoke this method outside a transaction, that’s why I don’t like this method to save data. If we use this without transaction and we have cascading between entities, then only the primary entity gets saved unless we flush the session.

flush(): Forces the session to flush. It is used to synchronize session data with database.

When you call session.flush(), the statements are executed in database but it will not committed. If you don’t call session.flush() and if you call session.commit() , internally commit() method executes the statement and commits.

So commit()= flush+commit. So session.flush() just executes the statements in database (but not commits) and statements are NOT IN MEMORY anymore. It just forces the session to flush.

Few important points:

We should avoid save outside transaction boundary, otherwise mapped entities will not be saved causing data inconsistency. It’s very normal to forget flushing the session because it doesn’t throw any exception or warnings. By default, Hibernate will flush changes automatically for you: before some query executions when a transaction is committed Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session)

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

How can I refresh or reload the JFrame?

You should use this code

this.setVisible(false); //this will close frame i.e. NewJFrame

new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed 

Force SSL/https using .htaccess and mod_rewrite

PHP Solution

Borrowing directly from Gordon's very comprehensive answer, I note that your question mentions being page-specific in forcing HTTPS/SSL connections.

function forceHTTPS(){
  $httpsURL = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  if( count( $_POST )>0 )
    die( 'Page should be accessed with HTTPS, but a POST Submission has been sent here. Adjust the form to point to '.$httpsURL );
  if( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS']!=='on' ){
    if( !headers_sent() ){
      header( "Status: 301 Moved Permanently" );
      header( "Location: $httpsURL" );
      exit();
    }else{
      die( '<script type="javascript">document.location.href="'.$httpsURL.'";</script>' );
    }
  }
}

Then, as close to the top of these pages which you want to force to connect via PHP, you can require() a centralised file containing this (and any other) custom functions, and then simply run the forceHTTPS() function.

HTACCESS / mod_rewrite Solution

I have not implemented this kind of solution personally (I have tended to use the PHP solution, like the one above, for it's simplicity), but the following may be, at least, a good start.

RewriteEngine on

# Check for POST Submission
RewriteCond %{REQUEST_METHOD} !^POST$

# Forcing HTTPS
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

# Forcing HTTP
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

How can I measure the similarity between two images?

The 'classic' way of measuring this is to break the image up into some canonical number of sections (say a 10x10 grid) and then computing a histogram of RGB values inside of each cell and compare corresponding histograms. This type of algorithm is preferred because of both its simplicity and it's invariance to scaling and (small!) translation.

API pagination best practices

If you've got pagination you also sort the data by some key. Why not let API clients include the key of the last element of the previously returned collection in the URL and add a WHERE clause to your SQL query (or something equivalent, if you're not using SQL) so that it returns only those elements for which the key is greater than this value?

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

Another reason could be because the filepath is empty where you are trying to write which is why it can't find it. just another reason why this error occurs.

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

"message failed to fetch from registry" while trying to install any module

It could be that the npm registry was down at the time or your connection dropped.

Either way you should upgrade node and npm.

I would recommend using nave to manage your node environments.

https://npmjs.org/package/nave

It allows you to easily install versions and quickly jump between them.

How to upload and parse a CSV file in php

untested but should give you the idea. the view:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>

upload.php controller:


$csv = array();

// check there are no errors
if($_FILES['csv']['error'] == 0){
    $name = $_FILES['csv']['name'];
    $ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
    $type = $_FILES['csv']['type'];
    $tmpName = $_FILES['csv']['tmp_name'];

    // check the file is a csv
    if($ext === 'csv'){
        if(($handle = fopen($tmpName, 'r')) !== FALSE) {
            // necessary if a large csv file
            set_time_limit(0);

            $row = 0;

            while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                // number of fields in the csv
                $col_count = count($data);

                // get the values from the csv
                $csv[$row]['col1'] = $data[0];
                $csv[$row]['col2'] = $data[1];

                // inc the row
                $row++;
            }
            fclose($handle);
        }
    }
}

Class 'ViewController' has no initializers in swift

Sometimes this error also appears when you have a var or a let that hasn't been intialized.

For example

class ViewController: UIViewController {
    var x: Double
    // or
    var y: String
    // or
    let z: Int
}

Depending on what your variable is supposed to do you might either set that var type as an optional or initialize it with a value like the following

class ViewController: UIViewCOntroller {
    // Set an initial value for the variable
    var x: Double = 0
    // or an optional String
    var y: String?
    // or
    let z: Int = 2
}

Compiling problems: cannot find crt1.o

This is a BUG reported in launchpad, but there is a workaround :

Run this to see where these files are located

$ find /usr/ -name crti*
/usr/lib/x86_64-linux-gnu/crti.o

then add this path to LIBRARY_PATH variable

$ export LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LIBRARY_PATH

Removing All Items From A ComboBox?

You need to remove each one individually unfortunately:

       For i = 1 To ListBox1.ListCount

           'Remove an item from the ListBox using ListBox1.RemoveItem 
       Next i

Update - I don't know why my answer did not include the full solution:

For i = ListBox1.ListCount - 1 to 0 Step - 1 
        ListBox1.RemoveItem i 
Next i 

Extreme wait-time when taking a SQL Server database offline

I tried all the suggestions below and nothing worked.

  1. EXEC sp_who
  2. Kill < SPID >

  3. ALTER DATABASE SET SINGLE_USER WITH Rollback Immediate

    ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE

    Result: Both the above commands were also stuck.

4 . Right-click the database -> Properties -> Options Set Database Read-Only to True Click 'Yes' at the dialog warning SQL Server will close all connections to the database.

Result: The window was stuck on executing.

As a last resort, I restarted the SQL server service from configuration manager and then ran ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE. It worked like a charm

How do I set path while saving a cookie value in JavaScript?

simply: document.cookie="name=value;path=/";

There is a negative point to it

Now, the cookie will be available to all directories on the domain it is set from. If the website is just one of many at that domain, it’s best not to do this because everyone else will also have access to your cookie information.

Validation of file extension before uploading file

$(function () {
    $('input[type=file]').change(function () {
        var val = $(this).val().toLowerCase(),
            regex = new RegExp("(.*?)\.(docx|doc|pdf|xml|bmp|ppt|xls)$");

        if (!(regex.test(val))) {
            $(this).val('');
            alert('Please select correct file format');
        }
    });
});

How to activate a specific worksheet in Excel?

Would the following Macro help you?

Sub activateSheet(sheetname As String)
'activates sheet of specific name
    Worksheets(sheetname).Activate
End Sub

Basically you want to make use of the .Activate function. Or you can use the .Select function like so:

Sub activateSheet(sheetname As String)
'selects sheet of specific name
    Sheets(sheetname).Select
End Sub

How to check if a variable is equal to one string or another string?

for a in soup("p",{'id':'pagination'})[0]("a",{'href': True}):
        if createunicode(a.text) in ['<','<']:
            links.append(a.attrMap['href'])
        else:
            continue

It works for me.

Returning a file to View/Download in ASP.NET MVC

Action method needs to return FileResult with either a stream, byte[], or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method. Sample video link How to download files using asp.net core

[Route("api/[controller]")]
public class DownloadController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Download()
    {
        var path = @"C:\Vetrivel\winforms.png";
        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
    }

    private Dictionary<string, string> GetMimeTypes()
    {
        return new Dictionary<string, string>
        {
            {".txt", "text/plain"},
            {".pdf", "application/pdf"},
            {".doc", "application/vnd.ms-word"},
            {".docx", "application/vnd.ms-word"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            ...
        };
    }
}

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

This should solve your problem. session_start() should be called before any character is sent back to the browser. In your case, HTML and blank lines were sent before you called session_start(). Documentation here.

To further explain your question of why it works when you submit to a different page, that page either do not use session_start() or calls session_start() before sending any character back to the client! This page on the other hand was calling session_start() much later when a lot of HTML has been sent back to the client (browser).

The better way to code is to have a common header file that calls connects to MySQL database, calls session_start() and does other common things for all pages and include that file on top of each page like below:

include "header.php";

This will stop issues like you are having as also allow you to have a common set of code to manage across a project. Something definitely for you to think about I would suggest after looking at your code.

<?php
session_start();

                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php



require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

SQL Server : trigger how to read value for Insert, Update, Delete

Here is the syntax to create a trigger:

CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
        [ WITH APPEND ]
        [ NOT FOR REPLICATION ]
        AS
        [ { IF UPDATE ( column )
            [ { AND | OR } UPDATE ( column ) ]
                [ ...n ]
        | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
                { comparison_operator } column_bitmask [ ...n ]
        } ]
        sql_statement [ ...n ]
    }
} 

If you want to use On Update you only can do it with the IF UPDATE ( column ) section. That's not possible to do what you are asking.

Bat file to run a .exe at the command prompt

If you want to be real smart, at the command line type:

echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd

Then you have CreateService.cmd that you can run whenever you want (.cmd is just another extension for .bat files)

Convert numpy array to tuple

I was not satisfied, so I finally used this:

>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])

>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)

I don't know if it's quicker, but it looks more effective ;)

Auto Generate Database Diagram MySQL

Try MySQL Workbench, formerly DBDesigner 4:

http://dev.mysql.com/workbench/

This has a "Reverse Engineer Database" mode:

Database -> Reverse Engineer

enter image description here

Difference between left join and right join in SQL Server

You seem to be asking, "If I can rewrite a RIGHT OUTER JOIN using LEFT OUTER JOIN syntax then why have a RIGHT OUTER JOIN syntax at all?" I think the answer to this question is, because the designers of the language didn't want to place such a restriction on users (and I think they would have been criticized if they did), which would force users to change the order of tables in the FROM clause in some circumstances when merely changing the join type.

Merge up to a specific commit

Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:

branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2

For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.

To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:

git co A
git co SHA-of-A2
git co -b AA

Then we created a branch BB from commit B3:

git co B
git co SHA-of-B3
git co -b BB

At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.

It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.

Statistics: combinations in Python

Using only standard library distributed with Python:

import itertools

def nCk(n, k):
    return len(list(itertools.combinations(range(n), k)))

Java: Calculating the angle between two points in degrees

you could add the following:

public float getAngle(Point target) {
    float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));

    if(angle < 0){
        angle += 360;
    }

    return angle;
}

by the way, why do you want to not use a double here?

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If You are trying to access it through Data Connections in Visual Studio 2015, and getting the above Error, Then Go to Advanced and set TrustServerCertificate=True for error to go away.

Add a common Legend for combined ggplots

@Guiseppe:

I have no idea of Grobs etc whatsoever, but I hacked together a solution for two plots, should be possible to extend to arbitrary number but its not in a sexy function:

plots <- list(p1, p2)
g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
tmp <- arrangeGrob(p1 + theme(legend.position = "none"), p2 + theme(legend.position = "none"), layout_matrix = matrix(c(1, 2), nrow = 1))
grid.arrange(tmp, legend, ncol = 1, heights = unit.c(unit(1, "npc") - lheight, lheight))

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

File sutest

#!/bin/bash
echo "uid is ${UID}"
echo "user is ${USER}"
echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500
user is stephenp
username is stephenp

but using sudo: sudo ./sutest gives

uid is 0
user is root
username is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bash
sudo -u ${USERNAME} normal_command_1
root_command_1
root_command_2
sudo -u ${USERNAME} normal_command_2
# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bash
sudo -u ${SUDO_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${SUDO_USER} normal_command_2
# etc.

A first stab at making it cross-platform could be...

#!/bin/bash
#
# set "THE_USER" to SUDO_USER if that's set,
#  else set it to USERNAME if THAT is set,
#   else set it to the string "unknown"
# should probably then test to see if it's "unknown"
#
THE_USER=${SUDO_USER:-${USERNAME:-unknown}}

sudo -u ${THE_USER} normal_command_1
root_command_1
root_command_2
sudo -u ${THE_USER} normal_command_2
# etc.

Laravel Migration table already exists, but I want to add new not the older

Also u may insert befor Schema::create('books', function(Blueprint $table) the following code Schema::drop('books');

Comment shortcut Android Studio

On PC it's by default set to Ctrl + /. This will toggle commenting a selection or current line.

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

In my case i have used .woff files from git repository, and i noticed git has changed my binary files. That with some null character at the file endings. I have rechanged to the orgnal .woff source files and it has corrected!

Also i have understood visual studio controller sending corrupted error like ERR_CONNECTION_RESET from the controller when it gots null character

I shared for all who live this problem

Getting all types in a namespace via reflection

You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.

Assembly.GetTypes() works on the local assembly, or you can load an assembly first then call GetTypes() on it.

URL encoding the space character: + or %20?

This confusion is because URLs are still 'broken' to this day.

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+
|      Part     |      Data         |
+---------------+-------------------+
|  Scheme       | http              |
|  Host         | www.google.com    |
+---------------+-------------------+

If we look at a more complex URL such as:

"https://bob:[email protected]:8080/file;p=1?q=2#third"

we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host             | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file;p=1           |
|  Path parameter   | p=1                 |
|  Query            | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

https://bob:[email protected]:8080/file;p=1?q=2#third
\___/   \_/ \___/ \______________/ \__/\_______/ \_/ \___/
  |      |    |          |          |      | \_/  |    |
Scheme User Password    Host       Port  Path |   | Fragment
        \_____________________________/       | Query
                       |               Path parameter
                   Authority

The reserved characters are different for each part.

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts:

"http://example.com/blue+light%20blue?blue%2Blight+blue".

From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

This boils down to:

You should have %20 before the ? and + after.

Source

How do I change the hover over color for a hover over table in Bootstrap?

For me @pvskisteak5 answer has caused a "flicker-effect". To fix this, add the following:

            .table-hover tbody tr:hover,
            .table-hover tbody tr:hover td,
            .table-hover tbody tr:hover th{
                background:#22313F !important;
                color:#fff !important;
            }

How does HTTP file upload work?

I have this sample Java Code:

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class TestClass {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(8081);
        Socket accept = socket.accept();
        InputStream inputStream = accept.getInputStream();

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        char readChar;
        while ((readChar = (char) inputStreamReader.read()) != -1) {
            System.out.print(readChar);
        }

        inputStream.close();
        accept.close();
        System.exit(1);
    }
}

and I have this test.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>File Upload!</title>
</head>
<body>
<form method="post" action="http://localhost:8081" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input type="submit">
</form>
</body>
</html>

and finally the file I will be using for testing purposes, named a.dat has the following content:

0x39 0x69 0x65

if you interpret the bytes above as ASCII or UTF-8 characters, they will actually will be representing:

9ie

So let 's run our Java Code, open up test.html in our favorite browser, upload a.dat and submit the form and see what our server receives:

POST / HTTP/1.1
Host: localhost:8081
Connection: keep-alive
Content-Length: 196
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary06f6g54NVbSieT6y
DNT: 1
Accept-Encoding: gzip, deflate
Accept-Language: en,en-US;q=0.8,tr;q=0.6
Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF

------WebKitFormBoundary06f6g54NVbSieT6y
Content-Disposition: form-data; name="file"; filename="a.dat"
Content-Type: application/octet-stream

9ie
------WebKitFormBoundary06f6g54NVbSieT6y--

Well I am not surprised to see the characters 9ie because we told Java to print them treating them as UTF-8 characters. You may as well choose to read them as raw bytes..

Cookie: JSESSIONID=27D0A0637A0449CF65B3CB20F40048AF 

is actually the last HTTP Header here. After that comes the HTTP Body, where meta and contents of the file we uploaded actually can be seen.

How can I run a php without a web server?

You should normally be able to run a php file (after a successful installation) just by running this command:

$ /path/to/php myfile.php // unix way
C:\php\php.exe myfile.php // windows way

You can read more about running PHP in CLI mode here.


It's worth adding that PHP from version 5.4 onwards is able to run a web server on its own. You can do it by running this code in a folder which you want to serve the pages from:

$ php -S localhost:8000

You can read more about running a PHP in a Web Server mode here.

Normalizing a list of numbers in Python

How long is the list you're going to normalize?

def psum(it):
    "This function makes explicit how many calls to sum() are done."
    print "Another call!"
    return sum(it)

raw = [0.07,0.14,0.07]
print "How many calls to sum()?"
print [ r/psum(raw) for r in raw]

print "\nAnd now?"
s = psum(raw)
print [ r/s for r in raw]

# if one doesn't want auxiliary variables, it can be done inside
# a list comprehension, but in my opinion it's quite Baroque    
print "\nAnd now?"
print [ r/s  for s in [psum(raw)] for r in raw]

Output

# How many calls to sum()?
# Another call!
# Another call!
# Another call!
# [0.25, 0.5, 0.25]
# 
# And now?
# Another call!
# [0.25, 0.5, 0.25]
# 
# And now?
# Another call!
# [0.25, 0.5, 0.25]

How to List All Redis Databases?

Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli:

$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1

Returning an empty array

Definitely the second one. In the first one, you use a constant empty List<?> and then convert it to a File[], which requires to create an empty File[0] array. And that is what you do in the second one in one single step.

How to not wrap contents of a div?

Forcing the buttons stay in the same line will make them go beyond the fixed width of the div they are in. If you are okay with that then you can make another div inside the div you already have. The new div in turn will hold the buttons and have the fixed width of however much space the two buttons need to stay in one line.

Here is an example:

<div id="parentDiv" style="width: [less-than-what-buttons-need]px;">
    <div id="holdsButtons" style="width: [>=-than-buttons-need]px;">
       <button id="button1">1</button>
       <button id="button2">2</button>
    </div>
</div>

You may want to consider overflow property for the chunk of the content outside of the parentDiv border.

Good luck!

Get unicode value of a character

First, I get the high side of the char. After, get the low side. Convert all of things in HexString and put the prefix.

int hs = (int) c  >> 8;
int ls = hs & 0x000F;

String highSide = Integer.toHexString(hs);
String lowSide = Integer.toHexString(ls);
lowSide = Integer.toHexString(hs & 0x00F0);
String hexa = Integer.toHexString( (int) c );

System.out.println(c+" = "+"\\u"+highSide+lowSide+hexa);

groovy: safely find a key in a map and return its value

The reason you get a Null Pointer Exception is because there is no key likesZZZ in your second example. Try:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likes" }.value
if(x)
    println "x value: ${x}"

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

Change language for bootstrap DateTimePicker

The option is locale: 'ru'

But first, you have to call the script ../moment.js/version/locale/ru.js

Hope this helps.

Avoid line break between html elements

There are several ways to prevent line breaks in content. Using &nbsp; is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.

The most robust alternative is to use nobr markup, which is nonstandard but universally supported and works even when CSS is disabled:

<td><nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</nobr></td>

(You can, but need not, use &nbsp; instead of spaces in this case.)

Another way is the nowrap attribute (deprecated/obsolete, but still working fine, except for some rare quirks):

<td nowrap><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>

Then there’s the CSS way, which works in CSS enabled browsers and needs a bit more code:

<style>
.nobr { white-space: nowrap }
</style>
...
<td class=nobr><i class="flag-bfh-ES"></i> +34 666 66 66 66</td>

Reading data from XML

Alternatively, you can use XPathNavigator:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();

string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");

..

/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
                                      XPathNavigator navigator, string xpath) {
    StringBuilder sb = new StringBuilder();
    sb.Append(description);
    XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
    while (bookNodesIterator.MoveNext())
       sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
    return sb.ToString();
}

What is the difference between PUT, POST and PATCH?

Request Types

  • create - POST
  • read - GET
  • create or update - PUT
  • delete - DELETE
  • update - PATCH

GET/PUT is idempotent PATCH can be sometimes idempotent

What is idempotent - It means if we fire the query multiple times it should not afftect the result of it.(same output.Suppose a cow is pregnant and if we breed it again then it cannot be pregnent multiple times)

get :-

simple get. Get the data from server and show it to user

{
id:1
name:parth
email:[email protected]
}

post :-

create new resource at Database. It means it adds new data. Its not idempotent.

put :-

Create new resource otherwise add to existing. Idempotent because it will update the same resource everytime and output will be the same. ex. - initial data

{
id:1
name:parth
email:[email protected]
}
{
id:1
email:[email protected]
}

patch

so now came patch request PATCH can be sometimes idempotent

id:1
name:parth
email:[email protected]
}

patch name:w

{
id:1
name:w
email:[email protected]
}
HTTP  Method
GET     yes
POST    no
PUT     yes
PATCH   no*
OPTIONS yes
HEAD    yes
DELETE  yes

Resources : Idempotent -- What is Idempotency?

Error: Cannot invoke an expression whose type lacks a call signature

I think what you want is:

abstract class Component {
  public deps: any = {};
  public props: any = {};

  public makePropSetter<T>(prop: string): (val: T) => T {
    return function(val) {
      this.props[prop] = val
      return val
    }
  }
}

class Post extends Component {
  public toggleBody: (val: boolean) => boolean;

  constructor () {
    super()
    this.toggleBody = this.makePropSetter<boolean>('showFullBody')
  }

  showMore (): boolean {
    return this.toggleBody(true)
  }

  showLess (): boolean {
    return this.toggleBody(false)
  }
}

The important change is in setProp (i.e., makePropSetter in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.

The <T> on makePropSetter allows you to lock that function in to a specific type. The <boolean> in the subclass's constructor is actually optional. Since you're assigning to toggleBody, and that already has the type fully specified, the TS compiler will be able to work it out on its own.

Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody respect that same signature.

How to pass a value to razor variable from javascript variable?

Step: 1 Your Html, First Store the value in your localstorage using javascript then add the line like below ,this is where you going to display the value in your html, my example is based on boostrap :

<label for="stringName" class="cols-sm-2 control-
label">@Html.Hidden("stringName", "")</label>

Step:2 Javascript

 $('#stringName').replaceWith(localStorage.getItem("itemName"));

Android Studio cannot resolve R in imported project?

Follow the five steps below:

  1. Step 1 ===>Delete(CTRL X) the additional tag(s) in XML manifest file.
  2. Step 2 ===>Open Build-->Clean project.
  3. Step 3 ===>Open XML manifest file and past the last additional tag(s) like: Tag Manifest file example: (<uses-permission android:name="android.permission.VIBRATE"></uses-permission>)
  4. Step 4 ===>Step 2 again.
  5. Step 5 ===> Open Tool-->Android-->Sync project with 'Gradle'.

I have had the same problem but after all the steps it's work for me.

SQL NVARCHAR and VARCHAR Limits

declare @p varbinary(max)
set @p = 0x
declare @local table (col text)

SELECT   @p = @p + 0x3B + CONVERT(varbinary(100), Email)
 FROM tbCarsList
 where email <> ''
 group by email
 order by email

 set @p = substring(@p, 2, 100000)

 insert @local values(cast(@p as varchar(max)))
 select DATALENGTH(col) as collen, col from @local

result collen > 8000, length col value is more than 8000 chars

PHP: How do you determine every Nth iteration of a loop?

The easiest way is to use the modulus division operator.

if ($counter % 3 == 0) {
   echo 'image file';
}

How this works: Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.

There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0.

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

My problems solved by remove all the runtime part

<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

How to use a jQuery plugin inside Vue

Option #1: Use ProvidePlugin

Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js and build/webpack.prod.conf.js so that jQuery becomes globally available to all your modules:

plugins: [

  // ...

  new webpack.ProvidePlugin({
    $: 'jquery',
    jquery: 'jquery',
    'window.jQuery': 'jquery',
    jQuery: 'jquery'
  })
]

Option #2: Use Expose Loader module for webpack

As @TremendusApps suggests in his answer, add the Expose Loader package:

npm install expose-loader --save-dev

Use in your entry point main.js like this:

import 'expose?$!expose?jQuery!jquery'

// ...

Node: log in a file instead of the console

You can now use Caterpillar which is a streams based logging system, allowing you to log to it, then pipe the output off to different transforms and locations.

Outputting to a file is as easy as:

var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');

Complete example on the Caterpillar Website

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

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

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

How to check encoding of a CSV file

Or you can execute in python console or in Jupyter Notebook:

import csv
data = open("file.csv","r") 
data

You will see information about the data object like this:

<_io.TextIOWrapper name='arch.csv' mode='r' encoding='cp1250'>

As you can see it contains encoding infotmation.

How can I center <ul> <li> into div

Could either be

div ul
{
 width: [INSERT FIXED WIDTH]
 margin: 0 auto;
}

or

div li
{
text-align: center;
}

depends on how it should look like (or combining those)

Convert from lowercase to uppercase all values in all character variables in dataframe

Alternatively, if you just want to convert one particular row to uppercase, use the code below:

df[[1]] <- toupper(df[[1]])

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

According to this thread, there is no way in Firebug to view what events are attached to listeners on a DOM element.

It looks like the best you can do is either what tj111 suggests, or you could right-click the element in the HTML viewer, and click "Log Events" so you can see which events are firing for a particular DOM element. I suppose one could do that to see what events could be firing off particular functions.

How do I automatically resize an image for a mobile site?

Your css with doesn't have any effect as the outer element doesn't have a width defined (and body is missing as well).

A different approach is to deliver already scaled images. http://www.sencha.com/products/io/ for example delivers the image already scaled down depending on the viewing device.

Calling Non-Static Method In Static Method In Java

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

If you're looking for a minimal solution that invalidates the cache, this edited version of Dr Manhattan's solution should be sufficient. Note that I'm specifying the root / directory to indicate I want the whole site refreshed.

export AWS_ACCESS_KEY_ID=<Key>
export AWS_SECRET_ACCESS_KEY=<Secret>
export AWS_DEFAULT_REGION=eu-west-1

echo "Invalidating cloudfrond distribution to get fresh cache"
aws cloudfront create-invalidation --distribution-id=<distributionId> --paths / --profile=<awsprofile>

Region Codes can be found here

You'll also need to create a profile using the aws cli. Use the aws configure --profile option. Below is an example snippet from Amazon.

$ aws configure --profile user2
AWS Access Key ID [None]: AKIAI44QH8DHBEXAMPLE
AWS Secret Access Key [None]: je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
Default region name [None]: us-east-1
Default output format [None]: text

Using :before CSS pseudo element to add image to modal

You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.

.Modal:before{
  content: '';
  background:url('blackCarrot.png');
  width: /* width of the image */;
  height: /* height of the image */;
  display: block;
}

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

Issue with background color and Google Chrome

I would try what Logan and 1mdm suggested, tho tweak the CSS, but I would really wait for a new Chrome version to come out with fixed bugs, before growing white hair.

IMHO the current Chrome version is still alpha version and was released so that it can spread while it is in development. I personally had issues with table widths, my code worked fine in EVERY browser but could not make it work in Chrome.

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

This should do it for you.

<div id="nav-wrap">
    <ul id="nav">
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
</div>

#nav-wrap {
    float: left;
    height: 87px;
    width: 900px;
}

#nav {
    display: inline;
    height: 87px;
    width: 100%;
}

.nav-item {
    float: left;
    height: 87px;
    line-height: 87px;
    text-align: center;
    text-decoration: none;
    width: 150px;

}

How do I detect what .NET Framework versions and service packs are installed?

Here is a PowerShell script to obtain installed .NET framework versions

function Get-KeyPropertyValue($key, $property)
{
    if($key.Property -contains $property)
    {
        Get-ItemProperty $key.PSPath -name $property | select -expand $property
    }
}

function Get-VersionName($key)
{
   $name = Get-KeyPropertyValue $key Version
   $sp = Get-KeyPropertyValue $key SP
   $install = Get-KeyPropertyValue $key Install
   if($sp)
   {
        "$($_.PSChildName) $name SP $sp"
   }
   else{
    "$($_.PSChildName) $name"
   }
}

function Get-FrameworkVersion{
   dir "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\" |? {$_.PSChildName -like "v*"} |%{
    if( $_.Property -contains "Version")
    {
        Get-VersionName $_
    }
    else{
        $parent = $_
        Get-ChildItem $_.PSPath |%{
            $versionName = Get-VersionName $_
            "$($parent.PSChildName) $versionName"
            }
        }
    }
}


$v4Directory = "hklm:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"
if(Test-Path $v4Directory)
{
    $v4 = Get-Item $v4Directory
    $version = Get-KeyPropertyValue $v4 Release
    switch($version){
        378389 {".NET Framework 4.5"; break;}
        378675 {".NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2"; break;}
        378758 {".NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2"; break;}
        379893 {".NET Framework 4.5.2"; break;}
        { 393295, 393297 -contains $_} {".NET Framework 4.6"; break;}
        { 394254, 394271 -contains $_} {".NET Framework 4.6.1"; break;}
        { 394802, 394806 -contains $_} {".NET Framework 4.6.2"; break; }
    }
}

It was written based on How to: Determine Which .NET Framework Versions Are Installed. Please use THE Get-FrameworkVersion() function to get information about installed .NET framework versions.

Angular.js programmatically setting a form field to dirty

you will have to manually set $dirty to true and $pristine to false for the field. If you want the classes to appear on your input, then you will have to manually add ng-dirty and remove ng-pristine classes from the element. You can use $setDirty() on the form level to do all of this on the form itself, but not the form inputs, form inputs do not currently have $setDirty() as you mentioned.

This answer may change in the future as they should add $setDirty() to inputs, seems logical.

Passing an array/list into a Python function

When you define your function using this syntax:

def someFunc(*args):
    for x in args
        print x

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):
    for x in myList:
        print x

Then you can call it with this:

items = [1,2,3,4,5]

someFunc(items)

You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):
    for x in args
        print x

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

MySQL: Grant **all** privileges on database

I could able to make it work only by adding GRANT OPTION, without that always receive permission denied error

GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost' WITH GRANT OPTION;

What is the standard way to add N seconds to datetime.time in Python?

You cannot simply add number to datetime because it's unclear what unit is used: seconds, hours, weeks...

There is timedelta class for manipulations with date and time. datetime minus datetime gives timedelta, datetime plus timedelta gives datetime, two datetime objects cannot be added although two timedelta can.

Create timedelta object with how many seconds you want to add and add it to datetime object:

>>> from datetime import datetime, timedelta
>>> t = datetime.now() + timedelta(seconds=3000)
>>> print(t)
datetime.datetime(2018, 1, 17, 21, 47, 13, 90244)

There is same concept in C++: std::chrono::duration.

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

This is more compact and respect the intial first position in array and just use the inital bound to add old value.

Public Sub ReDimPreserve(ByRef arr, ByVal size1 As Long, ByVal size2 As Long)
Dim arr2 As Variant
Dim x As Long, y As Long

'Check if it's an array first
If Not IsArray(arr) Then Exit Sub

'create new array with initial start
ReDim arr2(LBound(arr, 1) To size1, LBound(arr, 2) To size2)

'loop through first
For x = LBound(arr, 1) To UBound(arr, 1)
    For y = LBound(arr, 2) To UBound(arr, 2)
        'if its in range, then append to new array the same way
        arr2(x, y) = arr(x, y)
    Next
Next
'return byref
arr = arr2
End Sub

I call this sub with this line to resize the first dimension

ReDimPreserve arr2, UBound(arr2, 1) + 1, UBound(arr2, 2)

You can add an other test to verify if the initial size is not upper than new array. In my case it's not necessary

Show how many characters remaining in a HTML text box using JavaScript

Dynamic HTML element functionThe code in here with a little bit of modification and simplification:

<input disabled  maxlength="3" size="3" value="10" id="counter">
<textarea onkeyup="textCounter(this,'counter',10);" id="message">
</textarea>
<script>
function textCounter(field,field2,maxlimit)
{
 var countfield = document.getElementById(field2);
 if ( field.value.length > maxlimit ) {
  field.value = field.value.substring( 0, maxlimit );
  return false;
 } else {
  countfield.value = maxlimit - field.value.length;
 }
}
</script>

Hope this helps!

tip:

When merging the codes with your page, make sure the HTML elements(textarea, input) are loaded first before the scripts (Javascript functions)

CSS Input field text color of inputted text

To add color to an input, Use the following css code:

input{
     color: black;
}

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

My case is related to Greg B's -- Visual Studio creates two sites when SSL is enabled -- one for secure, and one for normal http requests. However Visual Studio chooses two ports at random, and depending on how you start the debugger you might be pointing towards the wrong page for the request type. Especially if you edit the URL but don't change the port number.

Seeing these posts jogged my memory.

I know this isn't APACHE related, but it is definitely a page that people with that error will find..

Table with 100% width with equal size columns

ALL YOU HAVE TO DO:

HTML:

<table id="my-table"><tr>
<td> CELL 1 With a lot of text in it</td>
<td> CELL 2 </td>
<td> CELL 3 </td>
<td> CELL 4 With a lot of text in it </td>
<td> CELL 5 </td>
</tr></table>

CSS:

#my-table{width:100%;} /*or whatever width you want*/
#my-table td{width:2000px;} /*something big*/

if you have th you need to set it too like this:

#my-table th{width:2000px;}

Can a table have two foreign keys?

CREATE TABLE User (
user_id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
userImage  LONGBLOB NOT NULL, 
Favorite VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);

and

CREATE TABLE Event (
    EventID INT NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (EventID),
    EventName VARCHAR(100) NOT NULL,
    EventLocation VARCHAR(100) NOT NULL,
    EventPriceRange VARCHAR(100) NOT NULL,
    EventDate Date NOT NULL,
    EventTime Time NOT NULL,
    EventDescription VARCHAR(255) NOT NULL,
    EventCategory VARCHAR(255) NOT NULL,
    EventImage  LONGBLOB NOT NULL,     
    index(EventID),
    FOREIGN KEY (EventID) REFERENCES User(user_id)
);

error: strcpy was not declared in this scope

This error sometimes occurs in a situation like this:

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

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

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

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

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

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

Document Root PHP

The Easiest way to do it is to have good site structure and write it as a constant.

DEFINE("BACK_ROOT","/var/www/");

java.util.Date vs java.sql.Date

I had the same issue, the easiest way i found to insert the current date into a prepared statement is this one:

preparedStatement.setDate(1, new java.sql.Date(new java.util.Date().getTime()));

How to check whether an array is empty using PHP?

Making the most appropriate decision requires knowing the quality of your data and what processes are to follow.

  1. If you are going to disqualify/disregard/remove this row, then the earliest point of filtration should be in the mysql query.
  • WHERE players IS NOT NULL
  • WHERE players != ''
  • WHERE COALESCE(players, '') != ''
  • WHERE players IS NOT NULL AND players != ''
  • ...it kind of depends on your store data and there will be other ways, I'll stop here.
  1. If you aren't 100% sure if the column will exist in the result set, then you should check that the column is declared. This will mean calling array_key_exists(), isset(), or empty() on the column. I am not going to bother delineating the differences here (there are other SO pages for that breakdown, here's a start: 1, 2, 3). That said, if you aren't in total control of the result set, then maybe you have over-indulged application "flexibility" and should rethink if the trouble of potentially accessing non-existent column data is worth it. Effectively, I am saying that you should never need to check if a column is declared -- ergo you should never need empty() for this task. If anyone is arguing that empty() is more appropriate, then they are pushing their own personal opinion about expressiveness of scripting. If you find the condition in #5 below to be ambiguous, add an inline comment to your code -- but I wouldn't. The bottom line is that there is no programmatical advantage to making the function call.

  2. Might your string value contain a 0 that you want to deem true/valid/non-empty? If so, then you only need to check if the column value has length.

Here is a Demo using strlen(). This will indicated whether or not the string will create meaningful array elements if exploded.

  1. I think it is important to mention that by unconditionally exploding, you are GUARANTEED to generate a non-empty array. Here's proof: Demo In other words, checking if the array is empty is completely useless -- it will be non-empty every time.

  2. If your string will NOT POSSIBLY contain a zero value (because, say, this is a csv consisting of ids which start from 1 and only increment), then if ($gamerow['players']) { is all you need -- end of story.

  3. ...but wait, what are you doing after determining the emptiness of this value? If you have something down-script that is expecting $playerlist, but you are conditionally declaring that variable, then you risk using the previous row's value or again generating Notices. So do you need to unconditionally declare $playerlist as something? If there are no truthy values in the string, does your application benefit from declaring an empty array? Chances are, the answer is yes. In this case, you can ensure that the variable is array-type by falling back to an empty array -- this way it won't matter if you feed that variable into a loop. The following conditional declarations are all equivalent.

  • if ($gamerow['players']) { $playerlist = explode(',', $gamerow['players']); } else { $playerlist = []; }
  • $playerlist = $gamerow['players'] ? explode(',', $gamerow['players']) : [];

Why have I gone to such length to explain this very basic task?

  1. I have whistleblown nearly every answer on this page and this answer is likely to draw revenge votes (this happens often to whistleblowers who defend this site -- if an answer has downvotes and no comments, always be skeptical).
  2. I think it is important that Stackoverflow is a trusted resource that doesn't poison researchers with misinformation and suboptimal techniques.
  3. This is how I show how much I care about upcoming developers so that they learn the how and the why instead of just spoon-feeding a generation of copy-paste programmers.
  4. I frequently use old pages to close new duplicate pages -- this is the responsibility of veteran volunteers who know how to quickly find duplicates. I cannot bring myself to use an old page with bad/false/suboptimal/misleading information as a reference because then I am actively doing a disservice to a new researcher.

Can regular JavaScript be mixed with jQuery?

Of course you can, but why do this? You have to include a <script></script>pair of tags that link to the jQuery web page, i.e.: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> . Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.

How can I check if a Perl module is installed on my system from the command line?

If you want to quickly check if a module is installed (at least on Unix systems, with Bash as shell), add this to your .bashrc file:

alias modver="perl -e\"eval qq{use \\\$ARGV[0];\\\\\\\$v=\\\\\\\$\\\${ARGV[0]}::VERSION;};\ print\\\$@?qq{No module found\\n}:\\\$v?qq{Version \\\$v\\n}:qq{Found.\\n};\"\$1"

Then you can:

=> modver XML::Simple
No module found

=> modver DBI
Version 1.607

Not an enclosing class error Android Studio

you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....

How to convert "0" and "1" to false and true

If you don't want to convert.Just use;

 bool _status = status == "1" ? true : false;

Perhaps you will return the values as you want.

Changing MongoDB data store directory

In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)

This is a bit of a hack, but adding these to the script made it start correctly:

add:

DBDIR=/database/mongodb

change:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}

to:

DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}

Retrieving parameters from a URL

parameters = dict([part.split('=') for part in get_parsed_url[4].split('&')])

This one is simple. The variable parameters will contain a dictionary of all the parameters.

An attempt was made to access a socket in a way forbidden by its access permissions

My windows firewall was blocking port 8080 so i changed it to 5000 and it worked!

Maven project version inheritance - do I have to specify the parent version?

EDIT: Since Maven 3.5.0 there is a nice solution for this using ${revision} placeholder. See FrVaBe's answer for details. For previous Maven versions see my original answer below.


No, there isn't. You always have to specify parent's version. Fortunately, it is inherited as the module's version what is desirable in most cases. Moreover, this parent's version declaration is bumped automatically by Maven Release Plugin, so - in fact - it's not a problem that you have version in 2 places as long as you use Maven Release Plugin for releasing or just bumping versions.

Notice that there are some cases when this behaviour is actually pretty OK and gives more flexibility you may need. Sometimes you want to use some of previous parent's version to inherit, however that's not a mainstream case.

what is the difference between const_iterator and iterator?

There is no performance difference.

A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value (const T&) and prevents modification of the referenced value: it enforces const-correctness.

When you have a const reference to the container, you can only get a const_iterator.

Edited: I mentionned “The const_iterator returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.

Edit: For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string use COW.)

how to use "tab space" while writing in text file

use \t instead of space.

bw.write("\t"); 

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

this is the key (vs evt.target). See example.

_x000D_
_x000D_
document.body.addEventListener("click", function (evt) {_x000D_
    console.dir(this);_x000D_
    //note evt.target can be a nested element, not the body element, resulting in misfires_x000D_
    console.log(evt.target);_x000D_
    alert("body clicked");_x000D_
});
_x000D_
<h4>This is a heading.</h4>_x000D_
<p>this is a paragraph.</p>
_x000D_
_x000D_
_x000D_

How do I clear my local working directory in Git?

To reset a specific file to the last-committed state (to discard uncommitted changes in a specific file):

git checkout thefiletoreset.txt

This is mentioned in the git status output:

(use "git checkout -- <file>..." to discard changes in working directory)

To reset the entire repository to the last committed state:

git reset --hard

To remove untracked files, I usually just delete all files in the working copy (but not the .git/ folder!), then do git reset --hard which leaves it with only committed files.

A better way is to use git clean (warning: using the -x flag as below will cause Git to delete ignored files):

git clean -d -x -f

will remove untracked files, including directories (-d) and files ignored by git (-x). Replace the -f argument with -n to perform a dry-run or -i for interactive mode, and it will tell you what will be removed.

Relevant links:

How to use mongoimport to import csv

My requirement was to import the .csv (with no headline) to remote MongoDB instance. For mongoimport v3.0.7below command worked for me:

mongoimport -h <host>:<port> -u <db-user> -p <db-password>  -d <database-name> -c <collection-name> --file <csv file location> --fields <name of the columns(comma seperated) in csv> --type csv

For example:

mongoimport -h 1234.mlab.com:61486 -u arpitaggarwal -p password  -d my-database -c employees --file employees.csv --fields name,email --type csv

Below is the screenshot of how it looks like after import:

enter image description here

where name and email are the columns in the .csv file.

Sort array of objects by single key with date value

  • Use Array.sort() to sort an array
  • Clone array using spread operator () to make the function pure
  • Sort by desired key (updated_at)
  • Convert date string to date object
  • Array.sort() works by subtracting two properties from current and next item if it is a number / object on which you can perform arrhythmic operations
const input = [
  {
    updated_at: '2012-01-01T06:25:24Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-09T11:25:13Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-05T04:13:24Z',
    foo: 'bar',
  }
];

const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));

const output = sortByUpdatedAt(input);

console.log(input);
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/

What does "where T : class, new()" mean?

That means that type T must be a class and have a constructor that does not take any arguments.

For example, you must be able to do this:

T t = new T();

What strategies and tools are useful for finding memory leaks in .NET?

I use Scitech's MemProfiler when I suspect a memory leak.

So far, I have found it to be very reliable and powerful. It has saved my bacon on at least one occasion.

The GC works very well in .NET IMO, but just like any other language or platform, if you write bad code, bad things happen.

How to link to a named anchor in Multimarkdown?

If you have headers in the markdown files, you can directly link them in the file.

Markdown Header -

## The Header

this will generate an implicit id #the-header (replace internal spaces with hyphens and make lowercase).

To navigate to this id, you can create the link like this:

[Link to Header](#the-header)

This is equivalent to:

<a href="#the-header">Link to Header</a>

Please note the reference's name is a lower-case #header.

SPAN vs DIV (inline-block)

If you want to have a valid xhtml document then you cannot put a div inside of a paragraph.

Also, a div with the property display: inline-block works differently than a span. A span is by default an inline element, you cannot set the width, height, and other properties associated with blocks. On the other hand, an element with the property inline-block will still "flow" with any surrounding text but you may set properties such as width, height, etc. A span with the property display:block will not flow in the same way as an inline-block element but will create a carriage return and have default margin.

Note that inline-block is not supported in all browsers. For instance in Firefox 2 and less you must use:

display: -moz-inline-stack;

which displays slightly different than an inline block element in FF3.

There is a great article here on creating cross browser inline-block elements.

How do I release memory used by a pandas dataframe?

As noted in the comments, there are some things to try: gc.collect (@EdChum) may clear stuff, for example. At least from my experience, these things sometimes work and often don't.

There is one thing that always works, however, because it is done at the OS, not language, level.

Suppose you have a function that creates an intermediate huge DataFrame, and returns a smaller result (which might also be a DataFrame):

def huge_intermediate_calc(something):
    ...
    huge_df = pd.DataFrame(...)
    ...
    return some_aggregate

Then if you do something like

import multiprocessing

result = multiprocessing.Pool(1).map(huge_intermediate_calc, [something_])[0]

Then the function is executed at a different process. When that process completes, the OS retakes all the resources it used. There's really nothing Python, pandas, the garbage collector, could do to stop that.

How to create a backup of a single table in a postgres database?

pg_dump -h localhost -p 5432 -U postgres -d mydb -t my_table > backup.sql

You can take the backup of a single table but I would suggest to take the backup of whole database and then restore whichever table you need. It is always good to have backup of whole database.

9 ways to use pg_dump

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

I encountered the same problem. It occurred because composer was not able to install the dependencies specified in composer.json file. try running

composer install 

If this does not solve the problem, make sure the following php modules are installed php-mbstring php-dom

To install this extensions run the following in terminal

sudo apt-get install php-mbstring php-dom

once the installation is complete

try running the command in your project root folder

composer install 

jQuery click function doesn't work after ajax call?

$('body').delegate('.deletelanguage','click',function(){
    alert("success");
});

or

$('body').on('click','.deletelanguage',function(){
    alert("success");
});

Is mongodb running?

Probably because I didn't shut down my dev server properly or a similar reason. To fix it, remove the lock and start the server with: sudo rm /var/lib/mongodb/mongod.lock ; sudo start mongodb

Unique random string generation

This works perfect for me

    private string GeneratePasswordResetToken()
    {
        string token = Guid.NewGuid().ToString();
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(token);
        return Convert.ToBase64String(plainTextBytes);
    }

Entity framework code-first null foreign key

You must make your foreign key nullable:

public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    public virtual Country Country { get; set; }
}

I can not find my.cnf on my windows computer

Start->Search->For Files and Folders->All Files and Folders

type "my.cnf" and hit search.

Comparing floating point number to zero

2 + 2 = 5(*)

(for some floating-precision values of 2)

This problem frequently arises when we think of"floating point" as a way to increase precision. Then we run afoul of the "floating" part, which means there is no guarantee of which numbers can be represented.

So while we might easily be able to represent "1.0, -1.0, 0.1, -0.1" as we get to larger numbers we start to see approximations - or we should, except we often hide them by truncating the numbers for display.

As a result, we might think the computer is storing "0.003" but it may instead be storing "0.0033333333334".

What happens if you perform "0.0003 - 0.0002"? We expect .0001, but the actual values being stored might be more like "0.00033" - "0.00029" which yields "0.000004", or the closest representable value, which might be 0, or it might be "0.000006".

With current floating point math operations, it is not guaranteed that (a / b) * b == a.

#include <stdio.h>

// defeat inline optimizations of 'a / b * b' to 'a'
extern double bodge(int base, int divisor) {
    return static_cast<double>(base) / static_cast<double>(divisor);
}

int main() {
    int errors = 0;
    for (int b = 1; b < 100; ++b) {
        for (int d = 1; d < 100; ++d) {
            // b / d * d ... should == b
            double res = bodge(b, d) * static_cast<double>(d);
            // but it doesn't always
            if (res != static_cast<double>(b))
                ++errors;
        }
    }
    printf("errors: %d\n", errors);
}

ideone reports 599 instances where (b * d) / d != b using just the 10,000 combinations of 1 <= b <= 100 and 1 <= d <= 100 .

The solution described in the FAQ is essentially to apply a granularity constraint - to test if (a == b +/- epsilon).

An alternative approach is to avoid the problem entirely by using fixed point precision or by using your desired granularity as the base unit for your storage. E.g. if you want times stored with nanosecond precision, use nanoseconds as your unit of storage.

C++11 introduced std::ratio as the basis for fixed-point conversions between different time units.

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

in your Project perspective, look for Application --> build.gradle and edit this lines

android { compileSdkVersion "android-N" buildToolsVersion "24.0.0 rc1"

like this:

android { compileSdkVersion 24 buildToolsVersion "23.0.3"

Is there a way to set background-image as a base64 encoded image?

I tried this (and worked for me):

var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(\'' + img + '\')';

ES6 syntax:

let img = 'data:image/png;base64, ...'
document.body.style.backgroundImage = `url('${img}')`

A bit better:

let setBackground = src => {
    this.style.backgroundImage = `url('${src}')`
};

let node = nodeIGotFromDOM, img = imageBase64EncodedFromMyGF;
setBackground.call(node, img);

Squash the first two commits in Git?

This will squash second commit into the first one:

A-B-C-... -> AB-C-...

git filter-branch --commit-filter '
    if [ "$GIT_COMMIT" = <sha1ofA> ];
    then
        skip_commit "$@";
    else
        git commit-tree "$@";
    fi
' HEAD

Commit message for AB will be taken from B (although I'd prefer from A).

Has the same effect as Uwe Kleine-König's answer, but works for non-initial A as well.

Proper way to get page content

One liner:

<? if (have_posts()):while(have_posts()): the_post(); the_content(); endwhile; endif; ?>