Programs & Examples On #Mgtwitterengine

MGTwitterEngine is an Objective-C/Cocoa class which makes it easy to add Twitter integration to your own Cocoa apps.

How to clear the logs properly for a Docker container?

To remove/clear docker container logs we can use below command

$(docker inspect container_id|grep "LogPath"|cut -d """ -f4) or $(docker inspect container_name|grep "LogPath"|cut -d """ -f4)

How to convert list to string

By using ''.join

list1 = ['1', '2', '3']
str1 = ''.join(list1)

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)

Android map v2 zoom to show all the markers

I have one other way to do this same thing works perfectly. so the idea behind to show all markers on the screen we need a center lat long and zoom level. here is the function which will give you both and need all marker's Latlng objects as input.

 public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) {
    float max = 0;

    if (l == null || l.length == 0) {
        return null;
    }
    LatLngBounds.Builder b = new LatLngBounds.Builder();
    for (int count = 0; count < l.length; count++) {
        if (l[count] == null) {
            continue;
        }
        b.include(l[count]);
    }

    LatLng center = b.build().getCenter();

    float distance = 0;
    for (int count = 0; count < l.length; count++) {
        if (l[count] == null) {
            continue;
        }
        distance = distance(center, l[count]);
        if (distance > max) {
            max = distance;
        }
    }

    double scale = max / 1000;
    int zoom = ((int) (16 - Math.log(scale) / Math.log(2)));
    return new Pair<LatLng, Integer>(center, zoom);
}

This function return Pair object which you can use like

Pair pair = getCenterWithZoomLevel(l1,l2,l3..); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));

you can instead of using padding to keep away your markers from screen boundaries, you can adjust zoom by -1.

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

Split large string in n-size chunks in JavaScript

const getChunksFromString = (str, chunkSize) => {
    var regexChunk = new RegExp(`.{1,${chunkSize}}`, 'g')   // '.' represents any character
    return str.match(regexChunk)
}

Call it as needed

console.log(getChunksFromString("Hello world", 3))   // ["Hel", "lo ", "wor", "ld"]

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

My answer might not be solution to your question but it will surely help others looking for similar issue like this one: javax.net.ssl.SSLHandshakeException: Chain validation failed

You just need to check your Android Device's Date and Time, it should be fix the issue. This resoled my problem.

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

If changing target sdk version doesn't help then if you have any dependency with version 3.0.2 then change it to 3.0.1.

e.g change

androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'

to

androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.1'

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

Difference between jQuery’s .hide() and setting CSS to display: none

To use both is a nice answer; it's not a question of either or.

The advantage of using both is that the CSS will hide the element immediately when the page loads. The jQuery .hide will flash the element for a quarter of a second then hide it.

In the case when we want to have the element not shown when the page loads we can use CSS and set display:none & use the jQuery .hide(). If we plan to toggle the element we can use jQuery toggle.

SELECT only rows that contain only alphanumeric characters in MySQL

Try this

select count(*) from table where cast(col as double) is null;

Android: checkbox listener

Change RadioGroup group with CompoundButton buttonView and then press Ctrl+Shift+O to fix your imports.

Angular 2: import external js file into component

Here is a simple way i did it in my project.

lets say you need to use clipboard.min.js and for the sake of the example lets say that inside clipboard.min.js there is a function that called test2().

in order to use test2() function you need:

  1. make a reference to the .js file inside you index.html.
  2. import clipboard.min.js to your component.
  3. declare a variable that will use you to call the function.

here are only the relevant parts from my project (see the comments):

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Angular QuickStart</title>
    <base href="/src/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="/node_modules/core-js/client/shim.min.js"></script>


    <script src="/node_modules/zone.js/dist/zone.js"></script>
    <script src="/node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function (err) { console.error(err); });
    </script>

    <!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
    <script src="app/txtzone/clipboard.min.js"></script>
</head>

<body>
    <my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

app.component.ts:

import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js

@Component({
    selector: 'txt-zone',
    templateUrl: 'app/txtzone/Txtzone.component.html',
    styleUrls: ['app/txtzone/TxtZone.css'],
})



export class TxtZoneComponent implements AfterViewInit {

    // call test2
    callTest2()
    {   
        new test2(); // the javascript function will execute
    }

}

HTML5 event handling(onfocus and onfocusout) using angular 2

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

works for me from Pardeep Jain

How do I calculate the MD5 checksum of a file in Python?

You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest(). A function to do this would look like the following:

def File_Checksum_Dis(dirname):
    
    if not os.path.exists(dirname):
        print(dirname+" directory is not existing");
    
    for fname in os.listdir(dirname):
        if not fname.endswith('~'):
            fnaav = os.path.join(dirname, fname);
            fd = open(fnaav, 'rb');
            data = fd.read();
            fd.close();
        
            print("-"*70);
            print("File Name is: ",fname);          
            print(hashlib.md5(data).hexdigest())
            print("-"*70);
                

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Xcode swift am/pm time to 24 hour format

Swift version 3.0.2 , Xcode Version 8.2.1 (8C1002) (12 hr format ):

func getTodayString() -> String{

        let formatter = DateFormatter()
        formatter.dateFormat = "h:mm:ss a "
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"

        let currentDateStr = formatter.string(from: Date())
        print(currentDateStr)
        return currentDateStr 
}

OUTPUT : 12:41:42 AM

Feel free to comment. Thanks

select data up to a space?

select left(col, charindex(' ', col) - 1)

How to solve Permission denied (publickey) error when using Git?

I had a slight different situation, I was logged on to a remote server and was using git on the server, when I ran any git command I got the same message

   Permission denied (publickey).
   fatal: The remote end hung up unexpectedly

The way I fixed it was by changing the file /etc/ssh_config on my Mac. from

ForwardAgent no 

to

ForwardAgent yes

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

How to replace a char in string with an Empty character in C#.NET

I have a latin version of the code of Razvan Dumitru because us use a million indicator even. Offcourse I use a double replace :D

public static string CleanNumb(string numb) 
{
    foreach (char c in ".,'´")
       numb = numb.Replace(c, ' ');

    return numb.Replace(" ", "");
}

Check whether number is even or odd

Least significant bit (rightmost) can be used to check if the number is even or odd. For all Odd numbers, rightmost bit is always 1 in binary representation.

public static boolean checkOdd(long number){
   return ((number & 0x1) == 1);
}

How to show full column content in a Spark Dataframe?

Try this in scala:

df.show(df.count.toInt, false)

The show method accepts an integer and a Boolean value but df.count returns Long...so type casting is required

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

How to print to console when using Qt

If you are printing to stderr using the stdio library, a call to fflush(stderr) should flush the buffer and get you real-time logging.

Javascript : natural sort of alphanumerical strings

The most fully-featured library to handle this as of 2019 seems to be natural-orderby.

const { orderBy } = require('natural-orderby')

const unordered = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12'
]

const ordered = orderBy(unordered)

// [ '19asd',
//   '123asd',
//   '12345asd',
//   'asd12',
//   'asd123' ]

It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.

Surprisingly, it's also only 1.6kB when gzipped.

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

Lately I created a chrome extension "eXtract Snippet" for copying the inspected element, html and only the relevant css and media queries from a page. Note that this would give you the actual relevant CSS

https://chrome.google.com/webstore/detail/extract-snippet/bfcjfegkgdoomgmofhcidoiampnpbdao?hl=en

How to update two tables in one statement in SQL Server 2005?

You can't update two tables at once, but you can link an update into an insert using OUTPUT INTO, and you can use this output as a join for the second update:

DECLARE @ids TABLE (id int);
BEGIN TRANSACTION

UPDATE Table1 
SET Table1.LastName = 'DR. XXXXXX'  
OUTPUT INSERTED.id INTO @ids
WHERE Table1.field = '010008';

UPDATE Table2 
SET Table2.WAprrs = 'start,stop' 
FROM Table2 
JOIN @ids i on i.id = Table2.id;

COMMIT;

I changed your example WHERE condition to be some other field than id. If it's id the you don't need this fancy OUTPUT, you can just UPDATE the second table for the same id='010008'.

OperationalError, no such column. Django

I see we have the same problem here, I have the same error. I want to write this for the future user who will experience the same error. After making changes to your class Snippet model like @Burhan Khalid said, you must migrate tables:

python manage.py makemigrations snippets
python manage.py migrate

And that should resolve the error. Enjoy.

Android webview launches browser when calling loadurl

I just found out that it depends on the formatting of the URL:

My code just uses

webview.loadUrl(url)

no need to set

webView.setWebViewClient(new WebViewClient())

at least in my case. Maybe that's useful for some of you.

How to get data out of a Node.js http get request

Shorter example using http.get:

require('http').get('http://httpbin.org/ip', (res) => {
    res.setEncoding('utf8');
    res.on('data', function (body) {
        console.log(body);
    });
});

How to properly create composite primary keys - MYSQL

@AlexCuse I wanted to add this as comment to your answer but gave up after making multiple failed attempt to add newlines in comments.

That said, t1ID is unique in table_1 but that doesn't makes it unique in INFO table as well.

For example:

Table_1 has:
Id Field
1 A
2 B

Table_2 has:
Id Field
1 X
2 Y

INFO then can have:
t1ID t2ID field
1 1 some
1 2 data
2 1 in-each
2 2 row

So in INFO table to uniquely identify a row you need both t1ID and t2ID

How to remove a column from an existing table?

To add columns in existing table:

ALTER TABLE table_name
 ADD
 column_name DATATYPE NULL  

To delete columns in existing table:

ALTER TABLE table_name
DROP COLUMN column_name

Example for boost shared_mutex (multiple reads/one write)?

1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.

boost::shared_mutex _access;
void reader()
{
  boost::shared_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access
}

void conditional_writer()
{
  boost::upgrade_lock< boost::shared_mutex > lock(_access);
  // do work here, without anyone having exclusive access

  if (something) {
    boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
    // do work here, but now you have exclusive access
  }

  // do more work here, without anyone having exclusive access
}

void unconditional_writer()
{
  boost::unique_lock< boost::shared_mutex > lock(_access);
  // do work here, with exclusive access
}

Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.

python dataframe pandas drop column using int

You can delete column on i index like this:

df.drop(df.columns[i], axis=1)

It could work strange, if you have duplicate names in columns, so to do this you can rename column you want to delete column by new name. Or you can reassign DataFrame like this:

df = df.iloc[:, [j for j, c in enumerate(df.columns) if j != i]]

Parsing Query String in node.js

Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:

// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');

// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';

// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
  // Parse the request URL. Relative URLs require an origin explicitly.
  const url = new URL(request.url, serverOrigin);
  // Parse the URL query. The leading '?' has to be removed before this.
  const query = parseQuery(url.search.substr(1));
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end(`Hello, ${query.name}!\n`);
});

// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);

// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);

If you run the script above, you can test the server response like this, for example:

curl -q http://localhost:8000/status?name=ryan
Hello, ryan!

How to use global variable in node.js?

I would suggest everytime when using global check if the variable is already define by simply check

if (!global.logger){
  global.logger = require('my_logger');
}

I've found it to have better performance

How to merge a Series and DataFrame

You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:

In [27]:

df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
Out[27]:
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:

df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)

This assumes that the indices match the length.

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

which theme you have used in activity add below one line code

for white

<style name="AppTheme.NoActionBar">
      <item name="android:tint">#ffffff</item>
  </style>

or 
 <style name="AppThemeName" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:tint">#ffffff</item>
</style>

for black

   <style name="AppTheme.NoActionBar">
      <item name="android:tint">#000000</item>
  </style>

or 
 <style name="AppThemeName" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:tint">#000000</item>
</style>

How to rollback a specific migration?

Well in rails 5 it's quite easy rake db:migrate:status or rails db:migrate:status

It was modified to handle both the same way Then just pick which Version you want to roll back and then run rake db:migrate VERSION=2013424230423

Make sure VERSION is all capital letters

If you have a problem with any step of the migration or stuck in the middle simply go to the migration file and comment out the lines that were already migrated.

Hope that helps

Draw radius around a point in Google map

Using the Google Maps API V3, create a Circle object, then use bindTo() to tie it to the position of your Marker (since they are both google.maps.MVCObject instances).

// Create marker 
var marker = new google.maps.Marker({
  map: map,
  position: new google.maps.LatLng(53, -2.5),
  title: 'Some location'
});

// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
  map: map,
  radius: 16093,    // 10 miles in metres
  fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');

You can make it look just like the Google Latitude circle by changing the fillColor, strokeColor, strokeWeight etc (full API).

See more source code and example screenshots.

Redirect to specified URL on PHP script completion?

<?
ob_start(); // ensures anything dumped out will be caught

// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever

// clear out the output buffer
while (ob_get_status()) 
{
    ob_end_clean();
}

// no redirect
header( "Location: $url" );
?>

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

The real limits for the alert text are not documented anywhere. The only thing the documentation says is:

In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification Service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)

This is what I could find doing some experiments.

  • Alerts: Prior to iOS 7, the alerts display limit was 107 characters. Bigger messages were truncated and you would get a "..." at the end of the displayed message. With iOS 7 the limit seems to be increased to 235 characters. If you go over 8 lines your message will also get truncated.
  • Banners: Banners get truncated around 62 characters or 2 lines.
  • Notification Center: The messages in the notification center get truncated around 110 characters or 4 lines.
  • Lock Screen: Same as a notification center.

Just as a reminder here is a very good note from the official documentation:

If necessary, iOS truncates your message so that it fits well in each notification delivery style; for best results, you shouldn’t truncate your message.

$(this).serialize() -- How to add a value?

While matt b's answer will work, you can also use .serializeArray() to get an array from the form data, modify it, and use jQuery.param() to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.

var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
    type: 'POST',
    url: this.action,
    data: $.param(data),
});

How to make image hover in css?

Hi you should give parent position relative and child absolute and give to height or width to absolute class as like this

Css

  .nkhome{
    margin-left:260px;
    width:59px;
    height:59px;
    margin-top:170px;
    position:relative;
    z-index:0;
}
.nkhome a:hover img{
    opacity:0.0;
}
.nkhome a:hover{
  background:url('http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg');
    width:100px;
    height:100px;
    position:absolute;
    top:0;
    z-index:1;

}

HTML

 <div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" /></a>
    </div>
?

Live demo http://jsfiddle.net/t5FEX/7/


or this

<div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" onmouseover="this.src='http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg'" 
            onmouseout="this.src='http://dummyimage.com/100/000/fff.jpg'"
            /></a>
    </div>?

Live demo http://jsfiddle.net/t5FEX/9/

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

MySQL "incorrect string value" error when save unicode string in Django

I just figured out one method to avoid above errors.

Save to database

user.first_name = u'Rytis'.encode('unicode_escape')
user.last_name = u'Slatkevicius'.encode('unicode_escape')
user.save()
>>> SUCCEED

print user.last_name
>>> Slatkevi\u010dius
print user.last_name.decode('unicode_escape')
>>> Slatkevicius

Is this the only method to save strings like that into a MySQL table and decode it before rendering to templates for display?

What is the difference between a mutable and immutable string in C#?

All string objects are immutable in C#. Objects of the class string, once created, can never represent any value other than the one they were constructed with. All operations that seem to "change" a string instead produce a new one. This is inefficient with memory, but extremely useful with regard to being able to trust that a string won't change out form under you- because as long as you don't change your reference, the string being referred to will never change.

A mutable object, by contrast, has data fields that can be altered. One or more of its methods will change the contents of the object, or it has a Property that, when written into, will change the value of the object.

If you have a mutable object- the most similar one to String is StringBuffer- then you have to make a copy of it if you want to be absolutely sure it won't change out from under you. This is why mutable objects are dangerous to use as keys into any form of Dictionary or set- the objects themselves could change, and the data structure would have no way of knowing, leading to corrupt data that would, eventually, crash your program.

However, you can change its contents- so it's much, much more memory efficient than making a complete copy because you wanted to change a single character, or something similar.

Generally, the right thing to do is use mutable objects while you're creating something, and immutable objects once you're done. This applies to objects that have immutable forms, of course; most of the collections don't. It's often useful to provide read-only forms of collections, though, which is the equivalent of immutable, when sending the internal state of your collection to other contexts- otherwise, something could take that return value, do something to it, and corrupt your data.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

It looks like you have a certificate in DER format instead of PEM. This is why it works correctly when you provide the -inform PEM command line argument (which tells openssl what input format to expect).

It's likely that your private key is using the same encoding. It looks as if the openssl rsa command also accepts a -inform argument, so try:

openssl rsa -text -in file.key -inform DER

A PEM encoded file is a plain-text encoding that looks something like:

-----BEGIN RSA PRIVATE KEY-----
MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh
ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU
QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw
8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe
-----END RSA PRIVATE KEY-----

While DER is a binary encoding format.

Update

Sometimes keys are distributed in PKCS#8 format (which can be either PEM or DER encoded). Try this and see what you get:

openssl pkcs8 -in file.key -inform der

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Hide Show content-list with only CSS, no javascript used

First, thanks to William.

Second - i needed a dynamic version. And it works!

An example:

CSS:

p[id^="detailView-"]
{
    display: none;
}

p[id^="detailView-"]:target
{
    display: block;
}

HTML:

<a href="#detailView-1">Show View1</a>
<p id="detailView-1">View1</p>

<a href="#detailView-2">Show View2</a>
<p id="detailView-2">View2</p>

What killed my process and why?

This looks like a good article on the subject: Taming the OOM killer.

The gist is that Linux overcommits memory. When a process asks for more space, Linux will give it that space, even if it is claimed by another process, under the assumption that nobody actually uses all of the memory they ask for. The process will get exclusive use of the memory it has allocated when it actually uses it, not when it asks for it. This makes allocation quick, and might allow you to "cheat" and allocate more memory than you really have. However, once processes start using this memory, Linux might realize that it has been too generous in allocating memory it doesn't have, and will have to kill off a process to free some up. The process to be killed is based on a score taking into account runtime (long-running processes are safer), memory usage (greedy processes are less safe), and a few other factors, including a value you can adjust to make a process less likely to be killed. It's all described in the article in a lot more detail.

Edit: And here is another article that explains pretty well how a process is chosen (annotated with some kernel code examples). The great thing about this is that it includes some commentary on the reasoning behind the various badness() rules.

how to generate public key from windows command prompt

If you've got git-bash installed (which comes with Git, Github for Windows, or Visual Studio 2015), then that includes a Windows version of ssh-keygen.

https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

Mysql - delete from multiple tables with one query

A join statement is unnecessarily complicated in this situation. The original question only deals with deleting records for a given user from multiple tables at the same time. Intuitively, you might expect something like this to work:

DELETE FROM table1,table2,table3,table4 WHERE user_id='$user_id'

Of course, it doesn't. But rather than writing multiple statements (redundant and inefficient), using joins (difficult for novices), or foreign keys (even more difficult for novices and not available in all engines or existing datasets) you could simplify your code with a LOOP!

As a basic example using PHP (where $db is your connection handle):

$tables = array("table1","table2","table3","table4");
foreach($tables as $table) {
  $query = "DELETE FROM $table WHERE user_id='$user_id'";
  mysqli_query($db,$query);
}

Hope this helps someone!

How do I use popover from Twitter Bootstrap to display an image?

Here I have an example of Bootstrap 3 popover showing an image with the tittle above it when the mouse hovers over some text. I've put in some inline styling that you may want to take out or change.....

This also works pretty well on mobile devices because the image will popup on the first tap and the link will open on the second. html:

<h5><a href="#" title="Solid Tiles Template" target="_blank" data-image-url="http://s29.postimg.org/t5pik8lyf/tiles1_preview.jpg" class="preview" rel="popover" style="color: green; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 1 <i class="fa fa-external-link"></i></a></h5>

<h5><a href="#" title="Clear Tiles Template" target="_blank" data-image-url="http://s9.postimg.org/rdonet7jj/tiles2_2_preview.jpg" class="preview" rel="popover" style="color: red; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 2 <i class="fa fa-external-link"></i></a></h5>

<h5><a href="#" title="Clear Tiles Template" target="_blank" data-image-url="http://s27.postimg.org/8scrcdu9v/tiles3_3_preview.jpg" class="preview" rel="popover" style="color: blue; font-style: normal; font-weight: bolder; font-size: 16px;">Template Preview 3 <i class="fa fa-external-link"></i></a></h5>

js:

$('.preview').popover({
    'trigger':'hover',
    'html':true,
    'content':function(){
        return "<img src='"+$(this).data('imageUrl')+"'>";
    }
});

https://jsfiddle.net/pepsimax_uk/myk38781/3/

Split array into chunks

Here's a version with tail recursion and array destructuring.

Far from the fastest performance, but I'm just amused that js can do this now. Even if it isn't optimized for it :(

const getChunks = (arr, chunk_size, acc = []) => {
    if (arr.length === 0) { return acc }
    const [hd, tl] = [ arr.slice(0, chunk_size), arr.slice(chunk_size) ]
    return getChunks(tl, chunk_size, acc.concat([hd]))
}

// USAGE
const my_arr = [1,2,3,4,5,6,7,8,9]
const chunks = getChunks(my_arr, 2)
console.log(chunks) // [[1,2],[3,4], [5,6], [7,8], [9]]

jQuery Toggle Text?

this is not the very clean and smart way but its very easy to understand and use somtimes - its like odd and even - boolean like:

  var moreOrLess = 2;

  $('.Btn').on('click',function(){

     if(moreOrLess % 2 == 0){
        $(this).text('text1');
        moreOrLess ++ ;
     }else{
        $(this).text('more'); 
        moreOrLess ++ ;
     }

});

Add text at the end of each line

You could try using something like:

sed -n 's/$/:80/' ips.txt > new-ips.txt

Provided that your file format is just as you have described in your question.

The s/// substitution command matches (finds) the end of each line in your file (using the $ character) and then appends (replaces) the :80 to the end of each line. The ips.txt file is your input file... and new-ips.txt is your newly-created file (the final result of your changes.)


Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:

sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt

So, for example, if your input file looked something like this (note the :80):

127.0.0.1
128.0.0.0:80
121.121.33.111

The final result would look something like this:

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

Combine several images horizontally with Python

""" 
merge_image takes three parameters first two parameters specify 
the two images to be merged and third parameter i.e. vertically
is a boolean type which if True merges images vertically
and finally saves and returns the file_name
"""
def merge_image(img1, img2, vertically):
    images = list(map(Image.open, [img1, img2]))
    widths, heights = zip(*(i.size for i in images))
    if vertically:
        max_width = max(widths)
        total_height = sum(heights)
        new_im = Image.new('RGB', (max_width, total_height))

        y_offset = 0
        for im in images:
            new_im.paste(im, (0, y_offset))
            y_offset += im.size[1]
    else:
        total_width = sum(widths)
        max_height = max(heights)
        new_im = Image.new('RGB', (total_width, max_height))

        x_offset = 0
        for im in images:
            new_im.paste(im, (x_offset, 0))
            x_offset += im.size[0]

    new_im.save('test.jpg')
    return 'test.jpg'

How to test my servlet using JUnit

Use Selenium for webbased unit tests. There's a Firefox plugin called Selenium IDE which can record actions on the webpage and export to JUnit testcases which uses Selenium RC to run the test server.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Use a content script to access the page context variables and functions

You can use a utility function I've created for the purpose of running code in the page context and getting back the returned value.

This is done by serializing a function to a string and injecting it to the web page.

The utility is available here on GitHub.

Usage examples -



// Some code that exists only in the page context -
window.someProperty = 'property';
function someFunction(name = 'test') {
    return new Promise(res => setTimeout(()=>res('resolved ' + name), 1200));
}
/////////////////

// Content script examples -

await runInPageContext(() => someProperty); // returns 'property'

await runInPageContext(() => someFunction()); // returns 'resolved test'

await runInPageContext(async (name) => someFunction(name), 'with name' ); // 'resolved with name'

await runInPageContext(async (...args) => someFunction(...args), 'with spread operator and rest parameters' ); // returns 'resolved with spread operator and rest parameters'

await runInPageContext({
    func: (name) => someFunction(name),
    args: ['with params object'],
    doc: document,
    timeout: 10000
} ); // returns 'resolved with params object'


How can I write maven build to add resources to classpath?

By default maven does not include any files from "src/main/java".

You have two possible way to that.

  1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

  2. Add to your pom (resource plugin):

?

 <resources>
       <resource>
           <directory>src/main/resources</directory>
        </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
  </resources>

How to draw a standard normal distribution in R

I am pretty sure this is a duplicate. Anyway, have a look at the following piece of code

x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=3)
plot(x, y, type="l", lwd=1)

I'm sure you can work the rest out yourself, for the title you might want to look for something called main= and y-axis labels are also up to you.

If you want to see more of the tails of the distribution, why don't you try playing with the seq(5, 15, ) section? Finally, if you want to know more about what dnorm is doing I suggest you look here

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

Find index of last occurrence of a sub-string using T-SQL

Reverse both your string and your substring, then search for the first occurrence.

Cannot refer to a non-final variable inside an inner class defined in a different method

Just an another explanation. Consider this example below

public class Outer{
     public static void main(String[] args){
         Outer o = new Outer();
         o.m1();        
         o=null;
     }
     public void m1(){
         //int x = 10;
         class Inner{
             Thread t = new Thread(new Runnable(){
                 public void run(){
                     for(int i=0;i<10;i++){
                         try{
                             Thread.sleep(2000);                            
                         }catch(InterruptedException e){
                             //handle InterruptedException e
                         }
                         System.out.println("Thread t running");                             
                     }
                 }
             });
         }
         new Inner().t.start();
         System.out.println("m1 Completes");
    }
}

Here Output will be

m1 Completes

Thread t running

Thread t running

Thread t running

................

Now method m1() completes and we assign reference variable o to null , Now Outer Class Object is eligible for GC but Inner Class Object is still exist who has (Has-A) relationship with Thread object which is running. Without existing Outer class object there is no chance of existing m1() method and without existing m1() method there is no chance of existing its local variable but if Inner Class Object uses the local variable of m1() method then everything is self explanatory.

To solve this we have to create a copy of local variable and then have to copy then into the heap with Inner class object, what java does for only final variable because they are not actually variable they are like constants(Everything happens at compile time only not at runtime).

Javascript callback when IFRAME is finished loading?

The innerHTML of your iframe is blank because your iframe tag doesn't surround any content in the parent document. In order to get the content from the page referred to by the iframe's src attribute, you need to access the iframe's contentDocument property. An exception will be thrown if the src is from a different domain though. This is a security feature that prevents you from executing arbitrary JavaScript on someone else's page, which would create a cross-site scripting vulnerability. Here is some example code the illustrates what I'm talking about:

<script src="http://prototypejs.org/assets/2009/8/31/prototype.js" type="text/javascript"></script>

<h1>Parent</h1>

<script type="text/javascript">
function on_load(iframe) {
  try {
    // Displays the first 50 chars in the innerHTML of the
    // body of the page that the iframe is showing.
    // EDIT 2012-04-17: for wider support, fallback to contentWindow.document
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    alert(doc.body.innerHTML.substring(0, 50));
  } catch (e) {
    // This can happen if the src of the iframe is
    // on another domain
    alert('exception: ' + e);
  }
}
</script>
<iframe id="child" src="iframe_content.html" onload="on_load(this)"></iframe>

To further the example, try using this as the content of the iframe:

<h1>Child</h1>

<a href="http://www.google.com/">Google</a>

<p>Use the preceeding link to change the src of the iframe
to see what happens when the src domain is different from
that of the parent page</p>

Display special characters when using print statement

Use repr:

a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

_x000D_
_x000D_
.contents {
  width: 50%;
  border: 1px solid black;
  height: 300px;
  overflow: auto;
}

table {
  position: relative;
}

th {
  position: sticky;
  top: 0;
  background: #ffffff;
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="contents">
  <table class="table">
    <thead>
      <tr>
        <th>colunn 1</th>
        <th>colunn 2</th>
        <th>colunn 3</th>
        <th>colunn 4</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Example 1</td>
        <td>Example 2</td>
        <td>Example 3</td>
        <td>Example 4</td>
        <tr>
          <tr>
            <td>Example 1</td>
            <td>Example 2</td>
            <td>Example 3</td>
            <td>Example 4</td>
            <tr>
              <tr>
                <td>Example 1</td>
                <td>Example 2</td>
                <td>Example 3</td>
                <td>Example 4</td>
                <tr>
                  <tr>
                    <td>Example 1</td>
                    <td>Example 2</td>
                    <td>Example 3</td>
                    <td>Example 4</td>
                    <tr>
                      <tr>
                        <td>Example 1</td>
                        <td>Example 2</td>
                        <td>Example 3</td>
                        <td>Example 4</td>
                        <tr>
                          <tr>
                            <td>Example 1</td>
                            <td>Example 2</td>
                            <td>Example 3</td>
                            <td>Example 4</td>
                            <tr>
                              <tr>
                                <td>Example 1</td>
                                <td>Example 2</td>
                                <td>Example 3</td>
                                <td>Example 4</td>
                                <tr>
                                  <tr>
                                    <td>Example 1</td>
                                    <td>Example 2</td>
                                    <td>Example 3</td>
                                    <td>Example 4</td>
                                    <tr>
                                      <tr>
                                        <td>Example 1</td>
                                        <td>Example 2</td>
                                        <td>Example 3</td>
                                        <td>Example 4</td>
                                        <tr>
                                          <tr>
                                            <td>Example 1</td>
                                            <td>Example 2</td>
                                            <td>Example 3</td>
                                            <td>Example 4</td>
                                            <tr>
    </tbody>
  </table>
</div>
_x000D_
_x000D_
_x000D_

How do you fix the "element not interactable" exception?

For the html code:

test.html

<button class="dismiss"  onclick="alert('hello')">
    <string for="exit">Dismiss</string>
</button>

the below python code worked for me. You can just try it.

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()

Maven plugin not using Eclipse's proxy settings

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">

     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>proxy.somewhere.com</host>
          <port>8080</port>
          <username>proxyuser</username>
          <password>somepassword</password>
          <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
        </proxy>
      </proxies>

    </settings>

Window > Preferences > Maven > User Settings

enter image description here

TCP: can two different sockets share a port?

A server socket listens on a single port. All established client connections on that server are associated with that same listening port on the server side of the connection. An established connection is uniquely identified by the combination of client-side and server-side IP/Port pairs. Multiple connections on the same server can share the same server-side IP/Port pair as long as they are associated with different client-side IP/Port pairs, and the server would be able to handle as many clients as available system resources allow it to.

On the client-side, it is common practice for new outbound connections to use a random client-side port, in which case it is possible to run out of available ports if you make a lot of connections in a short amount of time.

Foreign key referring to primary keys across multiple tables?

Assuming you must have two tables for the two employee types for some reason, I'll extend on vmarquez's answer:

Schema:

employees_ce (id, name)
employees_sn (id, name)
deductions (id, parentId, parentType, name)

Data in deductions:

deductions table
id      parentId      parentType      name
1       1             ce              gold
2       1             sn              silver
3       2             sn              wood
...

This would allow you to have deductions point to any other table in your schema. This kind of relation isn't supported by database-level constraints, IIRC so you'll have to make sure your App manages the constraint properly (which makes it more cumbersome if you have several different Apps/services hitting the same database).

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

Visual Studio mac - you can change the support here:

enter image description here

mysql: get record count between two date-time

select * from yourtable 
   where created < now() 
     and created > concat(curdate(),' 4:30:00 AM') 

Importing csv file into R - numeric values read as characters

If you're dealing with large datasets (i.e. datasets with a high number of columns), the solution noted above can be manually cumbersome, and requires you to know which columns are numeric a priori.

Try this instead.

char_data <- read.csv(input_filename, stringsAsFactors = F)
num_data <- data.frame(data.matrix(char_data))
numeric_columns <- sapply(num_data,function(x){mean(as.numeric(is.na(x)))<0.5})
final_data <- data.frame(num_data[,numeric_columns], char_data[,!numeric_columns])

The code does the following:

  1. Imports your data as character columns.
  2. Creates an instance of your data as numeric columns.
  3. Identifies which columns from your data are numeric (assuming columns with less than 50% NAs upon converting your data to numeric are indeed numeric).
  4. Merging the numeric and character columns into a final dataset.

This essentially automates the import of your .csv file by preserving the data types of the original columns (as character and numeric).

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try this:

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

Configuring angularjs with eclipse IDE

Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.

Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development

How can I compile LaTeX in UTF8?

\usepackage[utf8]{inputenc} will not work for a bibliographic entry such as this:

@ARTICLE{Hardy2007,
author = {Ibn Taymiyyah, A?mad ibn ?Abd al{-}Halim},
title = {Naq? al{-}man?iq},
shorttitle = {Naq? al-man?iq},
editor = {?amzah, A?mad},
publisher = {Maktabat a{l-}Sunnah},
address = {Cairo},
year = {1970},
sortname = {IbnTaymiyyaNaqdalmantiq},
keywords = { Logic, Medieval}} 

For this entry use \usepackage[utf8x]{inputenc}

PHP Error: Cannot use object of type stdClass as array (array and object issues)

If you're iterating over an object instead of an array, you'll need to access the properties using:

$id = $blog->id;
$title = $blog->title;
$content = $blog->content;

That, or change your object to an array.

How to press/click the button using Selenium if the button does not have the Id?

For Next button you can use xpath or cssSelector as below:

xpath for Next button: //input[@value='Next']

cssPath for Next button: input[value=Next]

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

Change http to https of the marked error or all the URL ending with *.xsd extension.

Subtracting time.Duration from time in Go

There's time.ParseDuration which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.

E.g. when you need to substract an hour and a half, you can do that like so:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    duration, _ := time.ParseDuration("-1.5h")

    then := now.Add(duration)

    fmt.Println("then:", then)
}

https://play.golang.org/p/63p-T9uFcZo

Android 'Unable to add window -- token null is not for an application' exception

I'm guessing - are you trying to create Dialog using.

 getApplicationContext()
 mContext which is passed by activity.

if You displaying dialog non activity class then you have to pass activity as a parameter.

Activity activity=YourActivity.this;

Now it will be work great.

If you find any trouble then let me know.

codeigniter model error: Undefined property

It solved throung second parameter in Model load:

$this->load->model('user','User');

first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
{
$this->load->model('User');
$result = $this->User->showusers();
}

how to get text from textview

Try Like this.

tv1.setText("  " + Integer.toString(X[i]) + "\n" + "+" + " " + Integer.toString(Y[i]));

Only on Firefox "Loading failed for the <script> with source"

As suggested above, this could possibly be an issue with your browser extensions. Disable all of your extensions including Adblock, and then try again as the code is loading fine in my browser right now (Google Chrome - latest) so it's probably an issue on your end. Also, have you tried a different browser like shudders IE if you have it? Adblock is known to conflict with domain names with track and market in them as a blanket rule. Try using private browsing mode or safe mode.

What is Ad Hoc Query?

Also want to add that ad hoc query is vulnerable to SQL injection attacks. We should try to avoid using it and use parameterized SQLs instead (like PreparedStatement in Java).

How to ignore certain files in Git

Create a .gitignore in the directory where .git is. You can list files in it separated by a newline. You also can use wildcards:

*.o
.*.swp

Java Look and Feel (L&F)

You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.

Just download the jar and import it into your classpath, or add it as a maven dependency:

<dependency>
        <groupId>com.jtattoo</groupId>
        <artifactId>JTattoo</artifactId>
        <version>1.6.11</version>
</dependency>

Here is a list of some of the cool themes they have available:

  • com.jtattoo.plaf.acryl.AcrylLookAndFeel
  • com.jtattoo.plaf.aero.AeroLookAndFeel
  • com.jtattoo.plaf.aluminium.AluminiumLookAndFeel
  • com.jtattoo.plaf.bernstein.BernsteinLookAndFeel
  • com.jtattoo.plaf.fast.FastLookAndFeel
  • com.jtattoo.plaf.graphite.GraphiteLookAndFeel
  • com.jtattoo.plaf.hifi.HiFiLookAndFeel
  • com.jtattoo.plaf.luna.LunaLookAndFeel
  • com.jtattoo.plaf.mcwin.McWinLookAndFeel
  • com.jtattoo.plaf.mint.MintLookAndFeel
  • com.jtattoo.plaf.noire.NoireLookAndFeel
  • com.jtattoo.plaf.smart.SmartLookAndFeel
  • com.jtattoo.plaf.texture.TextureLookAndFeel
  • com.jtattoo.plaf.custom.flx.FLXLookAndFeel

Regards

SQL Server: Invalid Column Name

If you are going to ALTER Table column and immediate UPDATE the table including the new column in the same script. Make sure that use GO command to after line of code of alter table as below.

ALTER TABLE Location 
ADD TransitionType SMALLINT NULL
GO   

UPDATE Location SET TransitionType =  4

ALTER TABLE Location 
    ALTER COLUMN TransitionType SMALLINT NOT NULL

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

In Java, how do I get the difference in seconds between 2 dates?

Not familiar with DateTime...

If you have two Dates you can call getTime on them to get millseconds, get the diff and divide by 1000. For example

Date d1 = ...;
Date d2 = ...;
long seconds = (d2.getTime()-d1.getTime())/1000;

If you have Calendar objects you can call

c.getTimeInMillis()

and do the same

Using Predicate in Swift

Use The Below code:

 func filterContentForSearchText(searchText:NSString, scopes scope:NSString)
{
    //var searchText = ""

    var resultPredicate : NSPredicate = NSPredicate(format: "name contains[c]\(searchText)", nil)

    //var recipes : NSArray = NSArray()

    var searchResults = recipes.filteredArrayUsingPredicate(resultPredicate)
}

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Two statements next to curly brace in an equation

Or this:

f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}

Eclipse error: 'Failed to create the Java Virtual Machine'

The problem appeared first right after patching DCEVM with version: DCEVM-8u181-installer.jar.

Then, temoving the flag -XX:+UseG1GC from eclipse.ini it fixed the issue.

Python List vs. Array - when to use?

Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t).

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).

array.array is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray.

However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.

To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.

MongoDB query multiple collections at once

As mentioned before in MongoDB you can't JOIN between collections.

For your example a solution could be:

var myCursor = db.users.find({admin:1});
var user_id = myCursor.hasNext() ? myCursor.next() : null;
db.posts.find({owner_id : user_id._id});

See the reference manual - cursors section: http://es.docs.mongodb.org/manual/core/cursors/

Other solution would be to embed users in posts collection, but I think for most web applications users collection need to be independent for security reasons. Users collection might have Roles, permissons, etc.

posts
{
 "content":"Some content",
 "user":{"_id":"12345", "admin":1},
 "via":"facebook"
},
{
 "content":"Some other content",
 "user":{"_id":"123456789", "admin":0},
 "via":"facebook"
}

and then:

db.posts.find({user.admin: 1 });

What is the command for cut copy paste a file from one directory to other directory

E:>move "blogger code.txt" d:/"blogger code.txt"

    1 file(s) moved.

"blogger code.txt" is a file name

The file move from E: drive to D: drive

Laravel: Get base url

Check this -

<a href="{{url('/abc/xyz')}}">Go</a>

This is working for me and I hope it will work for you.

How to perform OR condition in django queryset?

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

via Documentation

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Change the default base url for axios

From axios docs you have baseURL and url

baseURL will be prepended to url when making requests. So you can define baseURL as http://127.0.0.1:8000 and make your requests to /url

 // `url` is the server URL that will be used for the request
 url: '/user',

 // `baseURL` will be prepended to `url` unless `url` is absolute.
 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
 // to methods of that instance.
 baseURL: 'https://some-domain.com/api/',

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

Get index of clicked element in collection with jQuery

if you are using .bind(this), try this:

let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

$(this.pagination).find("a").on('click', function(evt) {
        let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);

        this.goTo(index);
    }.bind(this))

Load a WPF BitmapImage from a System.Drawing.Bitmap

My take on this built from a number of resources. https://stackoverflow.com/a/7035036 https://stackoverflow.com/a/1470182/360211

using System;
using System.Drawing;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using Microsoft.Win32.SafeHandles;

namespace WpfHelpers
{
    public static class BitmapToBitmapSource
    {
        public static BitmapSource ToBitmapSource(this Bitmap source)
        {
            using (var handle = new SafeHBitmapHandle(source))
            {
                return Imaging.CreateBitmapSourceFromHBitmap(handle.DangerousGetHandle(),
                    IntPtr.Zero, Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
            }
        }

        [DllImport("gdi32")]
        private static extern int DeleteObject(IntPtr o);

        private sealed class SafeHBitmapHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            [SecurityCritical]
            public SafeHBitmapHandle(Bitmap bitmap)
                : base(true)
            {
                SetHandle(bitmap.GetHbitmap());
            }

            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            protected override bool ReleaseHandle()
            {
                return DeleteObject(handle) > 0;
            }
        }
    }
}

Add a reference column migration in Rails 4

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID

How do you implement a Stack and a Queue in JavaScript?

The regular Array structure in Javascript is a Stack (first in, last out) and can also be used as a Queue (first in, first out) depending on the calls you make.

Check this link to see how to make an Array act like a Queue:

Queues

Mockito verify order / sequence of method calls

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}

SELECT INTO Variable in MySQL DECLARE causes syntax error?

SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,... FROM table_name WHERE condition;

Using Vim's tabs like buffers

Vim :help window explains the confusion "tabs vs buffers" pretty well.

A buffer is the in-memory text of a file.
A window is a viewport on a buffer.
A tab page is a collection of windows.

Opening multiple files is achieved in vim with buffers. In other editors (e.g. notepad++) this is done with tabs, so the name tab in vim maybe misleading.

Windows are for the purpose of splitting the workspace and displaying multiple files (buffers) together on one screen. In other editors this could be achieved by opening multiple GUI windows and rearranging them on the desktop.

Finally in this analogy vim's tab pages would correspond to multiple desktops, that is different rearrangements of windows.

As vim help: tab-page explains a tab page can be used, when one wants to temporarily edit a file, but does not want to change anything in the current layout of windows and buffers. In such a case another tab page can be used just for the purpose of editing that particular file.

Of course you have to remember that displaying the same file in many tab pages or windows would result in displaying the same working copy (buffer).

Table with table-layout: fixed; and how to make one column wider

You could just give the first cell (therefore column) a width and have the rest default to auto

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  width: 150px;_x000D_
}_x000D_
td+td {_x000D_
  width: auto;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>150px</td>_x000D_
    <td>equal</td>_x000D_
    <td>equal</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_


or alternatively the "proper way" to get column widths might be to use the col element itself

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
.wide {_x000D_
  width: 150px;_x000D_
}
_x000D_
<table>_x000D_
  <col span="1" class="wide">_x000D_
    <tr>_x000D_
      <td>150px</td>_x000D_
      <td>equal</td>_x000D_
      <td>equal</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

Get full path of the files in PowerShell

[alternative syntax]

For some people, directional pipe operators are not their taste, but they rather prefer chaining. See some interesting opinions on this topic shared in roslyn issue tracker: dotnet/roslyn#5445.

Based on the case and the context, one of this approach can be considered implicit (or indirect). For example, in this case using pipe against enumerable requires special token $_ (aka PowerShell's "THIS" token) might appear distasteful to some.

For such fellas, here is a more concise, straight-forward way of doing it with dot chaining:

(gci . -re -fi *.txt).FullName

(<rant> Note that PowerShell's command arguments parser accepts the partial parameter names. So in addition to -recursive; -recursiv, -recursi, -recurs, -recur, -recu, -rec and -re are accepted, but unfortunately not -r .. which is the only correct choice that makes sense with single - character (if we go by POSIXy UNIXy conventions)! </rant>)

What are the sizes used for the iOS application splash screen?

You can make them 1024 x 768. You can also check "Status bar is initially hidden" in the plist file.

Copy or rsync command

if you are using cp doesn't save existing files when copying folders of the same name. Lets say you have this folders:

/myFolder
  someTextFile.txt

/someOtherFolder
  /myFolder
    wellHelloThere.txt

Then you copy one over the other:

cp /someOtherFolder/myFolder /myFolder

result:

/myFolder
  wellHelloThere.txt

This is at least what happens on macOS and I wanted to preserve the diff files so I used rsync.

Getting the document object of an iframe

For even more robustness:

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;
}

and

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

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

Min / Max Validator in Angular 2 Final

Find the custom validator for min number validation. The selector name of our directive is customMin.

custom-min-validator.directive.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[customMin][formControlName],[customMin][formControl],[customMin][ngModel]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomMinDirective, multi: true}]
})
export class CustomMinDirective implements Validator {
  @Input()
  customMin: number;

  validate(c: FormControl): {[key: string]: any} {
      let v = c.value;
      return ( v < this.customMin)? {"customMin": true} : null;
  }
} 

Find the custom validator for max number validation. The selector name of our directive is customMax.

custom-max-validator.directive.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[customMax][formControlName],[customMax][formControl],[customMax][ngModel]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomMaxDirective, multi: true}]
})
export class CustomMaxDirective implements Validator {
  @Input()
  customMax: number;

  validate(c: FormControl): {[key: string]: any} {
      let v = c.value;
      return ( v > this.customMax)? {"customMax": true} : null;
  }
} 

We can use customMax with formControlName, formControl and ngModel attributes.

Using Custom Min and Max Validator in Template-driven Form

We will use our custom min and max validator in template-driven form. For min number validation we have customMin attribute and for max number validation we have customMax attribute. Now find the code snippet for validation.

<input name="num1" [ngModel]="user.num1" customMin="15" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" customMax="50"  #numberTwo="ngModel"> 

We can show validation error messages as following.

<div *ngIf="numberOne.errors?.customMin"> 
     Minimum required number is 15.
</div>  

<div *ngIf="numberTwo.errors?.customMax"> 
     Maximum number can be 50.
</div> 

To assign min and max number we can also use property biding. Suppose we have following component properties.

minNum = 15;
maxNum = 50; 

Now use property binding for customMin and customMax as following.

<input name="num1" [ngModel]="user.num1" [customMin]="minNum" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" [customMax]="maxNum"  #numberTwo="ngModel"> 

Given URL is not permitted by the application configuration

Missing from the other answers is how to allow localhost(or 0.0.0.0 or whatever) as an oauth callback url. Here is the explanation. How can I add localhost:3000 to Facebook App for development

How to prevent going back to the previous activity?

Just override the onKeyDown method and check if the back button was pressed.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        //Back buttons was pressed, do whatever logic you want
    }

    return false;
}

What is the Ruby <=> (spaceship) operator?

It's a general comparison operator. It returns either a -1, 0, or +1 depending on whether its receiver is less than, equal to, or greater than its argument.

Java: How to set Precision for double value?

public static String setPrecision(String number, int decimal) {
    double nbr = Double.valueOf(number);
    int integer_Part = (int) nbr;
    double float_Part = nbr - integer_Part;
    int floating_point = (int) (Math.pow(10, decimal) * float_Part);
    String final_nbr = String.valueOf(integer_Part) + "." + String.valueOf(floating_point);
    return final_nbr;
}

When does Git refresh the list of remote branches?

Use git fetch to fetch all latest created branches.

What are the rules for calling the superclass constructor?

If you have default parameters in your base constructor the base class will be called automatically.

using namespace std;

class Base
{
    public:
    Base(int a=1) : _a(a) {}

    protected:
    int _a;
};

class Derived : public Base
{
  public:
  Derived() {}

  void printit() { cout << _a << endl; }
};

int main()
{
   Derived d;
   d.printit();
   return 0;
}

Output is: 1

Find value in an array

I'm guessing that you're trying to find if a certain value exists inside the array, and if that's the case, you can use Array#include?(value):

a = [1,2,3,4,5]
a.include?(3)   # => true
a.include?(9)   # => false

If you mean something else, check the Ruby Array API

How can I get an HTTP response body as a string?

If you are using Jackson to deserialize the response body, one very simple solution is to use request.getResponseBodyAsStream() instead of request.getResponseBodyAsString()

How to switch to other branch in Source Tree to commit the code?

  1. Go to the log view (to be able to go here go to View -> log view).
  2. Double click on the line with the branch label stating that branch. Automatically, it will switch branch. (A prompt will dropdown and say switching branch.)
  3. If you have two or more branches on the same line, it will ask you via prompt which branch you want to switch. Choose the specific branch from the dropdown and click ok.

To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.

I get exception when using Thread.sleep(x) or wait()

A simpler way to wait is to use System.currentTimeMillis(), which returns the number of milliseconds since midnight on January 1, 1970 UTC. For example, to wait 5 seconds:

public static void main(String[] args) {
    //some code
    long original = System.currentTimeMillis();
    while (true) {
        if (System.currentTimeMillis - original >= 5000) {
            break;
        }
    }
    //more code after waiting
}

This way, you don't have to muck about with threads and exceptions. Hope this helps!

How to check user is "logged in"?

The simplest way:

if (Request.IsAuthenticated) ...

How to edit data in result grid in SQL Server Management Studio

If the query is written as a view, you can edit the view and update values. Updating values is not possible for all views. It is possible only for specific views. See Modifying Data Through View MSDN Link for more information. You can create view for the query and edit the 200 rows as given below:

enter image description here

How line ending conversions work with git core.autocrlf between different operating systems

The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:

  1. The repo may have different files with different EOLs
  2. Some files in the repo may have mixed EOL, e.g. a combination of CRLF and LF in the same file.

How this happens is not the issue here, but it does happen.

I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:

                 | Resulting conversion when       | Resulting conversion when 
                 | committing files with various   | checking out FROM repo - 
                 | EOLs INTO repo and              | with mixed files in it and
                 |  core.autocrlf value:           | core.autocrlf value:           
--------------------------------------------------------------------------------
File             | true       | input      | false | true       | input | false
--------------------------------------------------------------------------------
Windows-CRLF     | CRLF -> LF | CRLF -> LF | as-is | as-is      | as-is | as-is
Unix -LF         | as-is      | as-is      | as-is | LF -> CRLF | as-is | as-is
Mac  -CR         | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF    | as-is      | as-is      | as-is | as-is      | as-is | as-is
Mixed-CRLF+LF+CR | as-is      | as-is      | as-is | as-is      | as-is | as-is

As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.

Upon checkout (3 right columns), there is only 1 case where conversion happens when:

  1. core.autocrlf is true and
  2. the file in the repo has the LF EOL.

Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF+LF get normalized.

Note also that "old" Mac EOLs of CR only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLFs+LFs, by just converting LFs to CRLFs, then it will leave the file in a mixed mode with "lonely" CRs wherever a CRLF was converted to CRCRLF.
Git will then not convert anything, even in true mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.

I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input or false mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true.

Mock functions in Go

Warning: This might inflate executable file size a little bit and cost a little runtime performance. IMO, this would be better if golang has such feature like macro or function decorator.

If you want to mock functions without changing its API, the easiest way is to change the implementation a little bit:

func getPage(url string) string {
  if GetPageMock != nil {
    return GetPageMock()
  }

  // getPage real implementation goes here!
}

func downloader() {
  if GetPageMock != nil {
    return GetPageMock()
  }

  // getPage real implementation goes here!
}

var GetPageMock func(url string) string = nil
var DownloaderMock func() = nil

This way we can actually mock one function out of the others. For more convenient we can provide such mocking boilerplate:

// download.go
func getPage(url string) string {
  if m.GetPageMock != nil {
    return m.GetPageMock()
  }

  // getPage real implementation goes here!
}

func downloader() {
  if m.GetPageMock != nil {
    return m.GetPageMock()
  }

  // getPage real implementation goes here!
}

type MockHandler struct {
  GetPage func(url string) string
  Downloader func()
}

var m *MockHandler = new(MockHandler)

func Mock(handler *MockHandler) {
  m = handler
}

In test file:

// download_test.go
func GetPageMock(url string) string {
  // ...
}

func TestDownloader(t *testing.T) {
  Mock(&MockHandler{
    GetPage: GetPageMock,
  })

  // Test implementation goes here!

  Mock(new(MockHandler)) // Reset mocked functions
}

CSS fixed width in a span

Using HTML 5.0, it is possible to fix width of text block using <span> or <div>.

enter image description here

For <span>, what is important is to add following CCS line

display: inline-block;

For your empty <span> what is important is to add &nbsp; space.

My code is following

_x000D_
_x000D_
body_x000D_
 {_x000D_
 font-family: Arial;_x000D_
 font-size:20px;_x000D_
 }_x000D_
_x000D_
div_x000D_
 {_x000D_
 width:200px;_x000D_
 font-size:80px;_x000D_
 background-color: lime;_x000D_
 }_x000D_
div span_x000D_
 {_x000D_
 display:block;_x000D_
 width:200px;_x000D_
 background-color: lime;_x000D_
 }_x000D_
_x000D_
ul li span_x000D_
 {_x000D_
 display: inline-block;_x000D_
 width: 80px;_x000D_
 background-color: yellow;_x000D_
 }_x000D_
span.tab_x000D_
 {_x000D_
 display: inline-block;_x000D_
 width: 80px;_x000D_
 background-color: yellow;_x000D_
 }
_x000D_
&lt;DIV&gt;_x000D_
_x000D_
<div class='test'>ABCDEF</div>_x000D_
_x000D_
&lt;SPAN&gt;_x000D_
_x000D_
<div>_x000D_
    <span class='test'>ABCDEF</span>_x000D_
</div_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
  <li><span class='tab'>&nbsp;</span> The lazy dog.</li>_x000D_
  <li><span class='tab'>AND</span> The lazy cat.</li>_x000D_
  <li><span class='tab'>OR</span> The active goldfish.</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

PS: I have defined tab class because ul li span CSS selector is not working on my PC !

Reading a huge .csv file

Although Martijin's answer is prob best. Here is a more intuitive way to process large csv files for beginners. This allows you to process groups of rows, or chunks, at a time.

import pandas as pd
chunksize = 10 ** 8
for chunk in pd.read_csv(filename, chunksize=chunksize):
    process(chunk)

Attach parameter to button.addTarget action in Swift

Swift 5.0 code

I use theButton.tag but if i have plenty type of option, its be very long switch case.

theButton.addTarget(self, action: #selector(theFunc), for: .touchUpInside) 
theButton.frame.name = "myParameter"

.

@objc func theFunc(sender:UIButton){ 
print(sender.frame.name)
}

How to select <td> of the <table> with javascript?

try document.querySelectorAll("#table td");

C# Set collection?

I use Iesi.Collections http://www.codeproject.com/KB/recipes/sets.aspx

It's used in lot of OSS projects, I first came across it in NHibernate

Postman: sending nested JSON object

Just wanted to add one more problem that some people might find on top of all the other answers. Sending JSON object using RAW data and setting the type to application/json is what is to be done as has been mentioned above.

Even though I had done so, I got error in the POSTMAN request, it was because I accidentally forgot to create a default constructor for both child class.

Say if I had to send a JSON of format:

{
 "firstname" : "John",
 "lastname" : "Doe",
 "book":{
   "name":"Some Book",
   "price":12.2
  }
}

Then just make sure you create a default constructor for Book class.

I know this is a simple and uncommon error, but did certainly help me.

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

HTML Input="file" Accept Attribute File Type (CSV)

These days you can just use the file extension

<input type="file" ID="fileSelect" accept=".xlsx, .xls, .csv"/>

Re-doing a reverted merge in Git

I would suggest you to follow below steps to revert a revert, say SHA1.

git checkout develop #go to develop branch
git pull             #get the latest from remote/develop branch
git branch users/yourname/revertOfSHA1 #having HEAD referring to develop
git checkout users/yourname/revertOfSHA1 #checkout the newly created branch
git log --oneline --graph --decorate #find the SHA of the revert in the history, say SHA1
git revert SHA1
git push --set-upstream origin users/yourname/revertOfSHA1 #push the changes to remote

Now create PR for the branch users/yourname/revertOfSHA1

NodeJS - What does "socket hang up" actually mean?

There seems to be one additional case here, which is Electron not being a fan of the "localhost" domain name. In my case I needed to change this:

const backendApiHostUrl = "http://localhost:3000";

to this:

const backendApiHostUrl = "http://127.0.0.1:3000";

After that the problem just went away.

This means that DNS resolution (local or remote) might be causing some problems too.

Execute jar file with multiple classpath libraries from command prompt

You cannot use both -jar and -cp on the command line - see the java documentation that says that if you use -jar:

the JAR file is the source of all user classes, and other user class path settings are ignored.

You could do something like this:

java -cp lib\*.jar;. myproject.MainClass

Notice the ;. in the -cp argument, to work around a Java command-line bug. Also, please note that this is the Windows version of the command. The path separator on Unix is :.

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

In-Short Differences are

1) PCL is not going to have Full Access to .NET Framework , where as SharedProject has.

2) #ifdef for platform specific code - you can not write in PCL (#ifdef option isn’t available to you in a PCL because it’s compiled separately, as its own DLL, so at compile time (when the #ifdef is evaluated) it doesn’t know what platform it will be part of. ) where as Shared project you can.

3) Platform specific code is achieved using Inversion Of Control in PCL , where as using #ifdef statements you can achieve the same in Shared Project.

An excellent article which illustrates differences between PCL vs Shared Project can be found at the following link

http://hotkrossbits.com/2015/05/03/xamarin-forms-pcl-vs-shared-project/

PHP Unset Array value effect on other indexes

Test it yourself, but here's the output.

php -r '$a=array("a","b","c"); print_r($a); unset($a[1]); print_r($a);'
Array
(
    [0] => a
    [1] => b
    [2] => c
)
Array
(
    [0] => a
    [2] => c
)

Is Tomcat running?

Here are my two cents.

I have multiple tomcat instances running on different ports for my cluster setup. I use the following command to check each processes running on different ports.

/sbin/fuser 8080/tcp

Replace the port number as per your need.

And to kill the process use -k in the above command.

  • This is much faster than the ps -ef way or any other commands where you call a command and call another grep on top of it.
  • Works well with multiple installations of tomcat ,Or any other server that uses a port as a matter of fact running on the same server.

The equivalent command on BSD operating systems is fstat

C# LINQ find duplicates in List

Linq query:

var query = from s2 in (from s in someList group s by new { s.Column1, s.Column2 } into sg select sg) where s2.Count() > 1 select s2;

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

How to preview git-pull without doing fetch?

I think git fetch is what your looking for.

It will pull the changes and objects without committing them to your local repo's index.

They can be merged later with git merge.

Man Page

Edit: Further Explination

Straight from the Git- SVN Crash Course link

Now, how do you get any new changes from a remote repository? You fetch them:

git fetch http://host.xz/path/to/repo.git/ 

At this point they are in your repository and you can examine them using:

git log origin 

You can also diff the changes. You can also use git log HEAD..origin to see just the changes you don't have in your branch. Then if would like to merge them - just do:

git merge origin

Note that if you don't specify a branch to fetch, it will conveniently default to the tracking remote.

Reading the man page is honestly going to give you the best understanding of options and how to use it.

I'm just trying to do this by examples and memory, I don't currently have a box to test out on. You should look at:

git log -p //log with diff

A fetch can be undone with git reset --hard (link) , however all uncommitted changes in your tree will be lost as well as the changes you've fetched.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Calculating the difference between two Java date instances

Just call getTime on each, take the difference, and divide by the number of milliseconds in a day.

What is the "Upgrade-Insecure-Requests" HTTP header?

Short answer: it's closely related to the Content-Security-Policy: upgrade-insecure-requests response header, indicating that the browser supports it (and in fact prefers it).

It took me 30mins of Googling, but I finally found it buried in the W3 spec.

The confusion comes because the header in the spec was HTTPS: 1, and this is how Chromium implemented it, but after this broke lots of websites that were poorly coded (particularly WordPress and WooCommerce) the Chromium team apologized:

"I apologize for the breakage; I apparently underestimated the impact based on the feedback during dev and beta."
— Mike West, in Chrome Issue 501842

Their fix was to rename it to Upgrade-Insecure-Requests: 1, and the spec has since been updated to match.

Anyway, here is the explanation from the W3 spec (as it appeared at the time)...

The HTTPS HTTP request header field sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests directive in order to make that preference as seamless as possible to provide.

...

When a server encounters this preference in an HTTP request’s headers, it SHOULD redirect the user to a potentially secure representation of the resource being requested.

When a server encounters this preference in an HTTPS request’s headers, it SHOULD include a Strict-Transport-Security header in the response if the request’s host is HSTS-safe or conditionally HSTS-safe [RFC6797].

Android adding simple animations while setvisibility(view.Gone)

Try adding this line to the xml parent layout

 android:animateLayoutChanges="true"

Your layout will look like this

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:longClickable="false"
    android:orientation="vertical"
    android:weightSum="16">

    .......other code here

    </LinearLayout>

Traverse all the Nodes of a JSON Object Tree with JavaScript

Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.

function traverse(o, fn) {
    const stack = [o]

    while (stack.length) {
        const obj = stack.shift()

        Object.keys(obj).forEach((key) => {
            fn(key, obj[key], obj)
            if (obj[key] instanceof Object) {
                stack.unshift(obj[key])
                return
            }
        })
    }
}

const o = {
    name: 'Max',
    legal: false,
    other: {
        name: 'Maxwell',
        nested: {
            legal: true
        }
    }
}

const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)

What is the difference between synchronous and asynchronous programming (in node.js)

The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.

NumPy array initialization (fill with identical values)

I had

numpy.array(n * [value])

in mind, but apparently that is slower than all other suggestions for large enough n.

Here is full comparison with perfplot (a pet project of mine).

enter image description here

The two empty alternatives are still the fastest (with NumPy 1.12.1). full catches up for large arrays.


Code to generate the plot:

import numpy as np
import perfplot


def empty_fill(n):
    a = np.empty(n)
    a.fill(3.14)
    return a


def empty_colon(n):
    a = np.empty(n)
    a[:] = 3.14
    return a


def ones_times(n):
    return 3.14 * np.ones(n)


def repeat(n):
    return np.repeat(3.14, (n))


def tile(n):
    return np.repeat(3.14, [n])


def full(n):
    return np.full((n), 3.14)


def list_to_array(n):
    return np.array(n * [3.14])


perfplot.show(
    setup=lambda n: n,
    kernels=[empty_fill, empty_colon, ones_times, repeat, tile, full, list_to_array],
    n_range=[2 ** k for k in range(27)],
    xlabel="len(a)",
    logx=True,
    logy=True,
)

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

django admin - add custom form fields that are not part of the model

Django 2.1.1 The primary answer got me halfway to answering my question. It did not help me save the result to a field in my actual model. In my case I wanted a textfield that a user could enter data into, then when a save occurred the data would be processed and the result put into a field in the model and saved. While the original answer showed how to get the value from the extra field, it did not show how to save it back to the model at least in Django 2.1.1

This takes the value from an unbound custom field, processes, and saves it into my real description field:

class WidgetForm(forms.ModelForm):
    extra_field = forms.CharField(required=False)

    def processData(self, input):
        # example of error handling
        if False:
            raise forms.ValidationError('Processing failed!')

        return input + " has been processed"

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)

        # self.description = "my result" note that this does not work

        # Get the form instance so I can write to its fields
        instance = super(WidgetForm, self).save(commit=commit)

        # this writes the processed data to the description field
        instance.description = self.processData(extra_field)

        if commit:
            instance.save()

        return instance

    class Meta:
        model = Widget
        fields = "__all__"

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

Is there a way to get colored text in GitHubflavored Markdown?

You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:

```diff
+ this text is highlighted in green
- this text is highlighted in red
```

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Smooth scroll to specific div on click

Ned Rockson basically answers this question. However there is a fatal flaw within his solution. When the targeted element is closer to the bottom of the page than the viewport-height, the function doesn't reach its exit statement and traps the user on the bottom of the page. This is simply solved by limiting the iteration count.

var smoothScroll = function(elementId) {
    var MIN_PIXELS_PER_STEP = 16;
    var MAX_SCROLL_STEPS = 30;
    var target = document.getElementById(elementId);
    var scrollContainer = target;
    do {
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do {
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
                                 (targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);

    var iterations = 0;
    var stepFunc = function() {
        if(iterations > MAX_SCROLL_STEPS){
            return;
        }
        scrollContainer.scrollTop =
            Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);

        if (scrollContainer.scrollTop >= targetY) {
            return;
        }

        window.requestAnimationFrame(stepFunc);
    };

    window.requestAnimationFrame(stepFunc);
}

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

NOVEMBER 2018, have tried everything above with no success.

Below is the solution that worked finally. Unfortunately it's not using SSL, but it works!!!

var fromAddress = new MailAddress([email protected], "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");

const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "aspmx.l.google.com",
    Port = 25,
    EnableSsl = false
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

Converting between datetime and Pandas Timestamp objects

Pandas Timestamp to datetime.datetime:

pd.Timestamp('2014-01-23 00:00:00', tz=None).to_pydatetime()

datetime.datetime to Timestamp

pd.Timestamp(datetime(2014, 1, 23))

Download and install an ipa from self hosted url on iOS

More simply you can utilize DropBox for this. The steps basically remain the same. You can do the following-:

1) upload your .ipa to dropBox, Share the link for this .ipa

2) Paste the shared link for .ipa in your manifest.plist file , Upload manifest file in DropBox again share the link for this .plist file

3)paste the link for this Plist in your index.html file with a suitable tag.

Share this index.html file with anybody who can tap on the URL and download. or you can directly hit the URL instead.

How to make a gap between two DIV within the same column

I'm assuming you want the two boxes in the sidebar to be next to each other horizontally, so something like this fiddle? That uses inline-block, or you could achieve the same thing by floating the boxes.

EDIT - I've amended the above fiddle to do what I think you want, though your question could really do with being clearer. Similar to @balexandre's answer, though I've used :nth-child(odd) instead. Both will work, or if support for older browsers is important you'll have to stick with another helper class.

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

How to adjust layout when soft keyboard appears

In Kotlin or in ConstraintLayout you just add :

android:windowSoftInputMode="stateHidden|adjustResize"

OR

android:windowSoftInputMode="stateVisible|adjustResize"

Which state you need after activity launch, you can set from manifest.

in your AndroidManifest.xml like this:

      <activity
        android:name=".ActivityName"
        android:windowSoftInputMode="stateHidden|adjustResize"
        />

how to specify new environment location for conda create

If you want to use the --prefix or -p arguments, but want to avoid having to use the environment's full path to activate it, you need to edit the .condarc config file before you create the environment.

The .condarc file is in the home directory; C:\Users\<user> on Windows. Edit the values under the envs_dirs key to include the custom path for your environment. Assuming the custom path is D:\envs, the file should end up looking something like this:

ssl_verify: true
channels:
  - defaults
envs_dirs:
  - C:\Users\<user>\Anaconda3\envs
  - D:\envs

Then, when you create a new environment on that path, its name will appear along with the path when you run conda env list, and you should be able to activate it using only the name, and not the full path.

Command line screenshot

In summary, if you edit .condarc to include D:\envs, and then run conda env create -p D:\envs\myenv python=x.x, then activate myenv (or source activate myenv on Linux) should work.

Hope that helps!

P.S. I stumbled upon this through trial and error. I think what happens is when you edit the envs_dirs key, conda updates ~\.conda\environments.txt to include the environments found in all the directories specified under the envs_dirs, so they can be accessed without using absolute paths.

Handling identity columns in an "Insert Into TABLE Values()" statement?

The best practice is to explicitly list the columns:

Insert Into TableName(col1, col2,col2) Values(?, ?, ?)

Otherwise, your original insert will break if you add another column to your table.

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

Insert new item in array on any position in PHP

This is what worked for me for the associative array:

/*
 * Inserts a new key/value after the key in the array.
 *
 * @param $key
 *   The key to insert after.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 * @see array_insert_before()
 */
function array_insert_after($key, array &$array, $new_key, $new_value) {
  if (array_key_exists($key, $array)) {
    $new = array();
    foreach ($array as $k => $value) {
      $new[$k] = $value;
      if ($k === $key) {
        $new[$new_key] = $new_value;
      }
    }
    return $new;
  }
  return FALSE;
}

The function source - this blog post. There's also handy function to insert BEFORE specific key.

How to do an Integer.parseInt() for a decimal number?

String s="0.01";
int i = Double.valueOf(s).intValue();

mysql server port number

default port of mysql is 3306

default pot of sql server is 1433

Extension exists but uuid_generate_v4 fails

This worked for me.

create extension IF NOT EXISTS "uuid-ossp" schema pg_catalog version "1.1"; 

make sure the extension should by on pg_catalog and not in your schema...

Optional args in MATLAB functions

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})
   end

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

What is the most efficient way to store a list in the Django models?

Would this relationship not be better expressed as a one-to-many foreign key relationship to a Friends table? I understand that myFriends are just strings but I would think that a better design would be to create a Friend model and have MyClass contain a foreign key realtionship to the resulting table.

Is there a .NET/C# wrapper for SQLite?

Version 1.2 of Monotouch includes support for System.Data. You can find more details here: http://monotouch.net/Documentation/System.Data

But basically it allows you to use the usual ADO .NET patterns with sqlite.

Is it possible to decrypt MD5 hashes?

The only thing that can be work is (if we mention that the passwords are just hashed, without adding any kind of salt to prevent the replay attacks, if it is so you must know the salt)by the way, get an dictionary attack tool, the files of many words, numbers etc. then create two rows, one row is word,number (in dictionary) the other one is hash of the word, and compare the hashes if matches you get it...

that's the only way, without going into cryptanalysis.

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Laravel 5 Eloquent where and or in Clauses

Using advanced wheres:

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->where(function($q) {
          $q->where('Cab', 2)
            ->orWhere('Cab', 4);
      })
      ->get();

Or, even better, using whereIn():

CabRes::where('m__Id', 46)
      ->where('t_Id', 2)
      ->whereIn('Cab', $cabIds)
      ->get();

How to study design patterns?

My suggestion would be a combination of implement a few of them and analyze some implementations of them. For example, within .Net, there are uses of adapter patterns if you look at Data Adapters, as well as a few others if one does a little digging into the framework.

What is the Windows equivalent of the diff command?

I don't know if the following tool is exatly what you need. But I like to use, for specific files, some online tool. This way I can use it regardless of the operational system. Here is a example: diffchecker.com

But for my needs, I guess the best tool to track changes and logs of my project's files is GIT. If you work in a team, you can have some repo online in a server of yours, or use it with Bitbucket or Github.

Hope it helps somebody.

Pycharm/Python OpenCV and CV2 install error

here is a tutorial that worked for me without any problem.

Copied from the site above the important part:

Download the OpenCV version corresponding to your Python installation from here. In my case, I’ve used opencv_python-3.1.0-cp35-cp35m-win32.whl.

Now, open a cmd window like before. You can open this directly in your Downloads folder if you SHIFT and right click inside it. The idea is to open a cmd window where you’ve downloaded the above [...] file. Use the [...] command to install [...] OpenCV:

1     pip install "opencv_python-3.1.0-cp35-cp35m-win32.whl"

Additional note: don't forget to change the name of the downloaded file in the command you use. Apparently by installing opencv, you'll have access to cv2 too.

UnicodeDecodeError when reading CSV file in Pandas with Python

I am using Jupyter-notebook. And in my case, it was showing the file in the wrong format. The 'encoding' option was not working. So I save the csv in utf-8 format, and it works.

Mac OS X - EnvironmentError: mysql_config not found

brew install mysql added mysql to /usr/local/Cellar/..., so I needed to add :/usr/local/Cellar/ to my $PATH and then which mysql_config worked!

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

How to override !important?

Override using JavaScript

$('.mytable td').attr('style', 'display: none !important');

Worked for me.

Free Rest API to retrieve current datetime as string (timezone irrelevant)

TimezoneDb provides a free API: http://timezonedb.com/api

GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.

You can use Greenwich, UK if you'd like GMT.

Qt Creator color scheme

Linux, Qt Creator >= 3.4:

You could edit theese themes:

/usr/share/qtcreator/themes/default.creatortheme
/usr/share/qtcreator/themes/dark.creatortheme

How to jump to a particular line in a huge text file?

You can't jump ahead without reading in the file at least once, since you don't know where the line breaks are. You could do something like:

# Read in the file once and build a list of line offsets
line_offset = []
offset = 0
for line in file:
    line_offset.append(offset)
    offset += len(line)
file.seek(0)

# Now, to skip to line n (with the first line being line 0), just do
file.seek(line_offset[n])