Programs & Examples On #System.drawing.color

The System.Drawing namespace provides access to GDI+ basic graphics functionality.

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

Convert System.Drawing.Color to RGB and Hex Value

For hexadecimal code try this

  1. Get ARGB (Alpha, Red, Green, Blue) representation for the color
  2. Filter out Alpha channel: & 0x00FFFFFF
  3. Format out the value (as hexadecimal "X6" for hex)

For RGB one

  1. Just format out Red, Green, Blue values

Implementation

private static string HexConverter(Color c) {
  return String.Format("#{0:X6}", c.ToArgb() & 0x00FFFFFF);
}

public static string RgbConverter(Color c) {
  return String.Format("RGB({0},{1},{2})", c.R, c.G, c.B);
}

How to check if String value is Boolean type in Java?

Here's a method you can use to check if a value is a boolean:

boolean isBoolean(String value) {
    return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
            .anyMatch(b -> b.equalsIgnoreCase(value));
}

Examples of using it:

System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

I've run into the same problem, I found the solution at http://developer.android.com/tools/devices/emulator.html#vm-windows

Just follow this simple steps:

  1. Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager.

  2. After the download completes, run [sdk]/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe

  3. Follow the on-screen instructions to complete installation.

Why do people write #!/usr/bin/env python on the first line of a Python script?

this tells the script where is python directory !

#! /usr/bin/env python

Could not load the Tomcat server configuration

You tried to start Tomcat and got the following error:

Could not load the Tomcat server configuration at /Servers/Tomcat v7.0 Server at localhost-config. The configuration may be corrupt or incomplete

How to solve:

  • Close Eclipse
  • Copy all files from TOMCAT_7_HOME/conf to WORKSPACE_FOLDER/Servers/Tomcat v7.0 Server at localhost-config
  • Start Eclipse
  • Expand the Servers project, click on the Tomcat 7 project and hit F5
  • Start Tomcat from Eclipse

how to set background image in submit button?

.button {
    border: none;
    background: url('/forms/up.png') no-repeat top left;
    padding: 2px 8px;
}

Ellipsis for overflow text in dropdown boxes

NOTE: As of July 2020, text-overflow: ellipsis works for <select> on Chrome

HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhone’s modal select which, when open, looks totally different from the traditional pop-up menu).

If it bugs you, you can use a customizable replacement, like Chosen, which looks distinct from the native select.

Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in selects might be the result of a years-old oversight that everyone copied, and it might be time for a change.

Android WSDL/SOAP service client

i founded this tool to auto generate wsdl to android code,

http://www.wsdl2code.com/Example.aspx

public void callWebService(){
    SampleService srv1 = new SampleService();
    Request req = new Request();
    req.companyId = "1";
    req.userName = "userName";
    req.password = "pas";
    Response response =  srv1.ServiceSample(req);
}

Assigning multiple styles on an HTML element

The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:

<h2 style="text-align:center; font-family:tahoma">TITLE</h2>

Eclipse comment/uncomment shortcut?

  1. Single line comment Ctrl + /
  2. Single line uncomment Ctrl + /

  1. Multiline comment Ctrl + Shift + /
  2. Multiline uncomment Ctrl + Shift + \ (note the backslash)

How do I convert a Django QuerySet into list of dicts?

The .values() method will return you a result of type ValuesQuerySet which is typically what you need in most cases.

But if you wish, you could turn ValuesQuerySet into a native Python list using Python list comprehension as illustrated in the example below.

result = Blog.objects.values()             # return ValuesQuerySet object
list_result = [entry for entry in result]  # converts ValuesQuerySet into Python list
return list_result

I find the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result and actual_result must be of the same type (e.g. dictionary).

actual_result = some_function()
expected_result = {
    # dictionary content here ...
}
assert expected_result == actual_result

android get all contacts

This is the Method to get contact list Name and Number

 private void getAllContacts() {
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            if (hasPhoneNumber > 0) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Cursor phoneCursor = contentResolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
                        null);
                if (phoneCursor != null) {
                    if (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

   //At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
                        phoneCursor.close();
                    }


                }
            }
        }
    }
}

What is the point of "final class" in Java?

If the class is marked final, it means that the class' structure can't be modified by anything external. Where this is the most visible is when you're doing traditional polymorphic inheritance, basically class B extends A just won't work. It's basically a way to protect some parts of your code (to extent).

To clarify, marking class final doesn't mark its fields as final and as such doesn't protect the object properties but the actual class structure instead.

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

How to use JUnit to test asynchronous processes

For all Spring users out there, this is how I usually do my integration tests nowadays, where async behaviour is involved:

Fire an application event in production code, when an async task (such as an I/O call) has finished. Most of the time this event is necessary anyway to handle the response of the async operation in production.

With this event in place, you can then use the following strategy in your test case:

  1. Execute the system under test
  2. Listen for the event and make sure that the event has fired
  3. Do your assertions

To break this down, you'll first need some kind of domain event to fire. I'm using a UUID here to identify the task that has completed, but you're of course free to use something else as long as it's unique.

(Note, that the following code snippets also use Lombok annotations to get rid of boiler plate code)

@RequiredArgsConstructor
class TaskCompletedEvent() {
  private final UUID taskId;
  // add more fields containing the result of the task if required
}

The production code itself then typically looks like this:

@Component
@RequiredArgsConstructor
class Production {

  private final ApplicationEventPublisher eventPublisher;

  void doSomeTask(UUID taskId) {
    // do something like calling a REST endpoint asynchronously
    eventPublisher.publishEvent(new TaskCompletedEvent(taskId));
  }

}

I can then use a Spring @EventListener to catch the published event in test code. The event listener is a little bit more involved, because it has to handle two cases in a thread safe manner:

  1. Production code is faster than the test case and the event has already fired before the test case checks for the event, or
  2. Test case is faster than production code and the test case has to wait for the event.

A CountDownLatch is used for the second case as mentioned in other answers here. Also note, that the @Order annotation on the event handler method makes sure, that this event handler method gets called after any other event listeners used in production.

@Component
class TaskCompletionEventListener {

  private Map<UUID, CountDownLatch> waitLatches = new ConcurrentHashMap<>();
  private List<UUID> eventsReceived = new ArrayList<>();

  void waitForCompletion(UUID taskId) {
    synchronized (this) {
      if (eventAlreadyReceived(taskId)) {
        return;
      }
      checkNobodyIsWaiting(taskId);
      createLatch(taskId);
    }
    waitForEvent(taskId);
  }

  private void checkNobodyIsWaiting(UUID taskId) {
    if (waitLatches.containsKey(taskId)) {
      throw new IllegalArgumentException("Only one waiting test per task ID supported, but another test is already waiting for " + taskId + " to complete.");
    }
  }

  private boolean eventAlreadyReceived(UUID taskId) {
    return eventsReceived.remove(taskId);
  }

  private void createLatch(UUID taskId) {
    waitLatches.put(taskId, new CountDownLatch(1));
  }

  @SneakyThrows
  private void waitForEvent(UUID taskId) {
    var latch = waitLatches.get(taskId);
    latch.await();
  }

  @EventListener
  @Order
  void eventReceived(TaskCompletedEvent event) {
    var taskId = event.getTaskId();
    synchronized (this) {
      if (isSomebodyWaiting(taskId)) {
        notifyWaitingTest(taskId);
      } else {
        eventsReceived.add(taskId);
      }
    }
  }

  private boolean isSomebodyWaiting(UUID taskId) {
    return waitLatches.containsKey(taskId);
  }

  private void notifyWaitingTest(UUID taskId) {
    var latch = waitLatches.remove(taskId);
    latch.countDown();
  }

}

Last step is to execute the system under test in a test case. I'm using a SpringBoot test with JUnit 5 here, but this should work the same for all tests using a Spring context.

@SpringBootTest
class ProductionIntegrationTest {

  @Autowired
  private Production sut;

  @Autowired
  private TaskCompletionEventListener listener;

  @Test
  void thatTaskCompletesSuccessfully() {
    var taskId = UUID.randomUUID();
    sut.doSomeTask(taskId);
    listener.waitForCompletion(taskId);
    // do some assertions like looking into the DB if value was stored successfully
  }

}

Note, that in contrast to other answers here, this solution will also work if you execute your tests in parallel and multiple threads exercise the async code at the same time.

MySQL CURRENT_TIMESTAMP on create and on update

You cannot have two TIMESTAMP column with the same default value of CURRENT_TIMESTAMP on your table. Please refer to this link: http://www.mysqltutorial.org/mysql-timestamp.aspx

Simple linked list in C++

Here is my implementation.

#include <iostream>

using namespace std;

template< class T>
struct node{
    T m_data;
    node* m_next_node;

    node(T t_data, node* t_node) :
        m_data(t_data), m_next_node(t_node){}

    ~node(){
        std::cout << "Address :" << this << " Destroyed" << std::endl;
    }
};

template<class T>
class linked_list {
public:
    node<T>* m_list;

    linked_list(): m_list(nullptr){}

    void add_node(T t_data) {
        node<T>* _new_node = new node<T>(t_data, nullptr);
        _new_node->m_next_node = m_list;
        m_list = _new_node;
    }


    void populate_nodes(node<T>* t_node) {
        if  (t_node != nullptr) {
            std::cout << "Data =" << t_node->m_data
                      << ", Address =" << t_node->m_next_node
                      << std::endl;
            populate_nodes(t_node->m_next_node);
        }
    }

    void delete_nodes(node<T>* t_node) {
        if (t_node != nullptr) {
            delete_nodes(t_node->m_next_node);
        }
        delete(t_node);
    }

};


int main()
{
    linked_list<float>* _ll = new linked_list<float>();

    _ll->add_node(1.3);
    _ll->add_node(5.5);
    _ll->add_node(10.1);
    _ll->add_node(123);
    _ll->add_node(4.5);
    _ll->add_node(23.6);
    _ll->add_node(2);

    _ll->populate_nodes(_ll->m_list);

    _ll->delete_nodes(_ll->m_list);

    delete(_ll);

    return 0;
}

enter image description here

IntelliJ - show where errors are

In IntelliJ Idea 2019 you can find scope "Problems" under the "Project" view. Default scope is "Project".

"Problems" scope

jQuery: How can I show an image popup onclick of the thumbnail?

I like prettyPhoto

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

Using braces with dynamic variable names in PHP

i have a solution for dynamically created variable value and combined all value in a variable.

if($_SERVER['REQUEST_METHOD']=='POST'){
    $r=0;
    for($i=1; $i<=4; $i++){
        $a = $_POST['a'.$i];
        $r .= $a;
    }
    echo $r;
}

Is there any advantage of using map over unordered_map in case of trivial keys?

Significant differences that have not really been adequately mentioned here:

  • map keeps iterators to all elements stable, in C++17 you can even move elements from one map to the other without invalidating iterators to them (and if properly implemented without any potential allocation).
  • map timings for single operations are typically more consistent since they never need large allocations.
  • unordered_map using std::hash as implemented in the libstdc++ is vulnerable to DoS if fed with untrusted input (it uses MurmurHash2 with a constant seed - not that seeding would really help, see https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/).
  • Being ordered enables efficient range searches, e.g. iterate over all elements with key = 42.

Change <br> height using CSS

You can't change the height of the br tag itself, as it's not an element that takes up space in the page. It's just an instruction to create a new line.

You can change the line height using the line-height style. That will change the distance between the text blocks that you have separated by empty lines, but natually also the distance between lines in a text block.

For completeness: Text blocks in HTML is usually done using the p tag around text blocks. That way you can control the line height inside the p tag, and also the spacing between the p tags.

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

This is clearly a classpath problem. Take into consideration that the classpath must change a bit when you run your program outside the IDE. This is because the IDE loads the other JARs relative to the root folder of your project, while in the case of the final JAR this is usually not true.

What I like to do in these situations is build the JAR manually. It takes me at most 5 minutes and it always solves the problem. I do not suggest you do this. Find a way to use Maven, that's its purpose.

How to use glyphicons in bootstrap 3.0

If you're using less , and it's not loading the icons font you must check out the font path go to the file variable.less and change the @icon-font-path path , that worked for me.

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I am running VirtualBox 5.1.20, and had a similar issue. Here is a url to where I found the fix, and the fix I implemented:

# https://dsin.wordpress.com/2016/08/17/ubuntu-wrong-fs-type-bad-option-bad-superblock/
if [ "5.1.20" == "${VBOXVER}" ]; then
  rm /sbin/mount.vboxsf
  ln -s /usr/lib/VBoxGuestAdditions/mount.vboxsf /sbin/mount.vboxsf
fi

The link had something similar to /usr/lib/VBoxGuestAdditions/other/mount.vboxsf, rather than what I have in the script excerpt.

For a build script I use in vagrant for the additions:

https://github.com/rburkholder/vagrant/blob/master/scripts/additions.sh

Seems to be a fix at https://www.virtualbox.org/ticket/16670

How to remove "Server name" items from history of SQL Server Management Studio

For SQL 2005, delete the file:

C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

For SQL 2008, the file location, format and name changed:

C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin

How to clear the list:

  1. Shut down all instances of SSMS
  2. Delete/Rename the file
  3. Open SSMS

This request is registered on Microsoft Connect

How do I get the day of week given a date?

To get Sunday as 1 through Saturday as 7, this is the simplest solution to your question:

datetime.date.today().toordinal()%7 + 1

All of them:

import datetime

today = datetime.date.today()
sunday = today - datetime.timedelta(today.weekday()+1)

for i in range(7):
    tmp_date = sunday + datetime.timedelta(i)
    print tmp_date.toordinal()%7 + 1, '==', tmp_date.strftime('%A')

Output:

1 == Sunday
2 == Monday
3 == Tuesday
4 == Wednesday
5 == Thursday
6 == Friday
7 == Saturday

How can I trigger the click event of another element in ng-click using angularjs?

So it was a simple fix. Just had to move the ng-click to a scope click handler:

<input id="upload"
    type="file"
    ng-file-select="onFileSelect($files)"
    style="display: none;">

<button type="button"
    ng-click="clickUpload()">Upload</button>



$scope.clickUpload = function(){
    angular.element('#upload').trigger('click');
};

How can I select an element with multiple classes in jQuery?

The problem you're having, is that you are using a Group Selector, whereas you should be using a Multiples selector! To be more specific, you're using $('.a, .b') whereas you should be using $('.a.b').

For more information, see the overview of the different ways to combine selectors herebelow!


Group Selector : ","

Select all <h1> elements AND all <p> elements AND all <a> elements :

$('h1, p, a')

Multiples selector : "" (no character)

Select all <input> elements of type text, with classes code and red :

$('input[type="text"].code.red')

Descendant Selector : " " (space)

Select all <i> elements inside <p> elements:

$('p i')

Child Selector : ">"

Select all <ul> elements that are immediate children of a <li> element:

$('li > ul')

Adjacent Sibling Selector : "+"

Select all <a> elements that are placed immediately after <h2> elements:

$('h2 + a')

General Sibling Selector : "~"

Select all <span> elements that are siblings of <div> elements:

$('div ~ span')

CSS horizontal scroll

Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html

<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {  
    overflow: scroll;  
    width:100%;
}
#outer_wrapper #inner_wrapper {
    width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
    width: 250px;
    height:300px;
    float: left;
    margin: 0 4px 0 0;
    border:1px grey solid;
}
</style>
</head>
<body>

<div id="outer_wrapper">
    <div id="inner_wrapper">
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
             <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <div class="box">
            <!-- Add desired content here -->
            HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript 
        </div>
        <!-- more boxes here -->
    </div>
</div>
</body>
</html>

In Bash, how can I check if a string begins with some value?

While I find most answers here quite correct, many of them contain unnecessary Bashisms. POSIX parameter expansion gives you all you need:

[ "${host#user}" != "${host}" ]

and

[ "${host#node}" != "${host}" ]

${var#expr} strips the smallest prefix matching expr from ${var} and returns that. Hence if ${host} does not start with user (node), ${host#user} (${host#node}) is the same as ${host}.

expr allows fnmatch() wildcards, thus ${host#node??} and friends also work.

Find an element by class name, from a known parent element

var element = $("#parentDiv .myClassNameOfInterest")

How can I get dict from sqlite query?

Fastest on my tests:

conn.row_factory = lambda c, r: dict(zip([col[0] for col in c.description], r))
c = conn.cursor()

%timeit c.execute('SELECT * FROM table').fetchall()
19.8 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

vs:

conn.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])
c = conn.cursor()

%timeit c.execute('SELECT * FROM table').fetchall()
19.4 µs ± 75.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

You decide :)

What to do with commit made in a detached head

You can just do git merge <commit-number> or git cherry-pick <commit> <commit> ...

As suggested by Ryan Stewart you may also create a branch from the current HEAD:

git branch brand-name

Or just a tag:

git tag tag-name

Link entire table row?

Use the ::before pseudo element. This way only you don't have to deal with Javascript or creating links for each cell. Using the following table structure

<table>
  <tr>
    <td><a href="http://domain.tld" class="rowlink">Cell</a></td>
    <td>Cell</td>
    <td>Cell</td>
  </tr>
</table>

all we have to do is create a block element spanning the entire width of the table using ::before on the desired link (.rowlink) in this case.

table {
  position: relative;
}

.rowlink::before {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 1.5em; /* don't forget to set the height! */
}

demo

The ::before is highlighted in red in the demo so you can see what it's doing.

How can I determine if a String is non-null and not only whitespace in Groovy?

You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true

Eclipse/Java code completion not working

Check the lib of your project. It may be that you have include two such jar files in which same class is available or say one class in code can be refrenced in two jar files. In such case also eclipse stops assisting code as it is totally confused.

Better way to check this is go to the file where assist is not working and comment all imports there, than add imports one by one and check at each import if code-assist is working or not.You can easily find the class with duplicate refrences.

ASP.NET page life cycle explanation

This acronym might help you to remember the ASP.NET life cycle stages which I wrote about in the below blog post.

R-SIL-VP-RU

  1. Request
  2. Start
  3. Initialization
  4. Load
  5. Validation
  6. Post back handling
  7. Rendering
  8. Unload

From my blog: Understand ASP.NET Page life cycle and remember stages in easy way
18 May 2014

Best design for a changelog / auditing database table?

In the project I'm working on, audit log also started from the very minimalistic design, like the one you described:

event ID
event date/time
event type
user ID
description

The idea was the same: to keep things simple.

However, it quickly became obvious that this minimalistic design was not sufficient. The typical audit was boiling down to questions like this:

Who the heck created/updated/deleted a record 
with ID=X in the table Foo and when?

So, in order to be able to answer such questions quickly (using SQL), we ended up having two additional columns in the audit table

object type (or table name)
object ID

That's when design of our audit log really stabilized (for a few years now).

Of course, the last "improvement" would work only for tables that had surrogate keys. But guess what? All our tables that are worth auditing do have such a key!

How to remove unused imports in Intellij IDEA on commit?

Or you can do the following shortcut :

MAC : Shift + Command + A (Enter Action menu pops up)

And write : Optimize Imports

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

Simply alter your table, no need to any thing. just run this query on database. ALTER TABLE table_nameCONVERT TO CHARACTER SET utf8

it will definately work.

Using "If cell contains" in VBA excel

This does the same, enhanced with CONTAINS:

Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
     If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
        If xRet = "" Then
            xRet = LookupRange.Cells(I, ColumnNumber) & Char
        Else
            xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
        End If
    End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function

why numpy.ndarray is object is not callable in my simple for python loop

Avoid the for loopfor XY in xy: Instead read up how the numpy arrays are indexed and handled.

Numpy Indexing

Also try and avoid .txt files if you are dealing with matrices. Try to use .csv or .npy files, and use Pandas dataframework to load them just for clarity.

Find the most common element in a list

def popular(L):
C={}
for a in L:
    C[a]=L.count(a)
for b in C.keys():
    if C[b]==max(C.values()):
        return b
L=[2,3,5,3,6,3,6,3,6,3,7,467,4,7,4]
print popular(L)

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Find a commit on GitHub given the commit hash

The ability to search commits has recently been added to GitHub.

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master), or the "Issues" tab to see pull requests containing the commit.

To be more explicit you can add the hash: prefix to the search, but it's not really necessary.

There is also a REST API (at the time of writing it is still in preview).

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

How to check certificate name and alias in keystore files?

You can run from Java code.

try {

        File file = new File(keystore location);
        InputStream is = new FileInputStream(file);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "password";
        keystore.load(is, password.toCharArray());


        Enumeration<String> enumeration = keystore.aliases();
        while(enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement();
            System.out.println("alias name: " + alias);
            Certificate certificate = keystore.getCertificate(alias);
            System.out.println(certificate.toString());

        }

    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(null != is)
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

Certificate class holds all information about the keystore.

UPDATE- OBTAIN PRIVATE KEY

Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);

@prateek Hope this is what you looking for!

Spring Boot Configure and Use Two DataSources

I also had to setup connection to 2 datasources from Spring Boot application, and it was not easy - the solution mentioned in the Spring Boot documentation didn't work. After a long digging through the internet I made it work and the main idea was taken from this article and bunch of other places.

The following solution is written in Kotlin and works with Spring Boot 2.1.3 and Hibernate Core 5.3.7. Main issue was that it was not enough just to setup different DataSource configs, but it was also necessary to configure EntityManagerFactory and TransactionManager for both databases.

Here is config for the first (Primary) database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "firstDbEntityManagerFactory",
    transactionManagerRef = "firstDbTransactionManager",
    basePackages = ["org.path.to.firstDb.domain"]
)
@EnableTransactionManagement
class FirstDbConfig {

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.firstDb")
    fun firstDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Primary
    @Bean(name = ["firstDbEntityManagerFactory"])
    fun firstDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("firstDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(SomeEntity::class.java)
            .persistenceUnit("firstDb")
            // Following is the optional configuration for naming strategy
            .properties(
                singletonMap(
                    "hibernate.naming.physical-strategy",
                    "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl"
                )
            )
            .build()
    }

    @Primary
    @Bean(name = ["firstDbTransactionManager"])
    fun firstDbTransactionManager(
        @Qualifier("firstDbEntityManagerFactory") firstDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(firstDbEntityManagerFactory)
    }
}

And this is config for second database:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "secondDbEntityManagerFactory",
    transactionManagerRef = "secondDbTransactionManager",
    basePackages = ["org.path.to.secondDb.domain"]
)
@EnableTransactionManagement
class SecondDbConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.secondDb")
    fun secondDbDataSource(): DataSource {
        return DataSourceBuilder.create().build()
    }

    @Bean(name = ["secondDbEntityManagerFactory"])
    fun secondDbEntityManagerFactory(
        builder: EntityManagerFactoryBuilder,
        @Qualifier("secondDbDataSource") dataSource: DataSource
    ): LocalContainerEntityManagerFactoryBean {
        return builder
            .dataSource(dataSource)
            .packages(EntityFromSecondDb::class.java)
            .persistenceUnit("secondDb")
            .build()
    }

    @Bean(name = ["secondDbTransactionManager"])
    fun secondDbTransactionManager(
        @Qualifier("secondDbEntityManagerFactory") secondDbEntityManagerFactory: EntityManagerFactory
    ): PlatformTransactionManager {
        return JpaTransactionManager(secondDbEntityManagerFactory)
    }
}

The properties for datasources are like this:

spring.datasource.firstDb.jdbc-url=
spring.datasource.firstDb.username=
spring.datasource.firstDb.password=

spring.datasource.secondDb.jdbc-url=
spring.datasource.secondDb.username=
spring.datasource.secondDb.password=

Issue with properties was that I had to define jdbc-url instead of url because otherwise I had an exception.

p.s. Also you might have different naming schemes in your databases, which was the case for me. Since Hibernate 5 does not support all previous naming schemes, I had to use solution from this answer - maybe it will also help someone as well.

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

To be specific, to remove tableviewHeader space from top i made these changes:

YouStoryboard.storyboard > YouViewController > Select TableView > Size inspector > Content insets - Set it to never.

enter image description here

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

Replace words in a string - Ruby

If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"

Regular expressions have word boundaries, such as \b which matches start or end of a word. Thus,

'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"

In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"

How do I parse JSON from a Java HTTPResponse?

Jackson appears to support some amount of JSON parsing straight from an InputStream. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.

How to get body of a POST in php?

To access the entity body of a POST or PUT request (or any other HTTP method):

$entityBody = file_get_contents('php://input');

Also, the STDIN constant is an already-open stream to php://input, so you can alternatively do:

$entityBody = stream_get_contents(STDIN);

From the PHP manual entry on I/O streamsdocs:

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Specifically you'll want to note that the php://input stream, regardless of how you access it in a web SAPI, is not seekable. This means that it can only be read once. If you're working in an environment where large HTTP entity bodies are routinely uploaded you may wish to maintain the input in its stream form (rather than buffering it like the first example above).

To maintain the stream resource something like this can be helpful:

<?php

function detectRequestBody() {
    $rawInput = fopen('php://input', 'r');
    $tempStream = fopen('php://temp', 'r+');
    stream_copy_to_stream($rawInput, $tempStream);
    rewind($tempStream);

    return $tempStream;
}

php://temp allows you to manage memory consumption because it will transparently switch to filesystem storage after a certain amount of data is stored (2M by default). This size can be manipulated in the php.ini file or by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.

Of course, unless you have a really good reason for seeking on the input stream, you shouldn't need this functionality in a web application. Reading the HTTP request entity body once is usually enough -- don't keep clients waiting all day while your app figures out what to do.

Note that php://input is not available for requests specifying a Content-Type: multipart/form-data header (enctype="multipart/form-data" in HTML forms). This results from PHP already having parsed the form data into the $_POST superglobal.

How do I increase modal width in Angular UI Bootstrap?

there is another way wich you don't have to overwrite uibModal classes and use them if needed : you call $uibModal.open function with your own size type like "xlg" and then you define a class named "modal-xlg" like below :

.modal-xlg{
   width:1200px;
}

call $uibModal.open as :

 var modalInstance = $uibModal.open({
                ...  
                size: "xlg",
            });

and this will work . because whatever string you pass as size bootstrap will cocant it with "modal-" and this will play the role of class for window.

Round double value to 2 decimal places

You could do this:

NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setFormat:@0.00"];

// test
NSNumber* a = @12;
NSString* s = [f stringFromNumber:a];
NSLog(@"%@", s);

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

This could happen if you are not running the command prompt in administrator mode. If you are using windows 7, you can go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode. If not, you can also go to start -> all programs -> accessories -> right click command prompt and click 'run as administrator'.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

Dynamically fill in form values with jQuery

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

Some of the Answers are correct, but in case of working with new xampp or with some one not working other answers try this:

just go to the xampp folder:

xampp/apache/conf/extra/httpd-xampp.c­onf

and if you are trying to access from local ip in your network so change,

 Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
        Require local
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

Change to :

 Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
        Require all granted
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

Note: this is just for text, for the security of the xampp has some search....

VirtualBox error "Failed to open a session for the virtual machine"

For MAC users

After some research, this worked for me:

  • Quit VirtualBox
  • Right click "Applications" folder
  • Click on "Get Info"
  • Change "Everyone" Permission to "Read Only"
  • Open VirtualBox, and now it should work.

Mercurial stuck "waiting for lock"

I am very familiar with Mercurial's locking code (as of 1.9.1). The above advice is good, but I'd add that:

  1. I've seen this in the wild, but rarely, and only on Windows machines.
  2. Deleting lock files is the easiest fix, BUT you have to make sure nothing else is accessing the repository. (If the lock is a string of zeros, this is almost certainly true).

(For the curious: I haven't yet been able to catch the cause of this problem, but suspect it's either an older version of Mercurial accessing the repository or a problem in Python's socket.gethostname() call on certain versions of Windows.)

A python class that acts like dict

Here is an alternative solution:

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__dict__ = self

a = AttrDict()
a.a = 1
a.b = 2

Setting format and value in input type="date"

Please check this https://stackoverflow.com/a/9519493/1074944 and try this way also $('input[type="date"]').datepicker().prop('type','text'); check the demo

How can I add a variable to console.log?

There are several ways of consoling out the variable within a string.

Method 1 :

console.log("story", name, "story");

Benefit : if name is a JSON object, it will not be printed as "story" [object Object] "story"

Method 2 :

console.log("story " + name + " story");

Method 3: When using ES6 as mentioned above

console.log(`story ${name} story`);

Benefit: No need of extra , or +

Method 4:

console.log('story %s story',name);

Benefit: the string becomes more readable.

How can I convert a std::string to int?

1. std::stoi

std::string str = "10";  
int number = std::stoi(str); 

2. string streams

std::string str = "10";  
int number;  
std::istringstream(str) >> number

3. boost::lexical_cast

#include <boost/lexical_cast.hpp>
std::string str = "10";  
int number;
    
try 
{
    number = boost::lexical_cast<int>(str);
    std::cout << number << std::endl;
}
catch (boost::bad_lexical_cast const &e) // bad input
{
    std::cout << "error" << std::endl;
}

4. std::atoi

std::string str = "10";
int number = std::atoi(str.c_str()); 

5. sscanf()

 std::string str = "10";
 int number;
 if (sscanf(str .c_str(), "%d", &number) == 1) 
 {
     std::cout << number << '\n';
 } 
 else 
 {
     std::cout << "Bad Input";
 }

Can gcc output C code after preprocessing?

I'm using gcc as a preprocessor (for html files.) It does just what you want. It expands "#--" directives, then outputs a readable file. (NONE of the other C/HTML preprocessors I've tried do this- they concatenate lines, choke on special characters, etc.) Asuming you have gcc installed, the command line is:

gcc -E -x c -P -C -traditional-cpp code_before.cpp > code_after.cpp

(Doesn't have to be 'cpp'.) There's an excellent description of this usage at http://www.cs.tut.fi/~jkorpela/html/cpre.html.

The "-traditional-cpp" preserves whitespace & tabs.

Easiest way to convert a List to a Set in Java

For Java 8 it's very easy:

List < UserEntity > vList= new ArrayList<>(); 
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());

Counter increment in Bash loop not working

I think this single awk call is equivalent to your grep|grep|awk|awk pipeline: please test it. Your last awk command appears to change nothing at all.

The problem with COUNTER is that the while loop is running in a subshell, so any changes to the variable vanish when the subshell exits. You need to access the value of COUNTER in that same subshell. Or take @DennisWilliamson's advice, use a process substitution, and avoid the subshell altogether.

awk '
  /GET \/log_/ && /upstream timed out/ {
    split($0, a, ", ")
    split(a[2] FS a[4] FS $0, b)
    print "http://example.com" b[5] "&ip=" b[2] "&date=" b[7] "&time=" b[8] "&end=1"
  }
' | {
    while read WFY_URL
    do
        echo $WFY_URL #Some more action
        (( COUNTER++ ))
    done
    echo $COUNTER
}

How to check the multiple permission at single request in Android M?

I am late, but i want tell the library which i have ended with.

RxPermission is best library with reactive code, which makes permission code unexpected just 1 line.

RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.CAMERA,
         Manifest.permission.READ_PHONE_STATE)
.subscribe(granted -> {
    if (granted) {
       // All requested permissions are granted
    } else {
       // At least one permission is denied
    }
});

add in your build.gradle

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}

How to set a JVM TimeZone Properly

The accepted answer above:

-Duser.timezone="Europe/Sofia" 

Didn't work for me exactly. I only was able to successfully change my timezone when I didn't have quotes around the parameters:

-Duser.timezone=Europe/Sofia

How can I check if a MySQL table exists with PHP?

You can use many different queries to check if a table exists. Below is a comparison between several:

mysql_query('select 1 from `table_name` group by 1'); or  
mysql_query('select count(*) from `table_name`');

mysql_query("DESCRIBE `table_name`");  
70000   rows: 24ms  
1000000 rows: 24ms  
5000000 rows: 24ms

mysql_query('select 1 from `table_name`');  
70000   rows: 19ms  
1000000 rows: 23ms  
5000000 rows: 29ms

mysql_query('select 1 from `table_name` group by 1'); or  
mysql_query('select count(*) from `table_name`');  
70000   rows: 18ms  
1000000 rows: 18ms  
5000000 rows: 18ms  

These benchmarks are only averages:

socket.error: [Errno 48] Address already in use

This commonly happened use case for any developer.

It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)

function killport {
   kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
}

Usage:

killport port_number

Example:

killport 8080

Waiting on a list of Future

 /**
     * execute suppliers as future tasks then wait / join for getting results
     * @param functors a supplier(s) to execute
     * @return a list of results
     */
    private List getResultsInFuture(Supplier<?>... functors) {
        CompletableFuture[] futures = stream(functors)
                .map(CompletableFuture::supplyAsync)
                .collect(Collectors.toList())
                .toArray(new CompletableFuture[functors.length]);
        CompletableFuture.allOf(futures).join();
        return stream(futures).map(a-> {
            try {
                return a.get();
            } catch (InterruptedException | ExecutionException e) {
                //logger.error("an error occurred during runtime execution a function",e);
                return null;
            }
        }).collect(Collectors.toList());
    };

Replacing H1 text with a logo image: best method for SEO and accessibility?

A new (Keller) method is supposed to improve speed over the -9999px method:

.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}

recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

Subscript out of bounds - general definition and solution?

If this helps anybody, I encountered this while using purr::map() with a function I wrote which was something like this:

find_nearby_shops <- function(base_account) {
   states_table %>% 
        filter(state == base_account$state) %>% 
        left_join(target_locations, by = c('border_states' = 'state')) %>% 
        mutate(x_latitude = base_account$latitude,
               x_longitude = base_account$longitude) %>% 
        mutate(dist_miles = geosphere::distHaversine(p1 = cbind(longitude, latitude), 
                                                     p2 = cbind(x_longitude, x_latitude))/1609.344)
}

nearby_shop_numbers <- base_locations %>% 
    split(f = base_locations$id) %>% 
    purrr::map_df(find_nearby_shops) 

I would get this error sometimes with samples, but most times I wouldn't. The root of the problem is that some of the states in the base_locations table (PR) did not exist in the states_table, so essentially I had filtered out everything, and passed an empty table on to mutate. The moral of the story is that you may have a data issue and not (just) a code problem (so you may need to clean your data.)

Thanks for agstudy and zx8754's answers above for helping with the debug.

PHP filesize MB/KB conversion

function calcSize($size,$accuracy=2) {
    $units = array('b','Kb','Mb','Gb');
    foreach($units as $n=>$u) {
        $div = pow(1024,$n);
        if($size > $div) $output = number_format($size/$div,$accuracy).$u;
    }
    return $output;
}

How to rename HTML "browse" button of an input type=file?

The button isn't called the "browse button" — that's just the name your browser gives for it. Browsers are free to implement the file upload control however they like. In Safari, for example, it's called "Choose File" and it's on the opposite side of whatever you're probably using.

You can implement a custom look for the upload control using the technique outlined on QuirksMode, but that goes beyond just changing the button's text.

How do I install pip on macOS or OS X?

The simplest solution is to follow the installation instruction from pip's home site.

Basically, this consists in:

  • downloading get-pip.py. Be sure to do this by following a trusted link since you will have to run the script as root.
  • call sudo python get-pip.py

The main advantage of that solution is that it install pip for the python version that has been used to run get-pip.py, which means that if you use the default OS X installation of python to run get-pip.py you will install pip for the python install from the system.

Most solutions that use a package manager (homebrew or macport) on OS X create a redundant installation of python in the environment of the package manager which can create inconsistencies in your system since, depending on what you are doing, you may call one installation of python instead of another.

How to get Url Hash (#) from server side

That's because the browser doesn't transmit that part to the server, sorry.

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

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

CSS: Control space between bullet and <li>

To summarise the other answers here – if you want finer control over the space between bullets and the text in a <li> list item, your options are:

(1) Use a background image:

<style type="text/css">
li {
    list-style-type:none;
    background-image:url(bullet.png);
}
</style>

<ul>
    <li>Some text</li>
</ul>

Advantages:

  • You can use any image you want for the bullet
  • You can use CSS background-position to position the image pretty much anywhere you want in relation to the text, using pixels, ems or %

Disadvantages:

  • Adds an extra (albeit small) image file to your page, increasing the page weight
  • If a user increases the text size on their browser, the bullet will stay at the original size. It'll also likely get further out of position as the text size increases
  • If you're developing a 'responsive' layout using only percentages for widths, it could be difficult to get the bullet exactly where you want it over a range of screen widths

2. Use padding on the <li> tag

<style type="text/css">
ul {padding-left:1em}
li {padding-left:1em}
</style>

<ul>
    <li>Some text</li>
</ul>

Advantages:

  • No image = 1 less file to download
  • By adjusting the padding on the <li>, you can add as much extra horizontal space between the bullet and the text as you like
  • If the user increases the text size, the spacing and bullet size should scale proportionally

Disadvantages:

  • Can't move the bullet any closer to the text than the browser default
  • Limited to shapes and sizes of CSS's built-in bullet types
  • Bullet must be same colour as the text
  • No control over vertical positioning of the bullet

(3) Wrap the text in an extra <span> element

<style type="text/css">
li {
    padding-left:1em;
    color:#f00; /* red bullet */
}
li span {
    display:block;
    margin-left:-0.5em;
    color:#000; /* black text */
}
</style>

<ul>
    <li><span>Some text</span></li>
</ul>

Advantages:

  • No image = 1 less file to download
  • You get more control over the position of the bullet than with option (2) – you can move it closer to the text (although despite my best efforts it seems you can't alter the vertical position by adding padding-top to the <span>. Someone else may have a workaround for this, though...)
  • The bullet can be a different colour to the text
  • If the user increases their text size, the bullet should scale in proportion (providing you set the padding & margin in ems not px)

Disadvantages:

  • Requires an extra unsemantic element (this will probably lose you more friends on SO than it will in real life ;) but it's annoying for those who like their code to be as lean and efficient as possible, and it violates the separation of presentation and content that HTML / CSS is supposed to offer)
  • No control over the size and shape of the bullet

Here's hoping for some new list-style features in CSS4, so we can create smarter bullets without resorting to images or exta mark-up :)

Import cycle not allowed

Here is an illustration of your first import cycle problem.

                  project/controllers/account
                     ^                    \    
                    /                      \
                   /                        \ 
                  /                         \/
         project/components/mux <--- project/controllers/base

As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux imports project/controllers/account. Since Go does not support circular dependencies you get the import cycle not allowed error during compile time.

throwing an exception in objective-c/cocoa

Sample code for case: @throw([NSException exceptionWithName:...

- (void)parseError:(NSError *)error
       completionBlock:(void (^)(NSString *error))completionBlock {


    NSString *resultString = [NSString new];

    @try {

    NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];

    if(!errorData.bytes) {

        @throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
    }


    NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
                                                                 options:NSJSONReadingAllowFragments
                                                                   error:&error];

    resultString = dictFromData[@"someKey"];
    ...


} @catch (NSException *exception) {

      NSLog( @"Caught Exception Name: %@", exception.name);
      NSLog( @"Caught Exception Reason: %@", exception.reason );

    resultString = exception.reason;

} @finally {

    completionBlock(resultString);
}

}

Using:

[self parseError:error completionBlock:^(NSString *error) {
            NSLog(@"%@", error);
        }];

Another more advanced use-case:

- (void)parseError:(NSError *)error completionBlock:(void (^)(NSString *error))completionBlock {

NSString *resultString = [NSString new];

NSException* customNilException = [NSException exceptionWithName:@"NilException"
                                                          reason:@"object is nil"
                                                        userInfo:nil];

NSException* customNotNumberException = [NSException exceptionWithName:@"NotNumberException"
                                                                reason:@"object is not a NSNumber"
                                                              userInfo:nil];

@try {

    NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];

    if(!errorData.bytes) {

        @throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
    }


    NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
                                                                 options:NSJSONReadingAllowFragments
                                                                   error:&error];

    NSArray * array = dictFromData[@"someArrayKey"];

    for (NSInteger i=0; i < array.count; i++) {

        id resultString = array[i];

        if (![resultString isKindOfClass:NSNumber.class]) {

            [customNotNumberException raise]; // <====== HERE is just the same as: @throw customNotNumberException;

            break;

        } else if (!resultString){

            @throw customNilException;        // <======

            break;
        }

    }

} @catch (SomeCustomException * sce) {
    // most specific type
    // handle exception ce
    //...
} @catch (CustomException * ce) {
    // most specific type
    // handle exception ce
    //...
} @catch (NSException *exception) {
    // less specific type

    // do whatever recovery is necessary at his level
    //...
    // rethrow the exception so it's handled at a higher level

    @throw (SomeCustomException * customException);

} @finally {
    // perform tasks necessary whether exception occurred or not

}

}

Refresh a page using JavaScript or HTML

simply use..

location.reload(true/false);

If false, the page will be reloaded from cache, else from the server.

How do I set up curl to permanently use a proxy?

You can make a alias in your ~/.bashrc file :

alias curl="curl -x <proxy_host>:<proxy_port>"

Another solution is to use (maybe the better solution) the ~/.curlrc file (create it if it does not exist) :

proxy = <proxy_host>:<proxy_port>

What's the difference between "Layers" and "Tiers"?

Read Scott Hanselman's post on the issue: http://www.hanselman.com/blog/AReminderOnThreeMultiTierLayerArchitectureDesignBroughtToYouByMyLateNightFrustrations.aspx

Remember though, that in "Scott World" (which is hopefully your world also :) ) a "Tier" is a unit of deployment, while a "Layer" is a logical separation of responsibility within code. You may say you have a "3-tier" system, but be running it on one laptop. You may say your have a "3-layer" system, but have only ASP.NET pages that talk to a database. There's power in precision, friends.

How to write a PHP ternary operator

echo ($result ->vocation == 1) ? 'Sorcerer'
        : ($result->vocation == 2) ? 'Druid'
           :  ($result->vocation == 3) ? 'Paladin'
                    ....

;

It’s kind of ugly. You should stick with normal if statements.

What is the best way to manage a user's session in React?

To name a few we can use redux-react-session which is having good API for session management like, initSessionService, refreshFromLocalStorage, checkAuth and many other. It also provide some advanced functionality like Immutable JS.

Alternatively we can leverage react-web-session which provides options like callback and timeout.

What is &amp used for

My Source: http://htmlhelp.com/tools/validator/problems.html#amp

Another common error occurs when including a URL which contains an ampersand ("&"):

This is invalid:

a href="foo.cgi?chapter=1&section=2&copy=3&lang=en"

Explanation:

This example generates an error for "unknown entity section" because the "&" is assumed to begin an entity reference. Browsers often recover safely from this kind of error, but real problems do occur in some cases. In this example, many browsers correctly convert &copy=3 to ©=3, which may cause the link to fail. Since ⟨ is the HTML entity for the left-pointing angle bracket, some browsers also convert &lang=en to <=en. And one old browser even finds the entity §, converting &section=2 to §ion=2.

So the goal here is to avoid problems when you are trying to validate your website. So you should be replacing your ampersands with &amp; when writing a URL in your markup.

Note that replacing & with &amp; is only done when writing the URL in HTML, where "&" is a special character (along with "<" and ">"). When writing the same URL in a plain text email message or in the location bar of your browser, you would use "&" and not "&amp;". With HTML, the browser translates "&amp;" to "&" so the Web server would only see "&" and not "&amp;" in the query string of the request.

Hope this helps : )

SoapUI "failed to load url" error when loading WSDL

Inside the wsdl file look for the import element, which looks like this :

`<import  namespace="nameSpaceValue" location="Users/myname/.../targetxsdName.xsd"/>`

Change the location attribute in the above element to the location of your xsd files stored locally, and it should work.

Download files in laravel using Response::download

HTML href link click:

<a ="{{ route('download',$name->file) }}"> Download  </a>

In controller:

public function download($file){
    $file_path = public_path('uploads/cv/'.$file);
    return response()->download( $file_path);
}

In route:

Route::get('/download/{file}','Controller@download')->name('download');

div inside php echo

You can do the following:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

If you want to have it inside your statement, do this:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

You don't need the else statement, since you're only going to output the above when it's truthy anyway.

C# delete a folder and all files and folders within that folder

dir.Delete(true); // true => recursive delete

Difference between window.location.href=window.location.href and window.location.reload()

If I remember correctly, window.location.reload() reloads the current page with POST data, while window.location.href=window.location.href does not include the POST data.

As noted by @W3Max in the comments below, window.location.href=window.location.href will not reload the page if there's an anchor (#) in the URL - You must use window.location.reload() in this case.

Also, as noted by @Mic below, window.location.reload() takes an additional argument skipCache so that with using window.location.reload(true) the browser will skip the cache and reload the page from the server. window.location.reload(false) will do the opposite, and load the page from cache if possible.

Which characters are valid/invalid in a JSON key name?

The following characters must be escaped in JSON data to avoid any problems:

  • " (double quote)
  • \ (backslash)
  • all control characters like \n, \t

JSON Parser can help you to deal with JSON.

add to array if it isn't there already

Easy to write, but not the most effective one:

$array = array_unique(array_merge($array, $array_to_append));

This one is probably faster:

$array = array_merge($array, array_diff($array_to_append, $array));

Can someone explain mappedBy in JPA and Hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side.

This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

How does bitshifting work in Java?

00101011 = 43 in decimal

class test {    
    public static void main(String[] args){
       int a= 43;       
       String b= Integer.toBinaryString(a >> 2);        
       System.out.println(b);
    }   
}

Output:

101011 becomes 1010

How do I get the value of a textbox using jQuery?

There's a .val() method:

If you've got an input with an id of txtEmail you can use the following code to access the value of the text box:

$("#txtEmail").val()

You can also use the val(string) method to set that value:

$("#txtEmail").val("something")

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I am using a Cursor so I can not use the DiffUtils as proposed in the popular answers. In order to make it work for me I am disabling animations when the list is not idle. This is the extension that fixes this issue:

 fun RecyclerView.executeSafely(func : () -> Unit) {
        if (scrollState != RecyclerView.SCROLL_STATE_IDLE) {
            val animator = itemAnimator
            itemAnimator = null
            func()
            itemAnimator = animator
        } else {
            func()
        }
    }

Then you can update your adapter like that

list.executeSafely {
  adapter.updateICursor(newCursor)
}

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Font awesome is just a font so you can use the font size attribute in your CSS to change the size of the icon.

So you can just add a class to the icon like this:

.big-icon {
    font-size: 32px;
}

source of historical stock data

Why not model a fake stock market with Brownian Motion?

Plenty of resources for doing it. Easy to implement.

http://introcs.cs.princeton.edu/java/98simulation/

How to check for valid email address?

Use this filter mask on email input: emailMask: /[\w.\-@'"!#$%&'*+/=?^_{|}~]/i`

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

Can I redirect the stdout in python into some sort of string buffer?

Here's another take on this. contextlib.redirect_stdout with io.StringIO() as documented is great, but it's still a bit verbose for every day use. Here's how to make it a one-liner by subclassing contextlib.redirect_stdout:

import sys
import io
from contextlib import redirect_stdout

class capture(redirect_stdout):

    def __init__(self):
        self.f = io.StringIO()
        self._new_target = self.f
        self._old_targets = []  # verbatim from parent class

    def __enter__(self):
        self._old_targets.append(getattr(sys, self._stream))  # verbatim from parent class
        setattr(sys, self._stream, self._new_target)  # verbatim from parent class
        return self  # instead of self._new_target in the parent class

    def __repr__(self):
        return self.f.getvalue()  

Since __enter__ returns self, you have the context manager object available after the with block exits. Moreover, thanks to the __repr__ method, the string representation of the context manager object is, in fact, stdout. So now you have,

with capture() as message:
    print('Hello World!')
print(str(message)=='Hello World!\n')  # returns True

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Open file in a relative location in Python

Python just passes the filename you give it to the operating system, which opens it. If your operating system supports relative paths like main/2091/data.txt (hint: it does), then that will work fine.

You may find that the easiest way to answer a question like this is to try it and see what happens.

What is the proper way to check and uncheck a checkbox in HTML5?

<input type="checkbox" checked />

HTML5 does not require attributes to have values

finding the type of an element using jQuery

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName

Building a fat jar using maven

actually, adding the

<archive>
   <manifest>
    <addClasspath>true</addClasspath>
    <packageName>com.some.pkg</packageName>                     
    <mainClass>com.MainClass</mainClass>
  </manifest>
</archive>

declaration to maven-jar-plugin does not add the main class entry to the manifest file for me. I had to add it to the maven-assembly-plugin in order to get that in the manifest

missing private key in the distribution certificate on keychain

After you changed a Mac which are not the origin one who created the disitribution certificate, you will missing the private key.Just delete the origin certificate and recreate a new one, that works for me~

Are string.Equals() and == operator really same?

The Header property of the TreeViewItem is statically typed to be of type object.

Therefore the == yields false. You can reproduce this with the following simple snippet:

object s1 = "Hallo";

// don't use a string literal to avoid interning
string s2 = new string(new char[] { 'H', 'a', 'l', 'l', 'o' });

bool equals = s1 == s2;         // equals is false
equals = string.Equals(s1, s2); // equals is true

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

rdtsc solution did not work for me.

Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.

Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.

I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk

This fixed the issue for me.

What is the equivalent of 'describe table' in SQL Server?

The SQL Server equivalent to Oracle's describe command is the stored proc sp_help

The describe command gives you the information about the column names, types, length, etc.

In SQL Server, let's say you want to describe a table 'mytable' in schema 'myschema' in the database 'mydb', you can do following:

USE mydb;
exec sp_help 'myschema.mytable';

How to use BOOLEAN type in SELECT statement

You can definitely get Boolean value from a SELECT query, you just can't use a Boolean data-type.

You can represent a Boolean with 1/0.

CASE WHEN (10 > 0) THEN 1  ELSE 0 END (It can be used in SELECT QUERY)

SELECT CASE WHEN (10 > 0) THEN 1  ELSE 0 END AS MY_BOOLEAN_COLUMN
  FROM DUAL

Returns, 1 (in Hibernate/Mybatis/etc 1 is true). Otherwise, you can get printable Boolean values from a SELECT.

SELECT CASE WHEN (10 > 0) THEN 'true' ELSE 'false' END AS MY_BOOLEAN_COLUMN
 FROM DUAL

This returns the string 'true'.

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

Authentication plugin 'caching_sha2_password' is not supported

Modify Mysql encryption

ALTER USER 'lcherukuri'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

Create a batch file to run an .exe with an additional parameter

Found another solution for the same. It will be more helpful.

START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"

finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".

when exactly are we supposed to use "public static final String"?

This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.

In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.

How to write ternary operator condition in jQuery?

From what it looks like you are trying to do, toggle might better solve your problem.

EDIT: Sorry, toggle is just visibility, I don't think it will help your bg color toggling.

But here you go:

var box = $("#blackbox");
box.css('background') == 'pink' ? box.css({'background':'black'}) : box.css({'background':'pink'}); 

Ternary operator in PowerShell

I've recently improved (open PullRequest) the ternary conditional and null-coalescing operators in the PoweShell lib 'Pscx'
Pls have a look for my solution.


My github topic branch: UtilityModule_Invoke-Operators

Functions:

Invoke-Ternary
Invoke-TernaryAsPipe
Invoke-NullCoalescing
NullCoalescingAsPipe

Aliases

Set-Alias :?:   Pscx\Invoke-Ternary                     -Description "PSCX alias"
Set-Alias ?:    Pscx\Invoke-TernaryAsPipe               -Description "PSCX alias"
Set-Alias :??   Pscx\Invoke-NullCoalescing              -Description "PSCX alias"
Set-Alias ??    Pscx\Invoke-NullCoalescingAsPipe        -Description "PSCX alias"

Usage

<condition_expression> |?: <true_expression> <false_expression>

<variable_expression> |?? <alternate_expression>

As expression you can pass:
$null, a literal, a variable, an 'external' expression ($b -eq 4) or a scriptblock {$b -eq 4}

If a variable in the variable expression is $null or not existing, the alternate expression is evaluated as output.

How to reset a timer in C#?

Other alternative way to reset the windows.timer is using the counter, as follows:

int timerCtr = 0;
Timer mTimer;

private void ResetTimer() => timerCtr = 0;
private void mTimer_Tick()
{
    timerCtr++;
    // Perform task
}  

So if you intend to repeat every 1 second, you can set the timer interval at 100ms, and test the counter to 10 cycles.

This is suitable if the timer should wait for some processes those may be ended at the different time span.

Django Template Variables and Javascript

Note, that if you want to pass a variable to an external .js script then you need to precede your script tag with another script tag that declares a global variable.

<script type="text/javascript">
    var myVar = "{{ myVar }}"
</script>

<script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>

data is defined in the view as usual in the get_context_data

def get_context_data(self, *args, **kwargs):
    context['myVar'] = True
    return context

Why am I getting the error "connection refused" in Python? (Sockets)

try this command in terminal:

sudo ufw enable
ufw allow 12397

Query based on multiple where clauses in Firebase

I've written a personal library that allows you to order by multiple values, with all the ordering done on the server.

Meet Querybase!

Querybase takes in a Firebase Database Reference and an array of fields you wish to index on. When you create new records it will automatically handle the generation of keys that allow for multiple querying. The caveat is that it only supports straight equivalence (no less than or greater than).

const databaseRef = firebase.database().ref().child('people');
const querybaseRef = querybase.ref(databaseRef, ['name', 'age', 'location']);

// Automatically handles composite keys
querybaseRef.push({ 
  name: 'David',
  age: 27,
  location: 'SF'
});

// Find records by multiple fields
// returns a Firebase Database ref
const queriedDbRef = querybaseRef
 .where({
   name: 'David',
   age: 27
 });

// Listen for realtime updates
queriedDbRef.on('value', snap => console.log(snap));

How to solve static declaration follows non-static declaration in GCC C code?

This error can be caused by an unclosed set of brackets.

int main {
  doSomething {}
  doSomething else {
}

Not so easy to spot, even in this 4 line example.

This error, in a 150 line main function, caused the bewildering error: "static declaration of ‘savePair’ follows non-static declaration". There was nothing wrong with my definition of function savePair, it was that unclosed bracket.

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

How to dynamically change the color of the selected menu item of a web page?

At last I managed to achieve what I intended with all your help and the post Change a link style onclick. Here is the code for that. I used JavaScript for doing this.

<html>
    <head>
        <style type="text/css">
            .item {
                width:900px;
                padding:0;
                margin:0;
                list-style-type:none;
            }

            a {
                display:block;
                width:60;
                line-height:25px; /*24px*/
                border-bottom:1px  none #808080;
                font-family:'arial narrow',sans-serif;
                color:#00F;
                text-align:center;
                text-decoration:none;
                background:#CCC;
                border-radius: 5px;
                -webkit-border-radius: 5px;
                -moz-border-radius: 5px;
                margin-bottom:0em;
                padding: 0px;
            }

            a.item {
                float:left;        /* For horizontal left to right display. */
                width:145px;       /* For maintaining equal  */
                margin-right: 5px; /* space between two boxes. */
            }

            a.selected{
                background:orange;
                color:white;
            }
        </style>
    </head>
    <body>
        <a class="item" href="#" >item 1</a>
        <a class="item" href="#" >item 2</a>
        <a class="item" href="#" >item 3</a>
        <a class="item" href="#" >item 4</a>
        <a class="item" href="#" >item 5</a>
        <a class="item" href="#" >item 6</a>

        <script>
            var anchorArr=document.getElementsByTagName("a");
            var prevA="";
            for(var i=0;i<anchorArr.length;i++)
            {
                anchorArr[i].onclick = function(){
                    if(prevA!="" && prevA!=this)
                    {
                        prevA.className="item";
                    }
                    this.className="item selected";
                    prevA=this;
                }
            }
        </script>
    </body>
</html>

Authenticate with GitHub using a token

First, you need to create a personal access token (PAT). This is described here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/

Laughably, the article tells you how to create it, but gives absolutely no clue what to do with it. After about an hour of trawling documentation and Stack Overflow, I finally found the answer:

$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

I was actually forced to enable two-factor authentication by company policy while I was working remotely and still had local changes, so in fact it was not clone I needed, but push. I read in lots of places that I needed to delete and recreate the remote, but in fact my normal push command worked exactly the same as the clone above, and the remote did not change:

$ git push https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

(@YMHuang put me on the right track with the documentation link.)

Why is it common to put CSRF prevention tokens in cookies?

Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.

The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.

The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.

Integrating the ZXing library directly into my Android application

UPDATE! - SOLVED + GUIDE

I've managed to figure it out :) And down below you can read step-by-step guide so it hopefully can help others with the same problem as I had ;)

  1. Install Apache Ant - (See this YouTube video for config help)
  2. Download the ZXing source from ZXing homepage and extract it
  3. With the use of Windows Commandline (Run->CMD) navigate to the root directory of the downloaded zxing src.
  4. In the commandline window - Type ant -f core/build.xml press enter and let Apache work it's magic [having issues?]
  5. Enter Eclipse -> new Android Project, based on the android folder in the directory you just extracted
  6. Right-click project folder -> Properties -> Java Build Path -> Library -> Add External JARs...
  7. Navigate to the newly extracted folder and open the core directory and select core.jar ... hit enter!

Now you just have to correct a few errors in the translations and the AndroidManifest.xml file :) Now you can happily compile, and you will now have a working standalone barcode scanner app, based on the ZXing source ;)

Happy coding guys - I hope it can help others :)

How to resolve a Java Rounding Double issue

To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.

Given your example, the last line would be as following using BigDecimal.

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

This results in the following output.

877.85 = 1586.6 - 708.75

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

define ANDROID_SDK_ROOT as environment variable where your SDK is residing, default path would be "C:\Program Files (x86)\Android\android-sdk" and restart computer to take effect.

How to assign the output of a Bash command to a variable?

In shell you assign to a variable without the dollar-sign:

TEST=`pwd`
echo $TEST

that's better (and can be nested) but is not as portable as the backtics:

TEST=$(pwd)
echo $TEST

Always remember: the dollar-sign is only used when reading a variable.

How can I specify a display?

I faced similar problem today. So, here's a simple solution: While doing SSH to the machine, just add Ctrl - Y.

ssh user@ip_address -Y

After login, type firefox &. And you are good to go.

Simple way to compare 2 ArrayLists

List<String> oldList = Arrays.asList("a", "b", "c", "d", "e", "f");
List<String> modifiedList = Arrays.asList("a", "b", "c", "d", "e", "g");

List<String> added = new HashSet<>(modifiedList);
List<String> removed = new HashSet<>(oldList);

modifiedList.stream().filter(removed::remove).forEach(added::remove);

// added items
System.out.println(added);
// removed items
System.out.println(removed);

SQLite DateTime comparison

Sqlite can not compare on dates. we need to convert into seconds and cast it as integer.

Example

SELECT * FROM Table  
WHERE  
CAST(strftime('%s', date_field)  AS  integer) <=CAST(strftime('%s', '2015-01-01')  AS  integer) ;

Draggable div without jQuery UI

Here is my simple version.
The function draggable takes a jQuery object as argument.


/**
 * @param {jQuery} elem
 */
function draggable(elem){

    elem.mousedown(function(evt){
        var x = parseInt(this.style.left || 0) - evt.pageX;
        var y = parseInt(this.style.top || 0) - evt.pageY;

        elem.mousemove(function(evt){
            elem.css('left', x + evt.pageX);
            elem.css('top', y + evt.pageY);
        });
    });

    elem.mouseup(off);
    elem.mouseleave(off);

    function off(){
        elem.off("mousemove");
    }
}

How can I create C header files

Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.

If a header file contains a function, and is included by multiple .c files, each .c file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.

It is technically possible to create static functions in a header file for inclusion in multiple .c files. Though this is generally not done because it breaks from the convention that code is found in .c files and declarations are found in .h files.

See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.

$(document).ready not Working

One possibility when ready stops working is that you have javascript code somewhere that is throwing an exception in a $(document).ready(...) or $(...) call, which is stopping processing of the rest of the ready blocks. Identify a single page on which this is occurring and examine it for possible errors in other places.

Checking for empty or null List<string>

List in c# has a Count property. It can be used like so:

if(myList == null) // Checks if list is null
    // Wasn't initialized
else if(myList.Count == 0) // Checks if the list is empty
    myList.Add("new item");
else // List is valid and has something in it
    // You could access the element in the list if you wanted

Persistent invalid graphics state error when using ggplot2

try to get out grafics with x11() or win.graph() and solve this trouble.

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

onClick function of an input type="button" not working

When I try:

<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!"  />

It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.

Pls try:

<script type="text/javascript">
    function moreFields() {
        alert("The text will be show");
    }
</script>

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />

Hope it helped.

How to get N rows starting from row M from sorted table in T-SQL

In SQL 2012 you can use OFFSET and FETCH:

SELECT *
FROM MyTable
ORDER BY MyColumn
OFFSET @N ROWS
FETCH NEXT @M ROWS ONLY;


I personally prefer:

DECLARE @CurrentSetNumber int = 0;
DECLARE @NumRowsInSet int = 2;

SELECT *
FROM MyTable
ORDER BY MyColumn
OFFSET @NumRowsInSet * @CurrentSetNumber ROWS
FETCH NEXT @NumRowsInSet ROWS ONLY;

SET @CurrentSetNumber = @CurrentSetNumber + 1;

where @NumRowsInSet is the number of rows you want returned and @CurrentSetNumber is the number of @NumRowsInSet to skip.

System.Runtime.InteropServices.COMException (0x800A03EC)

Some googling reveals that potentially you've got a corrupt file:

http://bitterolives.blogspot.com/2009/03/excel-interop-comexception-hresult.html

and that you can tell excel to open it anyway with the CorruptLoad parameter, with something like...

Workbook workbook = excelApplicationObject.Workbooks.Open(path, CorruptLoad: true);

Create a menu Bar in WPF?

<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="_File">
            <MenuItem Header="_Open"/>
            <MenuItem Header="_Close"/>
            <MenuItem Header="_Save"/>
        </MenuItem>
    </Menu>
    <StackPanel></StackPanel>
</DockPanel>

sys.stdin.readline() reads without prompt, returning 'nothing in between'

If you need just one character and you don't want to keep things in the buffer, you can simply read a whole line and drop everything that isn't needed.

Replace:

stdin.read(1)

with

stdin.readline().strip()[:1]

This will read a line, remove spaces and newlines and just keep the first character.

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Connect to SQL Server Database from PowerShell

The answer are as below for Window authentication

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$SQLServer;Database=$SQLDBName;Integrated Security=True;"

strcpy() error in Visual studio 2012

Add this line top of the header

#pragma warning(disable : 4996)

SQL Query to add a new column after an existing column in SQL Server 2005

It is a bad idea to select * from anything, period. This is why SSMS adds every field name, even if there are hundreds, instead of select *. It is extremely inefficient regardless of how large the table is. If you don't know what the fields are, its still more efficient to pull them out of the INFORMATION_SCHEMA database than it is to select *.

A better query would be:

SELECT 
 COLUMN_NAME, 
 Case 
  When DATA_TYPE In ('varchar', 'char', 'nchar', 'nvarchar', 'binary') 
  Then convert(varchar(MAX), CHARACTER_MAXIMUM_LENGTH)  
  When DATA_TYPE In ('numeric', 'int', 'smallint', 'bigint', 'tinyint') 
  Then convert(varchar(MAX), NUMERIC_PRECISION) 
  When DATA_TYPE = 'bit' 
  Then convert(varchar(MAX), 1)
  When DATA_TYPE IN ('decimal', 'float') 
  Then convert(varchar(MAX), Concat(Concat(NUMERIC_PRECISION, ', '), NUMERIC_SCALE)) 
  When DATA_TYPE IN ('date', 'datetime', 'smalldatetime', 'time', 'timestamp') 
  Then '' 
 End As DATALEN, 
 DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
Where 
 TABLE_NAME = ''

urllib2 and json

You certainly want to hack the header to have a proper Ajax Request :

headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
           'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()

And to json.loads the POST on the server-side.

Edit : By the way, you have to urllib.urlencode(mydata_dict) before sending them. If you don't, the POST won't be what the server expect

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

System.Data.OracleClient requires Oracle client software version 8.1.7

Oracle Client version 11 cannot connect to 8i databases. You will need a client in version 10 at most.

Implementing a Custom Error page on an ASP.Net website

<system.webServer>     
<httpErrors errorMode="DetailedLocalOnly">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
    </httpErrors>
</system.webServer>

Launch Image does not show up in my iOS App

If you have changed your launch image from a previous image, and observe the following:

  • devices/simulators where the app was previously installed, still show the previous image and refuse to show the new one (uninstalling and reinstalling the app doesn't help)
  • devices/simulators where the app was not previously installed, show the new launch image

It is likely because of the caching of launch image done by iOS. Rebooting the device should solve the problem.

How to check if another instance of my shell script is running

Definitely works.

if [[ `pgrep -f $0` != "$$" ]]; then
        echo "Exiting ! Exist"
        exit
fi

How to scan a folder in Java?

import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

http://java.sun.com/javase/6/docs/api/java/io/File.html

Hover and Active only when not disabled

You can use :enabled pseudo-class, but notice IE<9 does not support it:

button:hover:enabled{
    /*your styles*/
}
button:active:enabled{
    /*your styles*/
}

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Force download a pdf link using javascript/ajax/jquery

Using Javascript you can download like this in a simple method

var oReq = new XMLHttpRequest();
// The Endpoint of your server 
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);

// Important to use the blob response type
oReq.responseType = "blob";

// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], { 
    type: 'application/pdf' 
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};

oReq.send();

Could not load NIB in bundle

for me, it solved just by changing the name of my cell's file into the same as its class.

In Attributes Inspector(Third tab on the right side bar in story board):

  1. Set the cell's Identifier( for example: "MyCellId"),
  2. Set the cell's Class (for example: "MyCellClass" when the file is "MyCellClass") ,
  3. Register the cell in your view controller as follow:

    tableView.register(UINib(nibName: "MyCellClass", bundle: nil), forCellReuseIdentifier: "MyCellId")

Multiline TextBox multiple newline

textBox1.Text = "Line1\r\r\Line2";
Solved the problem.

Is there an auto increment in sqlite?

You get one for free, called ROWID. This is in every SQLite table whether you ask for it or not.

If you include a column of type INTEGER PRIMARY KEY, that column points at (is an alias for) the automatic ROWID column.

ROWID (by whatever name you call it) is assigned a value whenever you INSERT a row, as you would expect. If you explicitly assign a non-NULL value on INSERT, it will get that specified value instead of the auto-increment. If you explicitly assign a value of NULL on INSERT, it will get the next auto-increment value.

Also, you should try to avoid:

 INSERT INTO people VALUES ("John", "Smith");

and use

 INSERT INTO people (first_name, last_name) VALUES ("John", "Smith");

instead. The first version is very fragile — if you ever add, move, or delete columns in your table definition the INSERT will either fail or produce incorrect data (with the values in the wrong columns).

Reading/writing an INI file

You should read and write data from xml files since you can save a whole object to xml and also you can populate a object from a saved xml. It is better an easy to manipulate objects.

Here is how to do it: Write Object Data to an XML File: https://msdn.microsoft.com/en-us/library/ms172873.aspx Read Object Data from an XML File: https://msdn.microsoft.com/en-us/library/ms172872.aspx

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

How to enable scrolling on website that disabled scrolling?

What worked for me was disabling the position: fixed; CSS.

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

identifier "string" undefined?

<string.h> is the old C header. C++ provides <string>, and then it should be referred to as std::string.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

PHP Composer behind http proxy

iconoclast's answer did not work for me.

I upgraded my php from 5.3.* (xampp 1.7.4) to 5.5.* (xampp 1.8.3) and the problem was solved.

Try iconoclast's answer first, if it doesn't work then upgrading might solve the problem.

How can I escape latex code received through user input?

I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:

s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]

Removing all line breaks and adding them after certain text

You can also go to Notepad++ and do the following steps:

Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)

Capture key press (or keydown) event on DIV element

Here example on plain JS:

_x000D_
_x000D_
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
  console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
  outline: none;_x000D_
}
_x000D_
<div _x000D_
  id="myDiv"_x000D_
  tabindex="0"_x000D_
>_x000D_
  Press me and start typing_x000D_
</div>
_x000D_
_x000D_
_x000D_

Enable remote connections for SQL Server Express 2012

One More Thing...

Kyralessa provides great information but I have one other thing to add where I was stumped even after this article.

Under SQL Server Network Configuration > Protocols for Server > TCP/IP Enabled. Right Click TCP/IP and choose properties. Under the IP Addresses you need to set Enabled to Yes for each connection type that you are using.

enter image description here

How to check if a line has one of the strings in a list?

strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

Should you use .htm or .html file extension? What is the difference, and which file is correct?

The short answer

There is none. They are exactly the same.

The long answer

Both .htm and .html are exactly the same and will work in the same way. The choice is down to personal preference, provided you’re consistent with your file naming you won’t have a problem with either.

Depending on the configuration of the web server, one of the file types will take precedence over the other. This should not be an issue since it’s unlikely that you’ll have both index.htm and index.html sitting in the same folder.

We always use the shorter .htm for our file names since file extensions are typically 3 characters long.

AND MORE ON: http://www.sightspecific.com/~mosh/WWW_FAQ/ext.html or http://www.sightspecific.com/~mosh/WWW_FAQ/ext.htm

I think I should add this part here:
There is one single slight difference between .htm and .html files. Consider a path in your server like: mydomain.com/myfolder. If you create an index.htm file inside that folder and you open that like this:mydomain.com/myfolder/, it will goes crazy and spit out your files as it is in your server,enter image description here
but if you create an index.html file in there and open that directory in your browser, it will load that file. I tested this on my VPS and found this Maybe you could somehow set your server to load index.htm files by default, but I guess the .html file is the default file type for browsers to open in each directory.

Finding the max/min value in an array of primitives using Java

Pass the array to a method that sorts it with Arrays.sort() so it only sorts the array the method is using then sets min to array[0] and max to array[array.length-1].

"Couldn't read dependencies" error with npm

This doesn't look like your issue, but for the sake of others, for me this was caused by an invalid version number in package.json (had to change 2.4 to 2.4.0).

How to make an HTTP get request with parameters

My preferred way is this. It handles the escaping and parsing for you.

WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");

How may I reference the script tag that loaded the currently-executing script?

Here's a bit of a polyfill that leverages document.CurrentScript if it exists and falls back to finding the script by ID.

<script id="uniqueScriptId">
    (function () {
        var thisScript = document.CurrentScript || document.getElementByID('uniqueScriptId');

        // your code referencing thisScript here
    ());
</script>

If you include this at the top of every script tag I believe you'll be able to consistently know which script tag is being fired, and you'll also be able to reference the script tag in the context of an asynchronous callback.

Untested, so leave feedback for others if you try it.

Change header background color of modal of twitter bootstrap

You can use the css below, put this in your custom css to override the bootstrap css.

.modal-header {
    padding:9px 15px;
    border-bottom:1px solid #eee;
    background-color: #0480be;
    -webkit-border-top-left-radius: 5px;
    -webkit-border-top-right-radius: 5px;
    -moz-border-radius-topleft: 5px;
    -moz-border-radius-topright: 5px;
     border-top-left-radius: 5px;
     border-top-right-radius: 5px;
 }

Program "make" not found in PATH

I had the same problem. Initially I had setup Eclipse CDT with Cygwing & was working smoothly. One day there happened a problem due to which I had to reset windows. After that when I opened Eclipse I started facing the issue described above. This is how I solved it.

First I searched that in the error the PATH variable value is same as the PATH variable of windows ( just by manual comparison of both two values ). I found that to be same. Now I realized that it is a PATH problem.

Then started looking for Cygwin whether it is there or not? It was there. I located & found that it exists in

C:\cygwin64\bin>
C:\cygwin64\bin>dir ma*
 Volume in drive C is Windows8_OS
 Volume Serial Number is 042E-11B5

 Directory of C:\cygwin64\bin

16-05-2015  18:34            10,259 mag.exe
13-08-2013  04:57               384 mailmail
11-04-2015  02:56             4,252 make-emacs-shortcut
15-02-2015  23:25           194,579 make.exe
04-05-2015  21:36            40,979 makeconv.exe
29-07-2013  11:57            29,203 makedepend.exe
16-05-2015  18:34            79,891 makeindex.exe
16-05-2015  18:34            34,323 makejvf.exe
07-05-2015  03:04               310 mako-render
18-04-2015  02:07            92,179 man.exe
18-04-2015  02:07           113,683 mandb.exe
13-08-2013  04:57               286 manhole
18-04-2015  02:07            29,203 manpath.exe
24-10-2014  13:31           274,461 mate-terminal.exe
24-10-2014  13:31             1,366 mate-terminal.wrapper
              15 File(s)        905,358 bytes
               0 Dir(s)  373,012,271,104 bytes free

C:\cygwin64\bin>

Then I simply went ahead & updated the PATH variable to include this path & restarted eclipse.

The code compiles & debugging (GDB ) is working nicely.

Hope this helps.

How to POST JSON Data With PHP cURL?

First,

  1. always define certificates with CURLOPT_CAPATH option,

  2. decide how your POSTed data will be transfered.

1 Certificates

By default:

  • CURLOPT_SSL_VERIFYHOST == 2 which "checks the existence of a common name and also verify that it matches the hostname provided" and

  • CURLOPT_VERIFYPEER == true which "verifies the peer's certificate".

So, all you have to do is:

const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
...
\curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);

taken from a working class where SERVER_ROOT is a constant defined during application bootstraping like in a custom classloader, another class etc.

Forget things like \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0); or \curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);.

Find cacert.pem there as seen in this question.

2 POST modes

There are actually 2 modes when posting data:

  • the data is transfered with Content-Type header set to multipart/form-data or,

  • the data is a urlencoded string with application/x-www-form-urlencoded encoding.

In the first case you pass an array while in the second you pass a urlencoded string.

multipart/form-data ex.:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

application/x-www-form-urlencoded ex.:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));

http_build_query:

Test it at your command line as

user@group:$ php -a
php > $fields = array('a' => 'sth', 'b' => 'else');
php > echo \http_build_query($fields);
a=sth&b=else

The other end of the POST request will define the appropriate mode of connection.

How to add to the end of lines containing a pattern with sed or awk?

You can append the text to $0 in awk if it matches the condition:

awk '/^all:/ {$0=$0" anotherthing"} 1' file

Explanation

  • /patt/ {...} if the line matches the pattern given by patt, then perform the actions described within {}.
  • In this case: /^all:/ {$0=$0" anotherthing"} if the line starts (represented by ^) with all:, then append anotherthing to the line.
  • 1 as a true condition, triggers the default action of awk: print the current line (print $0). This will happen always, so it will either print the original line or the modified one.

Test

For your given input it returns:

somestuff...
all: thing otherthing anotherthing
some other stuff

Note you could also provide the text to append in a variable:

$ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file
somestuff...
all: thing otherthing EXTRA TEXT
some other stuff

Flexbox: 4 items per row

Add a width to the .child elements. I personally would use percentages on the margin-left if you want to have it always 4 per row.

DEMO

.child {
    display: inline-block;
    background: blue;
    margin: 10px 0 0 2%;
    flex-grow: 1;
    height: 100px;
    width: calc(100% * (1/4) - 10px - 1px);
}

What methods of ‘clearfix’ can I use?

The overflow property can be used to clear floats with no additional mark-up:

.container { overflow: hidden; }

This works for all browsers except IE6, where all you need to do is enable hasLayout (zoom being my preferred method):

.container { zoom: 1; }

http://www.quirksmode.org/css/clearing.html

JavaScript: Is there a way to get Chrome to break on all errors?

Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.

Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.

If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error object given to the catch block has a stack property that shows where the exception happened.

When using SASS how can I import a file from a different directory?

Gulp will do the job for watching your sass files and also adding paths of other file with includePaths. example:

gulp.task('sass', function() {
  return gulp.src('scss/app.scss')
    .pipe($.sass({
      includePaths: sassPaths
    })
    .pipe(gulp.dest('css'));
});