Programs & Examples On #Jtextpane

A Java Swing text component that can be marked up with attributes that are represented graphically.

Creating and Naming Worksheet in Excel VBA

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet
Set WS = Sheets.Add

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test"

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

center MessageBox in parent form

Try this, it's simple enough to justify the time...

This is for Win32 API, written in C. Translate it as you need...

case WM_NOTIFY:{
  HWND X=FindWindow("#32770",NULL);
  if(GetParent(X)==H_frame){int Px,Py,Sx,Sy; RECT R1,R2;
    GetWindowRect(hwnd,&R1); GetWindowRect(X,&R2);
    Sx=R2.right-R2.left,Px=R1.left+(R1.right-R1.left)/2-Sx/2;
    Sy=R2.bottom-R2.top,Py=R1.top+(R1.bottom-R1.top)/2-Sy/2;
    MoveWindow(X,Px,Py,Sx,Sy,1);
  }
} break;

Add that to the WndProc code... You can set position as you like, in this case it just centres over the main program window. It will do this for any messagebox, or file open/save dialog, and likely some other native controls. I'm not sure, but I think you may need to include COMMCTRL or COMMDLG to use this, at least, you will if you want open/save dialogs.

I experimented with looking at the notify codes and hwndFrom of NMHDR, then decided it was just as effective, and far easier, not to. If you really want to be very specific, tell FindWindow to look for a unique caption (title) you give to the window you want it to find.

This fires before the messagebox is drawn onscreen, so if you set a global flag to indicate when action is done by your code, and look for a unique caption, you be sure that actions you take will only occur once (there will likely be multiple notifiers). I haven't explored this in detail, but I managed get CreateWindow to put an edit box on a messagebox dialog. It looked as out of place as a rat's ear grafted onto the spine of a cloned pig, but it works. Doing things this way may be far easier than having to roll your own.

Crow.

EDIT: Small correction to make sure that the right window is handled. Make sure that parent handles agree throughout, and this should work ok. It does for me, even with two instances of the same program...

Android - styling seek bar

Just replace color atributtes with your color

background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">

    <stroke android:width="1dp" android:color="#D9D9D9"/>
    <corners android:radius="1dp" />

</shape>

progress.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="line">

    <stroke android:width="1dp" android:color="#2EA5DE"/>
    <corners android:radius="1dp" />

</shape>

style.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@android:id/background"
        android:drawable="@drawable/seekbar_background"/>
    <item android:id="@android:id/progress">
        <clip android:drawable="@drawable/seekbar_progress" />
    </item>

</layer-list>

thumb.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <size android:height="30dp" android:width="30dp"/>
    <stroke android:width="18dp" android:color="#882EA5DE"/>
    <solid android:color="#2EA5DE" />
    <corners android:radius="1dp" />

</shape>

ImportError: No module named PIL

I used conda-forge to install pillow version 5, and that seemed to work for me:

conda install --channel conda-forge pillow=5

the normal conda install pillow did NOT work for me.

How to remove a variable from a PHP session array

if (isset($_POST['remove'])) {
    $key=array_search($_GET['name'],$_SESSION['name']);
    if($key!==false)
    unset($_SESSION['name'][$key]);
    $_SESSION["name"] = array_values($_SESSION["name"]);
} 

Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

If your PHP version is 5, try installing cURL by typing the following command in the terminal:

sudo apt-get install php5-curl

ValueError: setting an array element with a sequence

In my case, the problem was with a scatterplot of a dataframe X[]:

ax.scatter(X[:,0],X[:,1],c=colors,    
       cmap=CMAP, edgecolor='k', s=40)  #c=y[:,0],

#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,   
       cmap=CMAP, edgecolor='k', s=40)

How to compare strings in C conditional preprocessor-directives

The answere by Patrick and by Jesse Chisholm made me do the following:

#define QUEEN 'Q'
#define JACK 'J'

#define CHECK_QUEEN(s) (s==QUEEN)
#define CHECK_JACK(s) (s==JACK)

#define USER 'Q'

[... later on in code ...]

#if CHECK_QUEEN(USER)
  compile_queen_func();
#elif CHECK_JACK(USER)
  compile_jack_func();
#elif
#error "unknown user"
#endif

Instead of #define USER 'Q' #define USER QUEEN should also work but was not tested also works and might be easier to handle.

EDIT: According to the comment of @Jean-François Fabre I adapted my answer.

android.view.InflateException: Binary XML file: Error inflating class fragment

TL/DR: An exception occurred during the creation of a fragment referenced from a higher-level layout XML. This exception caused the higher-level layout inflation to fail, but the initial exception was not reported; only the higher-level inflation failure shows up in the stack trace. To find the root cause, you have to catch and log the initial exception.


The initial cause of the error could be a wide variety of things, which is why there are so many different answers here as to what fixed the problem for each person. For some, it had to do with the id, class, or name attributes. For others it was due to a permissions issue or a build setting. For me, those didn't fix the problem; instead there was a drawable resource that existed only in drawable-ldrtl-xhdpi, instead of in an applicable place like drawable.

But those are just details. The big-picture problem is that the error message that shows up in logcat doesn't describe the exception that started it all. When a higher-level layout XML references a fragment, the fragment's onCreateView() is called. When an exception occurs in a fragment's onCreateView() (for example while inflating the fragment's layout XML), it causes the inflation of the higher-level layout XML to fail. This higher-level inflation failure is what gets reported as an exception in the error logs. But the initial exception doesn't seem to travel up the chain well enough to be reported.

Given that situation, the question is how to expose the initial exception, when it doesn't show up in the error log.

The solution is pretty straightforward: Put a try/catch block around the contents of the fragment's onCreateView(), and in the catch clause, log the exception:

public View onCreateView(LayoutInflater inflater, ViewGroup contnr, Bundle savedInstSt) {
    try {
        mContentView = inflater.inflate(R.layout.device_detail_frag, null);
        // ... rest of body of onCreateView() ...
    } catch (Exception e) {
        Log.e(TAG, "onCreateView", e);
        throw e;
    }
}

It may not be obvious which fragment class's onCreateView() to do this to, in which case, do it to each fragment class that's used in the layout that caused the problem. For example, in the OP's case, the app's code where the exception occurred was

at android.app.Activity.setContentView(Activity.java:1901)

which is

   setContentView(R.layout.activity_main);

So you need to catch exceptions in the onCreateView() of any fragments referenced in layout activity_main.

In my case, the root cause exception turned out to be

Caused by: android.content.res.Resources$NotFoundException: Resource
   "com.example.myapp:drawable/details_view" (7f02006f)  is not a
   Drawable (color or path): TypedValue{t=0x1/d=0x7f02006f a=-1
   r=0x7f02006f}

This exception didn't show up in the error log until I caught it in onCreateView() and logged it explicitly. Once it was logged, the problem was easy enough to diagnose and fix (details_view.xml existed only under the ldrtl-xhdpi folder, for some reason). The key was catching the exception that was the root of the problem, and exposing it.

It doesn't hurt to do this as a boilerplate in all your fragments' onCreateView() methods. If there is an uncaught exception in there, it will crash the activity regardless. The only difference is that if you catch and log the exception in onCreateView(), you won't be in the dark as to why it happened.

P.S. I just realized this answer is related to @DaveHubbard's, but uses a different approach for finding the root cause (logging vs. debugger).

How to initialize private static members in C++?

int foo::i = 0; 

Is the correct syntax for initializing the variable, but it must go in the source file (.cpp) rather than in the header.

Because it is a static variable the compiler needs to create only one copy of it. You have to have a line "int foo:i" some where in your code to tell the compiler where to put it otherwise you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.

How to use a SQL SELECT statement with Access VBA

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

Image scaling causes poor quality in firefox/internet explorer but not chrome

Remember that sizes on the web are increasing dramatically. 3 years ago, I did an overhaul to bring our 500 px wide site layout to 1000. Now, where many sites are doing the jump to 1200, we jumped past that and went to a 2560 max optimized for 1600 wide (or 80% depending on the content level) main content area with responsiveness to allow the exact same ratios and look and feel on a laptop (1366x768) and on mobile (1280x720 or smaller).

Dynamic resizing is an integral part of this and will only become more-so as responsiveness becomes more and more important in 2013.

My smartphone has no trouble dealing with the content with 25 items on a page being resized - neither the computation for resizing nor the bandwidth. 3 seconds loads the page from fresh. Looks great on our 6 year old presentation laptop (1366x768) and on the projector (800x600).

Only on Mozilla Firefox does it look genuinely atrocious. It even looks just fine on IE8 (never used/updated since I installed it 2.5 years ago).

Removing the remembered login and password list in SQL Server Management Studio

In my scenario I only wanted to remove a specific username/password from the list which had many other saved connections I didn't want to forget. It turns out the SqlStudio.bin file others are discussing here is a .NET binary serialization of the Microsoft.SqlServer.Management.UserSettings.SqlStudio class, which can be deserialized, modified and reserialized to modify specific settings.

To accomplish removal of the specific login, I created a new C# .Net 4.6.1 console application and added a reference to the namespace which is located in the following dll: C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\Microsoft.SqlServer.Management.UserSettings.dll (your path may differ slightly depending on SSMS version)

From there I could easily create and modify the settings as desired:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Management.UserSettings;

class Program
{
    static void Main(string[] args)
    {
        var settingsFile = new FileInfo(@"C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin");

        // Backup our original file just in case...
        File.Copy(settingsFile.FullName, settingsFile.FullName + ".backup");

        BinaryFormatter fmt = new BinaryFormatter();

        SqlStudio settings = null;

        using(var fs = settingsFile.Open(FileMode.Open))
        {
            settings = (SqlStudio)fmt.Deserialize(fs);
        }

        // The structure of server types / servers / connections requires us to loop
        // through multiple nested collections to find the connection to be removed.
        // We start here with the server types

        var serverTypes = settings.SSMS.ConnectionOptions.ServerTypes;

        foreach (var serverType in serverTypes)
        {
            foreach (var server in serverType.Value.Servers)
            {
                // Will store the connection for the provided server which should be removed
                ServerConnectionSettings removeConn = null;

                foreach (var conn in server.Connections)
                {
                    if (conn.UserName == "adminUserThatShouldBeRemoved")
                    {
                        removeConn = conn;
                        break;
                    }
                }

                if (removeConn != null)
                {
                    server.Connections.RemoveItem(removeConn);
                }
            }
        }

        using (var fs = settingsFile.Open(FileMode.Create))
        {
            fmt.Serialize(fs, settings);
        }
    }
}

How can I select an element by name with jQuery?

Here's a simple solution: $('td[name=tcol1]')

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You could do it with JavaScript with something like this:

<input onblur="checkLength(this)" id="groupidtext" type="text" style="width: 100px;" maxlength="6" />
<!-- Or use event onkeyup instead if you want to check every character strike -->

function checkLength(el) {
  if (el.value.length != 6) {
    alert("length must be exactly 6 characters")
  }
}

Note this would work in older browsers which don't support HTML 5, but it relies on the user having JavaScript switched on.

Can I use jQuery to check whether at least one checkbox is checked?

$("#show").click(function() {
    var count_checked = $("[name='chk[]']:checked").length; // count the checked rows
        if(count_checked == 0) 
        {
            alert("Please select any record to delete.");
            return false;
        }
        if(count_checked == 1) {
            alert("Record Selected:"+count_checked);

        } else {
            alert("Record Selected:"+count_checked);
          }
});

Modifying a subset of rows in a pandas dataframe

For a massive speed increase, use NumPy's where function.

Setup

Create a two-column DataFrame with 100,000 rows with some zeros.

df = pd.DataFrame(np.random.randint(0,3, (100000,2)), columns=list('ab'))

Fast solution with numpy.where

df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)

Timings

%timeit df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
685 µs ± 6.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df.loc[df['a'] == 0, 'b'] = np.nan
3.11 ms ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Numpy's where is about 4x faster

How to Sign an Already Compiled Apk

create a key using

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

Matplotlib discrete colorbar

You could follow this example:

#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.

Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""

from pylab import *


delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('PiYG', 11)    # 11 discrete colors

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

which produces the following image:

poormans_contour

Formatting a number with leading zeros in PHP

Simple answer

$p = 1234567;
$p = sprintf("%08d",$p);

I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.

To clip the first 8 digits

$p = substr(sprintf('%08d', $p),0,8);

To clip the last 8 digits

$p = substr(sprintf('%08d', $p),-8,8);

Why is my toFixed() function not working?

You're not assigning the parsed float back to your value var:

value = parseFloat(value).toFixed(2);

should fix things up.

Call a Class From another class

Class2 class2 = new Class2();

Instead of calling the main, perhaps you should call individual methods where and when you need them.

How to detect when cancel is clicked on file input?

Combining Shiboe's and alx's solutions, i've got the most reliable code:

var selector = $('<input/>')
   .attr({ /* just for example, use your own attributes */
      "id": "FilesSelector",
      "name": "File",
      "type": "file",
      "contentEditable": "false" /* if you "click" on input via label, this prevents IE7-8 from just setting caret into file input's text filed*/
   })
   .on("click.filesSelector", function () {
      /* do some magic here, e.g. invoke callback for selection begin */
      var cancelled = false; /* need this because .one calls handler once for each event type */
      setTimeout(function () {
         $(document).one("mousemove.filesSelector focusin.filesSelector", function () {
            /* namespace is optional */
            if (selector.val().length === 0 && !cancelled) {
               cancelled = true; /* prevent double cancel */
               /* that's the point of cancel,   */
            }
         });                    
      }, 1); /* 1 is enough as we just need to delay until first available tick */
   })
   .on("change.filesSelector", function () {
      /* do some magic here, e.g. invoke callback for successful selection */
   })
   .appendTo(yourHolder).end(); /* just for example */

Generally, mousemove event does the trick, but in case user made a click and than:

  • cancelled file open dialog by escape key (without moving a mouse), made another accurate click to open file dialog again...
  • switched focus to any other application, than came back to browser's file open dialog and closed it, than opened again via enter or space key...

... we won't get mousemove event hence no cancel callback. Moreover, if user cancels second dialog and makes a mouse move, we'll get 2 cancel callbacks. Fortunately, special jQuery focusIn event bubbles up to the document in both cases, helping us to avoid such situations. The only limitation is if one blocks focusIn event either.

Using GCC to produce readable assembly?

Using the -S switch to GCC on x86 based systems produces a dump of AT&T syntax, by default, which can be specified with the -masm=att switch, like so:

gcc -S -masm=att code.c

Whereas if you'd like to produce a dump in Intel syntax, you could use the -masm=intel switch, like so:

gcc -S -masm=intel code.c

(Both produce dumps of code.c into their various syntax, into the file code.s respectively)

In order to produce similar effects with objdump, you'd want to use the --disassembler-options= intel/att switch, an example (with code dumps to illustrate the differences in syntax):

 $ objdump -d --disassembler-options=att code.c
 080483c4 <main>:
 80483c4:   8d 4c 24 04             lea    0x4(%esp),%ecx
 80483c8:   83 e4 f0                and    $0xfffffff0,%esp
 80483cb:   ff 71 fc                pushl  -0x4(%ecx)
 80483ce:   55                      push   %ebp
 80483cf:   89 e5                   mov    %esp,%ebp
 80483d1:   51                      push   %ecx
 80483d2:   83 ec 04                sub    $0x4,%esp
 80483d5:   c7 04 24 b0 84 04 08    movl   $0x80484b0,(%esp)
 80483dc:   e8 13 ff ff ff          call   80482f4 <puts@plt>
 80483e1:   b8 00 00 00 00          mov    $0x0,%eax
 80483e6:   83 c4 04                add    $0x4,%esp 
 80483e9:   59                      pop    %ecx
 80483ea:   5d                      pop    %ebp
 80483eb:   8d 61 fc                lea    -0x4(%ecx),%esp
 80483ee:   c3                      ret
 80483ef:   90                      nop

and

$ objdump -d --disassembler-options=intel code.c
 080483c4 <main>:
 80483c4:   8d 4c 24 04             lea    ecx,[esp+0x4]
 80483c8:   83 e4 f0                and    esp,0xfffffff0
 80483cb:   ff 71 fc                push   DWORD PTR [ecx-0x4]
 80483ce:   55                      push   ebp
 80483cf:   89 e5                   mov    ebp,esp
 80483d1:   51                      push   ecx
 80483d2:   83 ec 04                sub    esp,0x4
 80483d5:   c7 04 24 b0 84 04 08    mov    DWORD PTR [esp],0x80484b0
 80483dc:   e8 13 ff ff ff          call   80482f4 <puts@plt>
 80483e1:   b8 00 00 00 00          mov    eax,0x0
 80483e6:   83 c4 04                add    esp,0x4
 80483e9:   59                      pop    ecx
 80483ea:   5d                      pop    ebp
 80483eb:   8d 61 fc                lea    esp,[ecx-0x4]
 80483ee:   c3                      ret    
 80483ef:   90                      nop

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

Load json from local file with http.get() in angular 2

If you are using Angular CLI: 7.3.3 What I did is, On my assets folder I put my fake json data then on my services I just did this.

const API_URL = './assets/data/db.json';

getAllPassengers(): Observable<PassengersInt[]> {
    return this.http.get<PassengersInt[]>(API_URL);
  }

enter image description here

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

I was getting the xml as a String and using xml.getBytes() and getting this error. Changing to xml.getBytes(Charset.forName("UTF-8")) worked for me.

Android Fragment onAttach() deprecated

Download newest Support library with the sdk manager and include

compile 'com.android.support:appcompat-v7:23.1.1'

in gradle.app and set compile version to api 23

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

Install a .NET windows service without InstallUtil.exe

Here is a class I use when writing services. I usually have an interactive screen that comes up when the service is not called. From there I use the class as needed. It allows for multiple named instances on the same machine -hence the InstanceID field

Sample Call

  IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
  Inst.Install("MySvc", "My Sample Service", "Service that executes something",
                    _InstanceID,
// System.ServiceProcess.ServiceAccount.LocalService,      // this is more secure, but only available in XP and above and WS-2003 and above
  System.ServiceProcess.ServiceAccount.LocalSystem,       // this is required for WS-2000
  System.ServiceProcess.ServiceStartMode.Automatic);
  if (controller == null)
  {
    controller = new System.ServiceProcess.ServiceController(String.Format("MySvc_{0}", _InstanceID), ".");
                }
                if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    Start_Stop.Text = "Stop Service";
                    Start_Stop_Debugging.Enabled = false;
                }
                else
                {
                    Start_Stop.Text = "Start Service";
                    Start_Stop_Debugging.Enabled = true;
                }

The class itself

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;

namespace MySvc
{
    class IntegratedServiceInstaller
    {
        public void Install(String ServiceName, String DisplayName, String Description,
            String InstanceID,
            System.ServiceProcess.ServiceAccount Account, 
            System.ServiceProcess.ServiceStartMode StartMode)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceProcessInstaller ProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            ProcessInstaller.Account = Account;

            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();
            string processPath = Process.GetCurrentProcess().MainModule.FileName;
            if (processPath != null && processPath.Length > 0)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(processPath);

                String path = String.Format("/assemblypath={0}", fi.FullName);
                String[] cmdline = { path };
                Context = new System.Configuration.Install.InstallContext("", cmdline);
            }

            SINST.Context = Context;
            SINST.DisplayName = String.Format("{0} - {1}", DisplayName, InstanceID);
            SINST.Description = String.Format("{0} - {1}", Description, InstanceID);
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.StartType = StartMode;
            SINST.Parent = ProcessInstaller;

            // http://bytes.com/forum/thread527221.html
            SINST.ServicesDependedOn = new String[] { "Spooler", "Netlogon", "Netman" };

            System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
            SINST.Install(state);

            // http://www.dotnet247.com/247reference/msgs/43/219565.aspx
            using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(@"SYSTEM\CurrentControlSet\Services\{0}_{1}", ServiceName, InstanceID), true))
            {
                try
                {
                    Object sValue = oKey.GetValue("ImagePath");
                    oKey.SetValue("ImagePath", sValue);
                }
                catch (Exception Ex)
                {
                    System.Windows.Forms.MessageBox.Show(Ex.Message);
                }
            }

        }
        public void Uninstall(String ServiceName, String InstanceID)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext("c:\\install.log", null);
            SINST.Context = Context;
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.Uninstall(null);
        }
    }
}

Easy way to write contents of a Java InputStream to an OutputStream

you can use this method

public static void copyStream(InputStream is, OutputStream os)
 {
     final int buffer_size=1024;
     try
     {
         byte[] bytes=new byte[buffer_size];
         for(;;)
         {
           int count=is.read(bytes, 0, buffer_size);
           if(count==-1)
               break;
           os.write(bytes, 0, count);
         }
     }
     catch(Exception ex){}
 }

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

how to convert milliseconds to date format in android?

public static String convertDate(String dateInMilliseconds,String dateFormat) {
    return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}

Call this function

convertDate("82233213123","dd/MM/yyyy hh:mm:ss");

Entity Framework 5 Updating a Record

Depending on your use case, all the above solutions apply. This is how i usually do it however :

For server side code (e.g. a batch process) I usually load the entities and work with dynamic proxies. Usually in batch processes you need to load the data anyways at the time the service runs. I try to batch load the data instead of using the find method to save some time. Depending on the process I use optimistic or pessimistic concurrency control (I always use optimistic except for parallel execution scenarios where I need to lock some records with plain sql statements, this is rare though). Depending on the code and scenario the impact can be reduced to almost zero.

For client side scenarios, you have a few options

  1. Use view models. The models should have a property UpdateStatus(unmodified-inserted-updated-deleted). It is the responsibility of the client to set the correct value to this column depending on the user actions (insert-update-delete). The server can either query the db for the original values or the client should send the original values to the server along with the changed rows. The server should attach the original values and use the UpdateStatus column for each row to decide how to handle the new values. In this scenario I always use optimistic concurrency. This will only do the insert - update - delete statements and not any selects, but it might need some clever code to walk the graph and update the entities (depends on your scenario - application). A mapper can help but does not handle the CRUD logic

  2. Use a library like breeze.js that hides most of this complexity (as described in 1) and try to fit it to your use case.

Hope it helps

Random alpha-numeric string in JavaScript?

This function should give a random string in any length.

function randString(length) {
    var l = length > 25 ? 25 : length;
    var str = Math.random().toString(36).substr(2, l);
    if(str.length >= length){
        return str;
    }
    return str.concat(this.randString(length - str.length));
}

I've tested it with the following test that succeeded.

function test(){
    for(var x = 0; x < 300000; x++){
        if(randString(x).length != x){
            throw new Error('invalid result for len ' + x);
        }
    }
}

The reason i have chosen 25 is since that in practice the length of the string returned from Math.random().toString(36).substr(2, 25) has length 25. This number can be changed as you wish.

This function is recursive and hence calling the function with very large values can result with Maximum call stack size exceeded. From my testing i was able to get string in the length of 300,000 characters.

This function can be converted to a tail recursion by sending the string to the function as a second parameter. I'm not sure if JS uses Tail call optimization

Quicksort: Choosing the pivot

In a truly optimized implementation, the method for choosing pivot should depend on the array size - for a large array, it pays off to spend more time choosing a good pivot. Without doing a full analysis, I would guess "middle of O(log(n)) elements" is a good start, and this has the added bonus of not requiring any extra memory: Using tail-call on the larger partition and in-place partitioning, we use the same O(log(n)) extra memory at almost every stage of the algorithm.

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

ImportError: No module named google.protobuf

To find where the name google clashes .... try this:

python3

then >>> help('google')

... I got info about google-auth:

NAME
    google

PACKAGE CONTENTS
    auth (package)
    oauth2 (package)

Also then try

pip show google-auth

Then

sudo pip3 uninstall google-auth

... and re-try >>> help('google')

I then see protobuf:

NAME
    google

PACKAGE CONTENTS
    protobuf (package)

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

Annotation @Transactional. How to rollback?

Just throw any RuntimeException from a method marked as @Transactional.

By default all RuntimeExceptions rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters:

@Transactional(rollbackFor=Exception.class)

This will rollback transaction after throwing any exception.

Git push error pre-receive hook declined

Following resolved problem in my local machine:

A. First, ensure that you are using the correct log on details to connect to Bitbucket Server (ie. a username/password/SSH key that belongs to you) 

B. Then, ensure that the name/email address is correctly set in your local Git configuration: Set your local Git configuration for the account that you are trying to push under (the check asserts that you are the person who committed the files) * Note that this is case sensitive, both for name and email address * It is also space sensitive - some company accounts have extra spaces/characters in their name eg. "Contractor/ space space(LDN)".  You must include the same number of spaces in your configuration as on Bitbucket Server.  Check this in Notepad if stuck.

C. If you were using the wrong account, simply switch your account credentials (username/password/SSH key) and try pushing again.

D. Else, if your local configuration incorrect you will need to amend it

For MAC

open -a TextEdit.app ~/.gitconfig

NOTE: You will have to fix up the old commits that you were trying to push.

  1. Amend your last commit:

    > git commit --amend --reset-author
    
      
    <save and quit the commit file text editor that opens, if Vim then
    :wq to save and quit>
    
  2. Try re-pushing your commits:

    > git push
    

How to pause javascript code execution for 2 seconds

There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
            console.log(i);
        }
    };
    setTimeout(tick(i), 500 * i);
}

Demo here: http://jsfiddle.net/hW7Ch/

Submitting HTML form using Jquery AJAX

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })

Ansible: Set variable to file content

You can use the slurp module to fetch a file from the remote host: (Thanks to @mlissner for suggesting it)

vars:
  amazon_linux_ami: "ami-fb8e9292"
  user_data_file: "base-ami-userdata.sh"
tasks:
- name: Load data
  slurp:
    src: "{{ user_data_file }}"
  register: slurped_user_data
- name: Decode data and store as fact # You can skip this if you want to use the right hand side directly...
  set_fact:
    user_data: "{{ slurped_user_data.content | b64decode }}"

What is trunk, branch and tag in Subversion?

To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.

TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.

AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.

Get HTML code from website in C#

Getting HTML code from a website. You can use code like this.

string urlAddress = "http://google.com";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;

  if (String.IsNullOrWhiteSpace(response.CharacterSet))
     readStream = new StreamReader(receiveStream);
  else
     readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

  string data = readStream.ReadToEnd();

  response.Close();
  readStream.Close();
}

This will give you the returned HTML code from the website. But find text via LINQ is not that easy. Perhaps it is better to use regular expression but that does not play well with HTML code

Disallow Twitter Bootstrap modal window from closing

You can set default behavior of modal popup by using of below line of code:

 $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';

Add common prefix to all cells in Excel

  1. Enter the function of = CONCATENATE("X",A1) in one cell other than A say D
  2. Click the Cell D1, and drag the fill handle across the range that you want to fill.All the cells should have been added the specific prefix text.

You can see the changes made to the repective cells.

How to use SortedMap interface in Java?

You can use TreeMap which internally implements the SortedMap below is the example

Sorting by ascending ordering :

  Map<Float, String> ascsortedMAP = new TreeMap<Float, String>();

  ascsortedMAP.put(8f, "name8");
  ascsortedMAP.put(5f, "name5");
  ascsortedMAP.put(15f, "name15");
  ascsortedMAP.put(35f, "name35");
  ascsortedMAP.put(44f, "name44");
  ascsortedMAP.put(7f, "name7");
  ascsortedMAP.put(6f, "name6");

  for (Entry<Float, String> mapData : ascsortedMAP.entrySet()) {
    System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());
  }

Sorting by descending ordering :

If you always want this create the map to use descending order in general, if you only need it once create a TreeMap with descending order and put all the data from the original map in.

  // Create the map and provide the comparator as a argument
  Map<Float, String> dscsortedMAP = new TreeMap<Float, String>(new Comparator<Float>() {
    @Override
    public int compare(Float o1, Float o2) {
      return o2.compareTo(o1);
    }
  });
  dscsortedMAP.putAll(ascsortedMAP);

for further information about SortedMAP read http://examples.javacodegeeks.com/core-java/util/treemap/java-sorted-map-example/

Launch an app from within another (iPhone)

In Swift 4.1 and Xcode 9.4.1

I have two apps 1)PageViewControllerExample and 2)DelegateExample. Now i want to open DelegateExample app with PageViewControllerExample app. When i click open button in PageViewControllerExample, DelegateExample app will be opened.

For this we need to make some changes in .plist files for both the apps.

Step 1

In DelegateExample app open .plist file and add URL Types and URL Schemes. Here we need to add our required name like "myapp".

enter image description here

Step 2

In PageViewControllerExample app open .plist file and add this code

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>myapp</string>
</array>

Now we can open DelegateExample app when we click button in PageViewControllerExample.

//In PageViewControllerExample create IBAction
@IBAction func openapp(_ sender: UIButton) {

    let customURL = URL(string: "myapp://")
    if UIApplication.shared.canOpenURL(customURL!) {

        //let systemVersion = UIDevice.current.systemVersion//Get OS version
        //if Double(systemVersion)! >= 10.0 {//10 or above versions
            //print(systemVersion)
            //UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
        //} else {
            //UIApplication.shared.openURL(customURL!)
        //}

        //OR

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(customURL!, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(customURL!)
        }
    } else {
         //Print alert here
    }
}

How to pass the id of an element that triggers an `onclick` event to the event handling function

I would suggest the use of jquery mate.

With jQuery you would then be able to get the id of this element by

$(this).attr('id');

without jquery, if I remember correctly we used to access the id with a

this.id

Hope that helps :)

Notice: Array to string conversion in

mysql_fetch_assoc returns an array so you can not echo an array, need to print_r() otherwise particular string $money['money'].

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

How to set top-left alignment for UILabel for iOS application?

I have this problem to but my label was in UITableViewCell, and in fund that the easiest way to solve the problem was to create an empty UIView and set the label inside it with constraints to the top and to the left side only, on off curse set the number of lines to 0

Creating and returning Observable from Angular 2 Service

In the service.ts file -

a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class ClientListService {
    private clientList;

    constructor() {
        this.clientList = [
            {name: 'abc', address: 'Railpar'},
            {name: 'def', address: 'Railpar 2'},
            {name: 'ghi', address: 'Panagarh'},
            {name: 'jkl', address: 'Panagarh 2'},
        ];
    }

    getClientList () {
        return Observable.of(this.clientList);
    }
};

In the component where we are calling the get function of the service -

this.clientListService.getClientList().subscribe(res => this.clientList = res);

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

How to iterate (keys, values) in JavaScript?

WELCOME TO 2020 *Drools in ES6*

Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

Object.entries(myObject).forEach(([k,v]) => {
    console.log("The key: ",k)
    console.log("The value: ",v)
})
_x000D_
_x000D_
_x000D_

Edit:

As mentioned by Lazerbeak, map allows you to cycle an object and use the key and value to make an array.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

const myArray = Object.entries(myObject).map(([k, v]) => {
    return `The key '${k}' has a value of '${v}'`;
});

console.log(myArray);
_x000D_
_x000D_
_x000D_

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

I agree with chrylis: you believe you changed your project's compliance settings but probably you didnt.

Right click on your project and:

  • Java / Build Path : Go to Libraries tab and ensure yourself that you are really using jre6
  • Java / Compiler : Ensure yourself that you have selected 1.6 compliance

By the way you can "tell" eclipse that jre8 is 1.6 compliance clicking on Window/Preferences/Java/Installed JREs/Execution Environment and selecting in the left panel, Execution Environments, JavaSE-1.6 and in the Compatible JRE's panel, jre8

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

Print directly from browser without print popup window

This should work, I tried it by myself and it worked for me. If you pass True instead of false, the print dialog will appear.

this.print(false);

How to set up subdomains on IIS 7

This one drove me crazy... basically you need two things:

1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.

2) You must add an additional website in IIS 7 named subdomain.example.com

  • Sites > Add Website
  • Site Name: subdomain.example.com
  • Physical Path: select the subdomain directory
  • Binding: same ip as example.com
  • Host name: subdomain.example.com

C++ convert string to hexadecimal and vice versa

This will convert Hello World to 48656c6c6f20576f726c64 and print it.

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char hello[20]="Hello World";

    for(unsigned int i=0; i<strlen(hello); i++)
        cout << hex << (int) hello[i];
    return 0;
}

Should a RESTful 'PUT' operation return something

I think it is possible for the server to return content in response to a PUT. If you are using a response envelop format that allows for sideloaded data (such as the format consumed by ember-data), then you can also include other objects that may have been modified via database triggers, etc. (Sideloaded data is explicitly to reduce # of requests, and this seems like a fine place to optimize.)

If I just accept the PUT and have nothing to report back, I use status code 204 with no body. If I have something to report, I use status code 200, and include a body.

MongoDB logging all queries

This was asked a long time ago but this may still help someone:

MongoDB profiler logs all the queries in the capped collection system.profile. See this: database profiler

  1. Start mongod instance with --profile=2 option that enables logging all queries OR if mongod instances is already running, from mongoshell, run db.setProfilingLevel(2) after selecting database. (it can be verified by db.getProfilingLevel(), which should return 2)
  2. After this, I have created a script which utilises mongodb's tailable cursor to tail this system.profile collection and write the entries in a file. To view the logs I just need to tail it:tail -f ../logs/mongologs.txt. This script can be started in background and it will log all the operation on the db in the file.

My code for tailable cursor for the system.profile collection is in nodejs; it logs all the operations along with queries happening in every collection of MyDb:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const fs = require('fs');
const file = '../logs/mongologs'
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'MyDb';
//Mongodb connection

MongoClient.connect(url, function (err, client) {
   assert.equal(null, err);
   const db = client.db(dbName);
   listen(db, {})
});

function listen(db, conditions) {
var filter = { ns: { $ne: 'MyDb.system.profile' } }; //filter for query
//e.g. if we need to log only insert queries, use {op:'insert'}
//e.g. if we need to log operation on only 'MyCollection' collection, use {ns: 'MyDb.MyCollection'}
//we can give a lot of filters, print and check the 'document' variable below

// set MongoDB cursor options
var cursorOptions = {
    tailable: true,
    awaitdata: true,
    numberOfRetries: -1
};

// create stream and listen
var stream = db.collection('system.profile').find(filter, cursorOptions).stream();

// call the callback
stream.on('data', function (document) {
    //this will run on every operation/query done on our database
    //print 'document' to check the keys based on which we can filter
    //delete data which we dont need in our log file

    delete document.execStats;
    delete document.keysExamined;
    //-----
    //-----

    //append the log generated in our log file which can be tailed from command line
    fs.appendFile(file, JSON.stringify(document) + '\n', function (err) {
        if (err) (console.log('err'))
    })

});

}

For tailable cursor in python using pymongo, refer the following code which filters for MyCollection and only insert operation:

import pymongo
import time
client = pymongo.MongoClient()
oplog = client.MyDb.system.profile
first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()

ts = first['ts']
while True:
    cursor = oplog.find({'ts': {'$gt': ts}, 'ns': 'MyDb.MyCollection', 'op': 'insert'},
                        cursor_type=pymongo.CursorType.TAILABLE_AWAIT)
    while cursor.alive:
        for doc in cursor:
            ts = doc['ts']
            print(doc)
            print('\n')
        time.sleep(1)

Note: Tailable cursor only works with capped collections. It cannot be used to log operations on a collection directly, instead use filter: 'ns': 'MyDb.MyCollection'

Note: I understand that the above nodejs and python code may not be of much help for some. I have just provided the codes for reference.

Use this link to find documentation for tailable cursor in your languarge/driver choice Mongodb Drivers

Another feature that i have added after this logrotate.

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

In Ubuntu/Unix we can resolve this problem in 2 steps as described below.

  1. Type netstat -plten |grep java

    This will give an output similar to:

    tcp   0   0 0.0.0.0:8080   0.0.0.0:*  LISTEN   1001  76084  9488/java       
    

    Here 8080 is the port number at which the java process is listening and 9488 is its process id (pid).

  2. In order to free the occupied port, we have to kill this process using the kill command.

    kill -9 9488
    

    9488 is the process id from earlier. We use -9 to force stop the process.

Your port should now be free and you can restart the server.

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

How do I convert from a money datatype in SQL server?

I found this approach direct and useful.

CONVERT(VARCHAR(10), CONVERT(MONEY, fieldname)) AS PRICE

Sending Arguments To Background Worker?

You can use the DoWorkEventArgs.Argument property.

A full example (even using an int argument) can be found on Microsoft's site:

What order are the Junit @Before/@After called?

One potential gotcha that has bitten me before:

I like to have at most one @Before method in each test class, because order of running the @Before methods defined within a class is not guaranteed. Typically, I will call such a method setUpTest().

But, although @Before is documented as The @Before methods of superclasses will be run before those of the current class. No other ordering is defined., this only applies if each method marked with @Before has a unique name in the class hierarchy.

For example, I had the following:

public class AbstractFooTest {
  @Before
  public void setUpTest() { 
     ... 
  }
}

public void FooTest extends AbstractFooTest {
  @Before
  public void setUpTest() { 
    ...
  }
}

I expected AbstractFooTest.setUpTest() to run before FooTest.setUpTest(), but only FooTest.setupTest() was executed. AbstractFooTest.setUpTest() was not called at all.

The code must be modified as follows to work:

public void FooTest extends AbstractFooTest {
  @Before
  public void setUpTest() {
    super.setUpTest();
    ...
  }
}

How to directly execute SQL query in C#?

To execute your command directly from within C#, you would use the SqlCommand class.

Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:

string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
            reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
        }
    }
    finally
    {
        // Always call Close when done reading.
        reader.Close();
    }
}

Ternary operator in AngularJS templates

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>
      </div>
    </div>
  </body>

Button toggle and change header of button and show/hide div panel. See the Plunkr

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Run Executable from Powershell script with parameters

I was able to get this to work by using the Invoke-Expression cmdlet.

Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

How do you specify a different port number in SQL Management Studio?

Using the client manager affects all connections or sets a client machine specific alias.

Use the comma as above: this can be used in an app.config too

It's probably needed if you have firewalls between you and the server too...

Iteration ng-repeat only X times in AngularJs

You can use slice method in javascript array object

<div ng-repeat="item in items.slice(0, 4)">{{item}}</div>

Short n sweet

Save PHP variables to a text file

Use a combination of of fopen, fwrite and fread. PHP.net has excellent documentation and examples of each of them.

http://us2.php.net/manual/en/function.fopen.php
http://us2.php.net/manual/en/function.fwrite.php
http://us2.php.net/manual/en/function.fread.php

Getting the first character of a string with $str[0]

My only doubt would be how applicable this technique would be on multi-byte strings, but if that's not a consideration, then I suspect you're covered. (If in doubt, mb_substr() seems an obviously safe choice.)

However, from a big picture perspective, I have to wonder how often you need to access the 'n'th character in a string for this to be a key consideration.

View RDD contents in Python Spark?

In Spark 2.0 (I didn't tested with earlier versions). Simply:

print myRDD.take(n)

Where n is the number of lines and myRDD is wc in your case.

What is ":-!!" in C code?

This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.

The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO, rather than ...ON_ZERO. (There have been occasional discussions about whether this is a confusing name.)

You should read the expression like this:

sizeof(struct { int: -!!(e); }))
  1. (e): Compute expression e.

  2. !!(e): Logically negate twice: 0 if e == 0; otherwise 1.

  3. -!!(e): Numerically negate the expression from step 2: 0 if it was 0; otherwise -1.

  4. struct{int: -!!(0);} --> struct{int: 0;}: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.

  5. struct{int: -!!(1);} --> struct{int: -1;}: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.

So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof that field, so we get a size_t with the appropriate width (which will be zero in the case where e is zero).


Some people have asked: Why not just use an assert?

keithmo's answer here has a good response:

These macros implement a compile-time test, while assert() is a run-time test.

Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.

Typescript input onchange event.target.value

When using Child Component We check type like this.

Parent Component:

export default () => {

  const onChangeHandler = ((e: React.ChangeEvent<HTMLInputElement>): void => {
    console.log(e.currentTarget.value)
  }

  return (
    <div>
      <Input onChange={onChangeHandler} />
    </div>
  );
}

Child Component:

type Props = {
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
}

export Input:React.FC<Props> ({onChange}) => (
  <input type="tex" onChange={onChange} />
)

Python Progress Bar

I like Brian Khuu's answer for its simplicity and not needing external packages. I changed it a bit so I'm adding my version here:

import sys
import time


def updt(total, progress):
    """
    Displays or updates a console progress bar.

    Original source: https://stackoverflow.com/a/15860757/1391441
    """
    barLength, status = 20, ""
    progress = float(progress) / float(total)
    if progress >= 1.:
        progress, status = 1, "\r\n"
    block = int(round(barLength * progress))
    text = "\r[{}] {:.0f}% {}".format(
        "#" * block + "-" * (barLength - block), round(progress * 100, 0),
        status)
    sys.stdout.write(text)
    sys.stdout.flush()


runs = 300
for run_num in range(runs):
    time.sleep(.1)
    updt(runs, run_num + 1)

It takes the total number of runs (total) and the number of runs processed so far (progress) assuming total >= progress. The result looks like this:

[#####---------------] 27%

Procedure or function !!! has too many arguments specified

Yet another cause of this error is when you are calling the stored procedure from code, and the parameter type in code does not match the type on the stored procedure.

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

Getting the parent of a directory in Bash

If /home/smith/Desktop/Test/../ is what you want:

dirname 'path/to/child/dir'

as seen here.

How to Generate Unique Public and Private Key via RSA

What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:

public static string ConvertToNewKey(string oldPrivateKey)
{

    // get the current container name from the database...

    rsa.PersistKeyInCsp = false;
    rsa.Clear();
    rsa = null;

    string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...

       // re-encrypt existing data to use the new keys and write to database...

    return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
     string containerName = DateTime.Now.Ticks.ToString();
     // create the new key...
     // saves container name and public key to database...
     // and returns Private Key XML.
}

before creating the new key.

if statements matching multiple values

Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement

switch(value)
{
case 1:
case 2:
   return true;
default:
   return false
}

Calculate a MD5 hash from a string

This solution requires c# 8 and takes advantage of Span<T>. Note, you would still need to call .Replace("-", string.Empty).ToLowerInvariant() to format the result if necessary.

public static string CreateMD5(ReadOnlySpan<char> input)
{
    var encoding = System.Text.Encoding.UTF8;
    var inputByteCount = encoding.GetByteCount(input);
    using var md5 = System.Security.Cryptography.MD5.Create();

    Span<byte> bytes = inputByteCount < 1024
        ? stackalloc byte[inputByteCount]
        : new byte[inputByteCount];
    Span<byte> destination = stackalloc byte[md5.HashSize / 8];

    encoding.GetBytes(input, bytes);

    // checking the result is not required because this only returns false if "(destination.Length < HashSizeValue/8)", which is never true in this case
    md5.TryComputeHash(bytes, destination, out int _bytesWritten);

    return BitConverter.ToString(destination.ToArray());
}

Android - drawable with rounded corners at the top only

Building upon busylee's answer, this is how you can make a drawable that only has one unrounded corner (top-left, in this example):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <!-- A numeric value is specified in "radius" for demonstrative purposes only,
                  it should be @dimen/val_name -->
            <corners android:radius="10dp" />
        </shape>
    </item>
    <!-- To keep the TOP-LEFT corner UNROUNDED set both OPPOSITE offsets (bottom+right): -->
    <item
        android:bottom="10dp"
        android:right="10dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
        </shape>
    </item>
</layer-list>

Please note that the above drawable is not shown correctly in the Android Studio preview (2.0.0p7). To preview it anyway, create another view and use this as android:background="@drawable/...".

How to convert 'binary string' to normal string in Python3?

Decode it.

>>> b'a string'.decode('ascii')
'a string'

To get bytes from string, encode it.

>>> 'a string'.encode('ascii')
b'a string'

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

curl: (6) Could not resolve host: google.com; Name or service not known

Perhaps you have some very weird and restrictive SELinux rules in place?

If not, try strace -o /tmp/wtf -fF curl -v google.com and try to spot from /tmp/wtf output file what's going on.

How can I get city name from a latitude and longitude point?

There are many tools available

  1. google maps API as like all had written
  2. use this data "https://simplemaps.com/data/world-cities" download free version and convert excel to JSON with some online converter like "http://beautifytools.com/excel-to-json-converter.php"
  3. use IP address which is not good because using IP address of someone may not good users think that you can hack them.

other free and paid tools are available also

Advantages of SQL Server 2008 over SQL Server 2005?

I guess it depends on your role

For me as a developer:

  • Merge statement
  • Reporting Services improvement
  • Date/time changes

Edit, late update, after using it

  • filtered indexes
  • table valued parameters
  • Reporting Services without IIS

Confirm button before running deleting routine from website

Call this function onclick of button

/*pass whatever you want instead of id */
function doConfirm(id) {
    var ok = confirm("Are you sure to Delete?");
    if (ok) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                window.location = "create_dealer.php";
            }
        }

        xmlhttp.open("GET", "delete_dealer.php?id=" + id);
        // file name where delete code is written
        xmlhttp.send();
    }
}

Prepend text to beginning of string

var mystr = "Doe";
mystr = "John " + mystr;

Wouldn't this work for you?

Visual Studio Code - Convert spaces to tabs

  1. Highlight your Code (in file)
  2. Click Tab Size in bottom righthand corner of application window Tab Size in bottom righthand corner of application window image
  3. Select the appropriate Convert Indentation to Tabs Select the appropriate Convert Indentation to Tabs image

What is the purpose of a self executing function in javascript?

Namespacing. JavaScript's scopes are function-level.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

Change it like this and it should work:

var key = item.Key.ToString();
IQueryable<entity> pages = from p in context.pages
                           where  p.Serial == key
                           select p;

The reason why the exception is not thrown in the line the LINQ query is declared but in the line of the foreach is the deferred execution feature, i.e. the LINQ query is not executed until you try to access the result. And this happens in the foreach and not earlier.

Convert nested Python dict to object?

How about this:

from functools import partial
d2o=partial(type, "d2o", ())

This can then be used like this:

>>> o=d2o({"a" : 5, "b" : 3})
>>> print o.a
5
>>> print o.b
3

Microsoft Azure: How to create sub directory in a blob container

Got similar issue while trying Azure Sample first-serverless-app.
Here is the info of how i resolved by removing \ at front of $web.

Note: $web container was created automatically while enable static website. Never seen $root container anywhere.

//getting Invalid URI error while following tutorial as-is
az storage blob upload-batch -s . -d \$web --account-name firststgaccount01

//Remove "\" @destination param
az storage blob upload-batch -s . -d $web --account-name firststgaccount01

How to make EditText not editable through XML in Android?

Short answer: I used android:focusable="false" and it worked. Click listening is also working now.

How to change maven logging level to display only warning and errors?

I have noticed when using the 2.20.1 version of the maven sunfire plugin, all warnings are written down to a dumpstream file. e.g. /myproject/target/surefire-reports/2017-11-11T23-02-19_850.dumpstream

What is the default username and password in Tomcat?

Well, you need to look at the answers above, but you'll find that the manager app requires you to have a user with the role 'manager', I believe, so you'll probably want to add the following to your tomcat-users.xml file:

<role rolename="manager"/>
<user username="youruser" password="yourpass" roles="manager"/>

This might seem simplistic, but it's just a simple implementation that you can extend / replace with other authentication mechanisms.

How can I install a .ipa file to my iPhone simulator

You cannot run an ipa file in the simulator because the ipa file is compiled for a phone's ARM architecture, not the simulator's x86 architecture.

However, you can extract an app installed in a local simulator, send it to someone else, and have them copy it to the simulator on their machine.

In terminal, type:

open ~/Library/Application\ Support/iPhone\ Simulator/*/Applications

This will open all the applications folders of all the simulators you have installed. Each of the applications will be in a folder with a random hexadecimal name. You can work out which is your application by looking inside each of them. Once you have found out which one you want, right click it and choose "Compress ..." and it will make a zip file that you can easily copy to another computer and unzip to a similar location.

Kubernetes service external ip pending

Use NodePort:

$ kubectl run user-login --replicas=2 --labels="run=user-login" --image=kingslayerr/teamproject:version2  --port=5000

$ kubectl expose deployment user-login --type=NodePort --name=user-login-service

$ kubectl describe services user-login-service

(Note down the port)

$ kubectl cluster-info

(IP-> Get The IP where master is running)

Your service is accessible at (IP):(port)

jQuery - determine if input element is textbox or select list

If you just want to check the type, you can use jQuery's .is() function,

Like in my case I used below,

if($("#id").is("select")) {
 alert('Select'); 
else if($("#id").is("input")) {
 alert("input");
}

Getting attributes of Enum's value

This piece of code should give you a nice little extension method on any enum that lets you retrieve a generic attribute. I believe it's different to the lambda function above because it's simpler to use and slightly - you only need to pass in the generic type.

public static class EnumHelper
{
    /// <summary>
    /// Gets an attribute on an enum field value
    /// </summary>
    /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
    /// <param name="enumVal">The enum value</param>
    /// <returns>The attribute of type T that exists on the enum value</returns>
    /// <example><![CDATA[string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;]]></example>
    public static T GetAttributeOfType<T>(this Enum enumVal) where T:System.Attribute
    {
        var type = enumVal.GetType();
        var memInfo = type.GetMember(enumVal.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
        return (attributes.Length > 0) ? (T)attributes[0] : null;
    }
}

Install Chrome extension form outside the Chrome Web Store

For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.

Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.

Extensions can be loaded in unpacked mode by following the following steps:

  1. Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  2. Enable Developer mode by ticking the checkbox in the upper-right corner.
  3. Click on the "Load unpacked extension..." button.
  4. Select the directory containing your unpacked extension.

If you have a crx file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.

These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.

SQL ORDER BY multiple columns

It depends on the size of your database.

SQL is based on the SET theory: there is no order inherently used when querying a table.

So if you were to run the first query, it would first order by product price and then product name, IF there were any duplicates in the price category, say $20 for example, it would then order those duplicates by their names, therefore always maintaining that when you run your query it will always return the same set of result in the same order.

If you were to run the second query, it would only order by the name, so if there were two products with the same name (for some odd reason) then they wouldn't have a guaranteed order after you run the query.

How to increase Java heap space for a tomcat app

you can set this in catalina.sh as CATALINA_OPTS=-Xms512m -Xmx512m

Open your tomcat-dir/bin/catalina.sh file and add following line anywhere -

CATALINA_OPTS="$CATALINA_OPTS -Xms1024m -Xmx3024m"

and restart your tomcat

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

Disabling submit button until all fields have values

Grave digging... I like a different approach:

elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)

checkStatus = (e) =>
  elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
  filled = $.grep(elems, (n) -> n)
  bool = elems.size() != $(filled).size()
  $('input:submit').attr('disabled', bool)

Generating a PNG with matplotlib when DISPLAY is undefined

The clean answer is to take a little bit of time correctly prepare your execution environment.

The first technique you have to prepare your execution environment is to use a matplotlibrc file, as wisely recommended by Chris Q., setting

backend : Agg

in that file. You can even control — with no code changes — how and where matplotlib looks for and finds the matplotlibrc file.

The second technique you have to prepare your execution environment is to use the MPLBACKEND environment variable (and inform your users to make use of it):

export MPLBACKEND="agg"
python <program_using_matplotlib.py>

This is handy because you don't even have to provide another file on disk to make this work. I have employed this approach with, for example, testing in continuous integration, and running on remote machines that do not have displays.

Hard-coding your matplotlib backend to "Agg" in your Python code is like bashing a square peg into a round hole with a big hammer, when, instead, you could have just told matplotlib it needs to be a square hole.

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

In Python 2 (3 has different syntax):

What if you can't instantiate your Parent class before you need to call one of its methods?

Use super(ChildClass, self).method() to access parent methods.

class ParentClass(object):
    def method_to_call(self, arg_1):
        print arg_1

class ChildClass(ParentClass):
    def do_thing(self):
        super(ChildClass, self).method_to_call('my arg')

os.walk without digging into directories below

The same idea with listdir, but shorter:

[f for f in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, f))]

Convert JSON format to CSV format for MS Excel

You can use that gist, pretty easy to use, stores your settings in local storage: https://gist.github.com/4533361

Language Books/Tutorials for popular languages

Some books on Java I'd recommend:

For Beginners: Head First Java is an excellent introduction to the language. And I must also mention Head First Design Patterns which is a great resource for learners to grasp what can be quite challenging concepts. The easy-going fun style of these books are ideal for ppl new to programming.

A really thorough, comprehensive book on Java SE is Bruce Eckel's Thinking In Java v4. (At just under 1500 pages it's good for weight-training as well!) For those of us not on fat bank-bonuses there are older versions available for free download.

Of course, as many ppl have already mentioned, Josh Bloch's Effective Java v2 is an essential part of any Java developer's library.

Convert XLS to CSV on command line

I had a need to extract several cvs from different worksheets, so here is a modified version of plang code that allows you to specify the worksheet name.

if WScript.Arguments.Count < 3 Then
    WScript.Echo "Please specify the sheet, the source, the destination files. Usage: ExcelToCsv <sheetName> <xls/xlsx source file> <csv destination file>"
    Wscript.Quit
End If

csv_format = 6

Set objFSO = CreateObject("Scripting.FileSystemObject")

src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(1))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(2))

Dim oExcel
Set oExcel = CreateObject("Excel.Application")

Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)

oBook.Sheets(WScript.Arguments.Item(0)).Select
oBook.SaveAs dest_file, csv_format

oBook.Close False
oExcel.Quit

How to clear cache of Eclipse Indigo

I think you can find the answer you want in these two posts. They are mentioning Flash Builder, but essentially, the talk is about its Eclipse base.

Clear improperly cached compile errors in FlexBuilder: http://blog.aherrman.com/2010/05/clear-improperly-cached-compile-errors.html

How to fix Flash Builder broken workspace: http://va.lent.in/how-to-fix-flash-builder-broken-workspace/

src absolute path problem

<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How to add Options Menu to Fragment in Android

My problem was slightly different. I did everything right. But I was inheriting the wrong class for the activity hosting the fragment.

So to be clear, if you are overriding onCreateOptionsMenu(Menu menu, MenuInflater inflater) in the fragment, make sure your activity class which hosts this fragment inherits android.support.v7.app.ActionBarActivity (in case you would want to support below API level 11).

I was inheriting the android.support.v4.app.FragmentActivity to support API level below 11.

Hibernate: hbm2ddl.auto=update in production?

No, it's unsafe.

Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates in production. Write your own patches, review them with DBA, test them, then apply them manually.

Theoretically, if hbm2ddl update worked in development, it should work in production too. But in reality, it's not always the case.

Even if it worked OK, it may be sub-optimal. DBAs are paid that much for a reason.

Convert Object to JSON string

You can use the excellent jquery-Json plugin:

http://code.google.com/p/jquery-json/

Makes it easy to convert to and from Json objects.

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

How to write to a CSV line by line?

General way:

##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
    for line in text:
        file.write(line)
        file.write('\n')

OR

Using CSV writer :

import csv
with open(<path to output_csv>, "wb") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)

OR

Simplest way:

f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()

error: pathspec 'test-branch' did not match any file(s) known to git

I got this error because the instruction on the Web was

git checkout https://github.com/veripool/verilog-mode

which I did in a directory where (on my own initiative) i had run git init. The correct Web instruction (for newbies like me) should have been

git clone https://github.com/veripool/verilog-mode

PPT to PNG with transparent background

I just tried to make a transparent image with powerpoint after failing miserably with other online systems. I was successful. Amazing.

First I used word art to give me typefaces which convert well to PNG or JPEG. The ordinary text in powerpoint does not convert well. It gets fuzzy. Anyway, I typed in my words in white (my choice of colour as i wanted it against a navy blue background), arranged it how i wanted, then right clicked and selected format shape to remove lines, then shadow to set the transparency.

I took the transparency to 100%. It came out fine. i then right clicked to save as png. Opened the image with MS Picture manager and resized the image to my suiting. It did not come out with the powerpoint white background at all. Once resized, i dropped the image against my navy blue background and it was like magic.

Counter in foreach loop in C#

From MSDN:

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable(Of T) interface.

So, it's not necessarily Array. It could even be a lazy collection with no idea about the count of items in the collection.

How do you print in a Go test using the "testing" package?

The structs testing.T and testing.B both have a .Log and .Logf method that sound to be what you are looking for. .Log and .Logf are similar to fmt.Print and fmt.Printf respectively.

See more details here: http://golang.org/pkg/testing/#pkg-index

fmt.X print statements do work inside tests, but you will find their output is probably not on screen where you expect to find it and, hence, why you should use the logging methods in testing.

If, as in your case, you want to see the logs for tests that are not failing, you have to provide go test the -v flag (v for verbosity). More details on testing flags can be found here: https://golang.org/cmd/go/#hdr-Testing_flags

Experimental decorators warning in TypeScript compilation

In Visual Code Studio Go to File >> Preferences >> Settings, Search "decorator" in search field and Check the option as in image. enter image description here

Create zip file and ignore directory structure

Retain the parent directory so unzip doesn't spew files everywhere

When zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file

So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:

cd path/to/parent/dir/;
zip -r ../my.zip ../$(basename $PWD)
cd -;

The ../$(basename $PWD) is the magic that retains the parent directory.

So now unzip my.zip will give a folder containing all your files:

parent-directory
+-- file1
+-- file2
+-- dir1
¦   +-- file3
¦   +-- file4

Instead of littering the current directory with the unzipped files:

file1
file2
dir1
+-- file3
+-- file4

Remove duplicated rows using dplyr

Note: dplyr now contains the distinct function for this purpose.

Original answer below:


library(dplyr)
set.seed(123)
df <- data.frame(
  x = sample(0:1, 10, replace = T),
  y = sample(0:1, 10, replace = T),
  z = 1:10
)

One approach would be to group, and then only keep the first row:

df %>% group_by(x, y) %>% filter(row_number(z) == 1)

## Source: local data frame [3 x 3]
## Groups: x, y
## 
##   x y z
## 1 0 1 1
## 2 1 0 2
## 3 1 1 4

(In dplyr 0.2 you won't need the dummy z variable and will just be able to write row_number() == 1)

I've also been thinking about adding a slice() function that would work like:

df %>% group_by(x, y) %>% slice(from = 1, to = 1)

Or maybe a variation of unique() that would let you select which variables to use:

df %>% unique(x, y)

How to run PowerShell in CMD

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

How to break out of jQuery each Loop

I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.

$('.groupName').each(function() {
    if($(this).text() == groupname){
        alert('This group already exists');
        breakOut = true;
        return false;
    }
});
if(breakOut) {
    breakOut = false;
    return false;
} 

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Because linux is a built-in macro defined when the compiler is running on, or compiling for (if it is a cross-compiler), Linux.

There are a lot of such predefined macros. With GCC, you can use:

cp /dev/null emptyfile.c
gcc -E -dM emptyfile.c

to get a list of macros. (I've not managed to persuade GCC to accept /dev/null directly, but the empty file seems to work OK.) With GCC 4.8.1 running on Mac OS X 10.8.5, I got the output:

#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 65535
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __UINT_LEAST8_TYPE__ unsigned char
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 255
#define __WINT_MAX__ 2147483647
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 18446744073709551615UL
#define __WCHAR_MAX__ 2147483647
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __FLT_EVAL_METHOD__ 0
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __x86_64 1
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
#define __SIG_ATOMIC_TYPE__ int
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __GNUC_PATCHLEVEL__ 1
#define __UINT_FAST8_MAX__ 255
#define __DEC64_MAX_EXP__ 385
#define __INT8_C(c) c
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINT_LEAST8_MAX__ 255
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __APPLE_CC__ 1
#define __UINTMAX_TYPE__ long unsigned int
#define __DEC32_EPSILON__ 1E-6DF
#define __UINT32_MAX__ 4294967295U
#define __LDBL_MAX_EXP__ 16384
#define __WINT_MIN__ (-__WINT_MAX__ - 1)
#define __SCHAR_MAX__ 127
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __INT64_C(c) c ## LL
#define __DBL_DIG__ 15
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __SIZEOF_INT__ 4
#define __SIZEOF_POINTER__ 8
#define __USER_LABEL_PREFIX__ _
#define __STDC_HOSTED__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __DEC32_MAX__ 9.999999E96DF
#define __strong 
#define __INT32_MAX__ 2147483647
#define __SIZEOF_LONG__ 8
#define __APPLE__ 1
#define __UINT16_C(c) c
#define __DECIMAL_DIG__ 21
#define __LDBL_HAS_QUIET_NAN__ 1
#define __DYNAMIC__ 1
#define __GNUC__ 4
#define __MMX__ 1
#define __FLT_HAS_DENORM__ 1
#define __SIZEOF_LONG_DOUBLE__ 16
#define __BIGGEST_ALIGNMENT__ 16
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __INT_FAST32_MAX__ 2147483647
#define __DBL_HAS_INFINITY__ 1
#define __DEC32_MIN_EXP__ (-94)
#define __INT_FAST16_TYPE__ short int
#define __LDBL_HAS_DENORM__ 1
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __INT_LEAST32_MAX__ 2147483647
#define __DEC32_MIN__ 1E-95DF
#define __weak 
#define __DBL_MAX_EXP__ 1024
#define __DEC128_EPSILON__ 1E-33DL
#define __SSE2_MATH__ 1
#define __ATOMIC_HLE_RELEASE 131072
#define __PTRDIFF_MAX__ 9223372036854775807L
#define __amd64 1
#define __tune_core2__ 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __LONG_LONG_MAX__ 9223372036854775807LL
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WINT_T__ 4
#define __GXX_ABI_VERSION 1002
#define __FLT_MIN_EXP__ (-125)
#define __INT_FAST64_TYPE__ long long int
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __LP64__ 1
#define __DEC128_MIN__ 1E-6143DL
#define __REGISTER_PREFIX__ 
#define __UINT16_MAX__ 65535
#define __DBL_HAS_DENORM__ 1
#define __UINT8_TYPE__ unsigned char
#define __NO_INLINE__ 1
#define __FLT_MANT_DIG__ 24
#define __VERSION__ "4.8.1"
#define __UINT64_C(c) c ## ULL
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __INT32_C(c) c
#define __DEC64_EPSILON__ 1E-15DD
#define __ORDER_PDP_ENDIAN__ 3412
#define __DEC128_MIN_EXP__ (-6142)
#define __INT_FAST32_TYPE__ int
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __INT16_MAX__ 32767
#define __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 1080
#define __SIZE_TYPE__ long unsigned int
#define __UINT64_MAX__ 18446744073709551615ULL
#define __INT8_TYPE__ signed char
#define __FLT_RADIX__ 2
#define __INT_LEAST16_TYPE__ short int
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __UINTMAX_C(c) c ## UL
#define __SSE_MATH__ 1
#define __k8 1
#define __SIG_ATOMIC_MAX__ 2147483647
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __SIZEOF_PTRDIFF_T__ 8
#define __x86_64__ 1
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __INT_FAST16_MAX__ 32767
#define __UINT_FAST32_MAX__ 4294967295U
#define __UINT_LEAST64_TYPE__ long long unsigned int
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MAX_10_EXP__ 38
#define __LONG_MAX__ 9223372036854775807L
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __FLT_HAS_INFINITY__ 1
#define __UINT_FAST16_TYPE__ short unsigned int
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __CHAR16_TYPE__ short unsigned int
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __INT_LEAST16_MAX__ 32767
#define __DEC64_MANT_DIG__ 16
#define __INT64_MAX__ 9223372036854775807LL
#define __UINT_LEAST32_MAX__ 4294967295U
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __INT_LEAST64_TYPE__ long long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __DEC32_MAX_EXP__ 97
#define __INT_FAST8_MAX__ 127
#define __INTPTR_MAX__ 9223372036854775807L
#define __LITTLE_ENDIAN__ 1
#define __SSE2__ 1
#define __LDBL_MANT_DIG__ 64
#define __CONSTANT_CFSTRINGS__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __code_model_small__ 1
#define __k8__ 1
#define __INTPTR_TYPE__ long int
#define __UINT16_TYPE__ short unsigned int
#define __WCHAR_TYPE__ int
#define __SIZEOF_FLOAT__ 4
#define __pic__ 2
#define __UINTPTR_MAX__ 18446744073709551615UL
#define __DEC64_MIN_EXP__ (-382)
#define __INT_FAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __FLT_DIG__ 6
#define __UINT_FAST64_TYPE__ long long unsigned int
#define __INT_MAX__ 2147483647
#define __MACH__ 1
#define __amd64__ 1
#define __INT64_TYPE__ long long int
#define __FLT_MAX_EXP__ 128
#define __ORDER_BIG_ENDIAN__ 4321
#define __DBL_MANT_DIG__ 53
#define __INT_LEAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __DEC64_MIN__ 1E-383DD
#define __WINT_TYPE__ int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __SIZEOF_SHORT__ 2
#define __SSE__ 1
#define __LDBL_MIN_EXP__ (-16381)
#define __INT_LEAST8_MAX__ 127
#define __SIZEOF_INT128__ 16
#define __LDBL_MAX_10_EXP__ 4932
#define __ATOMIC_RELAXED 0
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define _LP64 1
#define __UINT8_C(c) c
#define __INT_LEAST32_TYPE__ int
#define __SIZEOF_WCHAR_T__ 4
#define __UINT64_TYPE__ long long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __DBL_DECIMAL_DIG__ 17
#define __FXSR__ 1
#define __DEC_EVAL_METHOD__ 2
#define __UINT32_C(c) c ## U
#define __INTMAX_MAX__ 9223372036854775807L
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __INT8_MAX__ 127
#define __PIC__ 2
#define __UINT_FAST32_TYPE__ unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __INT32_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __FLT_MIN_10_EXP__ (-37)
#define __INTMAX_TYPE__ long int
#define __DEC128_MAX_EXP__ 6145
#define __ATOMIC_CONSUME 1
#define __GNUC_MINOR__ 8
#define __UINTMAX_MAX__ 18446744073709551615UL
#define __DEC32_MANT_DIG__ 7
#define __DBL_MAX_10_EXP__ 308
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __INT16_C(c) c
#define __STDC__ 1
#define __PTRDIFF_TYPE__ long int
#define __ATOMIC_SEQ_CST 5
#define __UINT32_TYPE__ unsigned int
#define __UINTPTR_TYPE__ long unsigned int
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DEC128_MANT_DIG__ 34
#define __LDBL_MIN_10_EXP__ (-4931)
#define __SIZEOF_LONG_LONG__ 8
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __LDBL_DIG__ 18
#define __FLT_DECIMAL_DIG__ 9
#define __UINT_FAST16_MAX__ 65535
#define __GNUC_GNU_INLINE__ 1
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __SSE3__ 1
#define __UINT_FAST8_TYPE__ unsigned char
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_RELEASE 3

That's 236 macros from an empty file. When I added #include <stdio.h> to the file, the number of macros defined went up to 505. These includes all sorts of platform-identifying macros.

How to resolve "Waiting for Debugger" message?

I tried all the solutions above, it fixes the issue sometimes, but still from time to time I happened to get stuck with the "Waiting for the debugger to attach" message box.

The final solution in my case was to unplug all the Android devices but the one I want to debug on. I don't know which one is the culprit: the Nexus 7 running JB 4.2, the HTC One X running ICS, the HTC Desire S running Gingerbread, or the combintation of the 3, but as soon as I only have one device plugged in, it runs smooth as silk.

CodeIgniter - return only one row?

Change only in two line and you are getting actually what you want.

$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;

try it.

Convert seconds to Hour:Minute:Second

If you don't like accepted answer or popular ones, then try this one

function secondsToTime($seconds_time)
{
    if ($seconds_time < 24 * 60 * 60) {
        return gmdate('H:i:s', $seconds_time);
    } else {
        $hours = floor($seconds_time / 3600);
        $minutes = floor(($seconds_time - $hours * 3600) / 60);
        $seconds = floor($seconds_time - ($hours * 3600) - ($minutes * 60));
        return "$hours:$minutes:$seconds";
    }
}

secondsToTime(108620); // 30:10:20

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

Questions every good Database/SQL developer should be able to answer

At our company, instead of asking a lot of SQL questions that anyone with a good memory can answer, we created a SQL Developers test. The test is designed to have the candidate put together a solid schema with normalization and RI considerations, check constraints etc. And then be able to create some queries to produce results sets we're looking for. They create all this against a brief design specification we give them. They are allowed to do this at home, and take as much time as they need (within reason).

What are some good Python ORM solutions?

I usually use SQLAlchemy. It's pretty powerful and is probably the most mature python ORM.

If you're planning on using CherryPy, you might also look into dejavu as it's by Robert Brewer (the guy that is the current CherryPy project leader). I personally haven't used it, but I do know some people that love it.

SQLObject is a little bit easier to use ORM than SQLAlchemy, but it's not quite as powerful.

Personally, I wouldn't use the Django ORM unless I was planning on writing the entire project in Django, but that's just me.

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

Efficient way of having a function only execute once in a loop

You can also use one of the standard library functools.lru_cache or functools.cache decorators in front of the function:

from functools import lru_cache

@lru_cache def expensive_function(): return None

https://docs.python.org/3/library/functools.html

Python 3: ImportError "No Module named Setuptools"

Your setup.py file needs setuptools. Some Python packages used to use distutils for distribution, but most now use setuptools, a more complete package. Here is a question about the differences between them.

To install setuptools on Debian:

sudo apt-get install python3-setuptools

For an older version of Python (Python 2.x):

sudo apt-get install python-setuptools

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

If you need to setup this after the modal is shown, you can use @Nabid solution. However, sometimes you still need to allow some method to close the modal. Assuming you have a button with class really-close-the-modal, which should really close the modal, you can use this code (jquery):

var closeButtonClicked = false;

$('.really-close-the-modal').on('click', function () {
    closeButtonClicked = true;
});

$('#myModal').on('hide.bs.modal', function (e) {
    if (!closeButtonClicked) {
        e.preventDefault();
        e.stopPropagation();
        return false;
    }
    closeButtonClicked = false;
});

This isn't really nice code design, but it helped me in a situation where the modal was shown with a loader animation, until an ajax request returned, and only then could I know if the modal needed to be configured to prevent "implicit" closing. You can use a similar design to prevent closing the modal while it's still loading.

Uninstall mongoDB from ubuntu

use sudo with the command:

sudo apt-get remove --purge mongodb  
apt-get autoremove --purge mongodb  

PUT vs. POST in REST

Both are used for data transmission between client to server, but there are subtle differences between them, which are:

Enter image description here

Analogy:

  • PUT i.e. take and put where it was.
  • POST as send mail in post office.

enter image description here

Social Media/Network Analogy:

  • Post on social media: when we post message, it creates new post.
  • Put(i.e. edit) for the message we already Posted.

How to change the bootstrap primary color?

Using SaSS
change the brand color

$brand-primary:#some-color;

this will change the primary color accross all UI.

Using css-
suppose you want to change button primary color.So

btn.primary{
  background:#some-color;
}

search the element and add a new css/sass rule in a new file and attach it after u load the bootstrap css.

Convert JsonObject to String

You can use reliable library GSON

private static final Type DATA_TYPE_JSON = 
        new TypeToken<JSONObject>() {}.getType();           
JSONObject orderJSON = new JSONObject();
orderJSON.put("noOfLayers", "2");
orderJSON.put("baseMaterial", "mat");
System.out.println("JSON == "+orderJSON.toString());
String dataAsJson = new Gson().toJson(orderJSON, DATA_TYPE_JSON);
System.out.println("Value of dataAsJson == "+dataAsJson.toString());
String data = new Gson().toJson(dataAsJson);
System.out.println("Value of jsonString == "+data.toString());

How to Call VBA Function from Excel Cells?

A Function will not work, nor is it necessary:

Sub OpenWorkbook()
    Dim r1 As Range, r2 As Range, o As Workbook
    Set r1 = ThisWorkbook.Sheets("Sheet1").Range("A1")
    Set o = Workbooks.Open(Filename:="C:\TestFolder\ABC.xlsx")
    Set r2 = ActiveWorkbook.Sheets("Sheet1").Range("B2")
    [r1] = [r2]
    o.Close
End Sub

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

In Eclipse, go to the Servers project. Open the tree for the Tomcat version you are using. Open file server.xml and verify your Context tags.

Add marker to Google Map on Click

@Chaibi Alaa, To make the user able to add only once, and move the marker; You can set the marker on first click and then just change the position on subsequent clicks.

var marker;

google.maps.event.addListener(map, 'click', function(event) {
   placeMarker(event.latLng);
});


function placeMarker(location) {

    if (marker == null)
    {
          marker = new google.maps.Marker({
             position: location,
             map: map
          }); 
    } 
    else 
    {
        marker.setPosition(location); 
    } 
}

how to overwrite css style

You can add your styles in the required page after the external style sheet so they'll cascade and overwrite the first set of rules.

<link rel="stylesheet" href="allpages.css">
<style>
.flex-control-thumbs li {
  width: auto;
  float: none;
}
</style>

Face recognition Library

I would think Eigenface, which you are doing already, is the way to go if you want to calculate the distance between faces. You could try out different approaches like Support Vector Machine or Hidden Markov Model. I found a page that lists major algorithms that could be used for facial recognition: Face Recognition Homepage.

Also, when you say "better performance," do you mean speed or accuracy? What kind of problem are you having? How varying are the data? Are they mostly frontal face or do they include profiles?

How to run docker-compose up -d at system start up?

When we use crontab or the deprecated /etc/rc.local file, we need a delay (e.g. sleep 10, depending on the machine) to make sure that system services are available. Usually, systemd (or upstart) is used to manage which services start when the system boots. You can try use the similar configuration for this:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target

Or, if you want run without the -d flag:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
Restart=on-failure
StartLimitIntervalSec=60
StartLimitBurst=3

[Install]
WantedBy=multi-user.target

Change the WorkingDirectory parameter with your dockerized project path. And enable the service to start automatically:

systemctl enable docker-compose-app

MySQL direct INSERT INTO with WHERE clause

you can use UPDATE command.

UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id

jquery data selector

You can set a data-* attribute on an elm using attr(), and then select using that attribute:

var elm = $('a').attr('data-test',123); //assign 123 using attr()
elm = $("a[data-test=123]"); //select elm using attribute

and now for that elm, both attr() and data() will yield 123:

console.log(elm.attr('data-test')); //123
console.log(elm.data('test')); //123

However, if you modify the value to be 456 using attr(), data() will still be 123:

elm.attr('data-test',456); //modify to 456
elm = $("a[data-test=456]"); //reselect elm using new 456 attribute

console.log(elm.attr('data-test')); //456
console.log(elm.data('test')); //123

So as I understand it, seems like you probably should steer clear of intermingling attr() and data() commands in your code if you don't have to. Because attr() seems to correspond directly with the DOM whereas data() interacts with the 'memory', though its initial value can be from the DOM. But the key point is that the two are not necessarily in sync at all.

So just be careful.

At any rate, if you aren't changing the data-* attribute in the DOM or in the memory, then you won't have a problem. Soon as you start modifying values is when potential problems can arise.

Thanks to @Clarence Liu to @Ash's answer, as well as this post.

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I think I found the answer in my kernel source documentation: /usr/src/linux-2.6.37-rc3/Documentation/filesystems/proc.txt

1.7 TTY info in /proc/tty
-------------------------

Information about  the  available  and actually used tty's can be found in the
directory /proc/tty.You'll  find  entries  for drivers and line disciplines in
this directory, as shown in Table 1-11.


Table 1-11: Files in /proc/tty
..............................................................................
 File          Content                                        
 drivers       list of drivers and their usage                
 ldiscs        registered line disciplines                    
 driver/serial usage statistic and status of single tty lines 
..............................................................................

To see  which  tty's  are  currently in use, you can simply look into the file
/proc/tty/drivers:

  > cat /proc/tty/drivers 
  pty_slave            /dev/pts      136   0-255 pty:slave 
  pty_master           /dev/ptm      128   0-255 pty:master 
  pty_slave            /dev/ttyp       3   0-255 pty:slave 
  pty_master           /dev/pty        2   0-255 pty:master 
  serial               /dev/cua        5   64-67 serial:callout 
  serial               /dev/ttyS       4   64-67 serial 
  /dev/tty0            /dev/tty0       4       0 system:vtmaster 
  /dev/ptmx            /dev/ptmx       5       2 system 
  /dev/console         /dev/console    5       1 system:console 
  /dev/tty             /dev/tty        5       0 system:/dev/tty 
  unknown              /dev/tty        4    1-63 console 

Here is a link to this file: http://git.kernel.org/?p=linux/kernel/git/next/linux-next.git;a=blob_plain;f=Documentation/filesystems/proc.txt;hb=e8883f8057c0f7c9950fa9f20568f37bfa62f34a

Reversing a string in C

You can actually do something like this:

#include <string.h>

void reverse(char *);

int main(void){
 char name[7] = "walter";
 reverse(name);
 printf("%s", name);
}

void reverse(char *s) {
  size_t len = strlen(s);
  char *a = s;
  char *b = &s[(int)len - 1];
  char tmp;
  for (; a < b; ++a, --b) {
    tmp = *a;
    *a = *b;
    *b = tmp;
  }
}

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

We had a problem like this with ASP.Net. Our IIS was returning an Internal Server Error when trying to execute a jQuery $.post to get some html content due to PageHandlerFactory was restricted to respond only GET,HEAD,POST,DEBUG Verbs. So you can change that restriction adding the verb "OPTIONS" to the list or selecting "All Verbs"

You can modify that in your IIS Manager, selecting your website, then selecting Handler Mappings, double click in your PageHandlerFactory for *.apx files as you need (We use Integrated application pool with framework 4.0). Click on Request Restrictions, then go to Verbs Tabn and apply your modification.

Now our $.post request is working as expected :)

How to remove a field completely from a MongoDB document?

Try this: If your collection was 'example'

db.example.update({}, {$unset: {words:1}}, false, true);

Refer this:

http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset

UPDATE:

The above link no longer covers '$unset'ing. Be sure to add {multi: true} if you want to remove this field from all of the documents in the collection; otherwise, it will only remove it from the first document it finds that matches. See this for updated documentation:

https://docs.mongodb.com/manual/reference/operator/update/unset/

Example:

db.example.update({}, {$unset: {words:1}} , {multi: true});

Extracting hours from a DateTime (SQL Server 2005)

... you can use it on any granularity type i.e.:

DATEPART(YEAR, [date])

DATEPART(MONTH, [date]) 

DATEPART(DAY, [date])    

DATEPART(HOUR, [date]) 

DATEPART(MINUTE, [date])

(note: I like the [ ] around the date reserved word though. Of course that's in case your column with timestamp is labeled "date")

html - table row like a link

When i want simulate a <tr> with a link but respecting the html standards, I do this.

HTML:

<table>
    <tr class="trLink">
        <td>
            <a href="#">Something</a>
        </td>
    </tr>
</table>

CSS:

tr.trLink {
    cursor: pointer;
}
tr.trLink:hover {
   /*TR-HOVER-STYLES*/
}

tr.trLink a{
    display: block;
    height: 100%;
    width: 100%;
}
tr.trLink:hover a{
   /*LINK-HOVER-STYLES*/
}

In this way, when someone go with his mouse on a TR, all the row (and this links) gets the hover style and he can't see that there are multiple links.

Hope can help someone.

Fiddle HERE

String field value length in mongoDB

This query will give both field value and length:

db.usercollection.aggregate([
{
    $project: {
        "name": 1,
        "length": { $strLenCP: "$name" }
    }} ])

How to set selected index JComboBox by value

http://docs.oracle.com/javase/6/docs/api/javax/swing/JComboBox.html#setSelectedItem(java.lang.Object)

test.setSelectedItem("banana");

There are some caveats or potentially unexpected behavior as explained in the javadoc. Make sure to read that.

Constructors in Go

I like the explanation from this blog post:

The function New is a Go convention for packages that create a core type or different types for use by the application developer. Look at how New is defined and implemented in log.go, bufio.go and cypto.go:

log.go

// New creates a new Logger. The out variable sets the
// destination to which log data will be written.
// The prefix appears at the beginning of each generated log line.
// The flag argument defines the logging properties.
func New(out io.Writer, prefix string, flag int) * Logger {
    return &Logger{out: out, prefix: prefix, flag: flag}
}

bufio.go

// NewReader returns a new Reader whose buffer has the default size.
func NewReader(rd io.Reader) * Reader {
    return NewReaderSize(rd, defaultBufSize)
}

crypto.go

// New returns a new hash.Hash calculating the given hash function. New panics
// if the hash function is not linked into the binary.
func (h Hash) New() hash.Hash {
    if h > 0 && h < maxHash {
        f := hashes[h]
        if f != nil {
            return f()
        }
    }
    panic("crypto: requested hash function is unavailable")
}

Since each package acts as a namespace, every package can have their own version of New. In bufio.go multiple types can be created, so there is no standalone New function. Here you will find functions like NewReader and NewWriter.

How do you refresh the MySQL configuration file without restarting?

Specific actions you can do from SQL client and you don't need to restart anything:

SET GLOBAL log = 'ON';
FLUSH LOGS;

What is the syntax of the enhanced for loop in Java?

An enhanced for loop is just limiting the number of parameters inside the parenthesis.

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

Can be written as:

for (int myValue : myArray) {
    System.out.println(myValue);
}

Escaping quotes and double quotes

Using the backtick (`) works fine for me if I put them in the following places:

$cmd="\\server\toto.exe -batch=B -param=`"sort1;parmtxt='Security ID=1234'`""

$cmd returns as:

\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"

Is that what you were looking for?

The error PowerShell gave me referred to an unexpected token 'sort1', and that's how I determined where to put the backticks.

The @' ... '@ syntax is called a "here string" and will return exactly what is entered. You can also use them to populate variables in the following fashion:

$cmd=@'
"\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'""
'@

The opening and closing symbols must be on their own line as shown above.

Unable to make the session state request to the session state server

Another thing to check is whether you have Windows Firewall enabled, since that might be blocking port 42424.

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

How to discard local commits in Git?

What I do is I try to reset hard to HEAD. This will wipe out all the local commits:

git reset --hard HEAD^

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

Integer ASCII value to character in BASH using printf

this prints all the "printable" characters of your basic bash setup:

printf '%b\n' $(printf '\\%03o' {30..127})

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Case insensitive string compare in LINQ-to-SQL

where row.name.StartsWith(q, true, System.Globalization.CultureInfo.CurrentCulture)

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

First off, add a suffix to the application package in Gradle:

yourFlavor {
   applicationIdSuffix "yourFlavor"
}

This will cause your package to be named

com.domain.yourapp.yourFlavor

Then go to Firebase under your current project and add another android app to it with this package name.

Then replace the existing google-services.json file with the new one you generate with the new app in it.

Then you will end up with something that has multiple "client_info" sections. So you should end up with something like this:

"client_info": {
    "mobilesdk_app_id": "YOUR APP INFO",
    "android_client_info": {
      "package_name": "com.domain.yourapp"
    }
  }

"client_info": {
    "mobilesdk_app_id": "YOUR APP INFO - will be different then other app info",
    "android_client_info": {
      "package_name": "com.domain.yourapp.yourFlavor"
    }
  }

Finding first and last index of some value in a list in Python

Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value).

You can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)

What are POD types in C++?

Examples of all non-POD cases with static_assert from C++11 to C++17 and POD effects

std::is_pod was added in C++11, so let's consider that standard onwards for now.

std::is_pod will be removed from C++20 as mentioned at https://stackoverflow.com/a/48435532/895245 , let's update this as support arrives for the replacements.

POD restrictions have become more and more relaxed as the standard evolved, I aim to cover all relaxations in the example through ifdefs.

libstdc++ has at tiny bit of testing at: https://github.com/gcc-mirror/gcc/blob/gcc-8_2_0-release/libstdc%2B%2B-v3/testsuite/20_util/is_pod/value.cc but it just too little. Maintainers: please merge this if you read this post. I'm lazy to check out all the C++ testsuite projects mentioned at: https://softwareengineering.stackexchange.com/questions/199708/is-there-a-compliance-test-for-c-compilers

#include <type_traits>
#include <array>
#include <vector>

int main() {
#if __cplusplus >= 201103L
    // # Not POD
    //
    // Non-POD examples. Let's just walk all non-recursive non-POD branches of cppreference.
    {
        // Non-trivial implies non-POD.
        // https://en.cppreference.com/w/cpp/named_req/TrivialType
        {
            // Has one or more default constructors, all of which are either
            // trivial or deleted, and at least one of which is not deleted.
            {
                // Not trivial because we removed the default constructor
                // by using our own custom non-default constructor.
                {
                    struct C {
                        C(int) {}
                    };
                    static_assert(std::is_trivially_copyable<C>(), "");
                    static_assert(!std::is_trivial<C>(), "");
                    static_assert(!std::is_pod<C>(), "");
                }

                // No, this is not a default trivial constructor either:
                // https://en.cppreference.com/w/cpp/language/default_constructor
                //
                // The constructor is not user-provided (i.e., is implicitly-defined or
                // defaulted on its first declaration)
                {
                    struct C {
                        C() {}
                    };
                    static_assert(std::is_trivially_copyable<C>(), "");
                    static_assert(!std::is_trivial<C>(), "");
                    static_assert(!std::is_pod<C>(), "");
                }
            }

            // Not trivial because not trivially copyable.
            {
                struct C {
                    C(C&) {}
                };
                static_assert(!std::is_trivially_copyable<C>(), "");
                static_assert(!std::is_trivial<C>(), "");
                static_assert(!std::is_pod<C>(), "");
            }
        }

        // Non-standard layout implies non-POD.
        // https://en.cppreference.com/w/cpp/named_req/StandardLayoutType
        {
            // Non static members with different access control.
            {
                // i is public and j is private.
                {
                    struct C {
                        public:
                            int i;
                        private:
                            int j;
                    };
                    static_assert(!std::is_standard_layout<C>(), "");
                    static_assert(!std::is_pod<C>(), "");
                }

                // These have the same access control.
                {
                    struct C {
                        private:
                            int i;
                            int j;
                    };
                    static_assert(std::is_standard_layout<C>(), "");
                    static_assert(std::is_pod<C>(), "");

                    struct D {
                        public:
                            int i;
                            int j;
                    };
                    static_assert(std::is_standard_layout<D>(), "");
                    static_assert(std::is_pod<D>(), "");
                }
            }

            // Virtual function.
            {
                struct C {
                    virtual void f() = 0;
                };
                static_assert(!std::is_standard_layout<C>(), "");
                static_assert(!std::is_pod<C>(), "");
            }

            // Non-static member that is reference.
            {
                struct C {
                    int &i;
                };
                static_assert(!std::is_standard_layout<C>(), "");
                static_assert(!std::is_pod<C>(), "");
            }

            // Neither:
            //
            // - has no base classes with non-static data members, or
            // - has no non-static data members in the most derived class
            //   and at most one base class with non-static data members
            {
                // Non POD because has two base classes with non-static data members.
                {
                    struct Base1 {
                        int i;
                    };
                    struct Base2 {
                        int j;
                    };
                    struct C : Base1, Base2 {};
                    static_assert(!std::is_standard_layout<C>(), "");
                    static_assert(!std::is_pod<C>(), "");
                }

                // POD: has just one base class with non-static member.
                {
                    struct Base1 {
                        int i;
                    };
                    struct C : Base1 {};
                    static_assert(std::is_standard_layout<C>(), "");
                    static_assert(std::is_pod<C>(), "");
                }

                // Just one base class with non-static member: Base1, Base2 has none.
                {
                    struct Base1 {
                        int i;
                    };
                    struct Base2 {};
                    struct C : Base1, Base2 {};
                    static_assert(std::is_standard_layout<C>(), "");
                    static_assert(std::is_pod<C>(), "");
                }
            }

            // Base classes of the same type as the first non-static data member.
            // TODO failing on GCC 8.1 -std=c++11, 14 and 17.
            {
                struct C {};
                struct D : C {
                    C c;
                };
                //static_assert(!std::is_standard_layout<C>(), "");
                //static_assert(!std::is_pod<C>(), "");
            };

            // C++14 standard layout new rules, yay!
            {
                // Has two (possibly indirect) base class subobjects of the same type.
                // Here C has two base classes which are indirectly "Base".
                //
                // TODO failing on GCC 8.1 -std=c++11, 14 and 17.
                // even though the example was copy pasted from cppreference.
                {
                    struct Q {};
                    struct S : Q { };
                    struct T : Q { };
                    struct U : S, T { };  // not a standard-layout class: two base class subobjects of type Q
                    //static_assert(!std::is_standard_layout<U>(), "");
                    //static_assert(!std::is_pod<U>(), "");
                }

                // Has all non-static data members and bit-fields declared in the same class
                // (either all in the derived or all in some base).
                {
                    struct Base { int i; };
                    struct Middle : Base {};
                    struct C : Middle { int j; };
                    static_assert(!std::is_standard_layout<C>(), "");
                    static_assert(!std::is_pod<C>(), "");
                }

                // None of the base class subobjects has the same type as
                // for non-union types, as the first non-static data member
                //
                // TODO: similar to the C++11 for which we could not make a proper example,
                // but with recursivity added.

                // TODO come up with an example that is POD in C++14 but not in C++11.
            }
        }
    }

    // # POD
    //
    // POD examples. Everything that does not fall neatly in the non-POD examples.
    {
        // Can't get more POD than this.
        {
            struct C {};
            static_assert(std::is_pod<C>(), "");
            static_assert(std::is_pod<int>(), "");
        }

        // Array of POD is POD.
        {
            struct C {};
            static_assert(std::is_pod<C>(), "");
            static_assert(std::is_pod<C[]>(), "");
        }

        // Private member: became POD in C++11
        // https://stackoverflow.com/questions/4762788/can-a-class-with-all-private-members-be-a-pod-class/4762944#4762944
        {
            struct C {
                private:
                    int i;
            };
#if __cplusplus >= 201103L
            static_assert(std::is_pod<C>(), "");
#else
            static_assert(!std::is_pod<C>(), "");
#endif
        }

        // Most standard library containers are not POD because they are not trivial,
        // which can be seen directly from their interface definition in the standard.
        // https://stackoverflow.com/questions/27165436/pod-implications-for-a-struct-which-holds-an-standard-library-container
        {
            static_assert(!std::is_pod<std::vector<int>>(), "");
            static_assert(!std::is_trivially_copyable<std::vector<int>>(), "");
            // Some might be though:
            // https://stackoverflow.com/questions/3674247/is-stdarrayt-s-guaranteed-to-be-pod-if-t-is-pod
            static_assert(std::is_pod<std::array<int, 1>>(), "");
        }
    }

    // # POD effects
    //
    // Now let's verify what effects does PODness have.
    //
    // Note that this is not easy to do automatically, since many of the
    // failures are undefined behaviour.
    //
    // A good initial list can be found at:
    // https://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special/4178176#4178176
    {
        struct Pod {
            uint32_t i;
            uint64_t j;
        };
        static_assert(std::is_pod<Pod>(), "");

        struct NotPod {
            NotPod(uint32_t i, uint64_t j) : i(i), j(j) {}
            uint32_t i;
            uint64_t j;
        };
        static_assert(!std::is_pod<NotPod>(), "");

        // __attribute__((packed)) only works for POD, and is ignored for non-POD, and emits a warning
        // https://stackoverflow.com/questions/35152877/ignoring-packed-attribute-because-of-unpacked-non-pod-field/52986680#52986680
        {
            struct C {
                int i;
            };

            struct D : C {
                int j;
            };

            struct E {
                D d;
            } /*__attribute__((packed))*/;

            static_assert(std::is_pod<C>(), "");
            static_assert(!std::is_pod<D>(), "");
            static_assert(!std::is_pod<E>(), "");
        }
    }
#endif
}

GitHub upstream.

Tested with:

for std in 11 14 17; do echo $std; g++-8 -Wall -Werror -Wextra -pedantic -std=c++$std pod.cpp; done

on Ubuntu 18.04, GCC 8.2.0.

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

In addition to REMOTE_ADDR and HTTP_X_FORWARDED_FOR there are some other headers that can be set such as:

  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR can be comma delimited list of IPs
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED

I found the code on the following site useful:
http://www.grantburton.com/?p=97

How to echo (or print) to the js console with php

<?php  echo "<script>console.log({$yourVariable})</script>"; ?>

Where is the WPF Numeric UpDown control?

You can use NumericUpDown control for WPF written by me as a part of WPFControls library.

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

I modified the above function to account for carriage returns in IE. It's untested but I did something similar with it in my code so it should be workable.

function getCaret(el) {
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
    rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    var add_newlines = 0;
    for (var i=0; i<rc.text.length; i++) {
      if (rc.text.substr(i, 2) == '\r\n') {
        add_newlines += 2;
        i++;
      }
    }

    //return rc.text.length + add_newlines;

    //We need to substract the no. of lines
    return rc.text.length - add_newlines; 
  }  
  return 0; 
}

How to set HTML Auto Indent format on Sublime Text 3?

Create a Keybinding

To auto indent on Sublime text 3 with a key bind try going to

Preferences > Key Bindings - users

And adding this code between the square brackets

{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}

it sets shift + alt + f to be your full page auto indent.

Source here

Note: if this doesn't work correctly then you should convert your indentation to tabs. Also comments in your code can push your code to the wrong indentation level and may have to be moved manually.