Programs & Examples On #Gnustep

a free implementation of Cocoa (formerly NeXT's OpenStep) Objective-C libraries (called frameworks), widget toolkit, and application development tools. It is part of the GNU Project.

Configuring RollingFileAppender in log4j

Update: at least as early as 2013 (see Mubashar's comment) this started working.


According to Log4jXmlFormat you cannot configure it with log4j.properties, but only using the XML config format:

Note that TimeBasedRollingPolicy can only be configured with xml, not log4j.properties

Unfortunately, the example log4j.xml they provide doesn't work either:

log4j:ERROR Parsing error on line 14 and column 76
log4j:ERROR Element type "rollingPolicy" must be declared.
...
log4j:WARN Please set a rolling policy for the RollingFileAppender named 'FILE'

Java finished with non-zero exit value 2 - Android Gradle

I think it's conflicts of .jar file in your project.

I have removed android-support-v4.jar from libs folder and its working !!!

if your project gives error, check in your build.gradle file

dependencies {

}

mongodb group values by multiple fields

Using aggregate function like below :

[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]

it will give you result like following :

        {
            "total" : 1,
            "book" : "book33",
            "address" : "address90"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address1"
        }, 
        {
            "total" : 1,
            "book" : "book99",
            "address" : "address9"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address5"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address2"
        }, 
        {
            "total" : 1,
            "book" : "book3",
            "address" : "address4"
        }, 
        {
            "total" : 1,
            "book" : "book11",
            "address" : "address77"
        }, 
        {
            "total" : 1,
            "book" : "book9",
            "address" : "address3"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address15"
        }, 
        {
            "total" : 2,
            "book" : "book1",
            "address" : "address2"
        }, 
        {
            "total" : 3,
            "book" : "book1",
            "address" : "address1"
        }

I didn't quite get your expected result format, so feel free to modify this to one you need.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

This worked for me with Nginx, Node server and Angular 4

Edit your nginx web server config file as:

server {
listen 80;
server_name 52.xx.xxx.xx;

location / {
    proxy_set_header   X-Forwarded-For $remote_addr;
    proxy_set_header   Host $http_host;
    proxy_pass         "http://127.0.0.1:4200";
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
}

Android Studio - Auto complete and other features not working

If nothing works (like happened with me ) go to your user profile in windows at %userprofile% . You will find folders there (hidden) named with the version of the android studio you are using and prefixed with a dot.

like .AndroidStudio3.1. Just delete that .

How do I force git pull to overwrite everything on every pull?

I'm not sure how to do it in one command but you could do something like:

git reset --hard
git pull

or even

git stash
git pull

Returning the product of a list

I remember some long discussions on comp.lang.python (sorry, too lazy to produce pointers now) which concluded that your original product() definition is the most Pythonic.

Note that the proposal is not to write a for loop every time you want to do it, but to write a function once (per type of reduction) and call it as needed! Calling reduction functions is very Pythonic - it works sweetly with generator expressions, and since the sucessful introduction of sum(), Python keeps growing more and more builtin reduction functions - any() and all() are the latest additions...

This conclusion is kinda official - reduce() was removed from builtins in Python 3.0, saying:

"Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable."

See also The fate of reduce() in Python 3000 for a supporting quote from Guido (and some less supporting comments by Lispers that read that blog).

P.S. if by chance you need product() for combinatorics, see math.factorial() (new 2.6).

C++ Structure Initialization

As others have mentioned this is designated initializer.

This feature is part of C++20

How to split a string with any whitespace chars as delimiters

Apache Commons Lang has a method to split a string with whitespace characters as delimiters:

StringUtils.split("abc def")

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split(java.lang.String)

This might be easier to use than a regex pattern.

Check If only numeric values were entered in input. (jQuery)

I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.

$('#txtbox').on('paste', function (e) {
            var $this = $(this);
            setTimeout(function (e) {
                if (($this.val()).match(/[^0-9]/g))
                {
                    $("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");                       
                    setTimeout(function (e) {
                        $this.val(null);
                    },2500);
                }                   
            }, 5);
        });

C++ floating point to integer type conversions

For most cases (long for floats, long long for double and long double):

long a{ std::lround(1.5f) }; //2l
long long b{ std::llround(std::floor(1.5)) }; //1ll

Resizing an image in an HTML5 canvas

This is a javascript function adapted from @Telanor's code. When passing a image base64 as first argument to the function, it returns the base64 of the resized image. maxWidth and maxHeight are optional.

function thumbnail(base64, maxWidth, maxHeight) {

  // Max size for thumbnail
  if(typeof(maxWidth) === 'undefined') var maxWidth = 500;
  if(typeof(maxHeight) === 'undefined') var maxHeight = 500;

  // Create and initialize two canvas
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  var canvasCopy = document.createElement("canvas");
  var copyContext = canvasCopy.getContext("2d");

  // Create original image
  var img = new Image();
  img.src = base64;

  // Determine new ratio based on max size
  var ratio = 1;
  if(img.width > maxWidth)
    ratio = maxWidth / img.width;
  else if(img.height > maxHeight)
    ratio = maxHeight / img.height;

  // Draw original image in second canvas
  canvasCopy.width = img.width;
  canvasCopy.height = img.height;
  copyContext.drawImage(img, 0, 0);

  // Copy and resize second canvas to first canvas
  canvas.width = img.width * ratio;
  canvas.height = img.height * ratio;
  ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

  return canvas.toDataURL();

}

How to Validate Google reCaptcha on Form Submit

//validate
$receivedRecaptcha = $_POST['recaptchaRes'];
$google_secret =  "Yoursecretgooglepapikey";
$verifiedRecaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify?secret='.$google_secret.'&response='.$receivedRecaptcha;
$handle = curl_init($verifiedRecaptchaUrl);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // not safe but works
//curl_setopt($handle, CURLOPT_CAINFO, "./my_cert.pem"); // safe
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if ($httpCode >= 200 && $httpCode < 300) {
  if (strlen($response) > 0) {
        $responseobj = json_decode($response);
        if(!$responseobj->success) {
            echo "reCAPTCHA is not valid. Please try again!";
            }
        else {
            echo "reCAPTCHA is valid.";
        }
    }
} else {
  echo "curl failed. http code is ".$httpCode;
}

Relative div height

The div take the height of its parent, but since it has no content (expecpt for your divs) it will only be as height as its content.

You need to set the height of the body and html:

HTML:

<div class="block12">
    <div class="block1">1</div>
    <div class="block2">2</div>
</div>
<div class="block3">3</div>

CSS:

body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
.block12 {
    width: 100%;
    height: 50%;
    background: yellow;
    overflow: auto;
}
.block1, .block2 {
    width: 50%;
    height: 100%;
    display: inline-block;
    margin-right: -4px;
    background: lightgreen;
}
.block2 { background: lightgray }
.block3 {
    width: 100%;
    height: 50%;
    background: lightblue;
}

And a JSFiddle

Create an array with same element repeated multiple times

You can use the SpreadOpeator and the map() function to create an array with the same element repeated multiple times.

function fillArray(value,len){
       return [...Array(len).keys()].map(x=> value);
   }

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

In my case, I found that I set the post method as private mistakenly. after changing private to public.

[HttpPost]
private async Task<ActionResult> OnPostRemoveForecasting(){}

change to

[HttpPost]
public async Task<ActionResult> OnPostRemoveForecasting(){}

Now works fine.

Best way to remove from NSMutableArray while iterating?

In a more declarative way, depending on the criteria matching the items to remove you could use:

[theArray filterUsingPredicate:aPredicate]

@Nathan should be very efficient

Play/pause HTML 5 video using JQuery

For pausing multiple videos I have found that this works nicely:

$("video").each(function(){
    $(this).get(0).pause();
});

This can be put into a click function which is quite handy.

Bootstrap Dropdown menu is not working

100% working solution

just place your Jquery link first of all js and css links

Example Correct

<script src="jquery/jquery.js"></script>
<script type="text/javascript" src='js/bootstrap.min.js'></script>
<link rel="stylesheet" href="css/bootstrap.css" />

Example Wrong!

<script type="text/javascript" src='js/bootstrap.min.js'></script>
<link rel="stylesheet" href="css/bootstrap.css" />
<script src="jquery/jquery.js"></script>

Compare two files and write it to "match" and "nomatch" files

Though its really long back this question was posted, I wish to answer as it might help others. This can be done easily by means of JOINKEYS in a SINGLE step. Here goes the pseudo code:

  • Code JOINKEYS PAIRED(implicit) and get both the records via reformatting filed. If there is NO match from either of files then append/prefix some special character say '$'
  • Compare via IFTHEN for '$', if exists then it doesnt have a paired record, it'll be written into unpaired file and rest to paired file.

Please do get back incase of any questions.

Change Background color (css property) using Jquery

Try below jQuery snippet, you can change color :

<script type="text/javascript">
    $(document).ready(function(){
        $("#co").click(function() {
            $("body").css("background-color", "yellow");
        });
    });
</script>

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("#co").click(function() {_x000D_
        $("body").css("background-color", "yellow");_x000D_
    });_x000D_
});
_x000D_
body {_x000D_
    background-color:red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="co" click="change()">hello</div>
_x000D_
_x000D_
_x000D_

How to apply bold text style for an entire row using Apache POI?

This should work fine.

    Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
    Row row=sheet.getRow(0);
    CellStyle style=null;

    XSSFFont defaultFont= wb.createFont();
    defaultFont.setFontHeightInPoints((short)10);
    defaultFont.setFontName("Arial");
    defaultFont.setColor(IndexedColors.BLACK.getIndex());
    defaultFont.setBold(false);
    defaultFont.setItalic(false);

    XSSFFont font= wb.createFont();
    font.setFontHeightInPoints((short)10);
    font.setFontName("Arial");
    font.setColor(IndexedColors.WHITE.getIndex());
    font.setBold(true);
    font.setItalic(false);

    style=row.getRowStyle();
    style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFont(font);

If you do not create defaultFont all your workbook will be using the other one as default.

Java and SQLite

The wiki lists some more wrappers:

curl: (6) Could not resolve host: application

Windows consoles usually doesnt interpret double quotes correctly in a JSON array, so you can solve it adding a slash / before double quotes.

Can I add an image to an ASP.NET button?

I actually prefer to use the html button form element and make it runat=server. The button element can hold other elements inside it. You can even add formatting inside it with span's or strong's. Here is an example:

<button id="BtnSave" runat="server"><img src="Images/save.png" />Save</button>

add allow_url_fopen to my php.ini using .htaccess

allow_url_fopen is generally set to On. If it is not On, then you can try two things.

  1. Create an .htaccess file and keep it in root folder ( sometimes it may need to place it one step back folder of the root) and paste this code there.

    php_value allow_url_fopen On
    
  2. Create a php.ini file (for update server php5.ini) and keep it in root folder (sometimes it may need to place it one step back folder of the root) and paste the following code there:

    allow_url_fopen = On;
    

I have personally tested the above solutions; they worked for me.

Measuring elapsed time with the Time module

For a longer period.

import time
start_time = time.time()
...
e = int(time.time() - start_time)
print('{:02d}:{:02d}:{:02d}'.format(e // 3600, (e % 3600 // 60), e % 60))

would print

00:03:15

if more than 24 hours

25:33:57

That is inspired by Rutger Hofste's answer. Thank you Rutger!

Convert long/lat to pixel x/y on a given picture

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://stackoverflow.com/a/10401734/730823

How can I make Java print quotes, like "Hello"?

Take note, there are a few certain things to take note when running backslashes with specific characters.

System.out.println("Hello\\\");

The output above will be:

Hello\


System.out.println(" Hello\"  ");

The output above will be:

Hello"

How can I throw CHECKED exceptions from inside Java 8 streams?

TL;DR Just use Lombok's @SneakyThrows.

Christian Hujer has already explained in detail why throwing checked exceptions from a stream is, strictly speaking, not possible due to Java's limitations.

Some other answers have explained tricks to get around the limitations of the language but still being able to fulfil the requirement of throwing "the checked exception itself, and without adding ugly try/catches to the stream", some of them requiring tens of additional lines of boilerplate.

I am going to highlight another option for doing this that IMHO is far cleaner than all the others: Lombok's @SneakyThrows. It has been mentioned in passing by other answers but was a bit buried under a lot of unnecessary detail.

The resulting code is as simple as:

public List<Class> getClasses() throws ClassNotFoundException {
    List<Class> classes =
        Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
                .map(className -> getClass(className))
                .collect(Collectors.toList());
    return classes;
}

@SneakyThrows                                 // <= this is the only new code
private Class<?> getClass(String className) {
    return Class.forName(className);
}

We just needed one Extract Method refactoring (done by the IDE) and one additional line for @SneakyThrows. The annotation takes care of adding all the boilerplate to make sure that you can throw your checked exception without wrapping it in a RuntimeException and without needing to declare it explicitly.

React js onClick can't pass value to method

I have below 3 suggestion to this on JSX onClick Events -

  1. Actually, we don't need to use .bind() or Arrow function in our code. You can simple use in your code.

  2. You can also move onClick event from th(or ul) to tr(or li) to improve the performance. Basically you will have n number of "Event Listeners" for your n li element.

    So finally code will look like this:
    <ul onClick={this.onItemClick}>
        {this.props.items.map(item =>
               <li key={item.id} data-itemid={item.id}>
                   ...
               </li>
          )}
    </ul>
    

    // And you can access item.id in onItemClick method as shown below:

    onItemClick = (event) => {
       console.log(e.target.getAttribute("item.id"));
    }
    
  3. I agree with the approach mention above for creating separate React Component for ListItem and List. This make code looks good however if you have 1000 of li then 1000 Event Listeners will be created. Please make sure you should not have much event listener.

    import React from "react";
    import ListItem from "./ListItem";
    export default class List extends React.Component {
    
        /**
        * This List react component is generic component which take props as list of items and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = (item) => {
            if (this.props.onItemClick) {
                this.props.onItemClick(item);
            }
        }
    
        /**
        * render method will take list of items as a props and include ListItem component
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <div>
                  {this.props.items.map(item =>
                      <ListItem key={item.id} item={item} onItemClick={this.handleItemClick}/>
                  )}
                </div>
            );
        }
    
    }
    
    
    import React from "react";
    
    export default class ListItem extends React.Component {
        /**
        * This List react component is generic component which take props as item and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = () => {
            if (this.props.item && this.props.onItemClick) {
                this.props.onItemClick(this.props.item);
            }
        }
        /**
        * render method will take item as a props and print in li
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <li key={this.props.item.id} onClick={this.handleItemClick}>{this.props.item.text}</li>
            );
        }
    }
    

SQL query for finding records where count > 1

I wouldn't recommend the HAVING keyword for newbies, it is essentially for legacy purposes.

I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:

I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.

So I've taken a literal interpretation.

The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES but it could be a VIEW:

WITH PAYMENT_TALLIES (user_id, zip, tally)
     AS
     (
      SELECT user_id, zip, COUNT(*) AS tally
        FROM PAYMENT
       GROUP 
          BY user_id, zip
     )
SELECT DISTINCT *
  FROM PAYMENT AS P
 WHERE EXISTS (
               SELECT * 
                 FROM PAYMENT_TALLIES AS PT
                WHERE P.user_id = PT.user_id
                      AND PT.tally > 1
              );

How do I detect if software keyboard is visible on Android Device or not?

I did this by setting a GlobalLayoutListener, as follows:

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightView = activityRootView.getHeight();
                int widthView = activityRootView.getWidth();
                if (1.0 * widthView / heightView > 3) {
                    //Make changes for Keyboard not visible
                } else {
                    //Make changes for keyboard visible
                }
            }
        });

How to get substring from string in c#?

it's easy to rewrite this code in C#...

This method works if your value it's between 2 substrings !

for example:

stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"

calls should be:

myNameValue = SplitStringByASubstring(stringContent , "[myName]")

colorValue = SplitStringByASubstring(stringContent , "[color]")

etcValue = SplitStringByASubstring(stringContent , "[etc]")

How do you set the Content-Type header for an HttpClient request?

The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json in two places-for Accept and Content-Type headers):

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
                                    Encoding.UTF8, 
                                    "application/json");//CONTENT-TYPE header

client.SendAsync(request)
      .ContinueWith(responseTask =>
      {
          Console.WriteLine("Response: {0}", responseTask.Result);
      });

"Could not find bundler" error

The command is bundle update (there is no "r" in the "bundle").

To check if bundler is installed do : gem list bundler or even which bundle and the command will list either the bundler version or the path to it. If nothing is shown, then install bundler by typing gem install bundler.

Creating lowpass filter in SciPy - understanding methods and units

A few comments:

  • The Nyquist frequency is half the sampling rate.
  • You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use analog=True in the call to butter, and you should use scipy.signal.freqz (not freqs) to generate the frequency response.
  • One goal of those short utility functions is to allow you to leave all your frequencies expressed in Hz. You shouldn't have to convert to rad/sec. As long as you express your frequencies with consistent units, the scaling in the utility functions takes care of the normalization for you.

Here's my modified version of your script, followed by the plot that it generates.

import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt


def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y


# Filter requirements.
order = 6
fs = 30.0       # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)

# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()


# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0         # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()

lowpass example

Can constructors be async?

Some of the answers involve creating a new public method. Without doing this, use the Lazy<T> class:

public class ViewModel
{
    private Lazy<ObservableCollection<TData>> Data;

    async public ViewModel()
    {
        Data = new Lazy<ObservableCollection<TData>>(GetDataTask);
    }

    public ObservableCollection<TData> GetDataTask()
    {
        Task<ObservableCollection<TData>> task;

        //Create a task which represents getting the data
        return task.GetAwaiter().GetResult();
    }
}

To use Data, use Data.Value.

Shuffle an array with python, randomize array item order with python

I don't know I used random.shuffle() but it return 'None' to me, so I wrote this, might helpful to someone

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

Align two divs horizontally side by side center to the page using bootstrap css

Anyone going for Bootstrap 5 (beta as on date), here is what worked for me. In my case, I had to align two items in the card's header section side-by-side:

<div class="card small-card text-white bg-secondary">
    <div class="d-flex justify-content-between card-header">
        <div class="col-md-6 col-sm-6">
            <h4>100+ Components</h4>
        </div>
        <div class="ml-auto">
        <!--<div class="col-md-6 col-sm-6 ml-auto"> -->
            <i class="data-feather hoverzoom" data-feather="grid"></i>
        </div>
    </div>
    <div class="card-body">
        <p>Lorem ipsum dolor sit amet, adipscing elitr, sed diam
            nonumy eirmod tempor ividunt labor dolore magna.</p>
    </div>
</div>

The catch here is justify-content-between and ml-auto. You can get more info here at the official link. And a live working example here.

API pagination best practices

Just to add to this answer by Kamilk : https://www.stackoverflow.com/a/13905589

Depends a lot on how large dataset you are working on. Small data sets do work on effectively on offset pagination but large realtime datasets do require cursor pagination.

Found a wonderful article on how Slack evolved its api's pagination as there datasets increased explaining the positives and negatives at every stage : https://slack.engineering/evolving-api-pagination-at-slack-1c1f644f8e12

how to release localhost from Error: listen EADDRINUSE

simply kill the node as pkill -9 node in terminal of ubantu than start node

How do I improve ASP.NET MVC application performance?

Use the latest version of Task Parallel Library (TPL), according to .Net version. Have to choose the correct modules of TPL for different purposes.

All com.android.support libraries must use the exact same version specification

I ran ./gradlew tasks --all and checked for dependencies that were a different version from the targeted version (25.3.1). You'll get something like this:

app:prepareComAndroidSupportAnimatedVectorDrawable2531Library - Prepare com.android.support:animated-vector-drawable:25.3.1
app:prepareComAndroidSupportAppcompatV72531Library - Prepare com.android.support:appcompat-v7:25.3.1
app:prepareComAndroidSupportCardviewV72531Library - Prepare com.android.support:cardview-v7:25.3.1
app:prepareComAndroidSupportCustomtabs2531Library - Prepare com.android.support:customtabs:25.3.1
app:prepareComAndroidSupportDesign2531Library - Prepare com.android.support:design:25.3.1
app:prepareComAndroidSupportMediarouterV72531Library - Prepare com.android.support:mediarouter-v7:25.3.1
app:prepareComAndroidSupportPaletteV72531Library - Prepare com.android.support:palette-v7:25.3.1
app:prepareComAndroidSupportRecyclerviewV72531Library - Prepare com.android.support:recyclerview-v7:25.3.1
app:prepareComAndroidSupportSupportCompat2531Library - Prepare com.android.support:support-compat:25.3.1
app:prepareComAndroidSupportSupportCoreUi2531Library - Prepare com.android.support:support-core-ui:25.3.1
app:prepareComAndroidSupportSupportCoreUtils2531Library - Prepare com.android.support:support-core-utils:25.3.1
app:prepareComAndroidSupportSupportFragment2531Library - Prepare com.android.support:support-fragment:25.3.1
app:prepareComAndroidSupportSupportMediaCompat2531Library - Prepare com.android.support:support-media-compat:25.3.1
app:prepareComAndroidSupportSupportV42531Library - Prepare com.android.support:support-v4:25.3.1
app:prepareComAndroidSupportSupportVectorDrawable2531Library - Prepare com.android.support:support-vector-drawable:25.3.1
app:prepareComAndroidSupportTransition2531Library - Prepare com.android.support:transition:25.3.1
app:prepareComAndroidVolleyVolley100Library - Prepare com.android.volley:volley:1.0.0
app:prepareComCrashlyticsSdkAndroidAnswers1312Library - Prepare com.crashlytics.sdk.android:answers:1.3.12
app:prepareComCrashlyticsSdkAndroidBeta124Library - Prepare com.crashlytics.sdk.android:beta:1.2.4
app:prepareComCrashlyticsSdkAndroidCrashlytics267Library - Prepare com.crashlytics.sdk.android:crashlytics:2.6.7
app:prepareComCrashlyticsSdkAndroidCrashlyticsCore2316Library - Prepare com.crashlytics.sdk.android:crashlytics-core:2.3.16
app:prepareComFacebookAndroidFacebookAndroidSdk4161Library - Prepare com.facebook.android:facebook-android-sdk:4.16.1
app:prepareComGoogleAndroidGmsPlayServicesAnalytics1026Library - Prepare com.google.android.gms:play-services-analytics:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesAnalyticsImpl1026Library - Prepare com.google.android.gms:play-services-analytics-impl:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesAuth1026Library - Prepare com.google.android.gms:play-services-auth:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesAuthBase1026Library - Prepare com.google.android.gms:play-services-auth-base:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesBase1026Library - Prepare com.google.android.gms:play-services-base:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesBasement1026Library - Prepare com.google.android.gms:play-services-basement:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesCast1026Library - Prepare com.google.android.gms:play-services-cast:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesLocation1026Library - Prepare com.google.android.gms:play-services-location:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesMaps1026Library - Prepare com.google.android.gms:play-services-maps:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesTagmanagerV4Impl1026Library - Prepare com.google.android.gms:play-services-tagmanager-v4-impl:10.2.6
app:prepareComGoogleAndroidGmsPlayServicesTasks1026Library - Prepare com.google.android.gms:play-services-tasks:10.2.6
app:prepareComGoogleFirebaseFirebaseAnalytics1026Library - Prepare com.google.firebase:firebase-analytics:10.2.6
app:prepareComGoogleFirebaseFirebaseAnalyticsImpl1026Library - Prepare com.google.firebase:firebase-analytics-impl:10.2.6
app:prepareComGoogleFirebaseFirebaseAppindexing1024Library - Prepare com.google.firebase:firebase-appindexing:10.2.4
app:prepareComGoogleFirebaseFirebaseCommon1026Library - Prepare com.google.firebase:firebase-common:10.2.6
app:prepareComGoogleFirebaseFirebaseCore1026Library - Prepare com.google.firebase:firebase-core:10.2.6
app:prepareComGoogleFirebaseFirebaseIid1026Library - Prepare com.google.firebase:firebase-iid:10.2.6
app:prepareComGoogleFirebaseFirebaseMessaging1026Library - Prepare com.google.firebase:firebase-messaging:10.2.6
app:prepareComMindorksPlaceholderview027Library - Prepare com.mindorks:placeholderview:0.2.7
app:prepareDebugAndroidTestDependencies
app:prepareDebugDependencies
app:prepareDebugUnitTestDependencies
app:prepareInfoHoang8fAndroidSegmented105Library - Prepare info.hoang8f:android-segmented:1.0.5
app:prepareIoFabricSdkAndroidFabric1316Library - Prepare io.fabric.sdk.android:fabric:1.3.16
app:prepareNoNordicsemiAndroidLog211Library - Prepare no.nordicsemi.android:log:2.1.1
app:prepareNoNordicsemiAndroidSupportV18Scanner100Library - Prepare no.nordicsemi.android.support.v18:scanner:1.0.0

In this case, I was targeting 25.3.1, and had some dependencies targeting different versions when I ran this command. The trick is to identify the dependencies in this list that are targeting previous versions, and overriding that by importing the most recent version of the dependency in Gradle.

Accessing a value in a tuple that is in a list

Ignacio's answer is what you want. However, as someone also learning Python, let me try to dissect it for you... As mentioned, it is a list comprehension (covered in DiveIntoPython3, for example). Here are a few points:

[x[1] for x in L]

  • Notice the []'s around the line of code. These are what define a list. This tells you that this code returns a list, so it's of the list type. Hence, this technique is called a "list comprehension."
  • L is your original list. So you should define L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)] prior to executing the above code.
  • x is a variable that only exists in the comprehension - try to access x outside of the comprehension, or type type(x) after executing the above line and it will tell you NameError: name 'x' is not defined, whereas type(L) returns <class 'list'>.
  • x[1] points to the second item in each of the tuples whereas x[0] would point to each of the first items.
  • So this line of code literally reads "return the second item in a tuple for all tuples in list L."

It's tough to tell how much you attempted the problem prior to asking the question, but perhaps you just weren't familiar with comprehensions? I would spend some time reading through Chapter 3 of DiveIntoPython, or any resource on comprehensions. Good luck.

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.6;
  background: rgba(200, 54, 54, 0.5);  
  background-color: yellow;
  filter: alpha(opacity=50);
  zoom: 1;  
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";  
  -moz-opacity: 0.5; 
  -khtml-opacity: 0.5;  
}

Counter inside xsl:for-each loop

position(). E.G.:

<countNo><xsl:value-of select="position()" /></countNo>

What are the advantages and disadvantages of recursion?

For the most part recursion is slower, and takes up more of the stack as well. The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more "elegant". Check out some of the comparisons:

link

Get a CSS value with JavaScript

If you're into libraries, why not MyLibrary and getStyle.

The jQuery css method is misnamed, CSS is just one way of setting styles and doesn't necessarily represent the actual values of an element's style properties.

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

Ways to eliminate switch in code

In JavaScript using Associative array:
this:

function getItemPricing(customer, item) {
    switch (customer.type) {
        // VIPs are awesome. Give them 50% off.
        case 'VIP':
            return item.price * item.quantity * 0.50;

            // Preferred customers are no VIPs, but they still get 25% off.
        case 'Preferred':
            return item.price * item.quantity * 0.75;

            // No discount for other customers.
        case 'Regular':
        case
        default:
            return item.price * item.quantity;
    }
}

becomes this:

function getItemPricing(customer, item) {
var pricing = {
    'VIP': function(item) {
        return item.price * item.quantity * 0.50;
    },
    'Preferred': function(item) {
        if (item.price <= 100.0)
            return item.price * item.quantity * 0.75;

        // Else
        return item.price * item.quantity;
    },
    'Regular': function(item) {
        return item.price * item.quantity;
    }
};

    if (pricing[customer.type])
        return pricing[customer.type](item);
    else
        return pricing.Regular(item);
}

Courtesy

How to convert nanoseconds to seconds using the TimeUnit enum?

Well, you could just divide by 1,000,000,000:

long elapsedTime = end - start;
double seconds = (double)elapsedTime / 1_000_000_000.0;

If you use TimeUnit to convert, you'll get your result as a long, so you'll lose decimal precision but maintain whole number precision.

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

What is a 'workspace' in Visual Studio Code?

So, yet again the lesson of not polluting the source tree of a project with artifacts that aren't directly related to that project is being ignored.

There is zero reason for a Visual Studio Code workspace file (workspaces.json) or directory (.vscode) or whatever to be placed in the source tree. It could just as easily have been placed under your user settings.

I thought we figured this out about 20+ years ago, but it seems that some lessons are doomed to be repeated.

Location of the mongodb database on mac

The default data directory for MongoDB is /data/db.

This can be overridden by a dbpath option specified on the command line or in a configuration file.

If you install MongoDB via a package manager such as Homebrew or MacPorts these installs typically create a default data directory other than /data/db and set the dbpath in a configuration file.

If a dbpath was provided to mongod on startup you can check the value in the mongo shell:

db.serverCmdLineOpts()

You would see a value like:

"parsed" : {
    "dbpath" : "/usr/local/data"
},

Duplicate and rename Xcode project & associated folders

In the example code for the book "Instant OpenCV for iOS" I have found a bash script that copies a project from a folder to another.
Doing a little research I've found a blog post from what seems to be the original author of the script: http://mohrt.blogspot.it/2009/01/renaming-xcode-project-from-command.html, where you can download the script. I gave it a try and running it from terminal like this

    sh renameXcodeProject.sh <name-of-existing-folder> <name-of-folder-to-create>   

works fine.
Additional info can be found opening the file with a text editor. Hope that helps

What's the easiest way to call a function every 5 seconds in jQuery?

The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete

// IIFE
(function runForever(){
  // Do something here
  setTimeout(runForever, 5000)
})()

// Regular function with arguments
function someFunction(file, directory){
  // Do something here
  setTimeout(someFunction, 5000, file, directory)
  // YES, setTimeout passes any extra args to
  // function being called
}

json parsing error syntax error unexpected end of input

This error occurs on an empty JSON file reading.

To avoid this error in NodeJS I'm checking the file's size:

const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;

How to remove not null constraint in sql server using query

 ALTER TABLE YourTable ALTER COLUMN YourColumn columnType NULL

Check if null Boolean is true results in exception

Boolean types can be null. You need to do a null check as you have set it to null.

if (bool != null && bool)
{
  //DoSomething
}                   

How can I force WebKit to redraw/repaint to propagate style changes?

We recently encountered this and discovered that promoting the affected element to a composite layer with translateZ in CSS fixed the issue without needing extra JavaScript.

.willnotrender { 
   transform: translateZ(0); 
}

As these painting issues show up mostly in Webkit/Blink, and this fix mostly targets Webkit/Blink, it's preferable in some cases. Especially since the accepted answer almost certainly causes a reflow and repaint, not just a repaint.

Webkit and Blink have been working hard on rendering performance, and these kinds of glitches are the unfortunate side effect of optimizations that aim to reduce unnecessary flows and paints. CSS will-change or another succeeding specification will be the future solution, most likely.

There are other ways to achieve a composite layer, but this is the most common.

Laravel: PDOException: could not find driver

Even simpler in Ubuntu (18.04)

apt install php-mysql

Done. No need to edit any .ini files.

Happy coding!

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

If you're looking to paginate results, use the integrated paginator, it works great!

$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages

How to save a PNG image server-side, from a base64 data string

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

And as a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

An efficient method for extracting, decoding, and checking for errors is:

if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

What is the maximum length of a Push Notification alert text?

According to the WWDC 713_hd_whats_new_in_ios_notifications. The previous size limit of 256 bytes for a push payload has now been increased to 2 kilobytes for iOS 8.

Source: http://asciiwwdc.com/2014/sessions/713?q=notification#1414.0

login to remote using "mstsc /admin" with password

Save your username, password and sever name in an RDP file and run the RDP file from your script

Detecting iOS orientation change instantly

Why you didn`t use

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

?

Or you can use this

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

Or this

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

Hope it owl be useful )

"Please try running this command again as Root/Administrator" error when trying to install LESS

Honestly this is bad advice from npm. An installation can run arbitrary scripts and running it with sudo can be extremely dangerous! You could do sudo npm install -g less to install it globally, but instead I would recommend updating your npm settings:

#~/.npmrc
prefix=~/.npm_modules

Then you can update your path:

#~/.bashrc or ~/.zshrc, etc.
export PATH=$PATH:$HOME/.npm_modules/bin

Then you don't require root permissions to perform the installation and you can still use the binary.

This would only apply to your user, however. If you want the entire system to be able to use the module you would have to tell everyone to add your path. More complicated and robust solutions would include adding a folder with node modules / binaries that a group could install to and adding that to everyone's path.

How to check compiler log in sql developer?

control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).

if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up

for instance, hit Control-shift-L then execute this

CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;

and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "

(You can also see this in "View--Log")

One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)

No mapping found for HTTP request with URI.... in DispatcherServlet with name

In pom.xml make sure packaging is set to war like <packaging>war</packaging> ,not to jar or any thing else.

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

Is there a goto statement in Java?

James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.

Source: James Gosling, Q&A session

JavaScript: location.href to open in new window/tab?

window.open(
  'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
  '_blank' // <- This is what makes it open in a new window.
);

Convert List<String> to List<Integer> directly

Using lambda:

strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());

Android: How to enable/disable option menu item on button click?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    // getMenuInflater().inflate(R.menu.home, menu);
    return false;
}

How do I generate a list with a specified increment step?

The following example shows benchmarks for a few alternatives.

library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
##                     test replications elapsed  relative user.self sys.self
## 2          (0:5e+05) * 2          100   0.587  3.536145     0.344    0.244
## 1     seq(0, 1e6, by = 2)         100   2.760 16.626506     1.832    0.900
## 3 seq.int(0, 1e6, by = 2)         100   0.166  1.000000     0.056    0.096

In this case, seq.int is the fastest method and seq the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq as the most readable solution.

Convert Map<String,Object> to Map<String,String>

private Map<String, String> convertAttributes(final Map<String, Object> attributes) {
    final Map<String, String> result = new HashMap<String, String>();
    for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
        result.put(entry.getKey(), String.valueOf(entry.getValue()));
    }
    return result;
}

How to recursively find the latest modified file in a directory?

I find the following shorter and with more interpretable output:

find . -type f -printf '%TF %TT %p\n' | sort | tail -1

Given the fixed length of the standardised ISO format datetimes, lexicographical sorting is fine and we don't need the -n option on the sort.

If you want to remove the timestamps again, you can use:

find . -type f -printf '%TFT%TT %p\n' | sort | tail -1 | cut -f2- -d' '

Trim a string based on the string length

s = s.substring(0, Math.min(s.length(), 10));

Using Math.min like this avoids an exception in the case where the string is already shorter than 10.


Notes:

  1. The above does real trimming. If you actually want to replace the last three (!) characters with dots if it truncates, then use Apache Commons StringUtils.abbreviate.

  2. For typical implementations of String, s.substring(0, s.length()) will return s rather than allocating a new String.

  3. This may behave incorrectly1 if your String contains Unicode codepoints outside of the BMP; e.g. Emojis. For a (more complicated) solution that works correctly for all Unicode code-points, see @sibnick's solution.


1 - A Unicode codepoint that is not on plane 0 (the BMP) is represented as a "surrogate pair" (i.e. two char values) in the String. By ignoring this, we might trim to fewer than 10 code points, or (worse) truncate in the middle of a surrogate pair. On the other hand, String.length() is no longer an ideal measure of Unicode text length, so trimming based on it may be the wrong thing to do.

Installing PIL with pip

This works for me:

apt-get install python-dev
apt-get install libjpeg-dev
apt-get install libjpeg8-dev
apt-get install libpng3
apt-get install libfreetype6-dev
ln -s /usr/lib/i386-linux-gnu/libfreetype.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib

pip install PIL  --allow-unverified PIL --allow-all-external

How to change a table name using an SQL query?

Please use this on SQL Server 2005:

sp_rename old_table_name , new_table_name

it will give you:

Caution: Changing any part of an object name could break scripts and stored procedures.

but your table name will be changed.

How to update multiple columns in single update statement in DB2

For the sake of completeness and the edge case of wanting to update all columns of a row, you can do the following, but consider that the number and types of the fields must match.

Using a data structure

exec sql UPDATE TESTFILE
         SET ROW = :DataDs
         WHERE CURRENT OF CURSOR; //If using a cursor for update

Source: rpgpgm.com

SQL only

UPDATE t1 SET ROW = (SELECT *
                     FROM   t2
                     WHERE  t2.c3 = t1.c3)

Source: ibm.com

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

The best solution i found for myself is.

my user is sonar and whenever i am trying to connect to my database from external or other machine i am getting error as

ERROR 1045 (28000): Access denied for user 'sonar'@'localhost' (using password: YES)

Also as i am trying this from another machine and through Jenkins job my URL for accessing is

alm-lt-test.xyz.com

if you want to connect remotely you can specify it with different ways as follows:

mysql -u sonar -p -halm-lt-test.xyz.com
mysql -u sonar -p -h101.33.65.94
mysql -u sonar -p -h127.0.0.1 --protocol=TCP
mysql -u sonar -p -h172.27.59.54 --protocol=TCP

To access this with URL you just have to execute the following query.

GRANT ALL ON sonar.* TO 'sonar'@'localhost' IDENTIFIED BY 'sonar';
GRANT ALL ON sonar.* TO 'sonar'@'alm-lt-test.xyz.com' IDENTIFIED BY 'sonar';
GRANT ALL ON sonar.* TO 'sonar'@'127.0.0.1' IDENTIFIED BY 'sonar';
GRANT ALL ON sonar.* TO 'sonar'@'172.27.59.54' IDENTIFIED BY 'sonar';

Enter triggers button click

By pressing 'Enter' on focused <input type="text"> you trigger 'click' event on the first positioned element: <button> or <input type="submit">. If you press 'Enter' in <textarea>, you just make a new text line.

See the example here.

Your code prevents to make a new text line in <textarea>, so you have to catch key press only for <input type="text">.

But why do you need to press Enter in text field? If you want to submit form by pressing 'Enter', but the <button> must stay the first in the layout, just play with the markup: put the <input type="submit"> code before the <button> and use CSS to save the layout you need.

Catching 'Enter' and saving markup:

$('input[type="text"]').keypress(function (e) {
    var code = e.keyCode || e.which;
    if (code === 13)
    e.preventDefault();
    $("form").submit(); /*add this, if you want to submit form by pressing `Enter`*/
});

jQuery Scroll To bottom of the page

$("div").scrollTop(1000);

Works for me. Scrolls to the bottom.

Java - Search for files in a directory

If you want to use a dynamic filename filter you can implement FilenameFilter and pass in the constructor the dynamic name.

Of course this implies taht you must instantiate every time the class (overhead), but it works

Example:

public class DynamicFileNameFilter implements FilenameFilter {

    private String comparingname;

    public DynamicFileNameFilter(String comparingName){
        this.comparingname = comparingName;
    }

    @Override
    public boolean accept(File dir, String name) {
        File file = new File(name);

        if (name.equals(comparingname) && !file.isDirectory())
            return false;

        else
            return true;
    }

}

then you use where you need:

FilenameFilter fileNameFilter = new DynamicFileNameFilter("thedynamicNameorpatternYouAreSearchinfor");
File[] matchingFiles = dir.listFiles(fileNameFilter);

Insert multiple rows into single column

to insert values for a particular column with other columns remain same:-

INSERT INTO `table_name`(col1,col2,col3)
   VALUES (1,'val1',0),(1,'val2',0),(1,'val3',0)

Gradle DSL method not found: 'runProguard'

By changing runProguard to minifyEnabled, part of the issue gets fixed.

But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").

By removing application Id in the build.gradle file, you should be good to go.

Using "margin: 0 auto;" in Internet Explorer 8

Adding <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> solves the issue

error: ‘NULL’ was not declared in this scope

NULL isn't a keyword; it's a macro substitution for 0, and comes in stddef.h or cstddef, I believe. You haven't #included an appropriate header file, so g++ sees NULL as a regular variable name, and you haven't declared it.

HTML5 Email input pattern attribute

In HTML5 you can use the new 'email' type: http://www.w3.org/TR/html-markup/input.email.html

For example:

<input type="email" id="email" />

If the browser implements HTML5 it will make sure that the user has entered a valid email address in the field. Note that if the browser doesn't implement HTML5, it will be treated like a 'text' type, ie:

<input type="text" id="email" />

Call An Asynchronous Javascript Function Synchronously

One thing people might not consider: If you control the async function (which other pieces of code depend on), AND the codepath it would take is not necessarily asynchronous, you can make it synchronous (without breaking those other pieces of code) by creating an optional parameter.

Currently:

async function myFunc(args_etcetc) {
    // you wrote this
    return 'stuff';
}

(async function main() {
    var result = await myFunc('argsetcetc');
    console.log('async result:' result);
})()

Consider:

function myFunc(args_etcetc, opts={}) {
    /*
        param opts :: {sync:Boolean} -- whether to return a Promise or not
    */
    var {sync=false} = opts;
    if (sync===true)
        return 'stuff';
    else
        return new Promise((RETURN,REJECT)=> {
            RETURN('stuff');
        });
}


// async code still works just like before:
(async function main() {
    var result = await myFunc('argsetcetc');
    console.log('async result:', result);
})();
// prints: 'stuff'

// new sync code works, if you specify sync mode:
(function main() {
    var result = myFunc('argsetcetc', {sync:true});
    console.log('sync result:', result);
})();
// prints: 'stuff'

Of course this doesn't work if the async function relies on inherently async operations (network requests, etc.), in which case the endeavor is futile (without effectively waiting idle-spinning for no reason).

Also this is fairly ugly to return either a value or a Promise depending on the options passed in.

("Why would I have written an async function if it didn't use async constructs?" one might ask? Perhaps some modalities/parameters of the function require asynchronicity and others don't, and due to code duplication you wanted a monolithic block rather than separate modular chunks of code in different functions... For example perhaps the argument is either localDatabase (which doesn't require await) or remoteDatabase (which does). Then you could runtime error if you try to do {sync:true} on the remote database. Perhaps this scenario is indicative of another problem, but there you go.)

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

How do I tokenize a string in C++?

Simple C++ code (standard C++98), accepts multiple delimiters (specified in a std::string), uses only vectors, strings and iterators.

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept> 

std::vector<std::string> 
split(const std::string& str, const std::string& delim){
    std::vector<std::string> result;
    if (str.empty())
        throw std::runtime_error("Can not tokenize an empty string!");
    std::string::const_iterator begin, str_it;
    begin = str_it = str.begin(); 
    do {
        while (delim.find(*str_it) == std::string::npos && str_it != str.end())
            str_it++; // find the position of the first delimiter in str
        std::string token = std::string(begin, str_it); // grab the token
        if (!token.empty()) // empty token only when str starts with a delimiter
            result.push_back(token); // push the token into a vector<string>
        while (delim.find(*str_it) != std::string::npos && str_it != str.end())
            str_it++; // ignore the additional consecutive delimiters
        begin = str_it; // process the remaining tokens
        } while (str_it != str.end());
    return result;
}

int main() {
    std::string test_string = ".this is.a.../.simple;;test;;;END";
    std::string delim = "; ./"; // string containing the delimiters
    std::vector<std::string> tokens = split(test_string, delim);           
    for (std::vector<std::string>::const_iterator it = tokens.begin(); 
        it != tokens.end(); it++)
            std::cout << *it << std::endl;
}

Write string to output stream

You can create a PrintStream wrapping around your OutputStream and then just call it's print(String):

final OutputStream os = new FileOutputStream("/tmp/out");
final PrintStream printStream = new PrintStream(os);
printStream.print("String");
printStream.close();

Correct modification of state arrays in React.js

This code work for me:

fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
    this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
  })

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

git-diff to ignore ^M

As noted by VonC, this has already been included in git 2.16+. Unfortunately, the name of the option (--ignore-cr-at-eol) differs from the one used by GNU diff that I'm used to (--strip-trailing-cr).

When I was confronted with this problem, my solution was to invoke GNU diff instead of git's built-in diff, because my git is older than 2.16. I did that using this command line:

GIT_EXTERNAL_DIFF='diff -u --strip-trailing-cr "$2" "$5";true;#' git diff --ext-diff

That allows using --strip-trailing-cr and any other GNU diff options.

There's also this other way:

git difftool -y -x 'diff -u --strip-trailing-cr'

but it doesn't use the configured pager settings, which is why I prefer the former.

What is the significance of url-pattern in web.xml and how to configure servlet?

Servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

First specification of url-pattern a web.xml file for the server context on the servlet container at server .com matches the pattern in <url-pattern>/status/*</url-pattern> as follows:

http://server.com/server/status/synopsis               = Matches
http://server.com/server/status/complete?date=today    = Matches
http://server.com/server/status                        = Matches
http://server.com/server/server1/status                = Does not match

Second specification of url-pattern A context located at the path /examples on the Agent at example.com matches the pattern in <url-pattern>*.map</url-pattern> as follows:

 http://server.com/server/US/Oregon/Portland.map    = Matches
 http://server.com/server/US/server/Seattle.map     = Matches
 http://server.com/server/Paris.France.map          = Matches
 http://server.com/server/US/Oregon/Portland.MAP    = Does not match, the extension is uppercase
 http://example.com/examples/interface/description/mail.mapi  =Does not match, the extension is mapi rather than map`

Third specification of url-mapping,A mapping that contains the pattern <url-pattern>/</url-pattern> matches a request if no other pattern matches. This is the default mapping. The servlet mapped to this pattern is called the default servlet.

The default mapping is often directed to the first page of an application. Explicitly providing a default mapping also ensures that malformed URL requests into the application return are handled by the application rather than returning an error.

The servlet-mapping element below maps the server servlet instance to the default mapping.

<servlet-mapping>
  <servlet-name>server</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

For the context that contains this element, any request that is not handled by another mapping is forwarded to the server servlet.

And Most importantly we should Know about Rule for URL path mapping

  1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
  2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
  3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
  4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Reference URL Pattern

Visual Studio replace tab with 4 spaces?

You can edit this behavior in:

Tools->Options->Text Editor->All Languages->Tabs

Change Tab to use "Insert Spaces" instead of "Keep Tabs".

Note you can also specify this per language if you wish to have different behavior in a specific language.

Echo newline in Bash prints literal \n

If you're writing scripts and will be echoing newlines as part of other messages several times, a nice cross-platform solution is to put a literal newline in a variable like so:

newline='
'

echo "first line$newlinesecond line"
echo "Error: example error message n${newline}${usage}" >&2 #requires usage to be defined

Getting only 1 decimal place

>>> "{:.1f}".format(45.34531)
'45.3'

Or use the builtin round:

>>> round(45.34531, 1)
45.299999999999997

How can I change the Y-axis figures into percentages in a barplot?

Use:

+ scale_y_continuous(labels = scales::percent)

Or, to specify formatting parameters for the percent:

+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))

(the command labels = percent is obsolete since version 2.2.1 of ggplot2)

How to run a script at a certain time on Linux?

Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.

But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.

Set QLineEdit to accept only numbers

QLineEdit::setValidator(), for example:

myLineEdit->setValidator( new QIntValidator(0, 100, this) );

or

myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );

See: QIntValidator, QDoubleValidator, QLineEdit::setValidator

Define a fixed-size list in Java

Yes,

Commons library provides a built-in FixedSizeList which does not support the add, remove and clear methods (but the set method is allowed because it does not modify the List's size). In other words, if you try to call one of these methods, your list still retain the same size.

To create your fixed size list, just call

List<YourType> fixed = FixedSizeList.decorate(Arrays.asList(new YourType[100]));

You can use unmodifiableList if you want an unmodifiable view of the specified list, or read-only access to internal lists.

List<YourType> unmodifiable = java.util.Collections.unmodifiableList(internalList);

Shorthand if/else statement Javascript

Here is a way to do it that works, but may not be best practise for any language really:

var x,y;
x='something';
y=1;
undefined === y || (x = y);

alternatively

undefined !== y && (x = y);

Finding element's position relative to the document

I've found the following method to be the most reliable when dealing with edge cases that trip up offsetTop/offsetLeft.

function getPosition(element) {
    var clientRect = element.getBoundingClientRect();
    return {left: clientRect.left + document.body.scrollLeft,
            top: clientRect.top + document.body.scrollTop};
}

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

HTML form input tag name element array with JavaScript

Try this something like this:

var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
  alert(p_ids[i].value);
}

eclipse stuck when building workspace

In my case it helped to remove the source folders from my favorites in the Windows Explorer (Windows 8.0). It seems that the build was not actually stuck, but triggered in some kind of infinite loop (as mentioned here - Bug 342931).

XMLHttpRequest module not defined/found

Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.

So instead, you can use the xhr2 module. In other words:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

becomes:

var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();

But ... of course, there are more popular modules like Axios, because -for example- uses promises:

// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

Pass a variable to a PHP script running from the command line

Using getopt() function we can also read a parameter from the command line just. Pass a value with the php running command:

php abc.php --name=xyz

File abc.php

$val = getopt(null, ["name:"]);
print_r($val); // Output: ['name' => 'xyz'];

Regular expression negative lookahead

Lookarounds can be nested.

So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".

Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"

Difference between one-to-many and many-to-one relationship

There is no difference. It's just a matter of language and preference as to which way round you state the relationship.

ERROR Error: No value accessor for form control with unspecified name attribute on switch

This is kind of stupid, but I got this error message by accidentally using [formControl] instead of [formGroup]. See here:

WRONG

@Component({
  selector: 'app-application-purpose',
  template: `
    <div [formControl]="formGroup"> <!-- '[formControl]' IS THE WRONG ATTRIBUTE -->
      <input formControlName="formGroupProperty" />
    </div>
  `
})
export class MyComponent implements OnInit {
  formGroup: FormGroup

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      formGroupProperty: ''
    })
  }
}

RIGHT

@Component({
  selector: 'app-application-purpose',
  template: `
    <div [formGroup]="formGroup"> <!-- '[formGroup]' IS THE RIGHT ATTRIBUTE -->
      <input formControlName="formGroupProperty" />
    </div>
  `
})
export class MyComponent implements OnInit {
  formGroup: FormGroup

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      formGroupProperty: ''
    })
  }
}

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

If the script always outputs lines of 10 characters followed by 3 extra (in other words, you just want the first 10 characters), you can use

script | cut -c 1-10

If it outputs an uncertain number of non-space characters, followed by a space and then 2 other extra characters (in other words, you just want the first field), you can use

script | cut -d ' ' -f 1

... as in majhool's comment earlier. Depending on your platform, you may also have colrm, which, again, would work if the lines are a fixed length:

script | colrm 11

How can I output the value of an enum class in C++11

Following worked for me in C++11:

template <typename Enum>
constexpr typename std::enable_if<std::is_enum<Enum>::value,
                                  typename std::underlying_type<Enum>::type>::type
to_integral(Enum const& value) {
    return static_cast<typename std::underlying_type<Enum>::type>(value);
}

MySQL convert date string to Unix timestamp

For current date just use UNIX_TIMESTAMP() in your MySQL query.

MySQL show current connection info

There are MYSQL functions you can use. Like this one that resolves the user:

SELECT USER();

This will return something like root@localhost so you get the host and the user.

To get the current database run this statement:

SELECT DATABASE();

Other useful functions can be found here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

How to process each output line in a loop?

One of the easy ways is not to store the output in a variable, but directly iterate over it with a while/read loop.

Something like:

grep xyz abc.txt | while read -r line ; do
    echo "Processing $line"
    # your code goes here
done

There are variations on this scheme depending on exactly what you're after.

If you need to change variables inside the loop (and have that change be visible outside of it), you can use process substitution as stated in fedorqui's answer:

while read -r line ; do
    echo "Processing $line"
    # your code goes here
done < <(grep xyz abc.txt)

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Adding origin=${window.location.host} or "*" is not enough.

Add https:// before it and it will work.

Also, make sure that you are using an URL that can be embedded: take the video ID out and concatenate a string that has the YouTube video prefix and the video ID + embed definition.

How to Migrate to WKWebView?

WkWebView is much faster and reliable than UIWebview according to the Apple docs. Here, I posted my WkWebViewController.

import UIKit
import WebKit

class WebPageViewController: UIViewController,UINavigationControllerDelegate,UINavigationBarDelegate,WKNavigationDelegate{

    var webView: WKWebView?
    var webUrl="http://www.nike.com"

    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(true)
        navigationController!.navigationBar.hidden = false

    }
    override func viewDidLoad()
    {
        /* Create our preferences on how the web page should be loaded */
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = false

        /* Create a configuration for our preferences */
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences

        /* Now instantiate the web view */
        webView = WKWebView(frame: view.bounds, configuration: configuration)

        if let theWebView = webView{
            /* Load a web page into our web view */
            let url = NSURL(string: self.webUrl)
            let urlRequest = NSURLRequest(URL: url!)
            theWebView.loadRequest(urlRequest)
            theWebView.navigationDelegate = self
            view.addSubview(theWebView)

        }


    }
    /* Start the network activity indicator when the web view is loading */
    func webView(webView: WKWebView,didStartProvisionalNavigation navigation: WKNavigation){
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }

    /* Stop the network activity indicator when the loading finishes */
    func webView(webView: WKWebView,didFinishNavigation navigation: WKNavigation){
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }

    func webView(webView: WKWebView,
        decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse,decisionHandler: ((WKNavigationResponsePolicy) -> Void)){
            //print(navigationResponse.response.MIMEType)
            decisionHandler(.Allow)

    }
    override func didReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
    }

}

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

I disabled all installed extensions in Chrome - works for me. I have now clear console without errors.

How to set a transparent background of JPanel?

In my particular case it was easier to do this:

 panel.setOpaque(true);
 panel.setBackground(new Color(0,0,0,0,)): // any color with alpha 0 (in this case the color is black

Adding multiple columns AFTER a specific column in MySQL

This one is correct:

ALTER TABLE `users`
    ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
    ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
    ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;

How to split a comma-separated string?

Can try with this worked for me

 sg = sg.replaceAll(", $", "");

or else

if (sg.endsWith(",")) {
                    sg = sg.substring(0, sg.length() - 1);
                }

Has an event handler already been added?

This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.

public class MyClass
{
  event Action MyEvent;
}

...

MyClass myClass = new MyClass();
myClass.MyEvent += SomeFunction;

...

Action[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example

Console.WriteLine(handlers[0].Method.Name);//prints the name of the method

You can examine various properties on the Method property of the delegate to see if a specific function has been added.

If you are looking to see if there is just one attached, you can just test for null.

Best way to specify whitespace in a String.Split operation

If repeating the same code is the issue, write an extension method on the String class that encapsulates the splitting logic.

Requested bean is currently in creation: Is there an unresolvable circular reference?

i encountered this error in quite a stupid way

@Autowired
// private Bean bean;

public void myMethod() {
  return;
}

what happened is that I commented a line for some reason and left the annotation which made spring think that the method needs to be autowired

Can not find module “@angular-devkit/build-angular”

This worked for me: Type npm audit fix in the commandline. Afterwards I was able to use ng serve --open again.

How to access Winform textbox control from another class?

You can change the access modifier for the generated field in Form1.Designer.cs from private to public. Change this

private System.Windows.Forms.TextBox textBox1;

by this

public System.Windows.Forms.TextBox textBox1;

You can now handle it using a reference of the form Form1.textBox1.

Visual Studio will not overwrite this if you make any changes to the control properties, unless you delete it and recreate it.

You can also chane it from the UI if you are not confortable with editing code directly. Look for the Modifiers property:

Modifiers

Passing parameter via url to sql server reporting service

I've just solved this problem myself. I found the solution on MSDN: http://msdn.microsoft.com/en-us/library/ms155391.aspx.

The format basically is

http://<server>/reportserver?/<path>/<report>&rs:Command=Render&<parameter>=<value>

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

Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.

Documentation is here

> db.test.insert({x: 1})

> db.test.find()                                               // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }      

> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c"))           // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

Multiple axis line chart in excel

An alternative is to normalize the data. Below are three sets of data with widely varying ranges. In the top chart you can see the variation in one series clearly, in another not so clearly, and the third not at all.

In the second range, I have adjusted the series names to include the data range, using this formula in cell C15 and copying it to D15:E15

=C2&" ("&MIN(C3:C9)&" to "&MAX(C3:C9)&")"

I have normalized the values in the data range using this formula in C15 and copying it to the entire range C16:E22

=100*(C3-MIN(C$3:C$9))/(MAX(C$3:C$9)-MIN(C$3:C$9))

In the second chart, you can see a pattern: all series have a low in January, rising to a high in March, and dropping to medium-low value in June or July.

You can modify the normalizing formula however you need:

=100*C3/MAX(C$3:C$9)

=C3/MAX(C$3:C$9)

=(C3-AVERAGE(C$3:C$9))/STDEV(C$3:C$9)

etc.

Normalizing Data

How do I list / export private keys from a keystore?

A portion of code originally from Example Depot for listing all of the aliases in a key store:

    // Load input stream into keystore
    keystore.load(is, password.toCharArray());

    // List the aliases
    Enumeration aliases = keystore.aliases();
    for (; aliases.hasMoreElements(); ) {
        String alias = (String)aliases.nextElement();

        // Does alias refer to a private key?
        boolean b = keystore.isKeyEntry(alias);

        // Does alias refer to a trusted certificate?
        b = keystore.isCertificateEntry(alias);
    }

The exporting of private keys came up on the Sun forums a couple of months ago, and u:turingcompleter came up with a DumpPrivateKey class to stitch into your app.

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import sun.misc.BASE64Encoder;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args  <ul>
     *              <li> [0] Keystore filename.
     *              <li> [1] Keystore password.
     *              <li> [2] alias
     *              </ul>
     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        String b64 = new BASE64Encoder().encode(key.getEncoded());
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}

Note: this use Sun package, which is a "bad thing".
If you can download apache commons code, here is a version which will compile without warning:

javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java

and will give the same result:

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
//import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args  <ul>
     *              <li> [0] Keystore filename.
     *              <li> [1] Keystore password.
     *              <li> [2] alias
     *              </ul>
     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        //String b64 = new BASE64Encoder().encode(key.getEncoded());
        String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}

You can use it like so:

java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat

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

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

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

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

git add, commit and push commands in one?

If you're using fish shell (building off of btse's answer):

Save this file within '~/.config/fish/functions' as 'quickgit.fish'. Create the directory if it does not exist. '--git-dir=$PWD/.git' Ensures that we run the git commands against the git project where we called the function

function quickgit # This is the function name and command we call
    git --git-dir=$PWD/.git add . # Stage all unstaged files
    git --git-dir=$PWD/.git commit -a -m $argv # Commit files with the given argument as the commit message
    git --git-dir=$PWD/.git push # Push to remote
end

Restart terminal, navigate to project, make changes, and now you can call 'quickgit "example message"'. Changes will now be added, committed, and push :).

Also can be found as a Gist here: https://gist.github.com/Abushawish/3440a6087c212bd67ce1e93f8d283a69

Getting msbuild.exe without installing Visual Studio

Download MSBuild with the link from @Nicodemeus answer was OK, yet the installation was broken until I've added these keys into a register:

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0]
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))" 

Permission denied (publickey,keyboard-interactive)

The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?

Creating an iframe with given HTML dynamically

Do this

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

var frame_win = getIframeWindow(el);

console.log(frame_win);
...

getIframeWindow is defined here

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

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

Put it in double quotes:

echo "\t";

Single quotes do not expand escaped characters.

Use the documentation when in doubt.

Reading int values from SqlDataReader

TxtFarmerSize.Text = (int)reader[3];

How to edit HTML input value colour?

You can add color in the style rule of your input: color:#ccc;

Python logging not outputting anything

The default logging level is warning. Since you haven't changed the level, the root logger's level is still warning. That means that it will ignore any logging with a level that is lower than warning, including debug loggings.

This is explained in the tutorial:

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

The 'info' line doesn't print anything, because the level is higher than info.

To change the level, just set it in the root logger:

'root':{'handlers':('console', 'file'), 'level':'DEBUG'}

In other words, it's not enough to define a handler with level=DEBUG, the actual logging level must also be DEBUG in order to get it to output anything.

Customize Bootstrap checkboxes

Since Bootstrap 3 doesn't have a style for checkboxes I found a custom made that goes really well with Bootstrap style.

Checkboxes

_x000D_
_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border: 1px solid #a9a9a9;_x000D_
  border-radius: .25em;_x000D_
  width: 1.3em;_x000D_
  height: 1.3em;_x000D_
  float: left;_x000D_
  margin-right: .5em;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon {_x000D_
  position: absolute;_x000D_
  font-size: .8em;_x000D_
  line-height: 0;_x000D_
  top: 50%;_x000D_
  left: 15%;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr {_x000D_
  opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default checkbox -->_x000D_
<div class="checkbox">_x000D_
  <label>_x000D_
   <input type="checkbox" value="">_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
   Option one_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked checkbox -->_x000D_
<div class="checkbox">_x000D_
  <label>_x000D_
   <input type="checkbox" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
   Option two is checked by default_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled checkbox -->_x000D_
<div class="checkbox disabled">_x000D_
  <label>_x000D_
   <input type="checkbox" value="" disabled>_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>_x000D_
   Option three is disabled_x000D_
   </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Radio

_x000D_
_x000D_
.checkbox label:after,_x000D_
.radio label:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border: 1px solid #a9a9a9;_x000D_
  border-radius: .25em;_x000D_
  width: 1.3em;_x000D_
  height: 1.3em;_x000D_
  float: left;_x000D_
  margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
  border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
  position: absolute;_x000D_
  font-size: .8em;_x000D_
  line-height: 0;_x000D_
  top: 50%;_x000D_
  left: 13%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
  margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
  opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<!-- Default radio -->_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="">_x000D_
   <span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
   Option one_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Checked radio -->_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
   Option two is checked by default_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<!-- Disabled radio -->_x000D_
<div class="radio disabled">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="" disabled>_x000D_
   <span class="cr"><i class="cr-icon fa fa-circle"></i></span>_x000D_
   Option three is disabled_x000D_
   </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Custom icons

You can choose your own icon between the ones from Bootstrap or Font Awesome by changing [icon name] with your icon.

<span class="cr"><i class="cr-icon [icon name]"></i>

For example:

  • glyphicon glyphicon-remove for Bootstrap, or
  • fa fa-bullseye for Font Awesome

_x000D_
_x000D_
.checkbox label:after,_x000D_
.radio label:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.checkbox .cr,_x000D_
.radio .cr {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border: 1px solid #a9a9a9;_x000D_
  border-radius: .25em;_x000D_
  width: 1.3em;_x000D_
  height: 1.3em;_x000D_
  float: left;_x000D_
  margin-right: .5em;_x000D_
}_x000D_
_x000D_
.radio .cr {_x000D_
  border-radius: 50%;_x000D_
}_x000D_
_x000D_
.checkbox .cr .cr-icon,_x000D_
.radio .cr .cr-icon {_x000D_
  position: absolute;_x000D_
  font-size: .8em;_x000D_
  line-height: 0;_x000D_
  top: 50%;_x000D_
  left: 15%;_x000D_
}_x000D_
_x000D_
.radio .cr .cr-icon {_x000D_
  margin-left: 0.04em;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"],_x000D_
.radio label input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]+.cr>.cr-icon {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:checked+.cr>.cr-icon,_x000D_
.radio label input[type="radio"]:checked+.cr>.cr-icon {_x000D_
  opacity: 1;_x000D_
}_x000D_
_x000D_
.checkbox label input[type="checkbox"]:disabled+.cr,_x000D_
.radio label input[type="radio"]:disabled+.cr {_x000D_
  opacity: .5;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">_x000D_
_x000D_
<div class="checkbox">_x000D_
  <label>_x000D_
   <input type="checkbox" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon glyphicon glyphicon-remove"></i></span>_x000D_
   Bootstrap - Custom icon checkbox_x000D_
   </label>_x000D_
</div>_x000D_
_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="" checked>_x000D_
   <span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
   Font Awesome - Custom icon radio checked by default_x000D_
   </label>_x000D_
</div>_x000D_
<div class="radio">_x000D_
  <label>_x000D_
   <input type="radio" name="o3" value="">_x000D_
   <span class="cr"><i class="cr-icon fa fa-bullseye"></i></span>_x000D_
   Font Awesome - Custom icon radio_x000D_
   </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the proper way to URL encode Unicode characters?

The first question is what are your needs? UTF-8 encoding is a pretty good compromise between taking text created with a cheap editor and support for a wide variety of languages. In regards to the browser identifying the encoding, the response (from the web server) should tell the browser the encoding. Still most browsers will attempt to guess, because this is either missing or wrong in so many cases. They guess by reading some amount of the result stream to see if there is a character that does not fit in the default encoding. Currently all browser(? I did not check this, but it is pretty close to true) use utf-8 as the default.

So use utf-8 unless you have a compelling reason to use one of the many other encoding schemes.

Send Mail to multiple Recipients in java

Easy way to do

String[] listofIDS={"[email protected]","[email protected]"};

for(String cc:listofIDS) {
    message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
}

Minimal web server using netcat

mkfifo pipe;
while true ; 
do 
   #use read line from pipe to make it blocks before request comes in,
   #this is the key.
   { read line<pipe;echo -e "HTTP/1.1 200 OK\r\n";echo $(date);
   }  | nc -l -q 0 -p 8080 > pipe;  

done

Looping through array and removing items, without breaking for loop

Here is a simple linear time solution to this simple linear time problem.

When I run this snippet, with n = 1 million, each call to filterInPlace() takes .013 to .016 seconds. A quadratic solution (e.g. the accepted answer) would take a million times that, or so.

_x000D_
_x000D_
// Remove from array every item such that !condition(item).
function filterInPlace(array, condition) {
   var iOut = 0;
   for (var i = 0; i < array.length; i++)
     if (condition(array[i]))
       array[iOut++] = array[i];
   array.length = iOut;
}

// Try it out.  A quadratic solution would take a very long time.
var n = 1*1000*1000;
console.log("constructing array...");
var Auction = {auctions: []};
for (var i = 0; i < n; ++i) {
  Auction.auctions.push({seconds:1});
  Auction.auctions.push({seconds:2});
  Auction.auctions.push({seconds:0});
}
console.log("array length should be "+(3*n)+": ", Auction.auctions.length)
filterInPlace(Auction.auctions, function(auction) {return --auction.seconds >= 0; })
console.log("array length should be "+(2*n)+": ", Auction.auctions.length)
filterInPlace(Auction.auctions, function(auction) {return --auction.seconds >= 0; })
console.log("array length should be "+n+": ", Auction.auctions.length)
filterInPlace(Auction.auctions, function(auction) {return --auction.seconds >= 0; })
console.log("array length should be 0: ", Auction.auctions.length)
_x000D_
_x000D_
_x000D_

Note that this modifies the original array in place rather than creating a new array; doing it in place like this can be advantageous, e.g. in the case that the array is the program's single memory bottleneck; in that case, you don't want to create another array of the same size, even temporarily.

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

You could disable the warnings temporarily in places where they appear by using

#pragma warning(push)
#pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent
// deprecated code here
#pragma warning(pop)

so you don't disable all warnings, which can be harmful at times.

What is Linux’s native GUI API?

Linux is a kernel, not a full operating system. There are different windowing systems and gui's that run on top of Linux to provide windowing. Typically X11 is the windowing system used by Linux distros.

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

jQuery 'each' loop with JSON array

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

how to display data values on Chart.js

This animation option works for 2.1.3 on a bar chart.

Slightly modified @Ross answer

animation: {
duration: 0,
onComplete: function () {
    // render the value of the chart above the bar
    var ctx = this.chart.ctx;
    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
    ctx.fillStyle = this.chart.config.options.defaultFontColor;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';
    this.data.datasets.forEach(function (dataset) {
        for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(dataset.data[i], model.x, model.y - 5);
        }
    });
}}

How to change background color in the Notepad++ text editor?

Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.

The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.

C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes

https://draculatheme.com/notepad-plus-plus

How to display all methods of an object?

The short answer is you can't because Math and Date (off the top of my head, I'm sure there are others) are't normal objects. To see this, create a simple test script:

<html>
  <body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        alert("Math: " + Math);
        alert("Math: " + Math.sqrt);
        alert("Date: " + Date);
        alert("Array: " + Array);
        alert("jQuery: " + jQuery);
        alert("Document: " + document);
        alert("Document: " + document.ready);
      });
    </script>
  </body>
</html>

You see it presents as an object the same ways document does overall, but when you actually try and see in that object, you see that it's native code and something not exposed the same way for enumeration.

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

Handling back button in Android Navigation Component

For anyone looking for a Kotlin implementation see below.

Note that the OnBackPressedCallback only seems to work for providing custom back behavior to the built-in software/hardware back button and not the back arrow button/home as up button within the actionbar/toolbar. To also override the behavior for the actionbar/toolbar back button I'm providing the solution that's working for me. If this is a bug or you are aware of a better solution for that case please comment.

build.gradle

...
implementation "androidx.appcompat:appcompat:1.1.0-rc01"
implementation "androidx.navigation:navigation-fragment-ktx:2.0.0"
implementation "androidx.navigation:navigation-ui-ktx:2.0.0"
...

MainActivity.kt

...
import androidx.appcompat.app.AppCompatActivity
...

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_main)

        ...

        val navController = findNavController(R.id.nav_host_fragment)
        val appBarConfiguration = AppBarConfiguration(navController.graph)

        // This line is only necessary if using the default action bar.
        setupActionBarWithNavController(navController, appBarConfiguration)

        // This remaining block is only necessary if using a Toolbar from your layout.
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        toolbar.setupWithNavController(navController, appBarConfiguration)
        // This will handle back actions initiated by the the back arrow 
        // at the start of the toolbar.
        toolbar.setNavigationOnClickListener {
            // Handle the back button event and return to override 
            // the default behavior the same way as the OnBackPressedCallback.
            // TODO(reason: handle custom back behavior here if desired.)

            // If no custom behavior was handled perform the default action.
            navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
        }
    }

    /**
     * If using the default action bar this must be overridden.
     * This will handle back actions initiated by the the back arrow 
     * at the start of the action bar.
     */
    override fun onSupportNavigateUp(): Boolean {
        // Handle the back button event and return true to override 
        // the default behavior the same way as the OnBackPressedCallback.
        // TODO(reason: handle custom back behavior here if desired.)

        // If no custom behavior was handled perform the default action.
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
}

MyFragment.kt

...
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
...

class MyFragment : Fragment() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // Handle the back button event
            }
        }
        requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback)
    }
}

The official documentation can be viewed at https://developer.android.com/guide/navigation/navigation-custom-back

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

Set UILabel line spacing

Edit: Evidently NSAttributedString will do it, on iOS 6 and later. Instead of using an NSString to set the label's text, create an NSAttributedString, set attributes on it, then set it as the .attributedText on the label. The code you want will be something like this:

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:@"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
    value:style
    range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;

NSAttributedString's old attributedStringWithString did the same thing, but now that is being deprecated.

For historical reasons, here's my original answer:

Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, create multiple labels, or use a different font (perhaps one edited for a specific line height, see Phillipe's answer).

Long answer: In the print and online world, the space between lines of text is known as "leading" (rhymes with 'heading', and comes from the lead metal used decades ago). Leading is a read-only property of UIFont, which was deprecated in 4.0 and replaced by lineHeight. As far as I know, there's no way to create a font with a specific set of parameters such as lineHeight; you get the system fonts and any custom font you add, but can't tweak them once installed.

There is no spacing parameter in UILabel, either.

I'm not particularly happy with UILabel's behavior as is, so I suggest writing your own subclass or using a 3rd-party library. That will make the behavior independent of your font choice and be the most reusable solution.

I wish there was more flexibility in UILabel, and I'd be happy to be proven wrong!

Save and load MemoryStream to/from a file

You may use MemoryStream.WriteTo or Stream.CopyTo (supported in framework version 4.5.2, 4.5.1, 4.5, 4) methods to write content of memory stream to another stream.

memoryStream.WriteTo(fileStream);

Update:

fileStream.CopyTo(memoryStream);
memoryStream.CopyTo(fileStream);

Merge r brings error "'by' must specify uniquely valid columns"

Rather give names of the column on which you want to merge:

exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)

Authentication plugin 'caching_sha2_password' is not supported

If you are looking for the solution of following error

ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Acces s is denied: 'D:\softwares\spider\Lib\site-packages\libmysql.dll' Consider using the --user option or check the permissions.

The solution: You should add --user if you find an access-denied error.

 pip install --user mysql-connector-python

paste this command into cmd and solve your problem

How to get the name of a class without the package?

The following function will work in JDK version 1.5 and above.

public String getSimpleName()

Class Diagrams in VS 2017

VS 2017 Professional edition- Go to Quick launch type "Class..." select Class designer and install it.

Once installed go to Add New Items search "Class Diagram" and you are ready to go.

Implicit type conversion rules in C++ operators

My solution to the problem got WA(wrong answer), then i changed one of int to long long int and it gave AC(accept). Previously, I was trying to do long long int += int * int, and after I rectify it to long long int += long long int * int. Googling I came up with,

1. Arithmetic Conversions

Conditions for Type Conversion:

Conditions Met ---> Conversion

  • Either operand is of type long double. ---> Other operand is converted to type long double.

  • Preceding condition not met and either operand is of type double. ---> Other operand is converted to type double.

  • Preceding conditions not met and either operand is of type float. ---> Other operand is converted to type float.

  • Preceding conditions not met (none of the operands are of floating types). ---> Integral promotions are performed on the operands as follows:

    • If either operand is of type unsigned long, the other operand is converted to type unsigned long.
    • If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.
    • If the preceding two conditions are not met, and if either operand is of type long, t he other operand is converted to type long.
    • If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned int.
    • If none of the preceding conditions are met, both operands are converted to type int.

2 . Integer conversion rules

  • Integer Promotions:

Integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int. Integer promotions are applied as part of the usual arithmetic conversions to certain argument expressions; operands of the unary +, -, and ~ operators; and operands of the shift operators.

  • Integer Conversion Rank:

    • No two signed integer types shall have the same rank, even if they have the same representation.
    • The rank of a signed integer type shall be greater than the rank of any signed integer type with less precision.
    • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.
    • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type, if any.
    • The rank of any standard integer type shall be greater than the rank of any extended integer type with the same width.
    • The rank of char shall equal the rank of signed char and unsigned char.
    • The rank of any extended signed integer type relative to another extended signed integer type with the same precision is implementation-defined but still subject to the other rules for determining the integer conversion rank.
    • For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has greater rank than T3, then T1 has greater rank than T3.
  • Usual Arithmetic Conversions:

    • If both operands have the same type, no further conversion is needed.
    • If both operands are of the same integer type (signed or unsigned), the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
    • If the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type is converted to the type of the operand with unsigned integer type.
    • If the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type is converted to the type of the operand with signed integer type.
    • Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type. Specific operations can add to or modify the semantics of the usual arithmetic operations.

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

React components (both functional as well as class) must begin with a capital letter. Like

const App=(props)=><div>Hey</div>

class App extends React.Component{
   render(){
     return <div>Hey</div>
   }
}

React identifies user-defined components by following this semantic. React's JSX transpiles to React.createElement function which returns an object representation of the dom node. The type property of this object tells whether it is a user-defined component or a dom element like div. Therefore it is important to follow this semantics

Since useState hook can only be used inside the functional component(or a custom hook) this is the reason why you are getting the error because react is not able to identify it as a user-defined component in the first place.

useState can also be used inside the custom hooks which is used for the reusability and the abstraction of logic. So according to the rules of hooks, the name of a custom hook must begin with a "use" prefix and must be in a camelCase

How do I convert dmesg timestamp to custom date format?

you will need to reference the "btime" in /proc/stat, which is the Unix epoch time when the system was latest booted. Then you could base on that system boot time and then add on the elapsed seconds given in dmesg to calculate timestamp for each events.

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

How do I add a submodule to a sub-directory?

Note that starting git1.8.4 (July 2013), you wouldn't have to go back to the root directory anymore.

 cd ~/.janus/snipmate-snippets
 git submodule add <git@github ...> snippets

(Bouke Versteegh comments that you don't have to use /., as in snippets/.: snippets is enough)

See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae:

submodule: drop the top-level requirement

Use the new rev-parse --prefix option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository.

Since the interpretation of a relative submodule URL depends on whether or not "remote.origin.url" is configured, explicitly block relative URLs in "git submodule add" when not at the top level of the working tree.

Signed-off-by: John Keeping

Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f

This makes 'git rev-parse' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree.

This is useful for shell scripts where we may want to cd to the top of the working tree but need to handle relative paths given by the user on the command line.

Using generic std::function objects with member functions in one class

You can avoid std::bind doing this:

std::function<void(void)> f = [this]-> {Foo::doSomething();}

How do I install TensorFlow's tensorboard?

Adding this just for the sake of completeness of this question (some questions may get closed as duplicate of this one).

I usually use user mode for pip ie. pip install --user even if instructions assume root mode. That way, my tensorboard installation was in ~/.local/bin/tensorboard, and it was not in my path (which shouldn't be ideal either). So I was not able to access it.

In this case, running

sudo ln -s ~/.local/bin/tensorboard /usr/bin

should fix it.

How to delete a whole folder and content?

I'm using this recursive function to do the job:

public static void deleteDirAndContents(@NonNull File mFile){
    if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
        for (File file : mFile.listFiles()) {
            deleteDirAndContents(file);
        }
    } else {
        mFile.delete();
    }
}

The function checks if it is a directory or a file.

If it is a directory checks if it has child files, if it has child files will call herself again passing the children and repeating.

If it is a file it delete it.

(Don't use this function to clear the app cache by passing the cache dir because it will delete the cache dir too so the app will crash... If you want to clear the cache you use this function that won't delete the dir you pass to it:

public static void deleteDirContents(@NonNull File mFile){
        if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
            for (File file : mFile.listFiles()) {
                deleteDirAndContents(file);
            }
        }
    }

or you can check if it is the cache dir using:

if (!mFile.getAbsolutePath().equals(context.getCacheDir().getAbsolutePath())) {
    mFile.delete();
}

Example code to clear app cache:

public static void clearAppCache(Context context){
        try {
            File cache = context.getCacheDir();
            FilesUtils.deleteDirContents(cache);
        } catch (Exception e){
            MyLogger.onException(TAG, e);
        }
    }

Bye, Have a nice day & coding :D

How can I save application settings in a Windows Forms application?

The ApplicationSettings class doesn't support saving settings to the app.config file. That's very much by design; applications that run with a properly secured user account (think Vista UAC) do not have write access to the program's installation folder.

You can fight the system with the ConfigurationManager class. But the trivial workaround is to go into the Settings designer and change the setting's scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.

if else statement in AngularJS templates

    <div ng-if="modeldate==''"><span ng-message="required" class="change">Date is required</span> </div>

you can use the ng-if directive as above.

bash: npm: command not found?

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

How to show the last queries executed on MySQL?

You can do the flowing thing for monitoring mysql query logs.

Open mysql configuration file my.cnf

sudo nano /etc/mysql/my.cnf

Search following lines under a [mysqld] heading and uncomment these lines to enable log

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

Restart your mysql server for reflect changes

sudo service mysql start

Monitor mysql server log with following command in terminal

tail -f /var/log/mysql/mysql.log

How to use if statements in underscore.js templates?

If you prefer shorter if else statement, you can use this shorthand:

<%= typeof(id)!== 'undefined' ?  id : '' %>

It means display the id if is valid and blank if it wasn't.

Git error when trying to push -- pre-receive hook declined

In my case I got this error because a branch with the same name already existed. Deleting this branch off of the git server will fix this.

How can I convert String to Int?

int i = Convert.ToInt32(TextBoxD1.Text);

Make an Installation program for C# applications and include .NET Framework installer into the setup

Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:

Here is my step-by-step for windows forms application:

  1. Create setup project. You can use Setup Wizard.

    enter image description here

  2. Select project type.

    enter image description here

  3. Select output.

    enter image description here

  4. Hit Finish.

  5. Open setup project properties.

    enter image description here

  6. Chose to include .NET framework.

    enter image description here

  7. Build setup project

  8. Check output

    enter image description here


Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:

Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects

How unique is UUID?

Quoting from Wikipedia:

Thus, anyone can create a UUID and use it to identify something with reasonable confidence that the identifier will never be unintentionally used by anyone for anything else

It goes on to explain in pretty good detail on how safe it actually is. So to answer your question: Yes, it's safe enough.

fatal: does not appear to be a git repository

I met a similar problem when I tried to store my existing repo in my Ubunt One account, I fixed it by the following steps:

Step-1: create remote repo

$ cd ~/Ubuntu\ One/
$ mkdir <project-name>
$ cd <project-name>
$ mkdir .git
$ cd .git
$ git --bare init

Step-2: add the remote

$ git remote add origin /home/<linux-user-name>/Ubuntu\ One/<project-name>/.git

Step-3: push the exising git reop to the remote

$ git push -u origin --all

Shell script to delete directories older than n days

find supports -delete operation, so:

find /base/dir/* -ctime +10 -delete;

I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.

The most voted solution here is missing -maxdepth 0 so it will call rm -rf for every subdirectory, after deleting it. That doesn't make sense, so I suggest:

find /base/dir/* -maxdepth 0  -type d -ctime +10 -exec rm -rf {} \;

The -delete solution above doesn't use -maxdepth 0 because find would complain the dir is not empty. Instead, it implies -depth and deletes from the bottom up.

jQuery animate margin top

MarginTop should be marginTop.

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

You can always check for a table existence before creating it.

    if(!Schema::hasTable('books')){
 Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
}

IndexOf function in T-SQL

You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.

CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4

Mind that you need to use the wildcards in PATINDEX on either side.

How to create two columns on a web page?

I found a real cool Grid which I also use for columns. Check it out Simple Grid. Wich this CSS you can simply use:

<div class="grid">
    <div class="col-1-2">
       <div class="content">
           <p>...insert content left side...</p>
       </div>
    </div>
    <div class="col-1-2">
       <div class="content">
           <p>...insert content right side...</p>
       </div>
    </div>
</div>

I use it for all my projects.

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

After two days of going through the web, this is what I came up with in Kotlin. Tested and works on my app

  private fun setupActionBar() {
    supportActionBar?.apply {
        displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
        displayOptions = ActionBar.DISPLAY_SHOW_TITLE
        setDisplayShowCustomEnabled(true)
        title = ""


        val titleTextView = AppCompatTextView(this@MainActivity)
        titleTextView.text = getText(R.string.app_name)
        titleTextView.setSingleLine()
        titleTextView.textSize = 24f
        titleTextView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.appWhite))

        val layoutParams = ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT
        )
        layoutParams.gravity = Gravity.CENTER
        setCustomView(titleTextView, layoutParams)

        setBackgroundDrawable(
            ColorDrawable(
                ContextCompat.getColor(
                    this@MainActivity,
                    R.color.appDarkBlue
                )
            )
        )

    }
}

Override body style for content in an iframe

Override another domain iframe CSS

By using part of SimpleSam5's answer, I achieved this with a few of Tawk's chat iframes (their customization interface is fine but I needed further customizations).

In this particular iframe that shows up on mobile devices, I needed to hide the default icon and place one of my background images. I did the following:

Tawk_API.onLoad = function() {
// without a specific API, you may try a similar load function
// perhaps with a setTimeout to ensure the iframe's content is fully loaded
  $('#mtawkchat-minified-iframe-element').
    contents().find("head").append(
     $("<style type='text/css'>"+
       "#tawkchat-status-text-container {"+
         "background: url(https://example.net/img/my_mobile_bg.png) no-repeat center center blue;"+
         "background-size: 100%;"+
       "} "+
       "#tawkchat-status-icon {display:none} </style>")
   );
};

I do not own any Tawk's domain and this worked for me, thus you may do this even if it's not from the same parent domain (despite Jeremy Becker's comment on Sam's answer).

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow