Programs & Examples On #Time trial

What is Linux’s native GUI API?

Strictly speaking, the API of Linux consists of its system calls. These are all of the kernel functions that can be called by a user-mode (non-kernel) program. This is a very low-level interface that allows programs to do things like open and read files. See http://en.wikipedia.org/wiki/System_call for a general introduction.

A real Linux system will also have an entire "stack" of other software running on it, in order to provide a graphical user interface and other features. Each element of this stack will offer its own API.

No Android SDK found - Android Studio

I had the same problem, Android Studio just could not identify the android-sdk folder. All I did was to uninstall and reinstall android studio, and this time it actually identified the folder. Hope it also works out for you.

How to bring view in front of everything?

bringToFront() is the right way, but, NOTE that you must call bringToFront() and invalidate() method on highest-level view (under your root view), for e.g.:

Your view's hierarchy is:

-RelativeLayout
|--LinearLayout1
|------Button1
|------Button2
|------Button3
|--ImageView
|--LinearLayout2
|------Button4
|------Button5
|------Button6

So, when you animate back your buttons (1->6), your buttons will under (below) the ImageView. To bring it over (above) the ImageView you must call bringToFront() and invalidate() method on your LinearLayouts. Then it will work :) **NOTE: Remember to set android:clipChildren="false" for your root layout or animate-view's gradparent_layout. Let's take a look at my real code:

.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:hw="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/common_theme_color"
    android:orientation="vertical" >

    <com.binh.helloworld.customviews.HWActionBar
        android:id="@+id/action_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_actionbar_height"
        android:layout_alignParentTop="true"
        hw:titleText="@string/app_name" >
    </com.binh.helloworld.customviews.HWActionBar>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/action_bar"
        android:clipChildren="false" >

        <LinearLayout
            android:id="@+id/layout_top"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>

        <ImageView
            android:id="@+id/imgv_main"
            android:layout_width="@dimen/common_imgv_height"
            android:layout_height="@dimen/common_imgv_height"
            android:layout_centerInParent="true"
            android:contentDescription="@string/app_name"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:id="@+id/layout_bottom"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

Some code in .java

private LinearLayout layoutTop, layoutBottom;
...
layoutTop = (LinearLayout) rootView.findViewById(R.id.layout_top);
layoutBottom = (LinearLayout) rootView.findViewById(R.id.layout_bottom);
...
//when animate back
//dragedView is my layoutTop's child view (i added programmatically) (like buttons in above example) 
dragedView.setVisibility(View.GONE);
layoutTop.bringToFront();
layoutTop.invalidate();
dragedView.startAnimation(animation); // TranslateAnimation
dragedView.setVisibility(View.VISIBLE);

GLuck!

SQL LIKE condition to check for integer?

PostgreSQL supports regular expressions matching.

So, your example would look like

SELECT * FROM books WHERE title ~ '^\d+ ?' 

This will match a title starting with one or more digits and an optional space

Listening for variable changes in JavaScript

Using Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var myVar = 123;_x000D_
_x000D_
Object.defineProperty(this, 'varWatch', {_x000D_
  get: function () { return myVar; },_x000D_
  set: function (v) {_x000D_
    myVar = v;_x000D_
    print('Value changed! New value: ' + v);_x000D_
  }_x000D_
});_x000D_
_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Other example

_x000D_
_x000D_
// Console_x000D_
function print(t) {_x000D_
  var c = document.getElementById('console');_x000D_
  c.innerHTML = c.innerHTML + '<br />' + t;_x000D_
}_x000D_
_x000D_
// Demo_x000D_
var varw = (function (context) {_x000D_
  return function (varName, varValue) {_x000D_
    var value = varValue;_x000D_
  _x000D_
    Object.defineProperty(context, varName, {_x000D_
      get: function () { return value; },_x000D_
      set: function (v) {_x000D_
        value = v;_x000D_
        print('Value changed! New value: ' + value);_x000D_
      }_x000D_
    });_x000D_
  };_x000D_
})(window);_x000D_
_x000D_
varw('varWatch'); // Declare_x000D_
print(varWatch);_x000D_
varWatch = 456;_x000D_
print(varWatch);_x000D_
_x000D_
print('---');_x000D_
_x000D_
varw('otherVarWatch', 123); // Declare with initial value_x000D_
print(otherVarWatch);_x000D_
otherVarWatch = 789;_x000D_
print(otherVarWatch);
_x000D_
<pre id="console">_x000D_
</pre>
_x000D_
_x000D_
_x000D_

Check if a temporary table exists and delete if it exists before creating a temporary table

Note: This also works for ## temp tables.

i.e.

IF OBJECT_ID('tempdb.dbo.##AuditLogTempTable1', 'U') IS NOT NULL
DROP TABLE ##AuditLogTempTable1

Note: This type of command only suitable post SQL Server 2016. Ask yourself .. Do I have any customers that are still on SQL Server 2012 ?

DROP TABLE IF EXISTS ##AuditLogTempTable1

How to autosize and right-align GridViewColumn data in WPF?

I created a function for updating GridView column headers for a list and call it whenever the window is re-sized or the listview updates it's layout.

public void correctColumnWidths()
{
    double remainingSpace = myList.ActualWidth;

    if (remainingSpace > 0)
    {
         for (int i = 0; i < (myList.View as GridView).Columns.Count; i++)
              if (i != 2)
                   remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth;

          //Leave 15 px free for scrollbar
          remainingSpace -= 15;

          (myList.View as GridView).Columns[2].Width = remainingSpace;
    }
}

Add/delete row from a table

JavaScript with a few modifications:

function deleteRow(btn) {
  var row = btn.parentNode.parentNode;
  row.parentNode.removeChild(row);
}

And the HTML with a little difference:

<table id="dsTable">
  <tbody>
    <tr>
      <td>Relationship Type</td>
      <td>Date of Birth</td>
      <td>Gender</td>
    </tr>
    <tr>
      <td>Spouse</td>
      <td>1980-22-03</td>
      <td>female</td>
      <td><input type="button" value="Add" onclick="add()"/></td>
      <td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
    </tr>
    <tr>
      <td>Child</td>
      <td>2008-23-06</td>
      <td>female</td>
      <td><input type="button" value="Add" onclick="add()"/></td>
      <td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
    </tr>
  </tbody>
</table>???????????????????????????????????

Visual Studio Code: Auto-refresh file changes

VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.

There is currently no way to disable this behaviour.

How to make an embedded Youtube video automatically start playing?

You have to use

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>

?autoplay=1

and not

&autoplay=1

its the first URL param so its added with a ?

Printing leading 0's in C

If you are on a *nix machine:

man 3 printf

This will show a manual page, similar to:

0 The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - flags both appear, the 0 flag is ignored. If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. For other conversions, the behavior is undefined.

Even though the question is for C, this page may be of aid.

Populating a data frame in R in a loop

this works too.

df = NULL
for (k in 1:10)
    {
       x = 1
       y = 2
       z = 3
       df = rbind(df, data.frame(x,y,z))
     }

output will look like this

df #enter

x y z #col names
1 2 3

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

Regex for parsing directory and filename

A very late answer, but hope this will help

^(.+?)/([\w]+\.log)$

This uses lazy check for /, and I just modified the accepted answer

http://regex101.com/r/gV2xB7/1

Remove Android App Title Bar

for Title Bar

requestWindowFeature(Window.FEATURE_NO_TITLE);

for fullscreen

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

Place this after

super.onCreate(savedInstanceState);

but before

setContentView(R.layout.xml);

This worked for me.try this

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

comparing two strings in ruby

From what you printed, it seems var2 is an array containing one string. Or actually, it appears to hold the result of running .inspect on an array containing one string. It would be helpful to show how you are initializing them.

irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]

Linux / Bash, using ps -o to get process by specific name?

ps -fC PROCESSNAME

ps and grep is a dangerous combination -- grep tries to match everything on each line (thus the all too common: grep -v grep hack). ps -C doesn't use grep, it uses the process table for an exact match. Thus, you'll get an accurate list with: ps -fC sh rather finding every process with sh somewhere on the line.

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

MySQL LIMIT on DELETE statement

simply use

DELETE FROM test WHERE 1= 1 LIMIT 10 

Encrypting & Decrypting a String in C#

You may be looking for the ProtectedData class, which encrypts data using the user's logon credentials.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

accuracy_score is a classification metric, you cannot use it for a regression problem.

You can see the available regression metrics here

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

What is object slicing?

Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.

Explanation: Consider the following class declaration:

           class baseclass
          {
                 ...
                 baseclass & operator =(const baseclass&);
                 baseclass(const baseclass&);
          }
          void function( )
          {
                baseclass obj1=m;
                obj1=m;
          }

As baseclass copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing.

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>

mongoError: Topology was destroyed

Using mongoose here, but you could do a similar check without it

export async function clearDatabase() {
  if (mongoose.connection.readyState === mongoose.connection.states.disconnected) {
    return Promise.resolve()
  }
  return mongoose.connection.db.dropDatabase()
}

My use case was just tests throwing errors, so if we've disconnected, I don't run operations.

Change background color of selected item on a ListView

I know this is a old question, but i give a simple solution for this need (without loops!):

//On your adapter create a variable:
private View lastSelectedItem;

//Define the folowing method:
private void toggleBackgroundItem(View view) {
    if (lastSelectedItem != null) {
        lastSelectedItem.setBackgroundColor(Color.TRANSPARENT);
    }
    view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
    lastSelectedItem = view;

}
//finally invoque the method onItemClick
lvSac.setOnItemClickListener(new AdapterView.OnItemClickListener()

{
    @Override
    public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){

    toggleBackgroundItem(view);
}
}

how to get text from textview

If it is the sum of all the numbers you want, I made a little snippet for you that can handle both + and - using a regex (I left some print-calls in there to help visualise what happens):

    final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
    final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
    Matcher matcher = pattern.matcher(string);

    System.out.print(string);
    System.out.print('\n');
    int sum = 0;

    while( matcher.find() ){
        System.out.print(matcher.group(1));
        System.out.print(matcher.group(2));
        System.out.print('\n');
        sum += Integer.parseInt(matcher.group(1)+matcher.group(2));
    }
    System.out.print("\nSum: "+sum);

This code prints the following:

  5
- 9
+ 5
5
-9
5

Sum: 1

Edit: sorry if I misunderstood your question, it was a little bit unclear what you wanted to do. I assumed you wanted to get the sum of the numbers as an integer rather than a string.

Edit2: to get the numbers separate from each other, do something like this instead:

    final String string = "  " + 5 + "\n" + "-" + " " + 9+"\n"+"+"+" "+5; //Or get the value from a TextView
    final Pattern pattern = Pattern.compile("(-?).?(\\d+)");
    Matcher matcher = pattern.matcher(string);
    ArrayList<Integer> numbers = new ArrayList<Integer>();

    while( matcher.find() ){
        numbers.add(Integer.parseInt(matcher.group(1)+matcher.group(2)));
    }

Put a Delay in Javascript

Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

How do I find out which keystore was used to sign an app?

You can do this with the apksigner tool that is part of the Android SDK:

apksigner verify --print-certs my_app.apk

You can find apksigner inside the build-tools directory. For example: ~/Library/Android/sdk/build-tools/29.0.1/apksigner

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

Recommended method for escaping HTML in Java

For some purposes, HtmlUtils:

import org.springframework.web.util.HtmlUtils;
[...]
HtmlUtils.htmlEscapeDecimal("&"); //gives &#38;
HtmlUtils.htmlEscape("&"); //gives &amp;

Databound drop down list - initial value

I think what you want to do is this:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="--Select One--" Value="" />   
</asp:DropDownList>

Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.

If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>

Upload files from Java client to a HTTP server

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here's a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

See also

VBA: How to delete filtered rows in Excel?

As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.

ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)

As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().

Tooltip with HTML content without JavaScript

Similar to koningdavid's, but works on display:none and block, and adds additional styling.

_x000D_
_x000D_
div.tooltip {_x000D_
  position: relative;_x000D_
  /*  DO NOT include below two lines, as they were added so that the text that_x000D_
        is hovered over is offset from top of page*/_x000D_
  top: 10em;_x000D_
  left: 10em;_x000D_
  /* if want hover over icon instead of text based, uncomment below */_x000D_
  /*    background-image: url("../images/info_tooltip.svg");_x000D_
            /!* width and height of svg *!/_x000D_
            width: 16px;_x000D_
            height: 16px;*/_x000D_
}_x000D_
_x000D_
_x000D_
/* hide tooltip */_x000D_
_x000D_
div.tooltip span {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* show and style tooltip */_x000D_
_x000D_
div.tooltip:hover span {_x000D_
  /* show tooltip */_x000D_
  display: block;_x000D_
  /* position relative to container div.tooltip */_x000D_
  position: absolute;_x000D_
  bottom: 1em;_x000D_
  /* prettify */_x000D_
  padding: 0.5em;_x000D_
  color: #000000;_x000D_
  background: #ebf4fb;_x000D_
  border: 0.1em solid #b7ddf2;_x000D_
  /* round the corners */_x000D_
  border-radius: 0.5em;_x000D_
  /* prevent too wide tooltip */_x000D_
  max-width: 10em;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
  hover_over_me_x000D_
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis purus dui. Sed at orci. </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Portable way to get file size (in bytes) in shell?

If you use find from GNU fileutils:

size=$( find . -maxdepth 1 -type f -name filename -printf '%s' )

Unfortunately, other implementations of find usually don't support -maxdepth, nor -printf. This is the case for e.g. Solaris and macOS find.

Eclipse cannot load SWT libraries

I agree with Scott, what he listed worked. However just running it from any directory did not work. I had to cd to the /home/*/.swt/lib/linux/x86_64/ 0 files

directory first and then run the link command:

For 32 bit:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86/

And on Ubuntu 12.04 64 bit:

ln -s /usr/lib/jni/libswt-* ~/.swt/lib/linux/x86_64/

What is the JavaScript equivalent of var_dump or print_r in PHP?

Most modern browsers have a console in their developer tools, useful for this sort of debugging.

console.log(myvar);

Then you will get a nicely mapped out interface of the object/whatever in the console.

Check out the console documentation for more details.

successful/fail message pop up box after submit?

Instead of using a submit button, try using a <button type="button">Submit</button>

You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.

How to query MongoDB with "like"?

In nodejs project and use mongoose use Like query

var User = mongoose.model('User');

var searchQuery={};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
User.find(searchQuery, function(error, user) {
                if(error || user === null) {
                    return res.status(500).send(error);
                }
                return res.status(200).send(user);
            });

How to get exit code when using Python subprocess communicate method?

You should first make sure that the process has completed running and the return code has been read out using the .wait method. This will return the code. If you want access to it later, it's stored as .returncode in the Popen object.

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

I had a similar problem and the solution was in the right use of the '$' (end-of-string) character:

My main url.py looked like this (notice the $ character):

urlpatterns = [
url(r'^admin/', include(admin.site.urls )),
url(r'^$', include('card_purchase.urls' )),
]

and my url.py for my card_purchases app said:

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^purchase/$', views.purchase_detail, name='purchase')
]

I used the '$' twice. So a simple change worked:

urlpatterns = [
url(r'^admin/', include(admin.site.urls )),
url(r'^cp/', include('card_purchase.urls' )),
]

Notice the change in the second url! My url.py for my card_purchases app looks like this:

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^purchase/$', views.purchase_detail, name='purchase')
]

Apart from this, I can confirm that quotes around named urls are crucial!

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

Access parent's parent from javascript object

Here you go:

var life={
        users:{
             guys:function(){ life.mameAndDestroy(life.users.girls); },
             girls:function(){ life.kiss(life.users.guys); }
        },
        mameAndDestroy : function(group){ 
          alert("mameAndDestroy");
          group();
        },
        kiss : function(group){
          alert("kiss");
          //could call group() here, but would result in infinite loop
        }
};

life.users.guys();
life.users.girls();

Also, make sure you don't have a comma after the "girls" definition. This will cause the script to crash in IE (any time you have a comma after the last item in an array in IE it dies).

See it run

What is the shortcut in IntelliJ IDEA to find method / functions?

Intellij v 13.1.4, OSX

The Open Symbol keyboard shortcut is command+shift+s

How to use background thread in swift?

Swift 4.x

Put this in some file:

func background(work: @escaping () -> ()) {
    DispatchQueue.global(qos: .userInitiated).async {
        work()
    }
}

func main(work: @escaping () -> ()) {
    DispatchQueue.main.async {
        work()
    }
}

and then call it where you need:

background {
     //background job
     main {
       //update UI (or what you need to do in main thread)
     }
}

do { ... } while (0) — what is it good for?

Generically, do/while is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while or even a for loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:

do {
    char c = read_input();

    process_input(c);
} while (c != 'Q');

Android studio, gradle and NDK

To expand on what Naxos said (Thanks Naxos for sending me in the right direction!), I learned quite a bit from the recently released NDK examples and posted an answer in a similar question here.

How to configure NDK with Android Gradle plugin 0.7

This post has full details on linking prebuilt native libraries into your app for the various architectures as well as information on how to add NDK support directly to the build.gradle script. For the most part, you shouldn't need to do the work around zip and copy anymore.

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

How to generate a QR Code for an Android application?

Have you looked into ZXING? I've been using it successfully to create barcodes. You can see a full working example in the bitcoin application src

// this is a small sample use of the QRCodeEncoder class from zxing
try {
    // generate a 150x150 QR code
    Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);

    if(bm != null) {
        image_view.setImageBitmap(bm);
    }
} catch (WriterException e) { //eek }

How to create a multi line body in C# System.Net.Mail.MailMessage

As per the comment by drris, if IsBodyHtml is set to true then a standard newline could potentially be ignored by design, I know you mention avoiding HTML but try using <br /> instead, even if just to see if this 'solves' the problem - then you can rule out by what you know:

var message = new System.Net.Mail.MailMessage();
message.Body = "First Line <br /> second line";

You may also just try setting IsBodyHtml to false and determining if newlines work in that instance, although, unless you set it to true explicitly I'm pretty sure it defaults to false anyway.

Also as a side note, avoiding HTML in emails is not necessarily any aid in getting the message through spam filters, AFAIK - if anything, the most you do by this is ensure cross-mail-client compatibility in terms of layout. To 'play nice' with spam filters, a number of other things ought to be taken into account; even so much as the subject and content of the mail, who the mail is sent from and where and do they match et cetera. An email simply won't be discriminated against because it is marked up with HTML.

Generate list of all possible permutations of a string

You might look at "Efficiently Enumerating the Subsets of a Set", which describes an algorithm to do part of what you want - quickly generate all subsets of N characters from length x to y. It contains an implementation in C.

For each subset, you'd still have to generate all the permutations. For instance if you wanted 3 characters from "abcde", this algorithm would give you "abc","abd", "abe"... but you'd have to permute each one to get "acb", "bac", "bca", etc.

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

What is the best way to get the count/length/size of an iterator?

You will always have to iterate. Yet you can use Java 8, 9 to do the counting without looping explicitely:

Iterable<Integer> newIterable = () -> iter;
long count = StreamSupport.stream(newIterable.spliterator(), false).count();

Here is a test:

public static void main(String[] args) throws IOException {
    Iterator<Integer> iter = Arrays.asList(1, 2, 3, 4, 5).iterator();
    Iterable<Integer> newIterable = () -> iter;
    long count = StreamSupport.stream(newIterable.spliterator(), false).count();
    System.out.println(count);
}

This prints:

5

Interesting enough you can parallelize the count operation here by changing the parallel flag on this call:

long count = StreamSupport.stream(newIterable.spliterator(), *true*).count();

Can I display the value of an enum with printf()?

I had the same problem.

I had to print the color of the nodes where the color was: enum col { WHITE, GRAY, BLACK }; and the node: typedef struct Node { col color; };

I tried to print node->color with printf("%s\n", node->color); but all I got on the screen was (null)\n.

The answer bmargulies gave almost solved the problem.

So my final solution is:

static char *enumStrings[] = {"WHITE", "GRAY", "BLACK"};
printf("%s\n", enumStrings[node->color]);

How to generate all permutations of a list?

There's a function in the standard-library for this: itertools.permutations.

import itertools
list(itertools.permutations([1, 2, 3]))

If for some reason you want to implement it yourself or are just curious to know how it works, here's one nice approach, taken from http://code.activestate.com/recipes/252178/:

def all_perms(elements):
    if len(elements) <=1:
        yield elements
    else:
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                # nb elements[0:1] works in both string and list contexts
                yield perm[:i] + elements[0:1] + perm[i:]

A couple of alternative approaches are listed in the documentation of itertools.permutations. Here's one:

def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

And another, based on itertools.product:

def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

How to convert a string or integer to binary in Ruby?

If you are looking for a Ruby class/method I used this, and I have also included the tests:

class Binary
  def self.binary_to_decimal(binary)
    binary_array = binary.to_s.chars.map(&:to_i)
    total = 0

    binary_array.each_with_index do |n, i|
      total += 2 ** (binary_array.length-i-1) * n
    end
    total
   end
end

class BinaryTest < Test::Unit::TestCase
  def test_1
   test1 = Binary.binary_to_decimal(0001)
   assert_equal 1, test1
  end

 def test_8
    test8 = Binary.binary_to_decimal(1000)
    assert_equal 8, test8
 end

 def test_15
    test15 = Binary.binary_to_decimal(1111)
    assert_equal 15, test15
 end

 def test_12341
    test12341 = Binary.binary_to_decimal(11000000110101)
    assert_equal 12341, test12341
 end
end

Unable to create Android Virtual Device

Had to restart the Eclipse after completing the installation of ARM EABI v7a system image.

Add a border outside of a UIView (instead of inside)

How I placed a border around my UI view (main - SubscriptionAd) in Storyboard is to place it inside another UI view (background - BackgroundAd). The Background UIView has a background colour that matches the border colour i want, and the Main UIView has constraints value 2 from each side.

I will link the background view to my ViewController and then turn the border on and off by changing the background colour.

Image Of Nested UIView with Top View 2px constraints all around, making it smaller than larger

C# find highest array value and index

A succinct one-liner:

var max = anArray.Select((n, i) => (Number: n, Index: i)).Max();

Test case:

var anArray = new int[] { 1, 5, 7, 4, 2 };
var max = anArray.Select((n, i) => (Number: n, Index: i)).Max();
Console.WriteLine($"Maximum number = {max.Number}, on index {max.Index}.");
// Maximum number = 7, on index 2.

Features:

  • Uses Linq (not as optimized as vanilla, but the trade-off is less code).
  • Does not need to sort.
  • Computational complexity: O(n).
  • Space complexity: O(n).

Remarks:

  • Make sure the number (and not the index) is the first element in the tuple because tuple sorting is done by comparing tuple items from left to right.

Calculate business days

Personally, I think this is a cleaner and more concise solution:

function onlyWorkDays( $d ) {
    $holidays = array('2013-12-25','2013-12-31','2014-01-01','2014-01-20','2014-02-17','2014-05-26','2014-07-04','2014-09-01','2014-10-13','2014-11-11','2014-11-27','2014-12-25','2014-12-31');
    while (in_array($d->format("Y-m-d"), $holidays)) { // HOLIDAYS
        $d->sub(new DateInterval("P1D"));
    }
    if ($d->format("w") == 6) { // SATURDAY
        $d->sub(new DateInterval("P1D"));
    }
    if ($d->format("w") == 0) { // SUNDAY
        $d->sub(new DateInterval("P2D"));
    }
    return $d;
}

Just send the proposed new date to this function.

How do I increase the scrollback buffer in a running screen session?

As Already mentioned we have two ways!

 Per screen (session) interactive setting

And it's done interactively! And take effect immediately!

CTRL + A followed by : And we type scrollback 1000000 And hit ENTER

You detach from the screen and come back! It will be always the same.

You open another new screen! And the value is reset again to default! So it's not a global setting!

 And the permanent default setting

Which is done by adding defscrollback 1000000 to .screenrc (in home)

defscrollback and not scrollback (def stand for default)

What you need to know is if the file is not created ! You create it !

> cd ~ && vim .screenrc

And you add defscrollback 1000000 to it!

Or in one command

> echo "defscrollback 1000000" >> .screenrc

(if not created already)

Taking effect

When you add the default to .screenrc! The already running screen at re-attach will not take effect! The .screenrc run at the screen creation! And it make sense! Just as with a normal console and shell launch!

And all the new created screens will have the set value!

Checking the screen effective buffer size

To check type CTRL + A followed by i

And The result will be as

enter image description here

Importantly the buffer size is the number after the + sign
(in the illustration i set it to 1 000 000)

Note too that when you change it interactively! The effect is immediate and take over the default value!

Scrolling

CTRL+ A followed by ESC (to enter the copy mode).

Then navigate with Up,Down or PgUp PgDown

And ESC again to quit that mode.

(Extra info: to copy hit ENTER to start selecting! Then ENTER again to copy! Simple and cool)

Now the buffer is bigger!

And that's sum it up for the important details!

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

I used com.android.support.constraint:constraint-layout:1.0.0-alpha2 with classpath 'com.android.tools.build:gradle:2.1.0', it worked like charm.

java.lang.NoClassDefFoundError: Could not initialize class XXX

I had the same exception - but only while running in debug mode, this is how I solved the problem (after 3 whole days): in the build.gradle i had : "multiDexEnabled true" set in the defaultConfig section.

        defaultConfig {
    applicationId "com.xxx.yyy"
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 5123
    versionName "5123"
    // Enabling multidex support.
    multiDexEnabled true
}

but apparently this wasn't enough. but when i changed:

public class MyAppClass  extends Application 

to:

public class MyAppClass  extends MultiDexApplication 

this solved it. hope this will help someone

How to correctly save instance state of Fragments in back stack?

Thanks to DroidT, I made this:

I realize that if the Fragment does not execute onCreateView(), its view is not instantiated. So, if the fragment on back stack did not create its views, I save the last stored state, otherwise I build my own bundle with the data I want to save/restore.

1) Extend this class:

import android.os.Bundle;
import android.support.v4.app.Fragment;

public abstract class StatefulFragment extends Fragment {

    private Bundle savedState;
    private boolean saved;
    private static final String _FRAGMENT_STATE = "FRAGMENT_STATE";

    @Override
    public void onSaveInstanceState(Bundle state) {
        if (getView() == null) {
            state.putBundle(_FRAGMENT_STATE, savedState);
        } else {
            Bundle bundle = saved ? savedState : getStateToSave();

            state.putBundle(_FRAGMENT_STATE, bundle);
        }

        saved = false;

        super.onSaveInstanceState(state);
    }

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        if (state != null) {
            savedState = state.getBundle(_FRAGMENT_STATE);
        }
    }

    @Override
    public void onDestroyView() {
        savedState = getStateToSave();
        saved = true;

        super.onDestroyView();
    }

    protected Bundle getSavedState() {
        return savedState;
    }

    protected abstract boolean hasSavedState();

    protected abstract Bundle getStateToSave();

}

2) In your Fragment, you must have this:

@Override
protected boolean hasSavedState() {
    Bundle state = getSavedState();

    if (state == null) {
        return false;
    }

    //restore your data here

    return true;
}

3) For example, you can call hasSavedState in onActivityCreated:

@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);

    if (hasSavedState()) {
        return;
    }

    //your code here
}

How can I delay a method call for 1 second?

You could also use a block

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [object method]; 
});

Most of time you will want to use dispatch_get_main_queue, although if there is no UI in the method you could use a global queue.

Edit:

Swift 3 version:

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    object.method()
}

Equally, DispatchQueue.global().asyncAfter(... might also be a good option.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.

How to select bottom most rows?

All you need to do is reverse your ORDER BY. Add or remove DESC to it.

Got a NumberFormatException while trying to parse a text file for objects

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

Fastest way to list all primes below N

If you have control over N, the very fastest way to list all primes is to precompute them. Seriously. Precomputing is a way overlooked optimization.

Python: How do I make a subclass from a superclass?

class MySubClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

        # <the rest of your custom initialization code goes here>

The section on inheritance in the python documentation explains it in more detail

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

dynamic_cast and static_cast in C++

dynamic_cast uses RTTI. It can slow down your application, you can use modification of the visitor design pattern to achieve downcasting without RTTI http://arturx64.github.io/programming-world/2016/02/06/lazy-visitor.html

COPYing a file in a Dockerfile, no such file or directory?

Seems that the commands:

docker build -t imagename .

and:

docker build -t imagename - < Dockerfile2

are not executed the same way. If you want to build 2 docker images from within one folder with Dockerfile and Dockerfile2, the COPY command cannot be used in the second example using stdin (< Dockerfile2). Instead you have to use:

docker build -t imagename -f Dockerfile2 .

Then COPY does work as expected.

How to darken a background using CSS?

when you want to brightness or darker of background-color, you can use this css code

.brighter-span {
  filter: brightness(150%);
}

.darker-span {
  filter: brightness(50%);
}

What is meant with "const" at end of function declaration?

I always find it conceptually easier to think of that you are making the this pointer const (which is pretty much what it does).

Sqlite in chrome

You might be able to make use of sql.js.

sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten. no C bindings or node-gyp compilation here.

<script src='js/sql.js'></script>
<script>
    //Create the database
    var db = new SQL.Database();
    // Run a query without reading the results
    db.run("CREATE TABLE test (col1, col2);");
    // Insert two rows: (1,111) and (2,222)
    db.run("INSERT INTO test VALUES (?,?), (?,?)", [1,111,2,222]);

    // Prepare a statement
    var stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
    stmt.getAsObject({$start:1, $end:1}); // {col1:1, col2:111}

    // Bind new values
    stmt.bind({$start:1, $end:2});
    while(stmt.step()) { //
        var row = stmt.getAsObject();
        // [...] do something with the row of result
    }
</script>

sql.js is a single JavaScript file and is about 1.5MiB in size currently. While this could be a problem in a web-page, the size is probably acceptable for an extension.

How to remove all the occurrences of a char in c++ string

string RemoveChar(string str, char c) 
{
   string result;
   for (size_t i = 0; i < str.size(); i++) 
   {
          char currentChar = str[i];
          if (currentChar != c)
              result += currentChar;
   }
       return result;
}

This is how I did it.

Or you could do as Antoine mentioned:

See this question which answers the same problem. In your case:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

Subset data to contain only columns whose names match a condition

Using dplyr you can:

df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))

How do I concatenate two lists in Python?

A really concise way to combine a list of lists is

list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
reduce(list.__add__, list_of_lists)

which gives us

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Windows Batch Files: if else

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

Algorithm to calculate the number of divisors of a given number

Try something along these lines:

int divisors(int myNum) {
    int limit = myNum;
    int divisorCount = 0;
    if (x == 1) 
        return 1;
    for (int i = 1; i < limit; ++i) {
        if (myNum % i == 0) {
            limit = myNum / i;
            if (limit != i)
                divisorCount++;
            divisorCount++;
        }
    }
    return divisorCount;
}

Non-Static method cannot be referenced from a static context with methods and variables

Merely for the purposes of making your program work, take the contents of your main() method and put them in a constructor:

public BookStoreApp2()
{
   // Put contents of main method here
}

Then, in your main() method. Do this:

public void main( String[] args )
{
  new BookStoreApp2();
}

Convert Little Endian to Big Endian

You could do this:

int x = 0x12345678;

x = ( x >> 24 ) | (( x << 8) & 0x00ff0000 )| ((x >> 8) & 0x0000ff00) | ( x << 24)  ; 

printf("value = %x", x);  // x will be printed as 0x78563412

Curly braces in string in PHP

I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}

How do I attach events to dynamic HTML elements with jQuery?

You want to use the live() function. See the docs.

For example:

$("#anchor1").live("click", function() {
    $("#anchor1").append('<a class="myclass" href="#">test4</a>');
});

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

Update 24.3.2016

I have found this guide from VP https://knowhow.visual-paradigm.com/technical-support/running-vp-in-android-studio/ created on September 8, 2015.

Good to know - it is possible to integrate VP into Android studio (in my case 1.5.1) now. Do not forget to backup your Android Studio settings (you can find them in Users%userName/.AndroidStudioX.X on Windows) ahead of installation.

I was trying to make it work, but created vp project did not contain any diagrams. Maybe someone else will have more luck.


I was using this manual http://www.visual-paradigm.com/support/documents/vpuserguide/2381/2385/66578_creatingauml.html to make Visual Paradigm working in Android studio, but action in 2. did not invoke dialogue in 3. So I Have asked Visual Paradigm support for help and they replied that Android Studio integration is not supported right now.

Reply from Visual paradigm reply from Apr 17 2015:

Thank you for your inquiry and I'm very sorry that at the moment we only support integrate with the standard IntelliJ IDEA, but not integrate with the Android Studio. We may consider to support it in our future release, and I'll keep you post once there any update on this topics. Feel free to contact me for any questions and wish you have a good day!

This post was deleted, so I will try to make it more clear.

As such I am considering previous answers as misleading and not useful. Therefore I thing that it is important for others to know that, before they lose their time trying to make it working.

A completely free agile software process tool

One possibility would be to use a Google Drawing, part of Google Drive, if you want a more visual and easy-to-edit option. You can create the cards by grouping a color-filled rectangle and one or more text fields together. Being a sufficiently free-form online vector drawing program, it doesn't really limit your possibilities like if you use a more dedicated solution.

The only real downsides are that you have to first create the building blocks from the beginning, and don't get numerical statistics like with a more structured tool.

High Quality Image Scaling Library

You can try dotImage, one of my company's products, which includes an object for resampling images that has 18 filter types for various levels of quality.

Typical usage is:

// BiCubic is one technique available in PhotoShop
ResampleCommand resampler = new ResampleCommand(newSize, ResampleMethod.BiCubic);
AtalaImage newImage = resampler.Apply(oldImage).Image;

in addition, dotImage includes 140 some odd image processing commands including many filters similar to those in PhotoShop, if that's what you're looking for.

Where do I configure log4j in a JUnit test class?

I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

node.js execute system command synchronously

See execSync library.

It's fairly easy to do with node-ffi. I wouldn't recommend for server processes, but for general development utilities it gets things done. Install the library.

npm install node-ffi

Example script:

var FFI = require("node-ffi");
var libc = new FFI.Library(null, {
  "system": ["int32", ["string"]]
});

var run = libc.system;
run("echo $USER");

[EDIT Jun 2012: How to get STDOUT]

var lib = ffi.Library(null, {
    // FILE* popen(char* cmd, char* mode);
    popen: ['pointer', ['string', 'string']],

    // void pclose(FILE* fp);
    pclose: ['void', [ 'pointer']],

    // char* fgets(char* buff, int buff, in)
    fgets: ['string', ['string', 'int','pointer']]
});

function execSync(cmd) {
  var
    buffer = new Buffer(1024),
    result = "",
    fp = lib.popen(cmd, 'r');

  if (!fp) throw new Error('execSync error: '+cmd);

  while(lib.fgets(buffer, 1024, fp)) {
    result += buffer.readCString();
  };
  lib.pclose(fp);

  return result;
}

console.log(execSync('echo $HOME'));

delete all from table

This is deletes the table table_name.

Replace it with the name of the table, which shall be deleted.

DELETE FROM table_name;

Conversion from Long to Double in Java

Simple casting?

double d = (double)15552451L;

MSVCP120d.dll missing

I have found myself wasting time searching for a solution on this, and i suspect doing it again in future. So here's a note to myself and others who might find this useful.

If MSVCP120.DLL is missing, that means you have not installed Visual C++ Redistributable Packages for Visual Studio 2013 (x86 and x64). Install that, restart and you should find this file in c:\Windows\System32 .

Now if MSVCP120D.DLL is missing, this means that the application you are trying to run is built in Debug mode. As OP has mentioned, the debug version of the runtime is NOT distributable.

So what do we do?

Well, there is one option that I know of: Go to your Project's Debug configuration > C/C++ > Code Generation > Runtime Library and select Multi-threaded Debug (/MTd). This will statically link MSVCP120D.dll into your executable.

There is also a quick-fix if you just want to get something up quickly: Copy the MSVCP120D.DLL from sys32 (mine is C:\Windows\System32) folder. You may also need MSVCR120D.DLL.

Addendum to the quick fix: To reduce guesswork, you can use dependency walker. Open your application with dependency walker, and you'll see what dll files are needed.

For example, my recent application was built in Visual Studio 2015 (Windows 10 64-bit machine) and I am targeting it to a 32-bit Windows XP machine. Using dependency walker, my application (see screenshot) needs the following files:

  • opencv_*.dll <-- my own dll files (might also have dependency)
  • msvcp140d.dll <-- SysWOW64\msvcp140d.dll
  • kernel32.dll <-- SysWOW64\kernel32.dll
  • vcruntime140d.dll <-- SysWOW64\vcruntime140d.dll
  • ucrtbased.dll <-- SysWOW64\ucrtbased.dll

Aside from the opencv* files that I have built, I would also need to copy the system files from C:\Windows\SysWow64 (System32 for 32-bit).

You're welcome. :-)

TypeError: 'NoneType' object has no attribute '__getitem__'

move.CompleteMove() does not return a value (perhaps it just prints something). Any method that does not return a value returns None, and you have assigned None to self.values.

Here is an example of this:

>>> def hello(x):
...    print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>

You'll note y doesn't print anything, because its None (the only value that doesn't print anything on the interactive prompt).

maven compilation failure

Add <sourceDirectory>src</sourceDirectory> in your pom.xml with proper reference. Adding this solved my problem

Android Left to Right slide animation

I was not able to find any solution for this type of animation using ViewPropertyAnimator.

Here's an example:

Layout:

<FrameLayout
android:id="@+id/child_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/child_view"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
    />
</FrameLayout>

Animate - Right to left and exit view:

final childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.animate()
  .translationXBy(-containerView.getWidth())
  .setDuration(TRANSLATION_DURATION)
  .setInterpolator(new AccelerateDecelerateInterpolator())
  .setListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        childView.setVisibility(View.GONE);
    }
});

Animate - Right to left enter view:

final View childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.setTranslationX(containerView.getWidth());
childView.animate()
    .translationXBy(-containerView.getWidth())
    .setDuration(TRANSLATION_DURATION)
    .setInterpolator(new AccelerateDecelerateInterpolator())
    .setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationStart(Animator animation) {
            childView.setVisibility(View.VISIBLE);
        }
    });

How to wait for a number of threads to complete?

The join() was not helpful to me. see this sample in Kotlin:

    val timeInMillis = System.currentTimeMillis()
    ThreadUtils.startNewThread(Runnable {
        for (i in 1..5) {
            val t = Thread(Runnable {
                Thread.sleep(50)
                var a = i
                kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
                Thread.sleep(200)
                for (j in 1..5) {
                    a *= j
                    Thread.sleep(100)
                    kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
                }
                kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
            })
            t.start()
        }
    })

The result:

Thread-5|a=5
Thread-1|a=1
Thread-3|a=3
Thread-2|a=2
Thread-4|a=4
Thread-2|2*1=2
Thread-3|3*1=3
Thread-1|1*1=1
Thread-5|5*1=5
Thread-4|4*1=4
Thread-1|2*2=2
Thread-5|10*2=10
Thread-3|6*2=6
Thread-4|8*2=8
Thread-2|4*2=4
Thread-3|18*3=18
Thread-1|6*3=6
Thread-5|30*3=30
Thread-2|12*3=12
Thread-4|24*3=24
Thread-4|96*4=96
Thread-2|48*4=48
Thread-5|120*4=120
Thread-1|24*4=24
Thread-3|72*4=72
Thread-5|600*5=600
Thread-4|480*5=480
Thread-3|360*5=360
Thread-1|120*5=120
Thread-2|240*5=240
Thread-1|TaskDurationInMillis = 765
Thread-3|TaskDurationInMillis = 765
Thread-4|TaskDurationInMillis = 765
Thread-5|TaskDurationInMillis = 765
Thread-2|TaskDurationInMillis = 765

Now let me use the join() for threads:

    val timeInMillis = System.currentTimeMillis()
    ThreadUtils.startNewThread(Runnable {
        for (i in 1..5) {
            val t = Thread(Runnable {
                Thread.sleep(50)
                var a = i
                kotlin.io.println(Thread.currentThread().name + "|" + "a=$a")
                Thread.sleep(200)
                for (j in 1..5) {
                    a *= j
                    Thread.sleep(100)
                    kotlin.io.println(Thread.currentThread().name + "|" + "$a*$j=$a")
                }
                kotlin.io.println(Thread.currentThread().name + "|TaskDurationInMillis = " + (System.currentTimeMillis() - timeInMillis))
            })
            t.start()
            t.join()
        }
    })

And the result:

Thread-1|a=1
Thread-1|1*1=1
Thread-1|2*2=2
Thread-1|6*3=6
Thread-1|24*4=24
Thread-1|120*5=120
Thread-1|TaskDurationInMillis = 815
Thread-2|a=2
Thread-2|2*1=2
Thread-2|4*2=4
Thread-2|12*3=12
Thread-2|48*4=48
Thread-2|240*5=240
Thread-2|TaskDurationInMillis = 1568
Thread-3|a=3
Thread-3|3*1=3
Thread-3|6*2=6
Thread-3|18*3=18
Thread-3|72*4=72
Thread-3|360*5=360
Thread-3|TaskDurationInMillis = 2323
Thread-4|a=4
Thread-4|4*1=4
Thread-4|8*2=8
Thread-4|24*3=24
Thread-4|96*4=96
Thread-4|480*5=480
Thread-4|TaskDurationInMillis = 3078
Thread-5|a=5
Thread-5|5*1=5
Thread-5|10*2=10
Thread-5|30*3=30
Thread-5|120*4=120
Thread-5|600*5=600
Thread-5|TaskDurationInMillis = 3833

As it's clear when we use the join:

  1. The threads are running sequentially.
  2. The first sample takes 765 Milliseconds while the second sample takes 3833 Milliseconds.

Our solution to prevent blocking other threads was creating an ArrayList:

val threads = ArrayList<Thread>()

Now when we want to start a new thread we most add it to the ArrayList:

addThreadToArray(
    ThreadUtils.startNewThread(Runnable {
        ...
    })
)

The addThreadToArray function:

@Synchronized
fun addThreadToArray(th: Thread) {
    threads.add(th)
}

The startNewThread funstion:

fun startNewThread(runnable: Runnable) : Thread {
    val th = Thread(runnable)
    th.isDaemon = false
    th.priority = Thread.MAX_PRIORITY
    th.start()
    return th
}

Check the completion of the threads as below everywhere it's needed:

val notAliveThreads = ArrayList<Thread>()
for (t in threads)
    if (!t.isAlive)
        notAliveThreads.add(t)
threads.removeAll(notAliveThreads)
if (threads.size == 0){
    // The size is 0 -> there is no alive threads.
}

Git credential helper - update password

None of these answers ended up working for my Git credential issue. Here is what did work if anyone needs it (I'm using Git 1.9 on Windows 8.1).

To update your credentials, go to Control PanelCredential ManagerGeneric Credentials. Find the credentials related to your Git account and edit them to use the updated password.

Reference: How to update your Git credentials on Windows

Note that to use the Windows Credential Manager for Git you need to configure the credential helper like so:

git config --global credential.helper wincred

If you have multiple GitHub accounts that you use for different repositories, then you should configure credentials to use the full repository path (rather than just the domain, which is the default):

git config --global credential.useHttpPath true

How to convert Strings to and from UTF8 byte arrays in Java

You can convert directly via the String(byte[], String) constructor and getBytes(String) method. Java exposes available character sets via the Charset class. The JDK documentation lists supported encodings.

90% of the time, such conversions are performed on streams, so you'd use the Reader/Writer classes. You would not incrementally decode using the String methods on arbitrary byte streams - you would leave yourself open to bugs involving multibyte characters.

NSURLSession/NSURLConnection HTTP load failed on iOS 9

You can try add this function in file RCTHTTPRequestHandler.m

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]); }

How to create user for a db in postgresql?

From CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q

PHP (as tested on localhost, it works as expected):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);

Get Android Phone Model programmatically

For whom who looking for full list of properties of Build here is an example for Sony Z1 Compact:

Build.BOARD = MSM8974
Build.BOOTLOADER = s1
Build.BRAND = Sony
Build.CPU_ABI = armeabi-v7a
Build.CPU_ABI2 = armeabi
Build.DEVICE = D5503
Build.DISPLAY = 14.6.A.1.236
Build.FINGERPRINT = Sony/D5503/D5503:5.1.1/14.6.A.1.236/2031203XXX:user/release-keys
Build.HARDWARE = qcom
Build.HOST = BuildHost
Build.ID = 14.6.A.1.236
Build.IS_DEBUGGABLE = false
Build.MANUFACTURER = Sony
Build.MODEL = D5503
Build.PRODUCT = D5503
Build.RADIO = unknown
Build.SERIAL = CB5A1YGVMT
Build.SUPPORTED_32_BIT_ABIS = [Ljava.lang.String;@3dd90541
Build.SUPPORTED_64_BIT_ABIS = [Ljava.lang.String;@1da4fc3
Build.SUPPORTED_ABIS = [Ljava.lang.String;@525f635
Build.TAGS = release-keys
Build.TIME = 144792559XXXX
Build.TYPE = user
Build.UNKNOWN = unknown
Build.USER = BuildUser

You can easily list those properties for your device in debug mode using "evaluate expression" dialog using kotlin:

android.os.Build::class.java.fields.map { "Build.${it.name} = ${it.get(it.name)}"}.joinToString("\n")

How to re-enable right click so that I can inspect HTML elements in Chrome?

you can use following code for re-enable mouse right click.

document.oncontextmenu = function(){}

and you can use shortcut key (Ctrl+Shift+i) to open inspect elements in chrome in windows OS.

What is the Difference Between read() and recv() , and Between send() and write()?

Another thing on linux is:

send does not allow to operate on non-socket fd. Thus, for example to write on usb port, write is necessary.

How to export JavaScript array info to csv (on client side)?

Old question with many good answers, but here is another simple option that relies on two popular libraries to get it done. Some answers mention Papa Parse but roll their own solution for the download part. Combining Papa Parse and FileSaver.js, you can try the following:

const dataString = Papa.unparse(data, config);
const blob = new Blob([dataString], { type: 'text/csv;charset=utf-8' });
FileSaver.saveAs(blob, 'myfile.csv');

The config options for unparse are described here.

Bubble Sort Homework

This is what happens when you use variable name of negative meaning, you need to invert their values. The following would be easier to understand:

sorted = False
while not sorted:
    ...

On the other hand, the logic of the algorithm is a little bit off. You need to check whether two elements swapped during the for loop. Here's how I would write it:

def bubble(values):
    length = len(values) - 1
    sorted = False
    while not sorted:
        sorted = True
        for element in range(0,length):
            if values[element] > values[element + 1]:
                 hold = values[element + 1]
                 values[element + 1] = values[element]
                 values[element] = hold
                 sorted = False
    return values

Changing the resolution of a VNC session in linux

I have a simple idea, something like this:

#!/bin/sh

echo `xrandr --current | grep current | awk '{print $8}'` >> RES1
echo `xrandr --current | grep current | awk '{print $10}'` >> RES2
cat RES2 | sed -i 's/,//g' RES2

P1RES=$(cat RES1)
P2RES=$(cat RES2)
rm RES1 RES2
echo "$P1RES"'x'"$P2RES" >> RES
RES=$(cat RES)

# Play The Game

# Finish The Game with Lower Resolution

xrandr -s $RES

Well, I need a better solution for all display devices under Linux and Similars S.O

Getting only Month and Year from SQL DATE

I had a specific requirement to do something similar where it would show month-year which can be done by the following:

SELECT DATENAME(month, GETDATE()) + '-' + CAST(YEAR(GETDATE()) AS nvarchar) AS 'Month-Year'

In my particular case, I needed to have it down to the 3 letter month abreviation with a 2 digit year, looking something like this: SELECT LEFT(DATENAME(month, GETDATE()), 3) + '-' + CAST(RIGHT(YEAR(GETDATE()),2) AS nvarchar(2)) AS 'Month-Year'

how to compare the Java Byte[] array?

Use Arrays.equals() if you want to compare the actual content of arrays that contain primitive types values (like byte).

System.out.println(Arrays.equals(aa, bb));

Use Arrays.deepEquals for comparison of arrays that contain objects.

How to exclude file only from root folder in Git

From the documentation:

If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).

A leading slash matches the beginning of the pathname. For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".

So you should add the following line to your root .gitignore:

/config.php

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

How to get the response of XMLHttpRequest?

You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.

Here's an example (not compatible with IE6/7).

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.

$.get('http://example.com', function(responseText) {
    alert(responseText);
});

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

How do I position one image on top of another in HTML?

Ok, after some time, here's what I landed on:

_x000D_
_x000D_
.parent {_x000D_
  position: relative;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.image1 {_x000D_
  position: relative;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  border: 1px red solid;_x000D_
}_x000D_
.image2 {_x000D_
  position: absolute;_x000D_
  top: 30px;_x000D_
  left: 30px;_x000D_
  border: 1px green solid;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <img class="image1" src="https://placehold.it/50" />_x000D_
  <img class="image2" src="https://placehold.it/100" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

As the simplest solution. That is:

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

Applying CSS styles to all elements inside a DIV

If you're looking for a shortcut for writing out all of your selectors, then a CSS Preprocessor (Sass, LESS, Stylus, etc.) can do what you're looking for. However, the generated styles must be valid CSS.

Sass:

#applyCSS {
    .ui-bar-a {
       color: blue;
    }
    .ui-bar-a .ui-link-inherit {
       color: orange;
    }
    background: #CCC;
}

Generated CSS:

#applyCSS {
  background: #CCC;
}

#applyCSS .ui-bar-a {
  color: blue;
}

#applyCSS .ui-bar-a .ui-link-inherit {
  color: orange;
}

Inconsistent Accessibility: Parameter type is less accessible than method

You can get Parameter (class that have less accessibility) as object then convert it to your class by as keyword.

C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>


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

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

What is the definition of "interface" in object oriented programming

An interface is one of the more overloaded and confusing terms in development.

It is actually a concept of abstraction and encapsulation. For a given "box", it declares the "inputs" and "outputs" of that box. In the world of software, that usually means the operations that can be invoked on the box (along with arguments) and in some cases the return types of these operations.

What it does not do is define what the semantics of these operations are, although it is commonplace (and very good practice) to document them in proximity to the declaration (e.g., via comments), or to pick good naming conventions. Nevertheless, there are no guarantees that these intentions would be followed.

Here is an analogy: Take a look at your television when it is off. Its interface are the buttons it has, the various plugs, and the screen. Its semantics and behavior are that it takes inputs (e.g., cable programming) and has outputs (display on the screen, sound, etc.). However, when you look at a TV that is not plugged in, you are projecting your expected semantics into an interface. For all you know, the TV could just explode when you plug it in. However, based on its "interface" you can assume that it won't make any coffee since it doesn't have a water intake.

In object oriented programming, an interface generally defines the set of methods (or messages) that an instance of a class that has that interface could respond to.

What adds to the confusion is that in some languages, like Java, there is an actual interface with its language specific semantics. In Java, for example, it is a set of method declarations, with no implementation, but an interface also corresponds to a type and obeys various typing rules.

In other languages, like C++, you do not have interfaces. A class itself defines methods, but you could think of the interface of the class as the declarations of the non-private methods. Because of how C++ compiles, you get header files where you could have the "interface" of the class without actual implementation. You could also mimic Java interfaces with abstract classes with pure virtual functions, etc.

An interface is most certainly not a blueprint for a class. A blueprint, by one definition is a "detailed plan of action". An interface promises nothing about an action! The source of the confusion is that in most languages, if you have an interface type that defines a set of methods, the class that implements it "repeats" the same methods (but provides definition), so the interface looks like a skeleton or an outline of the class.

How to create JSON string in C#

Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?

laravel 5 : Class 'input' not found

It is Input and not input. This commit removed Input facade definition from config/app.php hence you have to manually add that in to aliases array as below,

'Input' => Illuminate\Support\Facades\Input::class,

Or You can import Input facade directly as required,

use Illuminate\Support\Facades\Input;

How to set $_GET variable

You could use the following code to redirect your client to a script with the _GET variables attached.

header("Location: examplepage.php?var1=value&var2=value");
die();

This will cause the script to redirect, make sure the die(); is kept in there, or they may not redirect.

How to highlight text using javascript

Using the surroundContents() method on the Range type. Its only argument is an element which will wrap that Range.

function styleSelected() {
  bg = document.createElement("span");
  bg.style.backgroundColor = "yellow";
  window.getSelection().getRangeAt(0).surroundContents(bg);
}

Error: " 'dict' object has no attribute 'iteritems' "

In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.

sql try/catch rollback/commit - preventing erroneous commit after rollback

I used below ms sql script pattern several times successfully which uses Try-Catch,Commit Transaction- Rollback Transaction,Error Tracking.

Your TRY block will be as follows

 BEGIN TRY
 BEGIN TRANSACTION T
 ----
 //your script block
 ----
 COMMIT TRANSACTION T 
 END TRY

Your CATCH block will be as follows

BEGIN CATCH
DECLARE @ErrMsg NVarChar(4000), 
        @ErrNum Int, 
        @ErrSeverity Int, 
        @ErrState Int, 
        @ErrLine Int, 
        @ErrProc NVarChar(200)
 SELECT @ErrNum = Error_Number(), 
       @ErrSeverity = Error_Severity(), 
       @ErrState = Error_State(), 
       @ErrLine = Error_Line(), 
       @ErrProc = IsNull(Error_Procedure(), '-')
 SET @ErrMsg = N'ErrLine: ' + rtrim(@ErrLine) + ', proc: ' + RTRIM(@ErrProc) + ', 
       Message: '+ Error_Message()

Your ROLLBACK script will be part of CATCH block as follows

IF (@@TRANCOUNT) > 0 
BEGIN
PRINT 'ROLLBACK: ' + SUBSTRING(@ErrMsg,1,4000)
ROLLBACK TRANSACTION T
END
ELSE
BEGIN
PRINT SUBSTRING(@ErrMsg,1,4000);   
END

END CATCH

Above different script blocks you need to use as one block. If any error happens in the TRY block it will go the the CATCH block. There it is setting various details about the error number,error severity,error line ..etc. At last all these details will get append to @ErrMsg parameter. Then it will check for the count of transaction (@@TRANCOUNT >0) , ie if anything is there in the transaction for rollback. If it is there then show the error message and ROLLBACK TRANSACTION. Otherwise simply print the error message.

We have kept our COMMIT TRANSACTION T script towards the last line of TRY block in order to make sure that it should commit the transaction(final change in the database) only after all the code in the TRY block has run successfully.

Exit while loop by user hitting ENTER key

The following works from me:

i = '0'
while len(i) != 0:
    i = list(map(int, input(),split()))

Getting number of elements in an iterator in Python

I like the cardinality package for this, it is very lightweight and tries to use the fastest possible implementation available depending on the iterable.

Usage:

>>> import cardinality
>>> cardinality.count([1, 2, 3])
3
>>> cardinality.count(i for i in range(500))
500
>>> def gen():
...     yield 'hello'
...     yield 'world'
>>> cardinality.count(gen())
2

The actual count() implementation is as follows:

def count(iterable):
    if hasattr(iterable, '__len__'):
        return len(iterable)

    d = collections.deque(enumerate(iterable, 1), maxlen=1)
    return d[0][0] if d else 0

Moving from one activity to another Activity in Android

public void onClick(View v)
{
 startActivity(new Intent(getApplicationContext(), Next.class));

}

it is direct way to move second activity and there is no need for call intent

UTF-8: General? Bin? Unicode?

Accepted answer is outdated.

If you use MySQL 5.5.3+, use utf8mb4_unicode_ci instead of utf8_unicode_ci to ensure the characters typed by your users won't give you errors.

utf8mb4 supports emojis for example, whereas utf8 might give you hundreds of encoding-related bugs like:

Incorrect string value: ‘\xF0\x9F\x98\x81…’ for column ‘data’ at row 1

Add a custom attribute to a Laravel / Eloquent model on load?

The problem is caused by the fact that the Model's toArray() method ignores any accessors which do not directly relate to a column in the underlying table.

As Taylor Otwell mentioned here, "This is intentional and for performance reasons." However there is an easy way to achieve this:

class EventSession extends Eloquent {

    protected $table = 'sessions';
    protected $appends = array('availability');

    public function getAvailabilityAttribute()
    {
        return $this->calculateAvailability();  
    }
}

Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.

Old answer (for Laravel versions < 4.08):

The best solution that I've found is to override the toArray() method and either explicity set the attribute:

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        $array['upper'] = $this->upper;
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

or, if you have lots of custom accessors, loop through them all and apply them:

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
    {
        $array = parent::toArray();
        foreach ($this->getMutatedAttributes() as $key)
        {
            if ( ! array_key_exists($key, $array)) {
                $array[$key] = $this->{$key};   
            }
        }
        return $array;
    }

    public function getUpperAttribute()
    {
        return strtoupper($this->title);    
    }

}

Iterate through the fields of a struct in Go

If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground

Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

How to define a preprocessor symbol in Xcode

You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png

If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.

Valid to use <a> (anchor tag) without href attribute?

Yes, it is valid to use the anchor tag without a href attribute.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

Yes, you can use class and other attributes, but you can not use target, download, rel, hreflang, and type.

The target, download, rel, hreflang, and type attributes must be omitted if the href attribute is not present.

As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a> without href. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.

Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link).

Source: W3C HTML5 Recommendation

Round number to nearest integer

I use and may advise the following solution (python3.6):

y = int(x + (x % (1 if x >= 0 else -1)))

It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):

round_methods = [lambda x: int(round(x)), 
                 lambda x: int(x + (x % (1 if x >= 0 else -1))),
                 lambda x: np.rint(x).astype(int),
                 lambda x: int(proper_round(x))]

for rm in round_methods:
    %timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

for rm in round_methods:
    print(rm(112.4), rm(112.5), rm(112.6))
    print(rm(-12.4), rm(-12.5), rm(-12.6))
    print('=' * 11)

Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========

Passing a variable to a powershell script via command line

Declare the parameter in test.ps1:

 Param(
                [Parameter(Mandatory=$True,Position=1)]
                [string]$input_dir,
                [Parameter(Mandatory=$True)]
                [string]$output_dir,
                [switch]$force = $false
                )

Run the script from Run OR Windows Task Scheduler:

powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

or,

 powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

How to loop through an array containing objects and access their properties

Here's an example on how you can do it :)

_x000D_
_x000D_
var students = [{_x000D_
    name: "Mike",_x000D_
    track: "track-a",_x000D_
    achievements: 23,_x000D_
    points: 400,_x000D_
  },_x000D_
  {_x000D_
    name: "james",_x000D_
    track: "track-a",_x000D_
    achievements: 2,_x000D_
    points: 21,_x000D_
  },_x000D_
]_x000D_
_x000D_
students.forEach(myFunction);_x000D_
_x000D_
function myFunction(item, index) {_x000D_
  for (var key in item) {_x000D_
    console.log(item[key])_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Hexadecimal value 0x00 is a invalid character

As kind of a late answer:

I've had this problem with SSRS ReportService2005.asmx when uploading a report.

    Public Shared Sub CreateReport(ByVal strFileNameAndPath As String, ByVal strReportName As String, ByVal strReportingPath As String, Optional ByVal bOverwrite As Boolean = True)
        Dim rs As SSRS_2005_Administration_WithFOA = New SSRS_2005_Administration_WithFOA
        rs.Credentials = ReportingServiceInterface.GetMyCredentials(strCredentialsURL)
        rs.Timeout = ReportingServiceInterface.iTimeout
        rs.Url = ReportingServiceInterface.strReportingServiceURL
        rs.UnsafeAuthenticatedConnectionSharing = True

        Dim btBuffer As Byte() = Nothing

        Dim rsWarnings As Warning() = Nothing
        Try
            Dim fstrStream As System.IO.FileStream = System.IO.File.OpenRead(strFileNameAndPath)
            btBuffer = New Byte(fstrStream.Length - 1) {}
            fstrStream.Read(btBuffer, 0, CInt(fstrStream.Length))
            fstrStream.Close()
        Catch ex As System.IO.IOException
            Throw New Exception(ex.Message)
        End Try

        Try
            rsWarnings = rs.CreateReport(strReportName, strReportingPath, bOverwrite, btBuffer, Nothing)

            If Not (rsWarnings Is Nothing) Then
                Dim warning As Warning
                For Each warning In rsWarnings
                    Log(warning.Message)
                Next warning
            Else
                Log("Report: {0} created successfully with no warnings", strReportName)
            End If

        Catch ex As System.Web.Services.Protocols.SoapException
            Log(ex.Detail.InnerXml.ToString())
        Catch ex As Exception
            Log("Error at creating report. Invalid server name/timeout?" + vbCrLf + vbCrLf + "Error Description: " + vbCrLf + ex.Message)
            Console.ReadKey()
            System.Environment.Exit(1)
        End Try
    End Sub ' End Function CreateThisReport

The problem occurs when you allocate a byte array that is at least 1 byte larger than the RDL (XML) file.

Specifically, I used a C# to vb.net converter, that converted

  btBuffer = new byte[fstrStream.Length];

into

  btBuffer = New Byte(fstrStream.Length) {}

But because in C# the number denotes the NUMBER OF ELEMENTS in the array, and in VB.NET, that number denotes the UPPER BOUND of the array, I had an excess byte, causing this error.

So the problem's solution is simply:

  btBuffer = New Byte(fstrStream.Length - 1) {}

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

Adding onClick event dynamically using jQuery

$("#bfCaptchaEntry").click(function(){
    myFunction();
});

Activity has leaked window that was originally added

You have to make Progressdialog object in onPreExecute method of AsyncTask and you should dismiss it on onPostExecute method.

npm install gives error "can't find a package.json file"

In my case there was mistake in my package.json:

npm ERR! package.json must be actual JSON, not just JavaScript.

How to perform a sum of an int[] array

int sum = 0;
for(int i = 0; i < A.length; i++){
  sum += A[i];
}

Pass C# ASP.NET array to Javascript array

I came up with this similar situation and I resolved it quiet easily.Here is what I did. Assuming you already have the value in array at your aspx.cs page.

1)Put a hidden field in your aspx page and us the hidden field ID to store the array value.

 HiddenField2.Value = string.Join(",", myarray);

2)Now that the hidden field has the value stored, just separated by commas. Use this hidden field in JavaScript like this. Simply create an array in JavaScript and then store the value in that array by removing the commas.

var hiddenfield2 = new Array();
hiddenfield2=document.getElementById('<%=HiddenField2.ClientID%>').value.split(',');

This should solve your problem.

SELECT data from another schema in oracle

Does the user that you are using to connect to the database (user A in this example) have SELECT access on the objects in the PCT schema? Assuming that A does not have this access, you would get the "table or view does not exist" error.

Most likely, you need your DBA to grant user A access to whatever tables in the PCT schema that you need. Something like

GRANT SELECT ON pct.pi_int
   TO a;

Once that is done, you should be able to refer to the objects in the PCT schema using the syntax pct.pi_int as you demonstrated initially in your question. The bracket syntax approach will not work.

How do I specify local .gem files in my Gemfile?

I would unpack your gem in the application vendor folder

gem unpack your.gem --target /path_to_app/vendor/gems/

Then add the path on the Gemfile to link unpacked gem.

gem 'your', '2.0.1', :path => 'vendor/gems/your'

Switch statement for greater-than/less-than

switch (Math.floor(scrollLeft/1000)) {
  case 0: // (<1000)
   //do stuff
   break;
  case 1: // (>=1000 && <2000)
   //do stuff;
   break;
}

Only works if you have regular steps...

EDIT: since this solution keeps getting upvotes, I must advice that mofolo's solution is a way better

print spaces with String.format()

You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

removing new line character from incoming stream using sed

To remove newlines, use tr:

tr -d '\n'

If you want to replace each newline with a single space:

tr '\n' ' '

The error ba: Event not found is coming from csh, and is due to csh trying to match !ba in your history list. You can escape the ! and write the command:

sed ':a;N;$\!ba;s/\n/ /g'  # Suitable for csh only!!

but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.

Oracle: How to find out if there is a transaction pending?

Matthew Watson can be modified to be used in RAC

select t.inst_id 
       ,s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;

Cookies on localhost with explicit domain

If you're setting a cookie from another domain (ie you set the cookie by making an XHR cross origin request), then you need to make sure you set the withCredentials attribute to true on the XMLHttpRequest you use to fetch the cookie as described here

Assign variable in if condition statement, good practice or not?

You can do assignments within if statements in Java as well. A good example would be reading something in and writing it out:

http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new

The code:

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException 
{
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

Warning :-Presenting view controllers on detached view controllers is discouraged

To avoid getting the warning in a push navigation, you can directly use :

[self.view.window.rootViewController presentViewController:viewController animated:YES completion:nil];

And then in your modal view controller, when everything is finished, you can just call :

[self dismissViewControllerAnimated:YES completion:nil];

Plain Old CLR Object vs Data Transfer Object

DTO classes are used to serialize/deserialize data from different sources. When you want to deserialize a object from a source, does not matter what external source it is: service, file, database etc. you may be only want to use some part of that but you want an easy way to deserialize that data to an object. after that you copy that data to the XModel you want to use. A serializer is a beautiful technology to load DTO objects. Why? you only need one function to load (deserialize) the object.

How to re-render flatlist?

OK.I just found out that if we want the FlatList to know the data change outside of the data prop,we need set it to extraData, so I do it like this now:

<FlatList data={...} extraData={this.state} .../>

refer to : https://facebook.github.io/react-native/docs/flatlist#extradata

Phone validation regex

Try this

\+?\(?([0-9]{3})\)?[-.]?\(?([0-9]{3})\)?[-.]?\(?([0-9]{4})\)?

It matches the following cases

  • +123-(456)-(7890)
  • +123.(456).(7890)
  • +(123).(456).(7890)
  • +(123)-(456)-(7890)
  • +123(456)(7890)
  • +(123)(456)(7890)
  • 123-(456)-(7890)
  • 123.(456).(7890)
  • (123).(456).(7890)
  • (123)-(456)-(7890)
  • 123(456)(7890)
  • (123)(456)(7890)

For further explanation on the pattern CLICKME

MySQL order by before group by

Your solution makes use of an extension to GROUP BY clause that permits to group by some fields (in this case, just post_author):

GROUP BY wp_posts.post_author

and select nonaggregated columns:

SELECT wp_posts.*

that are not listed in the group by clause, or that are not used in an aggregate function (MIN, MAX, COUNT, etc.).

Correct use of extension to GROUP BY clause

This is useful when all values of non-aggregated columns are equal for every row.

For example, suppose you have a table GardensFlowers (name of the garden, flower that grows in the garden):

INSERT INTO GardensFlowers VALUES
('Central Park',       'Magnolia'),
('Hyde Park',          'Tulip'),
('Gardens By The Bay', 'Peony'),
('Gardens By The Bay', 'Cherry Blossom');

and you want to extract all the flowers that grows in a garden, where multiple flowers grow. Then you have to use a subquery, for example you could use this:

SELECT GardensFlowers.*
FROM   GardensFlowers
WHERE  name IN (SELECT   name
                FROM     GardensFlowers
                GROUP BY name
                HAVING   COUNT(DISTINCT flower)>1);

If you need to extract all the flowers that are the only flowers in the garder instead, you could just change the HAVING condition to HAVING COUNT(DISTINCT flower)=1, but MySql also allows you to use this:

SELECT   GardensFlowers.*
FROM     GardensFlowers
GROUP BY name
HAVING   COUNT(DISTINCT flower)=1;

no subquery, not standard SQL, but simpler.

Incorrect use of extension to GROUP BY clause

But what happens if you SELECT non-aggregated columns that are non equal for every row? Which is the value that MySql chooses for that column?

It looks like MySql always chooses the FIRST value it encounters.

To make sure that the first value it encounters is exactly the value you want, you need to apply a GROUP BY to an ordered query, hence the need to use a subquery. You can't do it otherwise.

Given the assumption that MySql always chooses the first row it encounters, you are correcly sorting the rows before the GROUP BY. But unfortunately, if you read the documentation carefully, you'll notice that this assumption is not true.

When selecting non-aggregated columns that are not always the same, MySql is free to choose any value, so the resulting value that it actually shows is indeterminate.

I see that this trick to get the first value of a non-aggregated column is used a lot, and it usually/almost always works, I use it as well sometimes (at my own risk). But since it's not documented, you can't rely on this behaviour.

This link (thanks ypercube!) GROUP BY trick has been optimized away shows a situation in which the same query returns different results between MySql and MariaDB, probably because of a different optimization engine.

So, if this trick works, it's just a matter of luck.

The accepted answer on the other question looks wrong to me:

HAVING wp_posts.post_date = MAX(wp_posts.post_date)

wp_posts.post_date is a non-aggregated column, and its value will be officially undetermined, but it will likely be the first post_date encountered. But since the GROUP BY trick is applied to an unordered table, it is not sure which is the first post_date encountered.

It will probably returns posts that are the only posts of a single author, but even this is not always certain.

A possible solution

I think that this could be a possible solution:

SELECT wp_posts.*
FROM   wp_posts
WHERE  id IN (
  SELECT max(id)
  FROM wp_posts
  WHERE (post_author, post_date) = (
    SELECT   post_author, max(post_date)
    FROM     wp_posts
    WHERE    wp_posts.post_status='publish'
             AND wp_posts.post_type='post'
    GROUP BY post_author
  ) AND wp_posts.post_status='publish'
    AND wp_posts.post_type='post'
  GROUP BY post_author
)

On the inner query I'm returning the maximum post date for every author. I'm then taking into consideration the fact that the same author could theorically have two posts at the same time, so I'm getting only the maximum ID. And then I'm returning all rows that have those maximum IDs. It could be made faster using joins instead of IN clause.

(If you're sure that ID is only increasing, and if ID1 > ID2 also means that post_date1 > post_date2, then the query could be made much more simple, but I'm not sure if this is the case).

OR condition in Regex

Try

\d \w |\d

or add a positive lookahead if you don't want to include the trailing space in the match

\d \w(?= )|\d

When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.

PHP: Split string into array, like explode with no delimiter

What are you trying to accomplish? You can access characters in a string just like an array:

$s = 'abcd';
echo $s[0];

prints 'a'

Create a branch in Git from another branch

Create a Branch

  • Create branch when master branch is checked out. Here commits in master will be synced to the branch you created.

    $ git branch branch1

  • Create branch when branch1 is checked out . Here commits in branch1 will be synced to branch2

    $ git branch branch2


Checkout a Branch

git checkout command switch branches or restore working tree files

  • $ git checkout branchname

Renaming a Branch

  • $ git branch -m branch1 newbranchname

Delete a Branch

  • $ git branch -d branch-to-delete
  • $ git branch -D branch-to-delete ( force deletion without checking the merged status )

Create and Switch Branch

  • $ git checkout -b branchname

Branches that are completely included

  • $ git branch --merged


************************** Branch Differences [ git diff branch1..branch2 ] ************************

Multiline difference
  • $ git diff master..branch1
Singleline difference
  • $ git diff --color-words branch1..branch2

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

How do I do base64 encoding on iOS?

Here's a compact Objective-C version as a Category on NSData. It takes some thinking about...

@implementation NSData (DataUtils)

static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

- (NSString *)newStringInBase64FromData
{
 NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
 unsigned char * working = (unsigned char *)[self bytes];
 int srcLen = [self length];

 // tackle the source in 3's as conveniently 4 Base64 nibbles fit into 3 bytes
 for (int i=0; i<srcLen; i += 3)
 {
  // for each output nibble
  for (int nib=0; nib<4; nib++)
  {
   // nibble:nib from char:byt
   int byt = (nib == 0)?0:nib-1;
   int ix = (nib+1)*2;

   if (i+byt >= srcLen) break;

   // extract the top bits of the nibble, if valid
   unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);

   // extract the bottom bits of the nibble, if valid
   if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);

   [dest appendFormat:@"%c", base64[curr]];
  }
 }

 return dest;
}

@end

Padding can be added if required by making the scope of 'byt' wider and appending 'dest' with (2-byt) "=" characters before returning.

A Category can then be added to NSString, thus:

@implementation NSString (StringUtils)

- (NSString *)newStringInBase64FromString
{
 NSData *theData = [NSData dataWithBytes:[self UTF8String] length:[self length]]; 

 return [theData newStringInBase64FromData];
}

@end

Changing Tint / Background color of UITabBar

Another solution (which is a hack) is to set the alpha on the tabBarController to 0.01 so that it is virtually invisible yet still clickable. Then set a an ImageView control on the bottom of the MainWindow nib with your custom tabbar image underneath the alpha'ed tabBarCOntroller. Then swap the images, change colors or hightlight when the tabbarcontroller switches views.

However, you lose the '...more' and customize functionality.

How do I alter the position of a column in a PostgreSQL database table?

I don't think you can at present: see this article on the Postgresql wiki.

The three workarounds from this article are:

  1. Recreate the table
  2. Add columns and move data
  3. Hide the differences with a view.

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

With the release of Java 5, the product version was made distinct from the developer version as described here

How to export SQL Server 2005 query to CSV

set nocount on

the quotes are there, use -w2000 to keep each row on one line.

Various ways to remove local Git changes

It all depends on exactly what you are trying to undo/revert. Start out by reading the post in Ube's link. But to attempt an answer:

Hard reset

git reset --hard [HEAD]

completely remove all staged and unstaged changes to tracked files.

I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.

Clean

git clean [-f]

Remove files that are not tracked.

For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.

The -f (force) option will also remove files, that are not tracked and are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.

Git clean will not touch files, that are already being tracked.

Checkout "dot"

git checkout .

I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:

"undo all changes in my working tree".

I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.

Stashing

Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.

To sum up

Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using git reset --hard HEAD followed by git clean -f will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. It will wipe everything that has not been committed (except untracked files, in which case, use clean).

All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)

I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use git reset --hard was that you had never staged anything. Had you staged a change, neither git checkout . nor git clean -f would have reverted that.

Hope this covers.

Calling multiple JavaScript functions on a button click

Try this .... I got it... onClientClick="var b=validateView();if(b) var b=ShowDiv1();return b;"

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

Compilation error: stray ‘\302’ in program etc

Change the name of the file.c to some other file423.c. it may be because of the name conflict between c files.

Padding In bootstrap

There are padding built into various classes.

For example:

A asp.net web forms app:

<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />

this code above would place the Text of "Show Deleted" too close to the checkbox to what I see at nice to look at.

However with bootstrap

<div class="checkbox-inline">
    <asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
</div>

This created the space, if you don't want the text bold, that class=checkbox

Bootstrap is very flexible, so in this case I don't need a hack, but sometimes you need to.

How do I get the max and min values from a set of numbers entered?

System.out.print("Enter a Value: ");
val = s.nextInt();

This line is placed in last.The whole code is as follows:-

public static void main(String[] args){
    int min, max;

    Scanner s = new Scanner(System.in);
    System.out.print("Enter a Value: ");
    int val = s.nextInt();
    min = max = val;

    while (val != 0) {
        if (val < min) {
            min = val;
        }
        if (val > max) {
            max = val;
        }
        System.out.print("Enter a Value: ");
        val = s.nextInt();

    }
    System.out.println("Min: " + min);
    System.out.println("Max: " + max);
}

Create a CSS rule / class with jQuery at runtime

This isn't anything new compared to some of the other answers as it uses the concept described here and here, but I wanted to make use of JSON-style declaration:

function addCssRule(rule, css) {
  css = JSON.stringify(css).replace(/"/g, "").replace(/,/g, ";");
  $("<style>").prop("type", "text/css").html(rule + css).appendTo("head");
}

Usage:

addCssRule(".friend a, .parent a", {
  color: "green",
  "font-size": "20px"
});

I'm not sure if it covers all capabilities of CSS, but so far it works for me. If it doesn't, consider it a starting points for your own needs. :)

GROUP BY without aggregate function

Let me give some examples.

Consider this data.

CREATE TABLE DATASET ( VAL1 CHAR ( 1 CHAR ),
                   VAL2 VARCHAR2 ( 10 CHAR ),
                   VAL3 NUMBER );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'b', 'b-details', 2 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'a-details', 1 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 3 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'dup', 4 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 5 );

COMMIT;

Whats there in table now

SELECT * FROM DATASET;

VAL1 VAL2             VAL3
---- ---------- ----------
b    b-details           2
a    a-details           1
c    c-details           3
a    dup                 4
c    c-details           5

5 rows selected.

--aggregate with group by

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1;

VAL1   COUNT(*)
---- ----------
b             1
a             2
c             2

3 rows selected.

--aggregate with group by multiple columns but select partial column

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

VAL1  
---- 
b             
c             
a             
a             

4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1,
      VAL2
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b    b-details
    c    c-details
    a    dup
    a    a-details

    4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b
    c
    a
    a

    4 rows selected.

You have N columns in select (excluding aggregations), then you should have N or N+x columns

How to get the data-id attribute?

Try

this.dataset.id

_x000D_
_x000D_
$("#list li").on('click', function() {_x000D_
  alert( this.dataset.id );_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>_x000D_
_x000D_
<ul id="list" class="grid">_x000D_
  <li data-id="id-40" class="win">_x000D_
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">_x000D_
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />_x000D_
    </a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to put a div in center of browser using CSS?

For Older browsers, you need to add this line on top of HTML doc

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

  1. Eliminate discovery exceptions from your inquiries; go to the output Window (Ctrl-Alt-O), then switch the show output from dropdown (Shift-Alt-S) to Tests and make sure there are no discovery exceptions

  2. Test|Test settings|Default processor architecture can help if your tests are x86/x64 specific and discovery is triggering bittedness-related exceptions, i.e. not AnyCpu

  3. As suggested in this answer(upvote it if the technique helps) running the desktop console runner (instructions) can be a good cross check to eliminate other possibilities, e.g. mangled config files:-

    packages\xunit.runner.console.2.2.0\tools\xunit.console <tests.dll>

    NOTE The xunit.runner.console package is deprecated - when you get stuff working in VS, you'll be able to have dotnet test run them in CI contexts too


Go read the documentation - it's comprehensive, up to date, includes troubleshooting info and takes PRs:-

Important note: If you've previously installed the xUnit.net Visual Studio Runner VSIX (Extension), you must uninstall it first. The Visual Studio runner is only distributed via NuGet now. To remove it, to go Tools > Extensions and Updates. Scroll to the bottom of the list, and if xUnit.net is installed, uninstall it. This will force you to restart Visual Studio.

If you're having problems discovering or running tests, you may be a victim of a corrupted runner cache inside Visual Studio. To clear this cache, shut down all instances of Visual Studio, then delete the folder %TEMP%\VisualStudioTestExplorerExtensions. Also make sure your project is only linked against a single version of the Visual Studio runner NuGet package (xunit.runner.visualstudio).

The following steps worked for me:

  1. (Only if you suspect there is a serious mess on your machine - in general the more common case is that the visual studio integration is simply not installed yet)

    Do the DEL %TEMP%\VisualStudioTestExplorerExtensions as advised :-

    PS> del $env:TEMP\VisualStudioTestExplorerExtensions

  2. Install the NuGet Package xunit.runner.visualstudio in all test projects

    • Paket:

      .paket\paket add nuget xunit.runner.visualstudio -i
      

      You need to end up with the following in your paket.dependencies:

      nuget xunit.runner.visualstudio version_in_path: true

      Note the version_in_path: true bit is important

    • Nuget: Go to Package Manager Console (Alt-T,N,O) and

      Install-Package xunit.runner.visualstudio)
      

    Rebuild to make sure xunit.runner ends up in the output dir

  3. Close Test Explorer <- this was the missing bit for me

  4. Re-open Test Explorer (Alt-S,W,T)

  5. Run All tests (Ctrl R, A)

CKEditor automatically strips classes from div

Edit: this answer is for those who use ckeditor module in drupal.

I found a solution which doesn't require modifying ckeditor js file.

this answer is copied from here. all credits should goes to original author.

Go to "Admin >> Configuration >> CKEditor"; under Profiles, choose your profile (e.g. Full).

Edit that profile, and on "Advanced Options >> Custom JavaScript configuration" add config.allowedContent = true;.

enter image description here

Don't forget to flush the cache under "Performance tab."

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

Explicitly adding a npm version to file package.json ("npm": "1.1.x") and not checking in folder node_modules to Git worked for me.

It may be slower to deploy (since it downloads the packages each time), but I couldn't get the packages to compile when they were checked in. Heroku was looking for files that only existed on my local box.

"Application tried to present modally an active controller"?

Assume you have three view controllers instantiated like so:

UIViewController* vc1 = [[UIViewController alloc] init];
UIViewController* vc2 = [[UIViewController alloc] init];
UIViewController* vc3 = [[UIViewController alloc] init];

You have added them to a tab bar like this:

UITabBarController* tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:vc1, vc2, vc3, nil]];

Now you are trying to do something like this:

[tabBarController presentModalViewController:vc3];

This will give you an error because that Tab Bar Controller has a death grip on the view controller that you gave it. You can either not add it to the array of view controllers on the tab bar, or you can not present it modally.

Apple expects you to treat their UI elements in a certain way. This is probably buried in the Human Interface Guidelines somewhere as a "don't do this because we aren't expecting you to ever want to do this".

Error inflating class fragment

Just had this same error. The reason for mine was the visibility of my fragment class. It was set to default, should be public.

How to pass Multiple Parameters from ajax call to MVC Controller

In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.

var dataObject = JSON.stringify({
                    'input': $('#myInput').val(),
                    'name': $('#myName').val(),
                });

Now use it in ajax call

$.ajax({
          url: "/Home/SaveChart",
          type: 'POST',
          async: false,
          dataType: 'json',
          contentType: 'application/json',
          data: dataObject,
          success: function (data) { },
          error: function (xhr) { }            )};

Remove Last Comma from a string

In case its useful or a better way:

str = str.replace(/(\s*,?\s*)*$/, "");

It will replace all following combination end of the string:

1. ,<no space>
2. ,<spaces> 
3. ,  ,  , ,   ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>

Saving data to a file in C#

I think you might want something like this

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

How to check if iframe is loaded or it has a content?

You can use the iframe's load event to respond when the iframe loads.

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

This won't tell you whether the correct content loaded: To check that, you can inspect the contentDocument.

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running.

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

How to send email to multiple address using System.Net.Mail

My code to solve this problem:

private void sendMail()
{   
    //This list can be a parameter of metothd
    List<MailAddress> lst = new List<MailAddress>();

    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));
    lst.Add(new MailAddress("[email protected]"));


    try
    {


        MailMessage objeto_mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 25;
        client.Host = "10.15.130.28"; //or SMTP name
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
        objeto_mail.From = new MailAddress("[email protected]");

        //add each email adress
        foreach (MailAddress m in lst)
        {
            objeto_mail.To.Add(m);
        }


        objeto_mail.Subject = "Sending mail test";
        objeto_mail.Body = "Functional test for automatic mail :-)";
        client.Send(objeto_mail);


    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Angular 2: How to access an HTTP response body?

The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().

  this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
  .map(res => res.json())
  .subscribe(data => {
    console.log(data);
  })

https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data

Change Spinner dropdown icon

You need to create custom background like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <layer-list>
            <item>
                <shape>
                    <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear"/>

                    <stroke android:width="1dp" android:color="#504a4b"/>

                    <corners android:radius="5dp"/>

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp"/>
                </shape>
            </item>
            <item>
                <bitmap android:gravity="bottom|right" android:src="@drawable/drop_down"/> // you can place your dropdown image
            </item>
        </layer-list>
    </item>

</selector>

Then create style for spinner like this:

<style name="spinner_style">
        <item name="android:background">@drawable/YOURCUSTOMBACKGROUND</item>
        <item name="android:layout_marginLeft">5dp</item>
        <item name="android:layout_marginRight">5dp</item>
        <item name="android:layout_marginBottom">5dp</item>
</style>

after that apply this style to your spinner

round a single column in pandas

If you are doing machine learning and use tensorflow, many float are of 'float32', not 'float64', and none of the methods mentioned in this thread likely to work. You will have to first convert to float64 first.

x.astype('float')

before round(...).

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

Table fixed header and scrollable body

Don't need the wrap it in a div...

CSS:

tr {
width: 100%;
display: inline-table;
table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl