Programs & Examples On #Sfguard

sfGuard is a Symfony plugin that implements a user management and login system for an application. It supports both groups and individual users.

How to Debug Variables in Smarty like in PHP var_dump()

If you want something prettier I would advise

{"<?php\n\$data =\n"|@cat:{$yourvariable|@var_export:true|@cat:";\n?>"}|@highlight_string:true}

just replace yourvariable by your variable

How to skip the OPTIONS preflight request?

When performing certain types of cross-domain AJAX requests, modern browsers that support CORS will insert an extra "preflight" request to determine whether they have permission to perform the action. From example query:

$http.get( ‘https://example.com/api/v1/users/’ +userId,
  {params:{
           apiKey:’34d1e55e4b02e56a67b0b66’
          }
  } 
);

As a result of this fragment we can see that the address was sent two requests (OPTIONS and GET). The response from the server includes headers confirming the permissibility the query GET. If your server is not configured to process an OPTIONS request properly, client requests will fail. For example:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: accept, origin, x-requested-with, content-type
Access-Control-Allow-Methods: DELETE
Access-Control-Allow-Methods: OPTIONS
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Methods: GET
Access-Control-Allow-Methods: POST
Access-Control-Allow-Orgin: *
Access-Control-Max-Age: 172800
Allow: PUT
Allow: OPTIONS
Allow: POST
Allow: DELETE
Allow: GET

Erasing elements from a vector

Depending on why you are doing this, using a std::set might be a better idea than std::vector.

It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.

This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.

What is the single most influential book every programmer should read?

Dreaming in Code Has probably had the most profound impact in the last 6 months.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

I would suggest interested parties have a look at Maarten Balliauw's solution. I think it is very elegant.

In case the link dissapears, it's using the MultiButton attribute applied to a controller action to indicate which button click that action should relate to.

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Custom checkbox image android

If you are using custom adapters than android:focusable="false" and android:focusableInTouchMode="false" are nessesury to make list items clickable while using checkbox.

<CheckBox
        android:id="@+id/checkbox_fav"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/checkbox_layout"/>

In drawable>checkbox_layout.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/uncked_checkbox"
        android:state_checked="false"/>
    <item android:drawable="@drawable/selected_checkbox"
        android:state_checked="true"/>
    <item android:drawable="@drawable/uncked_checkbox"/>
</selector>

How do I convert datetime to ISO 8601 in PHP

You can try this way:

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DATE_ATOM);

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Hiding an Excel worksheet with VBA

You can do this programmatically using a VBA macro. You can make the sheet hidden or very hidden:

Sub HideSheet()

    Dim sheet As Worksheet

    Set sheet = ActiveSheet

    ' this hides the sheet but users will be able 
    ' to unhide it using the Excel UI
    sheet.Visible = xlSheetHidden

    ' this hides the sheet so that it can only be made visible using VBA
    sheet.Visible = xlSheetVeryHidden

End Sub

Difference between 'cls' and 'self' in Python classes?

Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.

-Python Tricks

How to access URL segment(s) in blade in Laravel 5?

BASED ON LARAVEL 5.7 & ABOVE

To get all segments of current URL:

$current_uri = request()->segments();

To get segment posts from http://example.com/users/posts/latest/

NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.

//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'

You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:

public function index()
{
    $prev_uri_segments = $this->prev_segments(url()->previous());
}

 /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}

How Exactly Does @param Work - Java

@param is a special format comment used by javadoc to generate documentation. it is used to denote a description of the parameter (or parameters) a method can receive. there's also @return and @see used to describe return values and related information, respectively:

http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#format

has, among other things, this:

/**
 * Returns an Image object that can then be painted on the screen. 
 * The url argument must specify an absolute {@link URL}. The name
 * argument is a specifier that is relative to the url argument. 
 * <p>
 * This method always returns immediately, whether or not the 
 * image exists. When this applet attempts to draw the image on
 * the screen, the data will be loaded. The graphics primitives 
 * that draw the image will incrementally paint on the screen. 
 *
 * @param  url  an absolute URL giving the base location of the image
 * @param  name the location of the image, relative to the url argument
 * @return      the image at the specified URL
 * @see         Image
 */
 public Image getImage(URL url, String name) {

How do I delete specific characters from a particular String in Java?

You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.

In some cases a StringBuffer might help you instead.

ImportError: No module named 'bottle' - PyCharm

I had virtual env site package problem and this helped me, maybe it will help you too enter image description here

How to create exe of a console application

Normally, the exe can be found in the debug folder, as suggested previously, but not in the release folder, that is disabled by default in my configuration. If you want to activate the release folder, you can do this: BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. Now you can copy and use it.

Adding timestamp to a filename with mv in BASH

mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log

Going to a specific line number using Less in Unix

You can use sed for this too -

sed -n '320123'p filename 

This will print line number 320123.

If you want a range then you can do -

sed -n '320123,320150'p filename 

If you want from a particular line to the very end then -

sed -n '320123,$'p filename 

std::string to char*

This would be better as a comment on bobobobo's answer, but I don't have the rep for that. It accomplishes the same thing but with better practices.

Although the other answers are useful, if you ever need to convert std::string to char* explicitly without const, const_cast is your friend.

std::string str = "string";
char* chr = const_cast<char*>(str.c_str());

Note that this will not give you a copy of the data; it will give you a pointer to the string. Thus, if you modify an element of chr, you'll modify str.

Generate a range of dates using SQL

For the fun of it, here's some code that should work in SQL Server, Oracle, or MySQL:

SELECT current_timestamp - CAST(d1.digit + d2.digit + d3.digit as int)
FROM 
(
    SELECT digit
    FROM
    (
        select '1' as digit
        union select '2'
        union select '3'
        union select '4'
        union select '5'
        union select '6'
        union select '7'
        union select '8'
        union select '9'
        union select '0'
    ) digits
) d1
CROSS JOIN
(
    SELECT digit
    FROM
    (
        select '1' as digit
        union select '2'
        union select '3'
        union select '4'
        union select '5'
        union select '6'
        union select '7'
        union select '8'
        union select '9'
        union select '0'
    ) digits
) d2
CROSS JOIN
(
    SELECT digit
    FROM
    (
        select '1' as digit
        union select '2'
        union select '3'
        union select '4'
        union select '5'
        union select '6'
        union select '7'
        union select '8'
        union select '9'
        union select '0'
    ) digits
) d3
WHERE CAST(d1.digit + d2.digit + d3.digit as int) < 365
ORDER BY d1.digit, d2.digit, d3.digit -- order not really needed here

Bonus points if you can give me a cross-platform syntax to re-use the digits table.

super() in Java

I have seen all the answers. But everyone forgot to mention one very important point:

super() should be called or used in the first line of the constructor.

Is it possible to disable the network in iOS Simulator?

Since Xcode does not provide such feature, you will definitely go for some third party application/ tool. Turning off the MAC network will also help to turn off the iOS Simulator network.

You can turn off you MAC internet from "System Preferences..." > "Network" and turn off the desire network source.

To turnoff you MAC Ethernet internet source: EtherNet Network Source

To turnoff you MAC WiFi internet source(if your MAC is on Wifi Internet): enter image description here

C# Convert a Base64 -> byte[]

You have to use Convert.FromBase64String to turn a Base64 encoded string into a byte[].

node.js - how to write an array to file

To do what you want, using the fs.createWriteStream(path[, options]) function in a ES6 way:

const fs = require('fs');
const writeStream = fs.createWriteStream('file.txt');
const pathName = writeStream.path;
 
let array = ['1','2','3','4','5','6','7'];
  
// write each value of the array on the file breaking line
array.forEach(value => writeStream.write(`${value}\n`));

// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
   console.log(`wrote all the array data to file ${pathName}`);
});

// handle the errors on the write process
writeStream.on('error', (err) => {
    console.error(`There is an error writing the file ${pathName} => ${err}`)
});

// close the stream
writeStream.end();

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

wkhtmltopdf: cannot connect to X server

  1. Download file from this link
  2. Extract it and move executable file(/wkhtmltox/bin/wkhtmltopdf) to /usr/bin/
  3. Rename it to wkhtmltopdf if current name is not wkhtmltopdf. So that now you have an executable at /usr/bin/wkhtmltopdf
  4. Set permissions: sudo chmod a+x /usr/bin/wkhtmltopdf
  5. Install required support packages. sudo apt-get install openssl build-essential xorg libssl-dev
  6. Now, check with wkhtmltopdf http://www.google.com test.pdf hint: detail information from this link

Vue v-on:click does not work on component

As mentioned by Chris Fritz (Vue.js Core Team Emeriti) in VueCONF US 2019

if we had Kia enter .native and then the root element of the base input changed from an input to a label suddenly this component is broken and it's not obvious and in fact, you might not even catch it right away unless you have a really good test. Instead by avoiding the use of the .native modifier which I currently consider an anti-pattern will be removed in Vue 3 you'll be able to explicitly define that the parent might care about which element listeners are added to...

With Vue 2

Using $listeners:

So, if you are using Vue 2 a better option to resolve this issue would be to use a fully transparent wrapper logic. For this Vue provides a $listeners property containing an object of listeners being used on the component. For example:

{
  focus: function (event) { /* ... */ }
  input: function (value) { /* ... */ },
}

and then we just need to add v-on="$listeners" to the test component like:

Test.vue (child component)

<template>
  <div v-on="$listeners">
    click here
  </div>
</template>

Now the <test> component is a fully transparent wrapper, meaning it can be used exactly like a normal <div> element: all the listeners will work, without the .native modifier.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" v-on="$listeners">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using $emit method:

We can also use $emit method for this purpose, which helps us to listen to child components events in parent component. For this, we first need to emit a custom event from child component like:

Test.vue (child component)

<test @click="$emit('my-event')"></test>

Important: Always use kebab-case for event names. For more information and demo regading this point please check out this answer: VueJS passing computed value from component to parent.

Now, we just need to listen to this emitted custom event in parent component like:

App.vue

<test @my-event="testFunction"></test>

So, basically instead of v-on:click or the shorthand @click we will simply use v-on:my-event or just @my-event.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" @click="$emit('my-event')">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @my-event="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_


With Vue 3

Using v-bind="$attrs":

Vue 3 is going to make our life much easier in many ways. One of the examples for it is that it will help us to create a simpler transparent wrapper with very less config by just using v-bind="$attrs". By using this on child components not only our listener will work directly from the parent but also any other attribute will also work just like it a normal <div> only.

So, with respect to this question, we will not need to update anything in Vue 3 and your code will still work fine as <div> is the root element here and it will automatically listen to all child events.

Demo #1:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const Test = {_x000D_
  template: `_x000D_
    <div class="child">_x000D_
      Click here_x000D_
    </div>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { Test },_x000D_
  setup() {_x000D_
    const testFunction = event => {_x000D_
      console.log("test clicked");_x000D_
    };_x000D_
    return { testFunction };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <test v-on:click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But for complex components with nested elements where we need to apply attributes and events to main <input /> instead of the parent label we can simply use v-bind="$attrs"

Demo #2:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const BaseInput = {_x000D_
  props: ['label', 'value'],_x000D_
  template: `_x000D_
    <label>_x000D_
      {{ label }}_x000D_
      <input v-bind="$attrs">_x000D_
    </label>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { BaseInput },_x000D_
  setup() {_x000D_
    const search = event => {_x000D_
      console.clear();_x000D_
      console.log("Searching...", event.target.value);_x000D_
    };_x000D_
    return { search };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
input{padding:8px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <base-input _x000D_
    label="Search: "_x000D_
    placeholder="Search"_x000D_
    @keyup="search">_x000D_
  </base-input><br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

get jquery `$(this)` id

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

What is Python Whitespace and how does it work?

It acts as curly bracket. We have to keep the number of white spaces consistent through out the program.

Example 1:

def main():
     print "we are in main function"
     print "print 2nd line"

main()

Result:

We are in main function
print 2nd line

Example 2:

def main():
    print "we are in main function"
print "print 2nd line"

main()

Result:

print 2nd line
We are in main function

Here, in the 1st program, both the statement comes under the main function since both have equal number of white spaces while in the 2nd program, the 1st line is printed later because the main function is called after the 2nd line Note - The 2nd line has no white space, so it is independent of the main function.

How to get a .csv file into R?

You need read.csv("C:/somedirectory/some/file.csv") and in general it doesn't hurt to actually look at the help page including its example section at the bottom.

How can I get a random number in Kotlin?

My suggestion would be an extension function on IntRange to create randoms like this: (0..10).random()

TL;DR Kotlin >= 1.3, one Random for all platforms

As of 1.3, Kotlin comes with its own multi-platform Random generator. It is described in this KEEP. The extension described below is now part of the Kotlin standard library, simply use it like this:

val rnds = (0..10).random() // generated random from 0 to 10 included

Kotlin < 1.3

Before 1.3, on the JVM we use Random or even ThreadLocalRandom if we're on JDK > 1.6.

fun IntRange.random() = 
       Random().nextInt((endInclusive + 1) - start) + start

Used like this:

// will return an `Int` between 0 and 10 (incl.)
(0..10).random()

If you wanted the function only to return 1, 2, ..., 9 (10 not included), use a range constructed with until:

(0 until 10).random()

If you're working with JDK > 1.6, use ThreadLocalRandom.current() instead of Random().

KotlinJs and other variations

For kotlinjs and other use cases which don't allow the usage of java.util.Random, see this alternative.

Also, see this answer for variations of my suggestion. It also includes an extension function for random Chars.

Origin null is not allowed by Access-Control-Allow-Origin

Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like

Origin null is not allowed by Access-Control-Allow-Origin.

Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;

--allow-file-access-from-files

More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;

C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files

Hope this will help!

Check if current directory is a Git repository

Use git rev-parse --git-dir

if git rev-parse --git-dir > /dev/null 2>&1; then
  : # This is a valid git repository (but the current working
    # directory may not be the top level.
    # Check the output of the git rev-parse command if you care)
else
  : # this is not a git repository
fi

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

Breaking out of a nested loop

Don't quote me on this, but you could use goto as suggested in the MSDN. There are other solutions, as including a flag that is checked in each iteration of both loops. Finally you could use an exception as a really heavyweight solution to your problem.

GOTO:

for ( int i = 0; i < 10; ++i ) {
   for ( int j = 0; j < 10; ++j ) {
      // code
      if ( break_condition ) goto End;
      // more code
   }
}
End: ;

Condition:

bool exit = false;
for ( int i = 0; i < 10 && !exit; ++i ) {
   for ( int j = 0; j < 10 && !exit; ++j ) {
      // code
      if ( break_condition ) {
         exit = true;
         break; // or continue
      }
      // more code
   }
}

Exception:

try {
    for ( int i = 0; i < 10 && !exit; ++i ) {
       for ( int j = 0; j < 10 && !exit; ++j ) {
          // code
          if ( break_condition ) {
             throw new Exception()
          }
          // more code
       }
    }
catch ( Exception e ) {}

Converting from hex to string

string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');

foreach (string val in parts)
{ 
    int x;
    if (int.TryParse(val, out x))
    {
         Console.Write(string.Format("{0:x2} ", x);
    }
}
Console.WriteLine();

You can split the string at the -
Convert the text to ints (int.TryParse)
Output the int as a hex string {0:x2}

URL encoding the space character: + or %20?

I would recommend %20.

Are you hard-coding them?

This is not very consistent across languages, though. If I'm not mistaken, in PHP urlencode() treats spaces as + whereas Python's urlencode() treats them as %20.

EDIT:

It seems I'm mistaken. Python's urlencode() (at least in 2.7.2) uses quote_plus() instead of quote() and thus encodes spaces as "+". It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.

EDIT #2:

I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:

import urllib
print(urllib.urlencode({' ' : '+ '})

>>> '+=%2B+'

Get img thumbnails from Vimeo?

The easiest JavaScript way that I found to get the thumbnail, without searching for the video id is using:

//Get the video thumbnail via Ajax
$.ajax({
    type:'GET',
    url: 'https://vimeo.com/api/oembed.json?url=' + encodeURIComponent(url),
    dataType: 'json',
    success: function(data) {
        console.log(data.thumbnail_url);
    }
});

Note: If someone need to get the video thumbnail related to the video id he can replace the $id with the video id and get an XML with the video details:

http://vimeo.com/api/v2/video/$id.xml

Example:

http://vimeo.com/api/v2/video/198340486.xml

Source

Why is the Java main method static?

If the main method would not be static, you would need to create an object of your main class from outside the program. How would you want to do that?

Trying to handle "back" navigation button action in iOS

Try this code using VIewWillDisappear method to detect the press of The back button of NavigationItem:

-(void) viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) 
    {
        // Navigation button was pressed. Do some stuff 
        [self.navigationController popViewControllerAnimated:NO];
    }
    [super viewWillDisappear:animated];
}

OR There is another way to get Action of the Navigation BAck button.

Create Custom button for UINavigationItem of back button .

For Ex:

In ViewDidLoad :

- (void)viewDidLoad 
{
    [super viewDidLoad];
    UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(home:)];
    self.navigationItem.leftBarButtonItem=newBackButton;
}

-(void)home:(UIBarButtonItem *)sender 
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

Swift :

override func willMoveToParentViewController(parent: UIViewController?) 
{
    if parent == nil 
    {
        // Back btn Event handler
    }
}

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

python pandas extract year from datetime: df['year'] = df['date'].year is not working

What worked for me was upgrading pandas to latest version:

From Command Line do:

conda update pandas

Oracle date function for the previous month

Getting last nth months data retrieve

SELECT * FROM TABLE_NAME 
WHERE DATE_COLUMN BETWEEN '&STARTDATE' AND '&ENDDATE'; 

How to remove text from a string?

_x000D_
_x000D_
var ret = "data-123".replace('data-','');_x000D_
console.log(ret);   //prints: 123
_x000D_
_x000D_
_x000D_

Docs.


For all occurrences to be discarded use:

var ret = "data-123".replace(/data-/g,'');

PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call.

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

Is there a better way to refresh WebView?

The best solution is to just do webView.loadUrl( "javascript:window.location.reload( true )" );. This should work on all versions and doesn't introduce new history entries.

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

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

This should pull the most recent version, and allow it to compile.

How to add a line break within echo in PHP?

You have to use br when using echo , like this :

echo "Thanks for your email" ."<br>". "Your orders details are below:"

and it will work properly

Render basic HTML view?

Try res.sendFile() function in Express routes.

var express = require("express");
var app     = express();
var path    = require("path");


app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

app.get('/about',function(req,res){
  res.sendFile(path.join(__dirname+'/about.html'));
});

app.get('/sitemap',function(req,res){
  res.sendFile(path.join(__dirname+'/sitemap.html'));
});

app.listen(3000);

console.log("Running at Port 3000");

Read here : http://codeforgeek.com/2015/01/render-html-file-expressjs/

How to send HTTP request in java?

Google java http client has nice API for http requests. You can easily add JSON support etc. Although for simple request it might be overkill.

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.io.InputStream;

public class Network {

    static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    public void getRequest(String reqUrl) throws IOException {
        GenericUrl url = new GenericUrl(reqUrl);
        HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

        InputStream is = response.getContent();
        int ch;
        while ((ch = is.read()) != -1) {
            System.out.print((char) ch);
        }
        response.disconnect();
    }
}

CSS text-overflow in a table cell?

It is worked for me

table {
    width: 100%;
    table-layout: fixed;
}

td {
   text-overflow: ellipsis;
   white-space: nowrap;
}

how to change color of TextinputLayout's label and edittext underline android

Based on Fedor Kazakov and others answers, I created a default config.

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Widget.Design.TextInputLayout" parent="AppTheme">
        <item name="hintTextAppearance">@style/AppTheme.TextFloatLabelAppearance</item>
        <item name="errorTextAppearance">@style/AppTheme.TextErrorAppearance</item>
        <item name="counterTextAppearance">@style/TextAppearance.Design.Counter</item>
        <item name="counterOverflowTextAppearance">@style/TextAppearance.Design.Counter.Overflow</item>
    </style>

    <style name="AppTheme.TextFloatLabelAppearance" parent="TextAppearance.Design.Hint">
        <!-- Floating label appearance here -->
        <item name="android:textColor">@color/colorAccent</item>
        <item name="android:textSize">20sp</item>
    </style>

    <style name="AppTheme.TextErrorAppearance" parent="TextAppearance.Design.Error">
        <!-- Error message appearance here -->
        <item name="android:textColor">#ff0000</item>
        <item name="android:textSize">20sp</item>
    </style>

</resources>

activity_layout.xml

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text hint here"
        android:text="5,2" />

</android.support.design.widget.TextInputLayout>

Focused:

Focused

Without focus:

Without focus

Error message:

enter image description here

MySQL Trigger: Delete From Table AFTER DELETE

create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;

How to create nested directories using Mkdir in Golang?

This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

package main

import (
    "fmt"
    "os"
)

func main()  {
    if err := ensureDir("/test-dir"); err != nil {
        fmt.Println("Directory creation failed with error: " + err.Error())
        os.Exit(1)
    }
    // Proceed forward
}

func ensureDir(dirName string) error {

    err := os.MkdirAll(dirName, os.ModeDir)

    if err == nil || os.IsExist(err) {
        return nil
    } else {
        return err
    }
}

Lightweight workflow engine for Java

Yes, in my perspective there is no reason why you should write your own. Most of the Open Source BPM/Workflow frameworks are extremely flexible, you just need to learn the basics. If you choose jBPM you will get much more than a simple workflow engine, so it depends what are you trying to build.

Cheers

Iterating through a golang map

You can make it by one line:

mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
    fmt.Println("k:", k, "v:", v)
}

Output is:

k: foo v: map[first:1]
k: boo v: map[second:2]

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

Use this to get your current time in specified format :

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 System.out.print(dateFormat.format(System.currentTimeMillis()));  }

Standard deviation of a list

In Python 2.7.1, you may calculate standard deviation using numpy.std() for:

  • Population std: Just use numpy.std() with no additional arguments besides to your data list.
  • Sample std: You need to pass ddof (i.e. Delta Degrees of Freedom) set to 1, as in the following example:

numpy.std(< your-list >, ddof=1)

The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

It calculates sample std rather than population std.

iframe to Only Show a Certain Part of the Page

I got this work good for me.

<div style="border: 3px solid rgb(201, 0, 1); overflow: hidden; margin: 15px auto; max-width: 736px;">
<iframe scrolling="no" src="http://www.w3schools.com/css/default.asp" style="border: 0px none; margin-left: -185px; height: 859px; margin-top: -533px; width: 926px;">
</iframe>
</div>

Is this working for you or not let us know.

Source: http://www.dimpost.com/2012/12/iframe-how-to-display-specific-part-of.html

How to serve an image using nodejs

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

I was getting the same error when I used this code to update the record:

@mysqli_query($dbc,$query or die()))

After removing or die, it started working properly.

Request string without GET arguments

I had the same problem when I wanted a link back to homepage. I tried this and it worked:

<a href="<?php echo $_SESSION['PHP_SELF']; ?>?">

Note the question mark at the end. I believe that tells the machine stop thinking on behalf of the coder :)

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

Differences between C++ string == and compare()?

compare has overloads for comparing substrings. If you're comparing whole strings you should just use == operator (and whether it calls compare or not is pretty much irrelevant).

Looping through GridView rows and Checking Checkbox Control

you have to iterate gridview Rows

for (int count = 0; count < grd.Rows.Count; count++)
{
    if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
    {     
      ((Label)grd.Rows[count].FindControl("labelID")).Text
    }
}

get UTC time in PHP

$time = time();
$check = $time+date("Z",$time);
echo strftime("%B %d, %Y @ %H:%M:%S UTC", $check);

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I had to allow ..\python27\python.exe in windows firewall. I don't need to do this on WinXP or Win8.

How to call an action after click() in Jquery?

If I've understood your question correctly, then you are looking for the mouseup event, rather than the click event:

$("#message_link").mouseup(function() {
    //Do stuff here
});

The mouseup event fires when the mouse button is released, and does not take into account whether the mouse button was pressed on that element, whereas click takes into account both mousedown and mouseup.

However, click should work fine, because it won't actually fire until the mouse button is released.

Calculating the difference between two Java date instances

You need to define your problem more clearly. You could just take the number of milliseconds between the two Date objects and divide by the number of milliseconds in 24 hours, for example... but:

  • This won't take time zones into consideration - Date is always in UTC
  • This won't take daylight saving time into consideration (where there can be days which are only 23 hours long, for example)
  • Even within UTC, how many days are there in August 16th 11pm to August 18th 2am? It's only 27 hours, so does that mean one day? Or should it be three days because it covers three dates?

Has an event handler already been added?

The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.

bool alreadyAdded = false;

This variable can be global.

if(!alreadyAdded)
{
    myClass.MyEvent += MyHandler;
    alreadyAdded = true;
}

How can I iterate through a string and also know the index (current position)?

Since std::distance is only constant time for random-access iterators, I would probably prefer explicit iterator arithmetic. Also, since we're writing C++ code here, I do believe a more C++ idiomatic solution is preferable over a C-style approach.

string str{"Test string"};
auto begin = str.begin();

for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
    cout << it - begin << *it;
}

Does Python have “private” variables in classes?

Python does not have any private variables like C++ or Java does. You could access any member variable at any time if wanted, too. However, you don't need private variables in Python, because in Python it is not bad to expose your classes member variables. If you have the need to encapsulate a member variable, you can do this by using "@property" later on without breaking existing client code.

In python the single underscore "_" is used to indicate, that a method or variable is not considered as part of the public api of a class and that this part of the api could change between different versions. You can use these methods/variables, but your code could break, if you use a newer version of this class.

The double underscore "__" does not mean a "private variable". You use it to define variables which are "class local" and which can not be easily overidden by subclasses. It mangles the variables name.

For example:

class A(object):
    def __init__(self):
        self.__foobar = None # will be automatically mangled to self._A__foobar

class B(A):
    def __init__(self):
        self.__foobar = 1 # will be automatically mangled to self._B__foobar

self.__foobar's name is automatically mangled to self._A__foobar in class A. In class B it is mangled to self._B__foobar. So every subclass can define its own variable __foobar without overriding its parents variable(s). But nothing prevents you from accessing variables beginning with double underscores. However, name-mangling prevents you from calling this variables /methods incidentally.

I strongly recommend to watch Raymond Hettingers talk "Pythons class development toolkit" from Pycon 2013 (should be available on Youtube), which gives a good example why and how you should use @property and "__"-instance variables.

If you have exposed public variables and you have the need to encapsulate them, then you can use @property. Therefore you can start with the simplest solution possible. You can leave member variables public unless you have a concrete reason to not do so. Here is an example:

class Distance:
    def __init__(self, meter):
        self.meter = meter


d = Distance(1.0)
print(d.meter)
# prints 1.0

class Distance:
    def __init__(self, meter):
        # Customer request: Distances must be stored in millimeters.
        # Public available internals must be changed.
        # This would break client code in C++.
        # This is why you never expose public variables in C++ or Java.
        # However, this is python.
        self.millimeter = meter * 1000

    # In python we have @property to the rescue.
    @property
    def meter(self):
        return self.millimeter *0.001

    @meter.setter
    def meter(self, value):
        self.millimeter = meter * 1000

d = Distance(1.0)
print(d.meter)
# prints 1.0

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

"Correct" way to specifiy optional arguments in R functions

I would tend to prefer using NULL for the clarity of what is required and what is optional. One word of warning about using default values that depend on other arguments, as suggested by Jthorpe. The value is not set when the function is called, but when the argument is first referenced! For instance:

foo <- function(x,y=length(x)){
    x <- x[1:10]
    print(y)
}
foo(1:20) 
#[1] 10

On the other hand, if you reference y before changing x:

foo <- function(x,y=length(x)){
    print(y)
    x <- x[1:10]
}
foo(1:20) 
#[1] 20

This is a bit dangerous, because it makes it hard to keep track of what "y" is being initialized as if it's not called early on in the function.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

Could not open input file: artisan

Most probably you are not in the right directory!

How to get current timestamp in milliseconds since 1970 just the way Java gets

Since C++11 you can use std::chrono:

  • get current system time: std::chrono::system_clock::now()
  • get time since epoch: .time_since_epoch()
  • translate the underlying unit to milliseconds: duration_cast<milliseconds>(d)
  • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
#include <chrono>
#include <cstdint>
#include <iostream>

uint64_t timeSinceEpochMillisec() {
  using namespace std::chrono;
  return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}

int main() {
  std::cout << timeSinceEpochMillisec() << std::endl;
  return 0;
}

Safely casting long to int in Java

I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception x and y, but not when they mean row and column (sometimes respectively)).

public static int intValue(long value) {
    int valueInt = (int)value;
    if (valueInt != value) {
        throw new IllegalArgumentException(
            "The long value "+value+" is not within range of the int type"
        );
    }
    return valueInt;
}

However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases IllegalArgumentException is almost certainly the wrong exception to be throwing as far as client code is concerned.

PHP regular expression - filter number only

Another way to get only the numbers in a regex string is as shown below:

$output = preg_replace("/\D+/", "", $input);

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

MySQL Select all columns from one table and some from another table

select a.* , b.Aa , b.Ab, b.Ac from table1 a left join table2 b on a.id=b.id

this should select all columns from table 1 and only the listed columns from table 2 joined by id.

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

Use Ant for running program with command line arguments

Can you be a bit more specific about what you're trying to do and how you're trying to do it?

If you're attempting to invoke the program using the <exec> task you might do the following:

<exec executable="name-of-executable">
  <arg value="arg0"/>
  <arg value="arg1"/>
</exec>

How to suppress "unused parameter" warnings in C?

A gcc/g++ specific way to suppress the unused parameter warning for a block of source code is to enclose it with the following pragma statements:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
<code with unused parameters here>
#pragma GCC diagnostic pop

How do I perform a JAVA callback between classes?

I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.

first define a generic callback:

public interface ITypedCallback<T> {
    void execute(T type);
}

create a new ITypedCallback instance on ServerConnections instantiation:

public Server(int _address) {
    serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
        @Override
        public void execute(Socket socket) {
            // do something with your socket here
        }
    });
}

call the execute methode on the callback object.

public class ServerConnections implements Runnable {

    private ITypedCallback<Socket> callback;

    public ServerConnections(ITypedCallback<Socket> _callback) {
        callback = _callback;
    }

    @Override
    public void run() {   
        try {
            mainSocket = new ServerSocket(serverPort);
            while (true) {
                callback.execute(mainSocket.accept());
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

btw: I didn't check if it's 100% correct, directly coded it here.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Iterating over every two elements in a list

Here we can have alt_elem method which can fit in your for loop.

def alt_elem(list, index=2):
    for i, elem in enumerate(list, start=1):
        if not i % index:
           yield tuple(list[i-index:i])


a = range(10)
for index in [2, 3, 4]:
    print("With index: {0}".format(index))
    for i in alt_elem(a, index):
       print(i)

Output:

With index: 2
(0, 1)
(2, 3)
(4, 5)
(6, 7)
(8, 9)
With index: 3
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
With index: 4
(0, 1, 2, 3)
(4, 5, 6, 7)

Note: Above solution might not be efficient considering operations performed in func.

Reading RFID with Android phones

First is understanding that RFID is very generic term. NFC is subset of RFID technology. NFC is used for prox card, credit cards, tap and go payment system. Your phones can read and emulate NFC (Apple pay, Google pay, etc.), if they support NFC. NFC is very short distance and low power - which is why you see tap and go type usage.

The more common RFID are the tags you see here and there. They come in a wide ranges of styles, uses and frequency.

HF - high frequency tags are what they use for "chipping" animals - cattle, dogs, cats. Read range is about 12 inches and requires an external antenna that is powered the bigger the antenna the more power it needs and the further it can read.

UFH tags look similar to HF tags but have a read range of several feet.

Also HF tags come single read and multi read. UFH is exclusviely multi read.

Mutiread means when a reader is active, you can litterally read about 1700 tags in under 10 seconds.

But this is a function of the size of the antenna and how much power you can push through the reader.

As to the direct question about Android and RFID - the best way to go is to get an external handheld reader that connects to your mobile device via Bluetooth. Bluetooth libraries exist for all mobile devices - Android, Apple, Windows. From there its just a matter of the manufacturer documentation about how to open a socket to the reader and how to decode the serial information.

The TSL line of readers is very popular because you don't have to deal with reading bytes and all that low level serial jazz that other manufactures do. They have a nice set of commands that are easy to use to control the reader.

Other manufactures are basic in that you open a serial socket and then read the output like you would see in terminal app like PuTTY.

How do I fetch only one branch of a remote Git repository?

I know there are a lot of answers already, but these are the steps that worked for me:

  1. git fetch <remote_name> <branch_name>
  2. git branch <branch_name> FETCH_HEAD
  3. git checkout <branch_name>

These are based on the answer by @Abdulsattar Mohammed, the comment by @Christoph on that answer, and these other stack overflow questions and their answers:

Multiple contexts with the same path error running web service in Eclipse using Tomcat

In your eclipse IDE on project explorer acess the server.xml like in:

enter image description here

And remove context tags with duplicates references for your project:

enter image description here

How and when to use ‘async’ and ‘await’

public static void Main(string[] args)
{
    string result = DownloadContentAsync().Result;
    Console.ReadKey();
}

// You use the async keyword to mark a method for asynchronous operations.
// The "async" modifier simply starts synchronously the current thread. 
// What it does is enable the method to be split into multiple pieces.
// The boundaries of these pieces are marked with the await keyword.
public static async Task<string> DownloadContentAsync()// By convention, the method name ends with "Async
{
    using (HttpClient client = new HttpClient())
    {
        // When you use the await keyword, the compiler generates the code that checks if the asynchronous operation is finished.
        // If it is already finished, the method continues to run synchronously.
        // If not completed, the state machine will connect a continuation method that must be executed WHEN the Task is completed.


        // Http request example. 
        // (In this example I can set the milliseconds after "sleep=")
        String result = await client.GetStringAsync("http://httpstat.us/200?sleep=1000");

        Console.WriteLine(result);

        // After completing the result response, the state machine will continue to synchronously execute the other processes.


        return result;
    }
}

What is the default value for enum variable?

I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.

enum E
{
    Foo = 0, Bar, Baz, Quux
}

Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.

Spring Boot yaml configuration for a list of strings

@Value("#{'${your.elements}'.split(',')}")  
private Set<String> stringSet;

yml file:

your:
 elements: element1, element2, element3

There is lot more you can play with spring spEL.

Return row of Data Frame based on value in a column - R

Based on the syntax provided

 Select * Where Amount = min(Amount)

You could do using:

 library(sqldf)

Using @Kara Woo's example df

  sqldf("select * from df where Amount in (select min(Amount) from df)")
  #Name Amount
 #1    B    120
 #2    E    120

What is the simplest and most robust way to get the user's current location on Android?

public static Location getBestLocation(Context ctxt) {
    Location gpslocation = getLocationByProvider(
        LocationManager.GPS_PROVIDER, ctxt);
    Location networkLocation = getLocationByProvider(
        LocationManager.NETWORK_PROVIDER, ctxt);
    Location fetchedlocation = null;
    // if we have only one location available, the choice is easy
    if (gpslocation != null) {
        Log.i("New Location Receiver", "GPS Location available.");
        fetchedlocation = gpslocation;
    } else {
        Log.i("New Location Receiver",
            "No GPS Location available. Fetching Network location lat="
                + networkLocation.getLatitude() + " lon ="
                + networkLocation.getLongitude());
        fetchedlocation = networkLocation;
    }
    return fetchedlocation;
}

/**
 * get the last known location from a specific provider (network/gps)
 */
private static Location getLocationByProvider(String provider, Context ctxt) {
    Location location = null;
    // if (!isProviderSupported(provider)) {
    // return null;
    // }
    LocationManager locationManager = (LocationManager) ctxt
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.i("New Location Receiver", "Cannot access Provider " + provider);
    }
    return location;
}

Setting environment variables for accessing in PHP when using Apache

You can also do this in a .htaccess file assuming they are enabled on the website.

SetEnv KOHANA_ENV production

Would be all you need to add to a .htaccess to add the environment variable

Difference between clustered and nonclustered index

You should be using indexes to help SQL server performance. Usually that implies that columns that are used to find rows in a table are indexed.

Clustered indexes makes SQL server order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.

Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.

Most column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns (e.g. country + city + street).

Also you will not notice performance issues until you have quite a bit of data in your tables. And another thing to think about is that SQL server needs statistics to do its query optimizations the right way, so make sure that you do generate that.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

The method in the post you link to calls Invoke/BeginInvoke before checking if the control's handle has been created in the case where it's being called from a thread that didn't create the control.

So you'll get the exception when your method is called from a thread other than the one that created the control. This can happen from remoting events or queued work user items...

EDIT

If you check InvokeRequired and HandleCreated before calling invoke you shouldn't get that exception.

How to return history of validation loss in Keras

For plotting the loss directly the following works:

model_ = model.fit(X, Y, epochs= ..., verbose=1 )
plt.plot(list(model_.history.values())[0],'k-o')

How can I make my website's background transparent without making the content (images & text) transparent too?

I think what's happening, is that, since the wrapper id is relatively position, it just appears on the same position with the body tag, what you should do, is that you can add a Z-index to the wrapper id.

#wrapper {
margin: auto;
text-align: left;
width: 832px;
position: relative;
padding-top: 27px;
z-index: 99; /* added this line */
 }

This should make layers above the transparent body tag.

How to get the PYTHONPATH in shell?

You can also try this:

Python 2.x:
python -c "import sys; print '\n'.join(sys.path)"

Python 3.x:
python3 -c "import sys; print('\n'.join(sys.path))"

The output will be more readable and clean, like so:

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload /Library/Python/2.7/site-packages /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC

How to make a phone call programmatically?

Take a look there : http://developer.android.com/guide/topics/intents/intents-filters.html

DO you have update your manifest file in order to give call rights ?

Echo tab characters in bash script

Use printf, not echo.

There are multiple different versions of the echo command. There's /bin/echo (which may or may not be the GNU Coreutils version, depending on the system), and the echo command is built into most shells. Different versions have different ways (or no way) to specify or disable escapes for control characters.

printf, on the other hand, has much less variation. It can exist as a command, typically /bin/printf, and it's built into some shells (bash and zsh have it, tcsh and ksh don't), but the various versions are much more similar to each other than the different versions of echo are. And you don't have to remember command-line options (with a few exceptions; GNU Coreutils printf accepts --version and --help, and the built-in bash printf accepts -v var to store the output in a variable).

For your example:

res='           'x # res = "\t\tx"
printf '%s\n' "[$res]"

And now it's time for me to admit that echo will work just as well for the example you're asking about; you just need to put double quotes around the argument:

echo "[$res]"

as kmkaplan wrote (two and a half years ago, I just noticed!). The problem with your original commands:

res='           'x # res = "\t\tx"
echo '['$res']' # expect [\t\tx]

isn't with echo; it's that the shell replaced the tab with a space before echo ever saw it.

echo is fine for simple output, like echo hello world, but you should use printf whenever you want to do something more complex. You can get echo to work, but the resulting code is likely to fail when you run it with a different echo implementation or a different shell.

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

Is there an Eclipse plugin to run system shell in the Console?

Aptana Studio 3 includes such terminal. I found it to be very similar to native terminal compared to what's mentioned in other answers.

Object cannot be cast from DBNull to other types

I faced this problem today and resolved it by checking the mapping class. I had a class which had 5 properties to which 5 columns returned from stored procedure were being mapped. Those properties were non-nullable and due to which i was getting the error. I made them nullable and the issue resolved.

    public int? Pause { get; set; }
    public int? Delay { get; set; }
    public int? Transition { get; set; }
    public int? TransitionTime { get; set; }
    public int? TransitionResolution { get; set; }

Added "?" with data type to made them nullable.

Secondly i also added isNull check in the stored procedure as well as follows:

    isnull(co_pivot.Pause, 0) as Pause,
    isnull(co_pivot.Delay, 0) as Delay,
    isnull(co_pivot.Transition, 0) as Transition,
    isnull(co_pivot.TransitionTime, 0) as TransitionTime,
    isnull(co_pivot.TransitionResolution, 0) as TransitionResolution

Hope this helps someone.

jquery smooth scroll to an anchor?

Best solution I have seen so far: jQuery: Smooth Scrolling Internal Anchor Links

HTML:

<a href="#comments" class="scroll">Scroll to comments</a>

Script:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

Capture keyboardinterrupt in Python without try-except

I know this is an old question but I came here first and then discovered the atexit module. I do not know about its cross-platform track record or a full list of caveats yet, but so far it is exactly what I was looking for in trying to handle post-KeyboardInterrupt cleanup on Linux. Just wanted to throw in another way of approaching the problem.

I want to do post-exit clean-up in the context of Fabric operations, so wrapping everything in try/except wasn't an option for me either. I feel like atexit may be a good fit in such a situation, where your code is not at the top level of control flow.

atexit is very capable and readable out of the box, for example:

import atexit

def goodbye():
    print "You are now leaving the Python sector."

atexit.register(goodbye)

You can also use it as a decorator (as of 2.6; this example is from the docs):

import atexit

@atexit.register
def goodbye():
    print "You are now leaving the Python sector."

If you wanted to make it specific to KeyboardInterrupt only, another person's answer to this question is probably better.

But note that the atexit module is only ~70 lines of code and it would not be hard to create a similar version that treats exceptions differently, for example passing the exceptions as arguments to the callback functions. (The limitation of atexit that would warrant a modified version: currently I can't conceive of a way for the exit-callback-functions to know about the exceptions; the atexit handler catches the exception, calls your callback(s), then re-raises that exception. But you could do this differently.)

For more info see:

Throwing exceptions from constructors

If you do throw an exception from a constructor, keep in mind that you need to use the function try/catch syntax if you need to catch that exception in a constructor initializer list.

e.g.

func::func() : foo()
{
    try {...}
    catch (...) // will NOT catch exceptions thrown from foo constructor
    { ... }
}

vs.

func::func()
    try : foo() {...}
    catch (...) // will catch exceptions thrown from foo constructor
    { ... }

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I solved the problem by creating a symbolic link to the library. I.e.

The actual library resides in

/usr/local/mysql/lib

And then I created a symbolic link in

/usr/lib

Using the command:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

so that I have the following mapping:

ls -l libmysqlclient.18.dylib 
lrwxr-xr-x  1 root  wheel  44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib

That was it. After that everything worked fine.

EDIT:

Notice, that since MacOS El Capitan the System Integrity Protection (SIP, also known as "rootless") will prevent you from creating links in /usr/lib/. You could disable SIP by following these instructions, but you can create a link in /usr/local/lib/ instead:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

jquery AJAX and json format

$.ajax({
   type: "POST",
   url: hb_base_url + "consumer",
   contentType: "application/json",
   dataType: "json",
   data: {
       data__value = JSON.stringify(
       {
           first_name: $("#namec").val(),
           last_name: $("#surnamec").val(),
           email: $("#emailc").val(),
           mobile: $("#numberc").val(),
           password: $("#passwordc").val()
       })
   },
   success: function(response) {
       console.log(response);
   },
   error: function(response) {
       console.log(response);
   }
});

(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:

(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:

$test = json_decode( $_POST['data__value'] );
echo $test->first_name;

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

Getting windbg without the whole WDK?

The saga continues with the Windows 10 version. I had to install Win Debug Tools on clean Windows 10 OS with Visual Studio 2015.

To make a long story short, just follow the instructions in the link provided by David Black. After downloading the files, instead of running the SDK installer, browse to the installers directory and execute the msi files directly.

I wonder how many man hours have been lost through the last decade because of MS sloppiness in regards to WDK/SDK installation?

Five equal columns in twitter bootstrap

Bootstrap by default can scale up to 12 columns? This means if we want to create a 12-column layout of equal width, we would write inside div class="col-md-1" twelve times.

<div class="row">
<div class="col-md-1"></div>    
<div class="col-md-2">1</div>
<div class="col-md-2">2</div>
<div class="col-md-2">3</div>
<div class="col-md-2">4</div>
<div class="col-md-2">5</div>
<div class="col-md-1"></div>
</div>

Can I make a phone call from HTML on Android?

Generally on Android, if you simply display the phone number, and the user taps on it, it will pull it up in the dialer. So, you could simply do

For more information, call us at <b>416-555-1234</b>

When the user taps on the bold part, since it's formatted like a phone number, the dialer will pop up, and show 4165551234 in the phone number field. The user then just has to hit the call button.

You might be able to do

For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a>

to cover both devices, but I'm not sure how well this would work. I'll give it a try shortly and let you know.

EDIT: I just gave this a try on my HTC Magic running a rooted Rogers 1.5 with SenseUI:

For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a><br />
<br />
Call at <a href='tel:416-555-1234'>our number</a>
<br />
<br />
<a href='416-555-1234'>Blah</a>
<br />
<br />
For more info, call <b>416-555-1234</b>

The first one, surrounding with the link and printing the phone number, worked perfectly. Pulled up the dialer with the hyphens and all. The second, saying our number with the link, worked exactly the same. This means that using <a href='tel:xxx-xxx-xxxx'> should work across the board, but I wouldn't suggest taking my one test as conclusive.

Linking straight to the number did the expected: Tried to pull up the nonexistent file from the server.

The last one did as I mentioned above, and pulled up the dialer, but without the nice formatting hyphens.

Case-insensitive search

I like @CHR15TO's answer, unlike other answers I've seen on other similar questions, that answer actually shows how to properly escape a user provided search string (rather than saying it would be necessary without showing how).

However, it's still quite clunky, and possibly relatively slower. So why not have a specific solution to what is likely a common requirement for coders? (And why not include it in the ES6 API BTW?)

My answer [https://stackoverflow.com/a/38290557/887092] on a similar question enables the following:

var haystack = 'A. BAIL. Of. Hay.';
var needle = 'bail.';
var index = haystack.naturalIndexOf(needle);

can't load package: package .: no buildable Go source files

If you want all packages in that repository, use ... to signify that, like:

go get code.google.com/p/go.text/...

select and echo a single field from mysql db using PHP

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

How to launch PowerShell (not a script) from the command line

Set the default console colors and fonts:

http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)

Set-StrictMode -Version Latest

Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'

New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location

Android: How to create a Dialog without a title?

You can hide the title of a dialog using:

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);


Previous version of this answer, which is overcomplicated:

You need to use an AlertDialog. There's a good explanation on the Android Developer's site about custom dialogs.

In very short summary, you do this with code like copied below from the official website. That takes a custom layot file, inflates it, gives it some basic text and icon, then creates it. You'd show it then with alertDialog.show().

AlertDialog.Builder builder;
AlertDialog alertDialog;

Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)
        mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
        (ViewGroup) findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();

In response to comment:

I assume that TextView with the id nr is in the View you are inflating with View view = inflater..... If so, then you need to change just one bit: instead of dialog.findView... make it view.findView.... Then once you've done that, remember to use dialog.show(), or even builder.show() without bothering to do builder.create().

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Angular 4 setting selected option in Dropdown

If you want to select a value as default, in your form builder give it a value :

this.myForm = this.FB.group({
    mySelect: [this.options[0].key, [/* Validators here */]]
});

Now in your HTML :

<form [formGroup]="myForm">
    <select [formControlName]="mySelect">
        <option *ngFor="let opt of options" [value]="opt.key">ANY TEXT YOU WANT HERE</option>
    </select>
</form>

What my code does is giving your select a value, that is equal to the first value of your options list. This is how you select an option as default in Angular, selected is useless.

Mac install and open mysql using terminal

For mac OS Catalina :

/usr/local/mysql/bin/mysql -uroot -p

This will prompt you to enter password of mysql

Moment.js - how do I get the number of years since a date, not rounded up?

I prefer this small method.

function getAgeFromBirthday(birthday) {
    if(birthday){
      var totalMonths = moment().diff(birthday, 'months');
      var years = parseInt(totalMonths / 12);
      var months = totalMonths % 12;
        if(months !== 0){
           return parseFloat(years + '.' + months);
         }
    return years;
      }
    return null;
}

DOUBLE vs DECIMAL in MySQL

"are there any issue we should expect from only storing and retreiving a money amount in a DOUBLE column ?"

It sounds like no rounding errors can be produced in your scenario and if there were, they would be truncated by the conversion to BigDecimal.

So I would say no.

However, there is no guarantee that some change in the future will not introduce a problem.

Remove lines that contain certain string

Today I needed to accomplish a similar task so I wrote up a gist to accomplish the task based on some research I did. I hope that someone will find this useful!

import os

os.system('cls' if os.name == 'nt' else 'clear')

oldfile = raw_input('{*} Enter the file (with extension) you would like to strip domains from: ')
newfile = raw_input('{*} Enter the name of the file (with extension) you would like me to save: ')

emailDomains = ['windstream.net', 'mail.com', 'google.com', 'web.de', 'email', 'yandex.ru', 'ymail', 'mail.eu', 'mail.bg', 'comcast.net', 'yahoo', 'Yahoo', 'gmail', 'Gmail', 'GMAIL', 'hotmail', 'comcast', 'bellsouth.net', 'verizon.net', 'att.net', 'roadrunner.com', 'charter.net', 'mail.ru', '@live', 'icloud', '@aol', 'facebook', 'outlook', 'myspace', 'rocketmail']

print "\n[*] This script will remove records that contain the following strings: \n\n", emailDomains

raw_input("\n[!] Press any key to start...\n")

linecounter = 0

with open(oldfile) as oFile, open(newfile, 'w') as nFile:
    for line in oFile:
        if not any(domain in line for domain in emailDomains):
            nFile.write(line)
            linecounter = linecounter + 1
            print '[*] - {%s} Writing verified record to %s ---{ %s' % (linecounter, newfile, line)

print '[*] === COMPLETE === [*]'
print '[*] %s was saved' % newfile
print '[*] There are %s records in your saved file.' % linecounter

Link to Gist: emailStripper.py

Best, Az

Mask for an Input to allow phone numbers?

<input type="text" formControlName="gsm" (input)="formatGsm($event.target.value)">

formatGsm(inputValue: String): String {
  const value = inputValue.replace(/[^0-9]/g, ''); // remove except digits
  let format = '(***) *** ** **'; // You can change format

  for (let i = 0; i < value.length; i++) {
    format = format.replace('*', value.charAt(i));
  }

  if (format.indexOf('*') >= 0) {
    format = format.substring(0, format.indexOf('*'));
  }

  return format.trim();
}

What is the use of GO in SQL Server Management Studio & Transact SQL?

Since Management Studio 2005 it seems that you can use GO with an int parameter, like:

INSERT INTO mytable DEFAULT VALUES
GO 10

The above will insert 10 rows into mytable. Generally speaking, GO will execute the related sql commands n times.

How can I truncate a double to only two decimal places in Java?

I have a slightly modified version of Mani's.

private static BigDecimal truncateDecimal(final double x, final int numberofDecimals) {
    return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_DOWN);
}

public static void main(String[] args) {
    System.out.println(truncateDecimal(0, 2));
    System.out.println(truncateDecimal(9.62, 2));
    System.out.println(truncateDecimal(9.621, 2));
    System.out.println(truncateDecimal(9.629, 2));
    System.out.println(truncateDecimal(9.625, 2));
    System.out.println(truncateDecimal(9.999, 2));
    System.out.println(truncateDecimal(3.545555555, 2));

    System.out.println(truncateDecimal(9.0, 2));
    System.out.println(truncateDecimal(-9.62, 2));
    System.out.println(truncateDecimal(-9.621, 2));
    System.out.println(truncateDecimal(-9.629, 2));
    System.out.println(truncateDecimal(-9.625, 2));
    System.out.println(truncateDecimal(-9.999, 2));
    System.out.println(truncateDecimal(-9.0, 2));
    System.out.println(truncateDecimal(-3.545555555, 2));

}

Output:

0.00
9.62
9.62
9.62
9.62
9.99
9.00
3.54
-9.62
-9.62
-9.62
-9.62
-9.99
-9.00
-3.54

Store output of sed into a variable

To store the third line into a variable, use below syntax:

variable=`echo "$1" | sed '3q;d' urfile`

To store the changed line into a variable, use below syntax: variable=echo 'overflow' | sed -e "s/over/"OVER"/g" output:OVERflow

Hive cast string to date dd-MM-yyyy

This will convert the whole column:

select from_unixtime(unix_timestamp(transaction_date,'yyyyMMdd')) from table1

How to show multiline text in a table cell

the below code works like magic to me >>

td { white-space:pre-line }

Eclipse CDT project built but "Launch Failed. Binary Not Found"

If you have a successful build, and getting a "Launch Binary not Found" Error. Try doing the following steps :

Click on Run -> Run Configuration -> C/C++ Application -> click on project_name debug -> click on browse and select your project file -> Press Ok -> below it Browse binary file ( Goto your Eclipse Workspace and select your project file -> You'll find two files 1.Debug 2.Src -> Click on Debug file -> Next click on the file with your project name and Press ok) -> then click apply and press run button.

This should solve the problem

How can you have SharePoint Link Lists default to opening in a new window?

Under the Links Tab ==> Edit the URL Item ==> Under the URL (Type the Web address)- format the value as follows:

Example: if the URL = http://www.abc.com ==> then suffix the value with ==>

  • #openinnewwindow/,'" target="http://www.abc.com'

SO, the final value should read as ==> http://www.abc.com#openinnewwindow/,'" target="http://www.abc.com'

DONE ==> this will open the URL in New Window

Regular Expression for any number greater than 0?

I think this would perfectly work :

([1-9][0-9]*(\.[0-9]*[1-9])?|0\.[0-9]*[1-9])

Valid:

 1
 1.2
 1.02
 0.1 
 0.02

Not valid :

0
01
01.2
1.10

Find and replace words/lines in a file

You might want to use Scanner to parse through and find the specific sections you want to modify. There's also Split and StringTokenizer that may work, but at the level you're working at Scanner might be what's needed.

Here's some additional info on what the difference is between them: Scanner vs. StringTokenizer vs. String.Split

Best way to parse command line arguments in C#?

I would strongly suggest using NDesk.Options (Documentation) and/or Mono.Options (same API, different namespace). An example from the documentation:

bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;

var p = new OptionSet () {
    { "n|name=", "the {NAME} of someone to greet.",
       v => names.Add (v) },
    { "r|repeat=", 
       "the number of {TIMES} to repeat the greeting.\n" + 
          "this must be an integer.",
        (int v) => repeat = v },
    { "v", "increase debug message verbosity",
       v => { if (v != null) ++verbosity; } },
    { "h|help",  "show this message and exit", 
       v => show_help = v != null },
};

List<string> extra;
try {
    extra = p.Parse (args);
}
catch (OptionException e) {
    Console.Write ("greet: ");
    Console.WriteLine (e.Message);
    Console.WriteLine ("Try `greet --help' for more information.");
    return;
}

Is there a way to view past mysql queries with phpmyadmin?

Yes, you can log queries to a special phpMyAdmin DB table.

See SQL_history.

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

Sort a two dimensional array based on one column

  1. install java8 jdk+jre

  2. use lamda expression to sort 2D array.

code:

import java.util.Arrays;
import java.util.Comparator;

class SortString {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "2009.07.25 20:24", "Message A" },
                new String[] { "2009.07.25 20:17", "Message G" },
                new String[] { "2009.07.25 20:25", "Message B" },
                new String[] { "2009.07.25 20:30", "Message D" },
                new String[] { "2009.07.25 20:01", "Message F" },
                new String[] { "2009.07.25 21:08", "Message E" },
                new String[] { "2009.07.25 19:54", "Message R" } 
        };
        // this is applicable only in java 8 version.
        Arrays.sort(data, (String[] s1, String[] s2) -> s1[0].compareTo(s2[0]));

        // we can also use Comparator.comparing and point to Comparable value we want to use        
        // Arrays.sort(data, Comparator.comparing(row->row[0]));

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]);
        }
    }
}

output

2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E

How to hide a TemplateField column in a GridView

GridView1.Columns[columnIndex].Visible = false;

Where is Developer Command Prompt for VS2013?

Visual studio command prompt is nothing but the regular command prompt where few environment variables are set by default. This variables are set in the batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat . So basically to get a visual studio command prompt for a particular version, just open regular command prompt and run this batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat (Change the visual studio version based on your installed version). Voila you have got the visual studio command prompt. You can write a script to run the batch file and open cmd.exe.

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

Please note that inserted, deleted means the same thing as inserted CROSS JOIN deleted and gives every combination of every row. I doubt this is what you want.

Something like this may help get you started...

SELECT
  CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
       WHEN  deleted.primaryKey IS NULL THEN 'This is an insert'
                                        ELSE 'This is an update'
  END  as Action,
  *
FROM
  inserted
FULL OUTER JOIN
  deleted
    ON inserted.primaryKey = deleted.primaryKey


Depending on what you want to do, you then reference the table you are interested in with inserted.userID or deleted.userID, etc.


Finally, be aware that inserted and deleted are tables and can (and do) contain more than one record.

If you insert 10 records at once, the inserted table will contain ALL 10 records. The same applies to deletes and the deleted table. And both tables in the case of an update.


EDIT Examplee Trigger after OPs edit.

ALTER TRIGGER [dbo].[UpdateUserCreditsLeft] 
  ON  [dbo].[Order]
  AFTER INSERT,UPDATE,DELETE
AS 
BEGIN

  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  UPDATE
    User
  SET
    CreditsLeft = CASE WHEN inserted.UserID IS NULL THEN <new value for a  DELETE>
                       WHEN  deleted.UserID IS NULL THEN <new value for an INSERT>
                                                    ELSE <new value for an UPDATE>
                  END
  FROM
    User
  INNER JOIN
    (
      inserted
    FULL OUTER JOIN
      deleted
        ON inserted.UserID = deleted.UserID  -- This assumes UserID is the PK on UpdateUserCreditsLeft
    )
      ON User.UserID = COALESCE(inserted.UserID, deleted.UserID)

END


If the PrimaryKey of UpdateUserCreditsLeft is something other than UserID, use that in the FULL OUTER JOIN instead.

PHP Session timeout

<?php 
session_start();

if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}

else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>

How do I disable fail_on_empty_beans in Jackson?

Adding a solution here for a different problem, but one that manifests with the same error... Take care when constructing json on the fly (as api responses or whatever) to escape literal double quotes in your string members. You may be consuming your own malformed json.

What is the syntax to insert one list into another list in python?

If we just do x.append(y), y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:

x = [1,2,3] y = [4,5,6] x.append(y[:])

Insert array into MySQL database with PHP

function insertQuery($tableName,$cols,$values,$connection){
  $numberOfColsAndValues = count($cols);
  $query = 'INSERT INTO '.$tableName.' ('.getColNames($cols,$numberOfColsAndValues).') VALUES ('.getColValues($values,$numberOfColsAndValues).')';
   if(mysqli_query($connection, $query))
      return true;
   else{
      echo "Error: " . $query . "<br>" . mysqli_error($connection);
      return false;
   }
}

function getColNames($cols,$numberOfColsAndValues){
  $result = '';
  foreach($cols as $key => $val){
    $result = $result.$val.', ';
  }
    return substr($result,0,strlen($result)-2);
}


function getColValues($values,$numberOfColsAndValues){
  $result = '';
  foreach($values as $key => $val){
    $val = "'$val'";
    $result = $result.$val.', ';
  }
    return substr($result,0,strlen($result)-2);
}

Finding the length of an integer in C

keep dividing by ten until you get zero, then just output the number of divisions.

int intLen(int x)
{
  if(!x) return 1;
  int i;
  for(i=0; x!=0; ++i)
  {
    x /= 10;
  }
  return i;
}

How to define global variable in Google Apps Script

I'm using a workaround by returning a function with an object of my global variables:

function globalVariables(){
  var variables = {
    sheetName: 'Sheet1',
    variable1: 1,
    variable2: 2
  };
  return variables;
}

function functionThatUsesVariable (){
  var sheet =   SpreadsheetApp.getActiveSpreadsheet().getSheetByName(globalVariables().sheetName);
}

Cropping an UIImage

- (UIImage *)getSubImage:(CGRect) rect{
    CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    CGRect smallBounds = CGRectMake(rect.origin.x, rect.origin.y, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));

    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImg = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();

    return smallImg;
}

What is the difference between encrypting and signing in asymmetric encryption?

In RSA crypto, when you generate a key pair, it's completely arbitrary which one you choose to be the public key, and which is the private key. If you encrypt with one, you can decrypt with the other - it works in both directions.

So, it's fairly simple to see how you can encrypt a message with the receiver's public key, so that the receiver can decrypt it with their private key.

A signature is proof that the signer has the private key that matches some public key. To do this, it would be enough to encrypt the message with that sender's private key, and include the encrypted version alongside the plaintext version. To verify the sender, decrypt the encrypted version, and check that it is the same as the plaintext.

Of course, this means that your message is not secret. Anyone can decrypt it, because the public key is well known. But when they do so, they have proved that the creator of the ciphertext has the corresponding private key.

However, this means doubling the size of your transmission - plaintext and ciphertext together (assuming you want people who aren't interested in verifying the signature, to read the message). So instead, typically a signature is created by creating a hash of the plaintext. It's important that fake hashes can't be created, so cryptographic hash algorithms such as SHA-2 are used.

So:

  • To generate a signature, make a hash from the plaintext, encrypt it with your private key, include it alongside the plaintext.
  • To verify a signature, make a hash from the plaintext, decrypt the signature with the sender's public key, check that both hashes are the same.

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

Notice: Array to string conversion in

The problem is that $money is an array and you are treating it like a string or a variable which can be easily converted to string. You should say something like:

 '.... Money:'.$money['money']

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

Entity Framework rollback and remove bad migration

You have 2 options:

  • You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version.

    I use this option on things that have gone to multiple environments.

  • The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version.

    Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration

    I use this option while developing.

Static image src in Vue.js template

This solution is for Vue-2 users:

  1. In vue-2 if you don't like to keep your files in static folder (relevant info), or
  2. In vue-2 & vue-cli-3 if you don't like to keep your files in public folder (static folder is renamed to public):

The simple solution is :)

<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}

If you like to keep your static images in static/assets/img or public/assets/img folder, then just do:

<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./

Testing Private method using mockito

Not possible through mockito. From their wiki

Why Mockito doesn't mock private methods?

Firstly, we are not dogmatic about mocking private methods. We just don't care about private methods because from the standpoint of testing private methods don't exist. Here are a couple of reasons Mockito doesn't mock private methods:

It requires hacking of classloaders that is never bullet proof and it changes the api (you must use custom test runner, annotate the class, etc.).

It is very easy to work around - just change the visibility of method from private to package-protected (or protected).

It requires me to spend time implementing & maintaining it. And it does not make sense given point #2 and a fact that it is already implemented in different tool (powermock).

Finally... Mocking private methods is a hint that there is something wrong with OO understanding. In OO you want objects (or roles) to collaborate, not methods. Forget about pascal & procedural code. Think in objects.

Spring 3 RequestMapping: Get path value

I have a similar problem and I resolved in this way:

@RequestMapping(value = "{siteCode}/**/{fileName}.{fileExtension}")
public HttpEntity<byte[]> getResource(@PathVariable String siteCode,
        @PathVariable String fileName, @PathVariable String fileExtension,
        HttpServletRequest req, HttpServletResponse response ) throws IOException {
    String fullPath = req.getPathInfo();
    // Calling http://localhost:8080/SiteXX/images/argentine/flag.jpg
    // fullPath conentent: /SiteXX/images/argentine/flag.jpg
}

Note that req.getPathInfo() will return the complete path (with {siteCode} and {fileName}.{fileExtension}) so you will have to process conveniently.

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • How to serialize SqlAlchemy result to JSON?

    For security reasons you should never return all the model's fields. I prefer to selectively choose them.

    Flask's json encoding now supports UUID, datetime and relationships (and added query and query_class for flask_sqlalchemy db.Model class). I've updated the encoder as follows:

    app/json_encoder.py

        from sqlalchemy.ext.declarative import DeclarativeMeta
        from flask import json
    
    
        class AlchemyEncoder(json.JSONEncoder):
            def default(self, o):
                if isinstance(o.__class__, DeclarativeMeta):
                    data = {}
                    fields = o.__json__() if hasattr(o, '__json__') else dir(o)
                    for field in [f for f in fields if not f.startswith('_') and f not in ['metadata', 'query', 'query_class']]:
                        value = o.__getattribute__(field)
                        try:
                            json.dumps(value)
                            data[field] = value
                        except TypeError:
                            data[field] = None
                    return data
                return json.JSONEncoder.default(self, o)
    

    app/__init__.py

    # json encoding
    from app.json_encoder import AlchemyEncoder
    app.json_encoder = AlchemyEncoder
    

    With this I can optionally add a __json__ property that returns the list of fields I wish to encode:

    app/models.py

    class Queue(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        song_id = db.Column(db.Integer, db.ForeignKey('song.id'), unique=True, nullable=False)
        song = db.relationship('Song', lazy='joined')
        type = db.Column(db.String(20), server_default=u'audio/mpeg')
        src = db.Column(db.String(255), nullable=False)
        created_at = db.Column(db.DateTime, server_default=db.func.now())
        updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
    
        def __init__(self, song):
            self.song = song
            self.src = song.full_path
    
        def __json__(self):
            return ['song', 'src', 'type', 'created_at']
    

    I add @jsonapi to my view, return the resultlist and then my output is as follows:

    [
    
    {
    
        "created_at": "Thu, 23 Jul 2015 11:36:53 GMT",
        "song": 
    
            {
                "full_path": "/static/music/Audioslave/Audioslave [2002]/1 Cochise.mp3",
                "id": 2,
                "path_name": "Audioslave/Audioslave [2002]/1 Cochise.mp3"
            },
        "src": "/static/music/Audioslave/Audioslave [2002]/1 Cochise.mp3",
        "type": "audio/mpeg"
    }
    
    ]
    

    Most simple code to populate JTable from ResultSet

    I think this is the Easiest way to populate/model a table with ResultSet.. Download and include rs2xml.jar Get rs2xml.jar in your libraries..

    import net.proteanit.sql.DbUtils;
    
        try
        {
        CreateConnection();
        PreparedStatement st =conn.prepareStatement("Select * from ABC;");
        ResultSet rs = st.executeQuery();
        tblToBeFilled.setModel(DbUtils.resultSetToTableModel(rs));
        conn.close();
        }
        catch(Exception ex)
        {
        JOptionPane.showMessageDialog(null, ex.toString());
        }
    

    How do I change the default schema in sql developer?

    Alternatively, just select 'Other Users' one of the element shows on the left hand side bottom of the current schema.

    Select what ever the schema you want from the available list.

    enter image description here

    How to create streams from string in Node.Js?

    Just create a new instance of the stream module and customize it according to your needs:

    var Stream = require('stream');
    var stream = new Stream();
    
    stream.pipe = function(dest) {
      dest.write('your string');
      return dest;
    };
    
    stream.pipe(process.stdout); // in this case the terminal, change to ya-csv
    

    or

    var Stream = require('stream');
    var stream = new Stream();
    
    stream.on('data', function(data) {
      process.stdout.write(data); // change process.stdout to ya-csv
    });
    
    stream.emit('data', 'this is my string');
    

    .htaccess - how to force "www." in a generic way?

    This will do it:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    

    Update Item to Revision vs Revert to Revision

    Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

    If you want to undo an earlier change permanently, use Revert to this revision instead.

    -- from TSVN help doc

    If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

    How can I use JSON data to populate the options of a select box?

    You should do it like this:

    function getResults(str) {
      $.ajax({
            url:'suggest.html',
            type:'POST',
            data: 'q=' + str,
            dataType: 'json',
            success: function( json ) {
               $.each(json, function(i, optionHtml){
                  $('#myselect').append(optionHtml);
               });
            }
        });
    };
    

    Cheers

    Need to ZIP an entire directory using Node.js

    This is another library which zips the folder in one line : zip-local

    var zipper = require('zip-local');
    
    zipper.sync.zip("./hello/world/").compress().save("pack.zip");
    

    Unix - copy contents of one directory to another

    Quite simple, with a * wildcard.

    cp -r Folder1/* Folder2/
    

    But according to your example recursion is not needed so the following will suffice:

    cp Folder1/* Folder2/
    

    EDIT:

    Or skip the mkdir Folder2 part and just run:

    cp -r Folder1 Folder2
    

    How to add to an NSDictionary

    Update version

    Objective-C

    Create:

    NSDictionary *dictionary = @{@"myKey1": @7, @"myKey2": @5}; 
    

    Change:

    NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];     //Make the dictionary mutable to change/add
    mutableDictionary[@"myKey3"] = @3;
    

    The short-hand syntax is called Objective-C Literals.

    Swift

    Create:

    var dictionary = ["myKey1": 7, "myKey2": 5]
    

    Change:

    dictionary["myKey3"] = 3
    

    Find running median from a stream of integers

    Can't you do this with just one heap? Update: no. See the comment.

    Invariant: After reading 2*n inputs, the min-heap holds the n largest of them.

    Loop: Read 2 inputs. Add them both to the heap, and remove the heap's min. This reestablishes the invariant.

    So when 2n inputs have been read, the heap's min is the nth largest. There'll need to be a little extra complication to average the two elements around the median position and to handle queries after an odd number of inputs.

    Which version of CodeIgniter am I currently using?

    For CodeIgniter 4, use the following:

    <?php    
        echo \CodeIgniter\CodeIgniter::CI_VERSION;
    ?>
    

    How to change the hosts file on android

    That didn't really work in my case - i.e. in order to overwrite hosts file you have to follow it's directions, ie:

    ./emulator -avd myEmulatorName -partition-size 280
    

    and then in other term window (pushing new hosts file /tmp/hosts):

    ./adb remount
    ./adb push /tmp/hosts /system/etc
    

    Cross browser method to fit a child div to its parent's width

    If you put position:relative; on the outer element, the inner element will place itself according to this one. Then a width:auto; on the inner element will be the same as the width of the outer.

    Select all elements with a "data-xxx" attribute without using jQuery

    Try it ? here

        <!DOCTYPE html>
        <html>
            <head></head>
            <body>
                <p data-foo="0"></p>
                <h6 data-foo="1"></h6>
                <script>
                    var a = document.querySelectorAll('[data-foo]');
    
                    for (var i in a) if (a.hasOwnProperty(i)) {
                        alert(a[i].getAttribute('data-foo'));
                    }
                </script>
            </body>
        </html>
    

    Using ListView : How to add a header view?

    I found out that inflating the header view as:

    inflater.inflate(R.layout.listheader, container, false);
    

    being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.

    So, my problem was solved solved by inflating the header view passing the list as container:

    ListView list = fragmentview.findViewById(R.id.listview);
    View headerView = inflater.inflate(R.layout.listheader, list, false);
    

    then

    list.addHeaderView(headerView, null, false);
    

    Kinda late answer but I hope this can help someone

    Why doesn't CSS ellipsis work in table cell?

    Check box-sizing css property of your td elements. I had problem with css template which sets it to border-box value. You need set box-sizing: content-box.

    C# Test if user has write access to a folder

    That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception may be an issue.

    There have been other similar questions asked previously.

    Remove the last line from a file in Bash

    I had trouble with all the answers here because I was working with a HUGE file (~300Gb) and none of the solutions scaled. Here's my solution:

    dd if=/dev/null of=<filename> bs=1 seek=$(echo $(stat --format=%s <filename> ) - $( tail -n1 <filename> | wc -c) | bc )
    

    In words: Find out the length of the file you want to end up with (length of file minus length of length of its last line, using bc) and, set that position to be the end of the file (by dding one byte of /dev/null onto it).

    This is fast because tail starts reading from the end, and dd will overwrite the file in place rather than copy (and parse) every line of the file, which is what the other solutions do.

    NOTE: This removes the line from the file in place! Make a backup or test on a dummy file before trying it out on your own file!

    Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

    Lets say, you wanted to have some CGAL-Demos portable. So you'd have a folder "CGAL", and in it, 1 subfolder called "lib": all (common) support-dlls for any programs in the CGAL-folder go here. In our example, this would be the Dll-Download: simply unzip into the "lib" directory. The further you scroll down on the demos-page, the more impressive the content. In my case, the polyhedron-demo seemed about right. If this runs on my 10+ yo notebook, I'm impressed. So I created a folder "demo" in the "CGAL"-directory, alongside "lib". Now create a .cmd-file in that folder. I named mine "Polyhedron.cmd". So we have a directory structure like this:

     CGAL - the bag for all the goodies
      lib - all libraries for all CGAL-packages
     demo - all the demos I'm interested in
    [...] - certainly some other collections, several apps per folder...
    Polyhedron.cmd - and a little script for every Qt-exe to make it truly portable.
    

    In this little example, "Polyhedron.cmd" contains the following text:

    @echo off
    set "me=%~dp0"
    set PATH=%me%lib
    set "QT_PLUGIN_PATH=%me%lib\plugins"
    start /b "CGAL Polyhedron Demo" "%me%demo\polyhedron\polyhedron_3.exe"
    

    All scripts can be the same apart from the last line, obviously. The only caveat is: the "DOS-Window" stays open for as long as you use the actual program. Close the shell-window, and you kill the *.exe as well. Whereever you copy the "CGAL"-folder, as the weird "%~dp0"-wriggle represents the full path to the *.cmd-file that we started, with trailing "\". So "%me%lib" is always the full path to the actual library ("CGAL\lib" in my case). The next 2 lines tell Qt where its "runtime" files are. This will be at least the file "qwindows.dll" for Windows-Qt programs plus any number of *.dlls. If I remember rightly, the Dll-library (at least when I downloaded it) had a little "bug" since it contains the "platforms"-directory with qwindows.dll in it. So when you open the lib directory, you need to create a folder "plugins" next to "platforms", and then move into "plugins". If a Qt-app, any Qt-app, doesn't find "qwindows.dll", it cannot find "windows". And it expects it in a directory named "platforms" in the "plugins" directory, which it has to get told by the OS its running on...and if the "QT_PLUGIN_PATH" is not exactly pointing to all the helper-dlls you need, some Qt-programs will still run with no probs. And some complain about missing *.dlls you've never heard off...

    Oracle: not a valid month

    You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

    ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
    SELECT TO_DATE('05-12-2015') FROM dual;
    
    05/12/2015
    

    Initializing multiple variables to the same value in Java

    Way too late to this but the simplest way I've found is:

    String foo = bar = baz = "hello"
    println(foo)
    println(bar)
    println(baz)
    

    Output:

    hello
    hello
    hello
    

    Uploading multiple files using formData()

    You have to get the files length to append in JS and then send it via AJAX request as below

    //JavaScript 
    var ins = document.getElementById('fileToUpload').files.length;
    for (var x = 0; x < ins; x++) {
        fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
    }
    
    //PHP
    $count = count($_FILES['fileToUpload']['name']);
    for ($i = 0; $i < $count; $i++) {
        echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'<br/>';
    }
    

    How can I store the result of a system command in a Perl variable?

    Try using qx{command} rather than backticks. To me, it's a bit better because: you can do SQL with it and not worry about escaping quotes and such. Depending on the editor and screen, my old eyes tend to miss the tiny back ticks, and it shouldn't ever have an issue with being overloaded like using angle brackets versus glob.

    Angular ng-click with call to a controller function not working

    I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href attributes blank.

    <a href="" data-router="article" ng-click="changeListName('metro')">
    

    Also I don't know what data-router is doing but if you still aren't getting the proper result, that could be why.

    Direct method from SQL command text to DataSet

    public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";
    
    public static DataSet LoaderDataSet(string StrSql)      
    {
        SqlConnection cnn;            
        SqlDataAdapter dad;
        DataSet dts = new DataSet();
        cnn = new SqlConnection(textDataSource);
        dad = new SqlDataAdapter(StrSql, cnn);
        try
        {
            cnn.Open();
            dad.Fill(dts);
            cnn.Close();
    
            return dts;
        }
        catch (Exception)
        {
    
            return dts;
        }
        finally
        {
            dad.Dispose();
            dts = null;
            cnn = null;
        }
    }
    

    Difference between chr(13) and chr(10)

    Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

    You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


    Historically, Line Feed would move down a line but not return to column 1:

    This  
        is  
            a  
                test.
    

    Similarly Carriage Return would return to column 1 but not move down a line:

    This  
    is  
    a  
    test.
    

    Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

    I'm getting an error "invalid use of incomplete type 'class map'

    I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

    class FooReader {
      public:
         /** Constructor */
         FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
         .......
      private:
         FooReaderPrivate* d;
    };
    
    ====== In a separate file =====
    class FooReaderPrivate {
      public:
         FooReaderPrivate(FooReader*) : parent(p) { }
      private:
         FooReader* parent;
    };
    

    The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

    Local Storage vs Cookies

    Well, local storage speed greatly depends on the browser the client is using, as well as the operating system. Chrome or Safari on a mac could be much faster than Firefox on a PC, especially with newer APIs. As always though, testing is your friend (I could not find any benchmarks).

    I really don't see a huge difference in cookie vs local storage. Also, you should be more worried about compatibility issues: not all browsers have even begun to support the new HTML5 APIs, so cookies would be your best bet for speed and compatibility.

    docker unauthorized: authentication required - upon push with successful login

    If you running windows 7 docker Registry

    1. Start **Docker Quick Start terminal** run (this terminal enables connection ) Until you pushed images , that will keep token alive .
    2. Login docker login
    3. Make sure you tag the image with username

      docker build -f Dockerfile -t 'username'/imagename

    4. push image

      docker image push username/imagename

    Note: image name all lowercase

    Converting JSON data to Java object

    If, by any change, you are in an application which already uses http://restfb.com/ then you can do:

    import com.restfb.json.JsonObject;
    
    ...
    
    JsonObject json = new JsonObject(jsonString);
    json.get("title");
    

    etc.

    querySelectorAll with multiple conditions

    With pure JavaScript you can do this (such as SQL) and anything you need, basically:

    _x000D_
    _x000D_
    <html>_x000D_
    _x000D_
    <body>_x000D_
    _x000D_
    <input type='button' value='F3' class="c2" id="btn_1">_x000D_
    <input type='button' value='F3' class="c3" id="btn_2">_x000D_
    <input type='button' value='F1' class="c2" id="btn_3">_x000D_
    _x000D_
    <input type='submit' value='F2' class="c1" id="btn_4">_x000D_
    <input type='submit' value='F1' class="c3" id="btn_5">_x000D_
    <input type='submit' value='F2' class="c1" id="btn_6">_x000D_
    _x000D_
    <br/>_x000D_
    <br/>_x000D_
    _x000D_
    <button onclick="myFunction()">Try it</button>_x000D_
    _x000D_
    <script>_x000D_
        function myFunction() _x000D_
        {_x000D_
            var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');_x000D_
    _x000D_
                arrFiltered.forEach(function (el)_x000D_
                {                _x000D_
                    var node = document.createElement("p");_x000D_
                    _x000D_
                    node.innerHTML = el.getAttribute('id');_x000D_
    _x000D_
                    window.document.body.appendChild(node);_x000D_
                });_x000D_
            }_x000D_
        </script>_x000D_
    _x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    How to get the mobile number of current sim card in real device?

    Sometimes you can retreive the phonenumber with a USSD request to your operator. For example I can get my phonenumber by dialing *116# This can probably be done within an app, I guess, if the USSD responce somehow could be catched. Offcourse this is not a method I would recommend to use within an app that is to be distributed, the code may even differ between operators.

    What is a practical, real world example of the Linked List?

    In the general case, linked lists are one of the most devilishly useful things you will encounter.

    Real world examples:

    • A bunch of people waiting in line for something or other - a special kind of LL called a "queue".

    • The stack of dishes in your china cabinet - a special kind of LL called a "stack".

    • The "take a number" lines (where the numbers have to start over again at "1" at some point) - a special kind of LL called a "circular queue".

    Generally the metaphor I like to use for almost all linked data structures though is a deck of cards. Just about anything you can do with linked lists, you can use a deck of cards to visualise. This is particularly handy to show yourself what is going on in some of the more esoteric sorting algorithms.

    My personal favorite: Bogosort = play 52 card pickup until your deck is sorted. :-)

    JQuery Event for user pressing enter in a textbox?

    It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.

    I would highly suggest the following methodology for binding, as it solves the following potential challenges:

    1. By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
    2. By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
    3. By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.

    Here is an example:

    <!DOCTYPE html>
      <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          $(function() {
            var $selector = $('textarea');
    
            // Prevent double-binding
            // (only a potential issue if script is loaded through AJAX)
            $(document.body).off('keyup', $selector);
    
            // Bind to keyup events on the $selector.
            $(document.body).on('keyup', $selector, function(event) {
              if(event.keyCode == 13) { // 13 = Enter Key
                alert('enter key pressed.');
              }
            });
          });
        </script>
      </head>
      <body>
    
      </body>
    </html>
    

    String comparison in Objective-C

    Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

    if ([category isEqualToString:@"Some String"])
    {
        // Do stuff...
    }
    

    Detect if range is empty

    Another possible solution. Count empty cells and subtract that value from the total number of cells

    Sub Emptys()
    
    Dim r As range
    Dim totalCells As Integer
    
    'My range To check'
    Set r = ActiveSheet.range("A1:B5")
    
    'Check for filled cells'
    totalCells = r.Count- WorksheetFunction.CountBlank(r)
    
    
    If totalCells = 0 Then
        MsgBox "Range is empty"
    Else
        MsgBox "Range is not empty"
    End If
    
    End Sub