Programs & Examples On #Flex datagrid

Grid component, part of Adobe Flex framework.

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

CHAR is a fixed-length data type that uses as much space as possible. So a:= a||'one '; will require more space than is available. Your problem can be reduced to the following example:

declare
  v_foo char(50);
begin
  v_foo := 'A';
  dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
  -- next line will raise:
  -- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
  v_foo := v_foo || 'B';
  dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));  
end;
/

Never use char. For rationale check the following question (read also the links):

jQuery: get parent, parent id?

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

Is how you would get the id of the parent's parent.

EDIT:

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

Is a more foolproof solution for your case.

check if command was successful in a batch file

Most commands/programs return a 0 on success and some other value, called errorlevel, to signal an error.

You can check for this in you batch for example by:

call <THE_COMMAND_HERE>
if %ERRORLEVEL% == 0 goto :next
echo "Errors encountered during execution.  Exited with status: %errorlevel%"
goto :endofscript

:next
echo "Doing the next thing"

:endofscript
echo "Script complete"

Android Studio emulator does not come with Play Store for API 23

Below is the method that worked for me on API 23-25 emulators. The explanation is provided for API 24 but works almost identically for other versions.

Credits: Jon Doe, zaidorx, pjl.

Warm advice for readers: please just go over the steps before following them, as some are automated via provided scripts.


  1. In the AVD manager of Android studio (tested on v2.2.3), create a new emulator with the "Android 7.0 (Google APIs)" target: AVD screen after creating the emulator.

  2. Download the latest Open GApps package for the emulator's architecture (CPU/ABI). In my case it was x86_64, but it can be something else depending on your choice of image during the device creation wizard. Interestingly, the architecture seems more important than the correct Android version (i.e. gapps for 6.0 also work on a 7.0 emulator).

  3. Extract the .apk files using from the following paths (relative to open_gapps-x86_64-7.0-pico-201#####.zip):

    .zip\Core\gmscore-x86_64.tar.lz\gmscore-x86_64\nodpi\priv-app\PrebuiltGmsCore\
    .zip\Core\gsfcore-all.tar.lz\gsfcore-all\nodpi\priv-app\GoogleServicesFramework\
    .zip\Core\gsflogin-all.tar.lz\gsflogin-all\nodpi\priv-app\GoogleLoginService\
    .zip\Core\vending-all.tar.lz\vending-all\nodpi\priv-app\Phonesky\
    

    Note that Open GApps use the Lzip compression, which can be opened using either the tool found on the Lzip website1,2, or on Mac using homebrew: brew install lzip. Then e.g. lzip -d gmscore-x86_64.tar.lz.

    I'm providing a batch file that utilizes 7z.exe and lzip.exe to extract all required .apks automatically (on Windows):

    @echo off
    echo.
    echo #################################
    echo Extracting Gapps...
    echo #################################
    7z x -y open_gapps-*.zip -oGAPPS
    
    echo Extracting Lzips...
    lzip -d GAPPS\Core\gmscore-x86_64.tar.lz
    lzip -d GAPPS\Core\gsfcore-all.tar.lz
    lzip -d GAPPS\Core\gsflogin-all.tar.lz
    lzip -d GAPPS\Core\vending-all.tar.lz
    
    move GAPPS\Core\*.tar
    
    echo. 
    echo #################################
    echo Extracting tars...
    echo #################################
    
    7z e -y -r *.tar *.apk
    
    echo.
    echo #################################
    echo Cleaning up...
    echo #################################
    rmdir /S /Q GAPPS
    del *.tar
    
    echo.
    echo #################################
    echo All done! Press any key to close.
    echo #################################
    pause>nul
    

    To use this, save the script in a file (e.g. unzip_gapps.bat) and put everything relevant in one folder, as demonstrated below: What it should look like...

  4. Update the su binary to be able to modify the permissions of the files we will later upload. A new su binary can be found in the SuperSU by Chainfire package "Recovery flashable" zip. Get the zip, extract it somewhere, create the a batch file with the following contents in the same folder, and finally run it:

    adb root
    adb remount
    
    adb push eu.chainfire.supersu_2.78.apk /system/app/
    adb push x64/su /system/xbin/su
    adb shell chmod 755 /system/xbin/su
    
    adb shell ln -s /system/xbin/su /system/bin/su
    adb shell "su --daemon &"
    adb shell rm /system/app/SdkSetup.apk
    
  5. Put all .apk files in one folder and create a batch file with these contents3:

    START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
    adb wait-for-device
    adb root
    adb shell stop
    adb remount
    adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore
    adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework
    adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService
    adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
    adb shell su root "chmod 777 /system/priv-app/**"
    adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
    adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
    adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
    adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
    adb shell start
    

    Notice that the path E:\...\android-sdk\tools\emulator.exe should be modified according to the location of the Android SDK on your system.

  6. Execute the above batch file (the console should look like this afterwards):

    O:\123>START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
    
    O:\123>adb wait-for-device
    Hax is enabled
    Hax ram_size 0x60000000
    HAX is working and emulator runs in fast virt mode.
    emulator: Listening for console connections on port: 5554
    emulator: Serial number of this emulator (for ADB): emulator-5554
    
    O:\123>adb root
    
    O:\123>adb shell stop
    
    O:\123>adb remount
    remount succeeded
    
    O:\123>adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/
    [100%] /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
    
    O:\123>adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/
    [100%] /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
    
    O:\123>adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService/
    [100%] /system/priv-app/GoogleLoginService/GoogleLoginService.apk
    
    O:\123>adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
    [100%] /system/priv-app/Phonesky/Phonesky.apk
    
    O:\123>adb shell su root "chmod 777 /system/priv-app/**"
    
    O:\123>adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
    
    O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
    
    O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
    
    O:\123>adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
    
    O:\123>adb shell start
    
  7. When the emulator loads - close it, delete the Virtual Device and then create another one using the same system image. This fixes the unresponsive Play Store app, "Google Play Services has stopped" and similar problems. It works because in the earlier steps we have actually modified the system image itself (take a look at the Date modified on android-sdk\system-images\android-24\google_apis\x86_64\system.img). This means that every device created from now on with the system image will have gapps installed!

  8. Start the new AVD. If it takes unusually long to load, close it and instead start it using:

    START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24
    adb wait-for-device
    adb shell "su --daemon &"
    

    After the AVD starts you will see the image below - notice the Play Store icon in the corner!

First boot with Play Store installed.


3 - I'm not sure all of these commands are needed, and perhaps some of them are overkill... it seems to work - which is what counts. :)

Calling ASP.NET MVC Action Methods from JavaScript

Javascript Function

function AddToCart(id) {
 $.ajax({
   url: '@Url.Action("AddToCart", "ControllerName")',
   type: 'GET',
   dataType: 'json',
   cache: false,
   data: { 'id': id },
   success: function (results) {
        alert(results)
   },
   error: function () {
    alert('Error occured');
   }
   });
   }

Controller Method to call

[HttpGet]
  public JsonResult AddToCart(string id)
  {
    string newId = id;
     return Json(newId, JsonRequestBehavior.AllowGet);
  }

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

How do I prevent an Android device from going to sleep programmatically?

what @eldarerathis said is correct in all aspects, the wake lock is the right way of keeping the device from going to sleep.

I don't know waht you app needs to do but it is really important that you think on how architect your app so that you don't force the phone to stay awake for more that you need, or the battery life will suffer enormously.

I would point you to this really good example on how to use AlarmManager to fire events and wake up the phone and (your app) to perform what you need to do and then go to sleep again: Alarm Manager (source: commonsware.com)

How to show validation message below each textbox using jquery?

You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.

This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.

Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.

Your fiddle is updated, see here: jsfiddle

The code:

$('form').on('submit', function (e) {
    var focusSet = false;
    if (!$('#email').val()) {
        if ($("#email").parent().next(".validation").length == 0) // only add if not added
        {
            $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        $('#email').focus();
        focusSet = true;
    } else {
        $("#email").parent().next(".validation").remove(); // remove it
    }
    if (!$('#password').val()) {
        if ($("#password").parent().next(".validation").length == 0) // only add if not added
        {
            $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        if (!focusSet) {
            $("#password").focus();
        }
    } else {
        $("#password").parent().next(".validation").remove(); // remove it
    }
});  

The CSS:

    .validation
    {
      color: red;
      margin-bottom: 20px;
    }

Error: unmappable character for encoding UTF8 during maven compilation

This happens in the following scenario: When working on Windows, the IDE is more than likely configured to edit files in Cp1252, which is a Microsoft adaptation of latin-11. The developer checks in, and the Continuous Integration server (usually running on Linux, which nowadays is all utf8) picks up the file, and tries to compile as a UTF-8 file, hence the warning.

Try changing the encoding to cp1252. This works. To avoid future problems of this kind, use the same encoding on all the developer machines.

Good luck...

What is the difference between square brackets and parentheses in a regex?

These regexes are equivalent (for matching purposes):

  • /^(7|8|9)\d{9}$/
  • /^[789]\d{9}$/
  • /^[7-9]\d{9}$/

The explanation:

  • (a|b|c) is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9) to make it a non capturing group.

  • [abc] is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d] = [abcd])

The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def) which does not translate to a character class.

.ssh directory not being created

I am assuming that you have enough permissions to create this directory.

To fix your problem, you can either ssh to some other location:

ssh [email protected]

and accept new key - it will create directory ~/.ssh and known_hosts underneath, or simply create it manually using

mkdir ~/.ssh
chmod 700 ~/.ssh

Note that chmod 700 is an important step!

After that, ssh-keygen should work without complaints.

Python: Generate random number between x and y which is a multiple of 5

The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.

To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.

Setting a PHP $_SESSION['var'] using jQuery

in (backend.php) be sure to include include

session_start();

-Taylor http://www.hawkessolutions.com

how to get domain name from URL

I don't know of any libraries, but the string manipulation of domain names is easy enough.

The hard part is knowing if the name is at the second or third level. For this you will need a data file you maintain (e.g. for .uk is is not always the third level, some organisations (e.g. bl.uk, jet.uk) exist at the second level).

The source of Firefox from Mozilla has such a data file, check the Mozilla licensing to see if you could reuse that.

What does T&& (double ampersand) mean in C++11?

An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references:

void foo(X& x);  // lvalue reference overload
void foo(X&& x); // rvalue reference overload

X x;
X foobar();

foo(x);        // argument is lvalue: calls foo(X&)
foo(foobar()); // argument is rvalue: calls foo(X&&)

So what is an rvalue? Anything that is not an lvalue. An lvalue being an expression that refers to a memory location and allows us to take the address of that memory location via the & operator.

It is almost easier to understand first what rvalues accomplish with an example:

 #include <cstring>
 class Sample {
  int *ptr; // large block of memory
  int size;
 public:
  Sample(int sz=0) : ptr{sz != 0 ? new int[sz] : nullptr}, size{sz} 
  {
     if (ptr != nullptr) memset(ptr, 0, sz);
  }
  // copy constructor that takes lvalue 
  Sample(const Sample& s) : ptr{s.size != 0 ? new int[s.size] :\
      nullptr}, size{s.size}
  {
     if (ptr != nullptr) memcpy(ptr, s.ptr, s.size);
     std::cout << "copy constructor called on lvalue\n";
  }

  // move constructor that take rvalue
  Sample(Sample&& s) 
  {  // steal s's resources
     ptr = s.ptr;
     size = s.size;        
     s.ptr = nullptr; // destructive write
     s.size = 0;
     cout << "Move constructor called on rvalue." << std::endl;
  }    
  // normal copy assignment operator taking lvalue
  Sample& operator=(const Sample& s)
  {
   if(this != &s) {
      delete [] ptr; // free current pointer
      size = s.size;

      if (size != 0) {
        ptr = new int[s.size];
        memcpy(ptr, s.ptr, s.size);
      } else 
         ptr = nullptr;
     }
     cout << "Copy Assignment called on lvalue." << std::endl;
     return *this;
  }    
 // overloaded move assignment operator taking rvalue
 Sample& operator=(Sample&& lhs)
 {
   if(this != &s) {
      delete [] ptr; //don't let ptr be orphaned 
      ptr = lhs.ptr;   //but now "steal" lhs, don't clone it.
      size = lhs.size; 
      lhs.ptr = nullptr; // lhs's new "stolen" state
      lhs.size = 0;
   }
   cout << "Move Assignment called on rvalue" << std::endl;
   return *this;
 }
//...snip
};     

The constructor and assignment operators have been overloaded with versions that take rvalue references. Rvalue references allow a function to branch at compile time (via overload resolution) on the condition "Am I being called on an lvalue or an rvalue?". This allowed us to create more efficient constructor and assignment operators above that move resources rather copy them.

The compiler automatically branches at compile time (depending on the whether it is being invoked for an lvalue or an rvalue) choosing whether the move constructor or move assignment operator should be called.

Summing up: rvalue references allow move semantics (and perfect forwarding, discussed in the article link below).

One practical easy-to-understand example is the class template std::unique_ptr. Since a unique_ptr maintains exclusive ownership of its underlying raw pointer, unique_ptr's can't be copied. That would violate their invariant of exclusive ownership. So they do not have copy constructors. But they do have move constructors:

template<class T> class unique_ptr {
  //...snip
 unique_ptr(unique_ptr&& __u) noexcept; // move constructor
};

 std::unique_ptr<int[] pt1{new int[10]};  
 std::unique_ptr<int[]> ptr2{ptr1};// compile error: no copy ctor.  

 // So we must first cast ptr1 to an rvalue 
 std::unique_ptr<int[]> ptr2{std::move(ptr1)};  

std::unique_ptr<int[]> TakeOwnershipAndAlter(std::unique_ptr<int[]> param,\
 int size)      
{
  for (auto i = 0; i < size; ++i) {
     param[i] += 10;
  }
  return param; // implicitly calls unique_ptr(unique_ptr&&)
}

// Now use function     
unique_ptr<int[]> ptr{new int[10]};

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(\
           static_cast<unique_ptr<int[]>&&>(ptr), 10);

cout << "output:\n";

for(auto i = 0; i< 10; ++i) {
   cout << new_owner[i] << ", ";
}

output:
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 

static_cast<unique_ptr<int[]>&&>(ptr) is usually done using std::move

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(std::move(ptr),0);

An excellent article explaining all this and more (like how rvalues allow perfect forwarding and what that means) with lots of good examples is Thomas Becker's C++ Rvalue References Explained. This post relied heavily on his article.

A shorter introduction is A Brief Introduction to Rvalue References by Stroutrup, et. al

How to get image size (height & width) using JavaScript?

Thought this might be helpful to some who are using Javascript and/or Typescript in 2019.

I found the following, as some have suggested, to be incorrect:

let img = new Image();
img.onload = function() {
  console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";

This is correct:

let img = new Image();
img.onload = function() {
  console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";

Conclusion:

Use img, not this, in onload function.

csv.Error: iterator should return strings, not bytes

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

Get List of connected USB Devices

To see the devices I was interested in, I had replace Win32_USBHub by Win32_PnPEntity in Adel Hazzah's code, based on this post. This works for me:

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management; // need to add System.Management to your project references.

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      ManagementObjectCollection collection;
      using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        collection = searcher.Get();      

      foreach (var device in collection)
      {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID"),
        (string)device.GetPropertyValue("PNPDeviceID"),
        (string)device.GetPropertyValue("Description")
        ));
      }

      collection.Dispose();
      return devices;
    }
  }

  class USBDeviceInfo
  {
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
    {
      this.DeviceID = deviceID;
      this.PnpDeviceID = pnpDeviceID;
      this.Description = description;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
  }
}

Does Index of Array Exist

You could check if the index is less than the length of the array. This doesn't check for nulls or other odd cases where the index can be assigned a value but hasn't been given one explicitly.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

How can I change the date format in Java?

Or you could go the regex route:

String date = "10/07/2010";
String newDate = date.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3/$2/$1");
System.out.println(newDate);

It works both ways too. Of course this won't actually validate your date and will also work for strings like "21432/32423/52352". You can use "(\\d{2})/(\\d{2})/(\\d{4}" to be more exact in the number of digits in each group, but it will only work from dd/MM/yyyy to yyyy/MM/dd and not the other way around anymore (and still accepts invalid numbers in there like 45). And if you give it something invalid like "blabla" it will just return the same thing back.

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Use the TextFieldParser class built into the .Net framework.

Here's some code copied from an MSDN forum post by Paul Clement. It converts the CSV into a new in-memory DataTable and then binds the DataGridView to the DataTable

    Dim TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Documents and Settings\...\My Documents\My Database\Text\SemiColonDelimited.txt")

    TextFileReader.TextFieldType = FileIO.FieldType.Delimited
    TextFileReader.SetDelimiters(";")

    Dim TextFileTable As DataTable = Nothing

    Dim Column As DataColumn
    Dim Row As DataRow
    Dim UpperBound As Int32
    Dim ColumnCount As Int32
    Dim CurrentRow As String()

    While Not TextFileReader.EndOfData
        Try
            CurrentRow = TextFileReader.ReadFields()
            If Not CurrentRow Is Nothing Then
                ''# Check if DataTable has been created
                If TextFileTable Is Nothing Then
                    TextFileTable = New DataTable("TextFileTable")
                    ''# Get number of columns
                    UpperBound = CurrentRow.GetUpperBound(0)
                    ''# Create new DataTable
                    For ColumnCount = 0 To UpperBound
                        Column = New DataColumn()
                        Column.DataType = System.Type.GetType("System.String")
                        Column.ColumnName = "Column" & ColumnCount
                        Column.Caption = "Column" & ColumnCount
                        Column.ReadOnly = True
                        Column.Unique = False
                        TextFileTable.Columns.Add(Column)
                    Next
                End If
                Row = TextFileTable.NewRow
                For ColumnCount = 0 To UpperBound
                    Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
                Next
                TextFileTable.Rows.Add(Row)
            End If
        Catch ex As _
        Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & _
            "is not valid and will be skipped.")
        End Try
    End While
    TextFileReader.Dispose()
    frmMain.DataGrid1.DataSource = TextFileTable

PHP order array by date?

You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.

$data = array(
    array(
        "title" => "Another title",
        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"
    ),
    array(
        "title" => "My title",
        "date"  => "Mon, 16 Jun 2010 06:55:57 +0200"
    )
);

function sortFunction( $a, $b ) {
    return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);

Bootstrap Carousel : Remove auto slide

Please try the following:

<script>
    $(document).ready(function() {      
        $('.carousel').carousel('pause');
    });
</script>

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

There are multiple JPA providers in your classpath. Or atleast in your Application server lib folder.

If you are using Maven Check for dependencies using command mentioned here https://stackoverflow.com/a/47474708/3333878

Then fix by removing/excluding unwanted dependency.

If you just have one dependecy in your classpath, then the application server's class loader might be the issue.

As JavaEE application servers like Websphere, Wildfly, Tomee etc., have their own implementations of JPA and other EE Standards, The Class loader might load it's own implementation instead of picking from your classpath in WAR/EAR file.

To avoid this, you can try below steps.

  1. Removing the offending jar in Application Servers library path. Proceed with Caution, as it might break other hosted applications.

In Tomee 1.7.5 Plume/ Web it will have bundled eclipselink-2.4.2 in the lib folder using JPA 2.0, but I had to use JPA 2.1 from org.hibernate:hibernate-core:5.1.17, so removed the eclipselink jar and added all related/ transitive dependencies from hibernate core.

  1. Add a shared library. and manually add jars to the app server's path. Websphere has this option.

  2. In Websphere, execution of class loader can be changed. so making it the application server's classpath to load last i.e, parent last and having your path load first. Can solve this.

Check if your appserver has above features, before proceeding with first point.

Ibm websphere References :

https://www.ibm.com/support/knowledgecenter/SSEQTP_9.0.5/com.ibm.websphere.base.doc/ae/trun_classload_server.html

https://www.ibm.com/support/pages/how-create-shared-library-and-associate-it-application-server-or-enterprise-application-websphere-application-server

Syntax for if/else condition in SCSS mixin

You could default the parameter to null or false.
This way, it would be shorter to test if a value has been passed as parameter.

@mixin clearfix($width: null) {

  @if not ($width) {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Which exception should I raise on bad/illegal argument combinations in Python?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There's really no point in doing class BadValueError(ValueError):pass - your custom class is identical in use to ValueError, so why not use that?

time delayed redirect?

 <script type="text/JavaScript">
      setTimeout("location.href = 'http://www.your_site.com';",1500);
 </script>

Change default date time format on a single database in SQL Server

You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:

set language 'british english'

Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as

1-Dec-2008

Distribution certificate / private key not installed

You can only have one distribution certificate. It unites a public key, known to Apple, with a private key, which lives in the keychain of some computer. If this distribution certificate was created on another computer, then the private key is on the keychain of that computer. And this distribution certificate does not work without it.

So to use this distribution certificate on this computer, you must find that computer, open Keychain Access, locate and export the private key, mail it or otherwise get it to this computer, and import it into the keychain of this computer.

If you go into the Accounts pref pane in Xcode and double-click your Team, you'll see a dialog that gives you help with this. If you see your distribution certificate and it says Not In Keychain, you can control-click that certificate to get a menu item that lets you email whoever created the certificate and ask them to send it to you. That person can use this same import to choose Export Certificate and can email you exported certificate.

Either way, the private key or exported certificate will be passworded. You'll need to know the password in order to use it.

Validation of radio button group using jQuery validation plugin

With newer releases of jquery (1.3+ I think), all you have to do is set one of the members of the radio set to be required and jquery will take care of the rest:

<input type="radio" name="myoptions" value="blue" class="required"> Blue<br />
<input type="radio" name="myoptions" value="red"> Red<br />
<input type="radio" name="myoptions" value="green"> Green

The above would require at least 1 of the 3 radio options w/ the name of "my options" to be selected before proceeding.

The label suggestion by Mahes, btw, works wonderfully!

Get final URL after curl is redirected

You can do this with wget usually. wget --content-disposition "url" additionally if you add -O /dev/null you will not be actually saving the file.

wget -O /dev/null --content-disposition example.com

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

Here's a C implementation based on Agoston's Computer Graphics and Geometric Modeling: Implementation and Algorithms p. 304, with H ? [0, 360] and S,V ? [0, 1].

#include <math.h>

typedef struct {
    double r;       // ? [0, 1]
    double g;       // ? [0, 1]
    double b;       // ? [0, 1]
} rgb;

typedef struct {
    double h;       // ? [0, 360]
    double s;       // ? [0, 1]
    double v;       // ? [0, 1]
} hsv;

rgb hsv2rgb(hsv HSV)
{
    rgb RGB;
    double H = HSV.h, S = HSV.s, V = HSV.v,
            P, Q, T,
            fract;

    (H == 360.)?(H = 0.):(H /= 60.);
    fract = H - floor(H);

    P = V*(1. - S);
    Q = V*(1. - S*fract);
    T = V*(1. - S*(1. - fract));

    if      (0. <= H && H < 1.)
        RGB = (rgb){.r = V, .g = T, .b = P};
    else if (1. <= H && H < 2.)
        RGB = (rgb){.r = Q, .g = V, .b = P};
    else if (2. <= H && H < 3.)
        RGB = (rgb){.r = P, .g = V, .b = T};
    else if (3. <= H && H < 4.)
        RGB = (rgb){.r = P, .g = Q, .b = V};
    else if (4. <= H && H < 5.)
        RGB = (rgb){.r = T, .g = P, .b = V};
    else if (5. <= H && H < 6.)
        RGB = (rgb){.r = V, .g = P, .b = Q};
    else
        RGB = (rgb){.r = 0., .g = 0., .b = 0.};

    return RGB;
}

JSON.net: how to deserialize without using the default constructor?

The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

Admittedly, this solution is rather very limited to specific cases.

internal Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}

Django Cookies, how can I set them?

Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).

Setting a cookie:

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

Retrieving a cookie:

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

  # OR

  try:
    value = request.COOKIES['cookie_name']
  except KeyError:
    # Cookie is not set

Common sources of unterminated string literal

Look for linebreaks! Those are often the cause.

Linux command line howto accept pairing for bluetooth device without pin

For Ubuntu 14.04 and Android try:

hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS

PIN dialog pops up on Android device. Enter same PIN.

Note: sudo apt-get install bluez-utils might be necessary.

Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.

Difference between a SOAP message and a WSDL?

We need to define what is a web service before telling what are the difference between the SOAP and WSDL where the two (SOAP and WSDL) are components of a web service

Most applications are developed to interact with users, the user enters or searches for data through an interface and the application then responds to the user's input.

A Web service does more or less the same thing except that a Web service application communicates only from machine to machine or application to application. There is often no direct user interaction.

A Web service basically is a collection of open protocols that is used to exchange data between applications. The use of open protocols enables Web services to be platform independent. Software that are written in different programming languages and that run on different platforms can use Web services to exchange data over computer networks such as the Internet. In other words, Windows applications can talk to PHP, Java and Perl applications and many others, which in normal circumstances would not be possible.

How Do Web Services Work?

Because different applications are written in different programming languages, they often cannot communicate with each other. A Web service enables this communication by using a combination of open protocols and standards, chiefly XML, SOAP and WSDL. A Web service uses XML to tag data, SOAP to transfer a message and finally WSDL to describe the availability of services. Let's take a look at these three main components of a Web service application.

Simple Object Access Protocol (SOAP)

The Simple Object Access Protocol or SOAP is a protocol for sending and receiving messages between applications without confronting interoperability issues (interoperability meaning the platform that a Web service is running on becomes irrelevant). Another protocol that has a similar function is HTTP. It is used to access Web pages or to surf the Net. HTTP ensures that you do not have to worry about what kind of Web server -- whether Apache or IIS or any other -- serves you the pages you are viewing or whether the pages you view were created in ASP.NET or HTML.

Because SOAP is used both for requesting and responding, its contents vary slightly depending on its purpose.

Below is an example of a SOAP request and response message

SOAP Request:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPrice> 
    <m:BookName>The Fleamarket</m:BookName> 
    </m:GetBookPrice> 
</soap:Body> 
</soap:Envelope>

SOAP Response:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPriceResponse> 
    <m: Price>10.95</m: Price> 
    </m:GetBookPriceResponse> 
</soap:Body> 
</soap:Envelope> 

Although both messages look the same, they carry out different methods. For instance looking at the above examples you can see that the requesting message uses the GetBookPrice method to get the book price. The response is carried out by the GetBookPriceResponse method, which is going to be the message that you as the "requestor" will see. You can also see that the messages are composed using XML.

Web Services Description Language or WSDL

WSDL is a document that describes a Web service and also tells you how to access and use its methods.

WSDL takes care of how do you know what methods are available in a Web service that you stumble across on the Internet.

Take a look at a sample WSDL file:

<?xml version="1.0" encoding="UTF-8"?> 
<definitions  name ="DayOfWeek"  
  targetNamespace="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:tns="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"  
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns="http://schemas.xmlsoap.org/wsdl/">  
  <message name="DayOfWeekInput"> 
    <part name="date" type="xsd:date"/> 
  </message> 
  <message name="DayOfWeekResponse"> 
    <part name="dayOfWeek" type="xsd:string"/> 
  </message> 
  <portType name="DayOfWeekPortType"> 
    <operation name="GetDayOfWeek"> 
      <input message="tns:DayOfWeekInput"/> 
      <output message="tns:DayOfWeekResponse"/> 
    </operation> 
  </portType> 
  <binding name="DayOfWeekBinding" type="tns:DayOfWeekPortType"> 
    <soap:binding style="document"  
      transport="http://schemas.xmlsoap.org/soap/http"/> 
    <operation name="GetDayOfWeek"> 
      <soap:operation soapAction="getdayofweek"/> 
      <input> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"  
          encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </input> 
      <output> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"   
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </output> 
    </operation> 
  </binding> 
  <service name="DayOfWeekService" > 
    <documentation> 
      Returns the day-of-week name for a given date 
    </documentation> 
    <port name="DayOfWeekPort" binding="tns:DayOfWeekBinding"> 
      <soap:address location="http://localhost:8090/dayofweek/DayOfWeek"/> 
    </port> 
  </service> 
</definitions> 

The main things to remember about a WSDL file are that it provides you with:

  • A description of a Web service

  • The methods a Web service uses and the parameters that it takes

  • A way to locate Web services

  • In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

    Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

    Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

    So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

    Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

    How do I parse JSON into an int?

    Its very simple.

    Example JSON:

    {
       "value":1
    }
    


    int z = jsonObject.getInt("value");
    

    Extract data from log file in specified range of time

    well, I have spent some time on your date format.....

    however, finally i worked it out..

    let's take an example file (named logFile), i made it a bit short. say, you want to get last 5 mins' log in this file:

    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
    ### lines below are what you want (5 mins till the last record)
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
    172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
    

    here is the solution:

    # this variable you could customize, important is convert to seconds. 
    # e.g 5days=$((5*24*3600))
    x=$((5*60))   #here we take 5 mins as example
    
    # this line get the timestamp in seconds of last line of your logfile
    last=$(tail -n1 logFile|awk -F'[][]' '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; print d;}' )
    
    #this awk will give you lines you needs:
    awk -F'[][]' -v last=$last -v x=$x '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; if (last-d<=x)print $0 }' logFile      
    

    output:

    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
    172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET
    

    EDIT

    you may notice that in the output the [ and ] are disappeared. If you do want them back, you can change the last awk line print $0 -> print $1 "[" $2 "]" $3

    Aborting a shell script if any command returns a non-zero value

    The $? variable is rarely needed. The pseudo-idiom command; if [ $? -eq 0 ]; then X; fi should always be written as if command; then X; fi.

    The cases where $? is required is when it needs to be checked against multiple values:

    command
    case $? in
      (0) X;;
      (1) Y;;
      (2) Z;;
    esac
    

    or when $? needs to be reused or otherwise manipulated:

    if command; then
      echo "command successful" >&2
    else
      ret=$?
      echo "command failed with exit code $ret" >&2
      exit $ret
    fi
    

    Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

    This work around will fix the issue found by @Cletus.

    function submitForm(form) {
        //get the form element's document to create the input control with
        //(this way will work across windows in IE8)
        var button = form.ownerDocument.createElement('input');
        //make sure it can't be seen/disrupts layout (even momentarily)
        button.style.display = 'none';
        //make it such that it will invoke submit if clicked
        button.type = 'submit';
        //append it and click it
        form.appendChild(button).click();
        //if it was prevented, make sure we don't get a build up of buttons
        form.removeChild(button);
    }
    

    Will work on all modern browsers.
    Will work across tabs/spawned child windows (yes, even in IE<9).
    And is in vanilla!

    Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.

    Replace or delete certain characters from filenames of all files in a folder

    The PowerShell answers are good, but the Rename-Item command doesn't work in the same target directory unless ALL of your files have the unwanted character in them (fails if it finds duplicates).

    If you're like me and had a mix of good names and bad names, try this script instead (will replace spaces with an underscore):

    Get-ChildItem -recurse -name | ForEach-Object { Move-Item $_ $_.replace(" ", "_") }
    

    How to add a JAR in NetBeans

    If your project's source code has import statements that reference classes that are in widget.jar, you should add the jar to your projects Compile-time Libraries. (The jar widget.jar will automatically be added to your project's Run-time Libraries). That corresponds to (1).

    If your source code has imports for classes in some other jar and the source code for those classes has import statements that reference classes in widget.jar, you should add widget.jar to the Run-time libraries list. That corresponds to (2).

    You can add the jars directly to the Libraries list in the project properties. You can also create a Library that contains the jar file and then include that Library in the Compile-time or Run-time Libraries list.

    If you create a NetBeans Library for widget.jar, you can also associate source code for the jar's content and Javadoc for the APIs defined in widget.jar. This additional information about widget.jar will be used by NetBeans as you debug code. It will also be used to provide addition information when you use code completion in the editor.

    You should avoid using Tools >> Java Platform to add a jar to a project. That dialog allows you to modify the classpath that is used to compile and run all projects that use the Java Platform that you create. That may be useful at times but hides your project's dependency on widget.jar almost completely.

    create table in postgreSQL

    -- Table: "user"
    
    -- DROP TABLE "user";
    
    CREATE TABLE "user"
    (
      id bigserial NOT NULL,
      name text NOT NULL,
      email character varying(20) NOT NULL,
      password text NOT NULL,
      CONSTRAINT user_pkey PRIMARY KEY (id)
    )
    WITH (
      OIDS=FALSE
    );
    ALTER TABLE "user"
      OWNER TO postgres;
    

    SQLite select where empty?

    It looks like you can simply do:

    SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';
    

    Test case:

    CREATE TABLE your_table (id int, some_column varchar(10));
    
    INSERT INTO your_table VALUES (1, NULL);
    INSERT INTO your_table VALUES (2, '');
    INSERT INTO your_table VALUES (3, 'test');
    INSERT INTO your_table VALUES (4, 'another test');
    INSERT INTO your_table VALUES (5, NULL);
    

    Result:

    SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';
    
    id        
    ----------
    1         
    2         
    5    
    

    More elegant "ps aux | grep -v grep"

    You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

    preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
    $result = $matches[1];
    

    The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

    An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

    preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
    $result = $matches[0];
    

    I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

    $test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
    user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
    user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
    user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
    user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
    user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
    root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
    root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";
    
    $lines = explode("\n", $test);
    
    foreach($lines as $line){
            if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                    print_r($matches);
            }
    
    }
    

    The above prints:

    Array
    (
        [0] => .php cust1 cron
        [1] => cust1
    )
    Array
    (
        [0] => .php cust3 cron
        [1] => cust3
    )
    Array
    (
        [0] => .php cust4 cron
        [1] => cust4
    )
    Array
    (
        [0] => .php cust89 cron
        [1] => cust89
    )
    Array
    (
        [0] => .php cust435 cron
        [1] => cust435
    )
    Array
    (
        [0] => .php cust16 cron
        [1] => cust16
    )
    

    You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

    best way to preserve numpy arrays on disk

    I'm a big fan of hdf5 for storing large numpy arrays. There are two options for dealing with hdf5 in python:

    http://www.pytables.org/

    http://www.h5py.org/

    Both are designed to work with numpy arrays efficiently.

    scp or sftp copy multiple files with single command

    Is more simple without using scp:

    tar cf - file1 ... file_n | ssh user@server 'tar xf -'
    

    This also let you do some things like compress the stream (-C) or (since OpenSSH v7.3) -J any times to jump through one (or more) proxy servers.

    You can avoid using passwords coping your public key to ~/.ssh/authorized_keys with ssh-copy-id.

    Posted also here (with more details) and here.

    Git error: src refspec master does not match any

    The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

    git push origin master
    

    Which will create this new master branch for you. Little things like this are very confusing with git.

    If this didn't fix your issue then it's probably a gitolite-related issue:

    Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

    repo    phonegap                                                                                                                                                                           
        RW+     =   myusername otherusername                                                                                                                                               
    
    repo    gitolite-admin                                                                                                                                                                         
        RW+     =   myusername                                                                                                                                                               
    

    Please make sure you're setting your conf file correctly.

    Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

    Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

    Determine if string is in list in JavaScript

    EcmaScript 6 and up

    If you're using ES6 or higher, the cleanest way is to construct an array of the items and use Array.includes:

    ['a', 'b', 'c'].includes('b')
    

    This has some inherent benefits over indexOf because it can properly test for the presence of NaN in the list, and can match missing array elements such as the middle one in [1, , 2] to undefined. includes also works on JavaScript typed arrays such as Uint8Array.

    If you're concerned about browser support (such as for IE or Edge), you can check Array.includes at CanIUse.Com, and if you want to target a browser or browser version that's missing includes, I recommend polyfill.io for polyfilling.

    Without An Array

    You could add a new isInList property to strings as follows:

    if (!String.prototype.isInList) {
      Object.defineProperty(String.prototype, 'isInList', {
        get: () => function(...args) {
          let value = this.valueOf();
          for (let i = 0, l = args.length; i < l; i += 1) {
            if (arguments[i] === value) return true;
          }
          return false;
        }
      });
    }
    

    Then use it like so:

    'fox'.isInList('weasel', 'fox', 'stoat') // true
    'fox'.isInList('weasel', 'stoat') // false
    

    You can do the same thing for Number.prototype.

    Note that Object.defineProperty cannot be used in IE8 and earlier, or very old versions of other browsers. However, it is a far superior solution to String.prototype.isInList = function() { ... } because using simple assignment like that will create an enumerable property on String.prototype, which is more likely to break code.

    Array.indexOf

    If you are using a modern browser, indexOf always works. However, for IE8 and earlier you'll need a polyfill.

    If indexOf returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN, and while it can match an explicit undefined, it can’t match a missing element to undefined as in the array [1, , 2].

    Polyfill for indexOf or includes in IE, or any other browser/version lacking support

    If you don't want to use a service like polyfill.io as mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf.

    In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf() function that is not standards-compliant:

    if (!Array.prototype.indexOf) {
       Array.prototype.indexOf = function(item) {
          var i = this.length;
          while (i--) {
             if (this[i] === item) return i;
          }
          return -1;
       }
    }
    

    However, I don't think modifying Array.prototype is the best answer in the long term. Modifying Object and Array prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in will return the new function name as one of the keys:

    Array.prototype.blah = function() { console.log('blah'); };
    let arr = [1, 2, 3];
    for (let x in arr) { console.log(x); }
    // Result:
    0
    1
    2
    blah // Extra member iterated over!
    

    Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.

    The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x)) and only then work with that x.

    The new ES6 ways to avoid this extra-key problem are:

    1. Use of instead of in, for (let x of arr). However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includes as stated above.

    2. Define your new properties on the prototype using Object.defineProperty(), as this will make the property (by default) non-enumerable. This only truly solves the problem if all the JavaScript libraries or modules you use also do this.

    How to recursively list all the files in a directory in C#?

    This one helped me to get all files in a directory and sub directories, May be helpful for someone. [ Inspired from above answers ]

    static void Main(string[] args)
        {
            try
            {
                var root = @"G:\logs";
                DirectorySearch(root);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
    
    
    
    
    
    public static void DirectorySearch(string root, bool isRootItrated = false)
    {
        if (!isRootItrated)
        {
            var rootDirectoryFiles = Directory.GetFiles(root);
            foreach (var file in rootDirectoryFiles)
            {
                Console.WriteLine(file);
            } 
        }
    
        var subDirectories = Directory.GetDirectories(root);
        if (subDirectories?.Any() == true)
        {
            foreach (var directory in subDirectories)
            {
                var files = Directory.GetFiles(directory);
                foreach (var file in files)
                {
                    Console.WriteLine(file);
                }
                DirectorySearch(directory, true);
            }
        }
    }
    

    Start an external application from a Google Chrome Extension?

    Question has a good pagerank on google, so for anyone who's looking for answer to this question this might be helpful.

    There is an extension in google chrome marketspace to do exactly that: https://chrome.google.com/webstore/detail/hccmhjmmfdfncbfpogafcbpaebclgjcp

    How to get a list of column names

    Use a recursive query. Given

    create table t (a int, b int, c int);
    

    Run:

    with recursive
      a (cid, name) as (select cid, name from pragma_table_info('t')),
      b (cid, name) as (
        select cid, '|' || name || '|' from a where cid = 0
        union all
        select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
      )
    select name
    from b
    order by cid desc
    limit 1;
    

    Alternatively, just use group_concat:

    select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')
    

    Both yield:

    |a|b|c|
    

    Intermediate language used in scalac?

    maybe this will help you out:

    http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

    or this page:

    www.scala-lang.org/node/6372‎

    How do I stop/start a scheduled task on a remote computer programmatically?

    What about /disable, and /enable switch for a /change command?

    schtasks.exe /change /s <machine name> /tn <task name> /disable
    schtasks.exe /change /s <machine name> /tn <task name> /enable
    

    How to convert a hex string to hex number

    Try this:

    hex_str = "0xAD4"
    hex_int = int(hex_str, 16)
    new_int = hex_int + 0x200
    print hex(new_int)
    

    If you don't like the 0x in the beginning, replace the last line with

    print hex(new_int)[2:]
    

    How do I print the content of a .txt file in Python?

    How to read and print the content of a txt file

    Assume you got a file called file.txt that you want to read in a program and the content is this:

    this is the content of the file
    with open you can read it and
    then with a loop you can print it
    on the screen. Using enconding='utf-8'
    you avoid some strange convertions of
    caracters. With strip(), you avoid printing
    an empty line between each (not empty) line
    

    You can read this content: write the following script in notepad:

    with open("file.txt", "r", encoding="utf-8") as file:
        for line in file:
            print(line.strip())
    

    save it as readfile.py for example, in the same folder of the txt file.

    Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:

    C:\examples> python readfile.py

    You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).

    output

    this is the content of the file
    with open you can read it and
    then with a loop you can print it
    on the screen. Using enconding='utf-8'
    you avoid some strange convertions of
    caracters. With strip(), you avoid printing
    an empty line between each (not empty) line
    

    How do I align spans or divs horizontally?

    I would try to give them all display: block; attribute and using float: left;.

    You can then set width and/or height as you like. You can even specify some vertical-alignment rules.

    Setting up Eclipse with JRE Path

    Add the following -vm D:/Java/jdk1.6.0_30/bin/javaw.exe in the begin of eclipse.ini like this :

    -vm
      D:/Java/jdk1.6.0_30/bin/javaw.exe
      -startup
      plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
      --launcher.library
      plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
      -product
       org.eclipse.epp.package.jee.product
       --launcher.defaultAction
       openFile
       --launcher.XXMaxPermSize
       1024M
       -showsplash
       org.eclipse.platform
        --launcher.XXMaxPermSize
       1024m
        --launcher.defaultAction
       openFile
       --launcher.appendVmargs
       -vmargs
       -Dosgi.requiredJavaVersion=1.6
       -Xms1024m
       -Xmx2048m
    

    Why does the html input with type "number" allow the letter 'e' to be entered in the field?

    A simple solution to exclude everything but integer numbers

    _x000D_
    _x000D_
    <input  
        type="number"
        min="1" 
        step="1"
        onkeypress="return event.keyCode === 8 || event.charCode >= 48 && event.charCode <= 57">
    _x000D_
    _x000D_
    _x000D_

    How to convert std::string to LPCSTR?

    The MultiByteToWideChar answer that Charles Bailey gave is the correct one. Because LPCWSTR is just a typedef for const WCHAR*, widestr in the example code there can be used wherever a LPWSTR is expected or where a LPCWSTR is expected.

    One minor tweak would be to use std::vector<WCHAR> instead of a manually managed array:

    // using vector, buffer is deallocated when function ends
    std::vector<WCHAR> widestr(bufferlen + 1);
    
    ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
    
    // Ensure wide string is null terminated
    widestr[bufferlen] = 0;
    
    // no need to delete; handled by vector
    

    Also, if you need to work with wide strings to start with, you can use std::wstring instead of std::string. If you want to work with the Windows TCHAR type, you can use std::basic_string<TCHAR>. Converting from std::wstring to LPCWSTR or from std::basic_string<TCHAR> to LPCTSTR is just a matter of calling c_str. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar (and its inverse WideCharToMultiByte) comes into the picture.

    Bulk Record Update with SQL

    The SQL you posted in your question is one way to do it. Most things in SQL have more than one way to do it.

    UPDATE
      [Table1] 
    SET
      [Description]=(SELECT [Description] FROM [Table2] t2 WHERE t2.[ID]=Table1.DescriptionID)
    

    If you are planning on running this on a PROD DB, it is best to create a snapshot or mirror of it first and test it out. Verify the data ends up as you expect for a couple records. And if you are satisfied, run it on the real DB.

    Disable sorting for a particular column in jQuery DataTables

    As of 1.10.5, simply include

    'orderable: false'

    in columnDefs and target your column with

    'targets: [0,1]'

    Table should like like:

    var table = $('#data-tables').DataTable({
        columnDefs: [{
            targets: [0],
            orderable: false
        }]
    });
    

    Responsive timeline UI with Bootstrap3

    BootFlat

    You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

    enter image description here

    CSS selector based on element text?

    It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:

    <li><span class="foo">some text</span></li>
    <li>some other text</li>
    

    Then refer to it the usual way:

    li > span.foo {...}
    

    How do you push just a single Git branch (and no other branches)?

    yes, just do the following

    git checkout feature_x
    git push origin feature_x
    

    Is the practice of returning a C++ reference variable evil?

    About horrible code:

    int& getTheValue()
    {
       return *new int;
    }
    

    So, indeed, memory pointer lost after return. But if you use shared_ptr like that:

    int& getTheValue()
    {
       std::shared_ptr<int> p(new int);
       return *p->get();
    }
    

    Memory not lost after return and will be freed after assignment.

    SmartGit Installation and Usage on Ubuntu

    You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).

    To add the PPA run:

    sudo add-apt-repository ppa:eugenesan/ppa
    sudo apt-get update
    

    To install smartgit (after adding the PPA) run:

    sudo apt-get install smartgit
    

    To install smartgithg (after adding the PPA) run:

    sudo apt-get install smartgithg
    

    This should add a menu option for you

    For more information, see Eugene San PPA.

    This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release

    How to find out the location of currently used MySQL configuration file in linux

    you can find it by running the following command

    mysql --help
    

    it will give you the mysql installed directory and all commands for mysql.

    Error - replacement has [x] rows, data has [y]

    You could use cut

     df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
        labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))
    

    data

     set.seed(24)
     df <- data.frame(value= sample(0:2500, 100, replace=TRUE))
    

    HSL to RGB color conversion

    PHP implementation of @Mohsen's code (including Test!)

    Sorry to re-post this. But I really haven't seen any other implementation that gives the quality I needed.

    /**
     * Converts an HSL color value to RGB. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     * Assumes h, s, and l are contained in the set [0, 1] and
     * returns r, g, and b in the set [0, 255].
     *
     * @param   {number}  h       The hue
     * @param   {number}  s       The saturation
     * @param   {number}  l       The lightness
     * @return  {Array}           The RGB representation
     */
      
    function hue2rgb($p, $q, $t){
                if($t < 0) $t += 1;
                if($t > 1) $t -= 1;
                if($t < 1/6) return $p + ($q - $p) * 6 * $t;
                if($t < 1/2) return $q;
                if($t < 2/3) return $p + ($q - $p) * (2/3 - $t) * 6;
                return $p;
            }
    function hslToRgb($h, $s, $l){
        if($s == 0){
            $r = $l;
            $g = $l;
            $b = $l; // achromatic
        }else{
            $q = $l < 0.5 ? $l * (1 + $s) : $l + $s - $l * $s;
            $p = 2 * $l - $q;
            $r = hue2rgb($p, $q, $h + 1/3);
            $g = hue2rgb($p, $q, $h);
            $b = hue2rgb($p, $q, $h - 1/3);
        }
    
        return array(round($r * 255), round($g * 255), round($b * 255));
    }
    
    /* Uncomment to test * /
    for ($i=0;$i<360;$i++) {
      $rgb=hslToRgb($i/360, 1, .9);
      echo '<div style="background-color:rgb(' .$rgb[0] . ', ' . $rgb[1] . ', ' . $rgb[2] . ');padding:2px;"></div>';
    }
    /* End Test */
    

    Creating a new empty branch for a new project

    Make an empty new branch like this:

    true | git mktree | xargs git commit-tree | xargs git branch proj-doc
    

    If your proj-doc files are already in a commit under a single subdir you can make the new branch this way:

    git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc
    

    which might be more convenient than git branch --orphan if that would leave you with a lot of git rm and git mving to do.

    Try

    git branch --set-upstream proj-doc origin/proj-doc
    

    and see if that helps with your fetching-too-much problem. Also if you really only want to fetch a single branch it's safest to just specify it on the commandline.

    HintPath vs ReferencePath in Visual Studio

    Look in the file Microsoft.Common.targets

    The answer to the question is in the file Microsoft.Common.targets for your target framework version.

    For .Net Framework version 4.0 (and 4.5 !) the AssemblySearchPaths-element is defined like this:

        <!--
        The SearchPaths property is set to find assemblies in the following order:
    
            (1) Files from current project - indicated by {CandidateAssemblyFiles}
            (2) $(ReferencePath) - the reference path property, which comes from the .USER file.
            (3) The hintpath from the referenced item itself, indicated by {HintPathFromItem}.
            (4) The directory of MSBuild's "target" runtime from GetFrameworkPath.
                The "target" runtime folder is the folder of the runtime that MSBuild is a part of.
            (5) Registered assembly folders, indicated by {Registry:*,*,*}
            (6) Legacy registered assembly folders, indicated by {AssemblyFolders}
            (7) Resolve to the GAC.
            (8) Treat the reference's Include as if it were a real file name.
            (9) Look in the application's output folder (like bin\debug)
        -->
    <AssemblySearchPaths Condition=" '$(AssemblySearchPaths)' == ''">
      {CandidateAssemblyFiles};
      $(ReferencePath);
      {HintPathFromItem};
      {TargetFrameworkDirectory};
      {Registry:$(FrameworkRegistryBase),$(TargetFrameworkVersion),$(AssemblyFoldersSuffix)$(AssemblyFoldersExConditions)};
      {AssemblyFolders};
      {GAC};
      {RawFileName};
      $(OutDir)
    </AssemblySearchPaths>
    

    For .Net Framework 3.5 the definition is the same, but the comment is wrong. The 2.0 definition is slightly different, it uses $(OutputPath) instead of $(OutDir).

    On my machine I have the following versions of the file Microsoft.Common.targets:

    C:\Windows\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets
    C:\Windows\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets
    C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets
    
    C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Microsoft.Common.targets
    C:\Windows\Microsoft.NET\Framework64\v3.5\Microsoft.Common.targets
    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Common.targets
    

    This is with Visual Studio 2008, 2010 and 2013 installed on Windows 7.

    The fact that the output directory is searched can be a bit frustrating (as the original poster points out) because it may hide an incorrect HintPath. The solution builds OK on your local machine, but breaks when you build on in a clean folder structure (e.g. on the build machine).

    installing python packages without internet and using source code as .tar.gz and .whl

    If you want to install a bunch of dependencies from, say a requirements.txt, you would do:

    mkdir dependencies
    pip download -r requirements.txt -d "./dependencies"
    tar cvfz dependencies.tar.gz dependencies
    

    And, once you transfer the dependencies.tar.gz to the machine which does not have internet you would do:

    tar zxvf dependencies.tar.gz
    cd dependencies
    pip install * -f ./ --no-index
    

    Html.Textbox VS Html.TextboxFor

    Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.

    1:  @Html.TextBox("Name")
    2:  Html.TextBoxFor(m => m.Name)
    

    will both produce

    <input id="Name" name="Name" type="text" />
    

    So what does that mean in terms of use?

    Generally two things:

    1. The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
    2. Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.

    It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.

    HTML5 Email Validation

    You can follow this pattern also

    <form action="/action_page.php">
      E-mail: <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
      <input type="submit">
    </form>
    

    Ref : In W3Schools

    How to upload files in asp.net core?

    Fileservice.cs:

    public class FileService : IFileService
    {
        private readonly IWebHostEnvironment env;
    
        public FileService(IWebHostEnvironment env)
        {
            this.env = env;
        }
    
        public string Upload(IFormFile file)
        {
            var uploadDirecotroy = "uploads/";
            var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);
    
            if (!Directory.Exists(uploadPath))
                Directory.CreateDirectory(uploadPath);
    
            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(uploadPath, fileName);
    
            using (var strem = File.Create(filePath))
            {
                file.CopyTo(strem);
            }
            return fileName;
        }
    }
    

    IFileService:

    namespace studentapps.Services
    {
        public interface IFileService
        {
            string Upload(IFormFile file);
        }
    }
    

    StudentController:

    [HttpGet]
    public IActionResult Create()
    {
        var student = new StudentCreateVM();
        student.Colleges = dbContext.Colleges.ToList();
        return View(student);
    }
    
    [HttpPost]
    public IActionResult Create([FromForm] StudentCreateVM vm)
    {
        Student student = new Student()
        {
            DisplayImage = vm.DisplayImage.FileName,
            Name = vm.Name,
            Roll_no = vm.Roll_no,
            CollegeId = vm.SelectedCollegeId,
        };
    
    
        if (ModelState.IsValid)
        {
            var fileName = fileService.Upload(vm.DisplayImage);
            student.DisplayImage = fileName;
            getpath = fileName;
    
            dbContext.Add(student);
            dbContext.SaveChanges();
            TempData["message"] = "Successfully Added";
        }
        return RedirectToAction("Index");
    }
    

    Clone contents of a GitHub repository (without the folder itself)

    If the current directory is empty, you can do that with:

    git clone git@github:me/name.git .
    

    (Note the . at the end to specify the current directory.) Of course, this also creates the .git directory in your current folder, not just the source code from your project.

    This optional [directory] parameter is documented in the git clone manual page, which points out that cloning into an existing directory is only allowed if that directory is empty.

    How do I check if PHP is connected to a database already?

    Try using PHP's mysql_ping function:

    echo @mysql_ping() ? 'true' : 'false';
    

    You will need to prepend the "@" to suppose the MySQL Warnings you'll get for running this function without being connected to a database.

    There are other ways as well, but it depends on the code that you're using.

    How to convert an integer to a character array using C

    Make use of the log10 function to determine the number of digits and do like below:

    char * toArray(int number)
    {
        int n = log10(number) + 1;
        int i;
        char *numberArray = calloc(n, sizeof(char));
        for (i = n-1; i >= 0; --i, number /= 10)
        {
            numberArray[i] = (number % 10) + '0';
        }
        return numberArray;
    }
    

    Or the other option is sprintf(yourCharArray,"%ld", intNumber);

    Group By Multiple Columns

    Ok got this as:

    var query = (from t in Transactions
                 group t by new {t.MaterialID, t.ProductID}
                 into grp
                        select new
                        {
                            grp.Key.MaterialID,
                            grp.Key.ProductID,
                            Quantity = grp.Sum(t => t.Quantity)
                        }).ToList();
    

    How can I get the image url in a Wordpress theme?

    src="<?php bloginfo('template_url'); ?>/image_dir/img.ext"
    worked for me for wordpress 3.6 i used it to get header logo using as

    <img src="<?php bloginfo('template_url'); ?>/images/logo.jpg">
    

    Reset auto increment counter in postgres

    if you want to Reset auto increment from GUI, then follow this steps.

    1. Go to your Database
    2. Click on Public
    3. in the tables Listing page you can see TABS like 'Tables', 'Views', 'Sequences' like that.
    4. Click on Sequences
    5. when you click on 'Sequences' you can see all the Sequences Listing, click on any that you want to Reset
    6. After that you can see multiple choice like 'Alter', 'Set Value', 'Restart', 'Reset' etc...
    7. then click on Reset, then add one New Row.

    Xcode "Device Locked" When iPhone is unlocked

    I recently ran into this issue with XCode 8 just after updating my device from iOS 9 to 10. The exact error I received was:Development cannot be enabled while your device is locked. Please unlock your device and reattach. I received this error even when my phone was unlocked, and after unplugging and re-plugging in the device.

    As is mentioned in several answers, the device is locked message is actually referring to the device not trusting the MacBook. In my case, I think my phone defaulted to not trusting my computer after updating to iOS 10. Here are the steps that worked for me to reset the settings (this is the same process that is mentioned in the Apple support page in tehprofessors' answer):

    1. Disconnect your device from your MacBook and close Xcode.
    2. On your device go to Settings > General > Reset, then tap Reset Location & Privacy
    3. Plug your device back into your computer, and on the device you will be prompted to trust the computer. Tap trust.
    4. Now reopen Xcode and rebuild the project.
    5. The device locked error should disappear.

    How to return a dictionary | Python

    def prepare_table_row(row):
        lst = [i.text for i in row if i != u'\n']
        return dict(rank = int(lst[0]),
                    grade = str(lst[1]),
                    channel=str(lst[2])),
                    videos = float(lst[3].replace(",", " ")),
                    subscribers = float(lst[4].replace(",", "")),
                    views = float(lst[5].replace(",", "")))
    

    Add unique constraint to combination of two columns

    This can also be done in the GUI:

    1. Under the table "Person", right click Indexes
    2. Click/hover New Index
    3. Click Non-Clustered Index...

    enter image description here

    1. A default Index name will be given but you may want to change it.
    2. Check Unique checkbox
    3. Click Add... button

    enter image description here

    1. Check the columns you want included

    enter image description here

    1. Click OK in each window.

    Javascript: how to validate dates in format MM-DD-YYYY?

    Short and fast.

    _x000D_
    _x000D_
    function dateValid(date) {_x000D_
      var match = date.match(/^(\d\d)-(\d\d)-(\d{4})$/) || [];_x000D_
      var m = (match[1] | 0) - 1;_x000D_
      var d = match[2] | 0;_x000D_
      var y = match[3] | 0;_x000D_
      return !(_x000D_
          m < 0 ||                     // Before January_x000D_
          m > 11 ||                    // After December_x000D_
          d < 1 ||                     // Before the 1st of the month_x000D_
          d - 30 > (2773 >> m & 1) ||  // After the 30th or 31st of the month using bitmap_x000D_
          m == 1 && d - 28 >           // After the 28th or 29th of February depending on leap year_x000D_
              (!(y % 4) && y % 100 || !(y % 400)));_x000D_
    }_x000D_
    _x000D_
    console.log('02-29-2000', dateValid('02-29-2000'));_x000D_
    console.log('02-29-2001', dateValid('02-29-2001'));_x000D_
    console.log('12-31-1970', dateValid('12-31-1970'));_x000D_
    console.log('Hello', dateValid('Hello'));
    _x000D_
    _x000D_
    _x000D_

    PostgreSQL: Drop PostgreSQL database through command line

    Try this. Note there's no database specified - it just runs "on the server"

    psql -U postgres -c "drop database databasename"
    

    If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
    To clean them up, do this:

    SELECT * FROM pg_prepared_xacts;
    

    then for every id you see, run this:

    ROLLBACK PREPARED '<id>';
    

    Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

    I faced this issue once and was able to resolve it by fixing of my /etc/hosts. It just was unable to resolve localhost name... Details are here: http://itvictories.com/node/6

    In fact, there is 99% that error related to /etc/hosts file

    X server just unable to resolve localhost and all consequent actions just fails.

    Please be sure that you have a record like

    127.0.0.1 localhost
    

    in your /etc/hosts file.

    Replace non-numeric with empty string

    try this

    public static string cleanPhone(string inVal)
            {
                char[] newPhon = new char[inVal.Length];
                int i = 0;
                foreach (char c in inVal)
                    if (c.CompareTo('0') > 0 && c.CompareTo('9') < 0)
                        newPhon[i++] = c;
                return newPhon.ToString();
            }
    

    C program to check little vs. big endian

    In short, yes.

    Suppose we are on a 32-bit machine.

    If it is little endian, the x in the memory will be something like:

           higher memory
              ----->
        +----+----+----+----+
        |0x01|0x00|0x00|0x00|
        +----+----+----+----+
        A
        |
       &x
    

    so (char*)(&x) == 1, and *y+48 == '1'.

    If it is big endian, it will be:

        +----+----+----+----+
        |0x00|0x00|0x00|0x01|
        +----+----+----+----+
        A
        |
       &x
    

    so this one will be '0'.

    Angular2 dynamic change CSS property

    I did this plunker to explore one way to do what you want.

    Here I get mystyle from the parent component but you can get it from a service.

    import {Component, View} from 'angular2/angular2'
    
    @Component({
      selector: '[my-person]',
      inputs: [
        'name',
        'mystyle: customstyle'
      ],
      host: {
        '[style.backgroundColor]': 'mystyle.backgroundColor'
      }
    })
    @View({
      template: `My Person Component: {{ name }}`
    })
    export class Person {}
    

    Bootstrap Dropdown with Hover

        $('.navbar .dropdown').hover(function() {
          $(this).find('.dropdown-menu').first().stop(true, true).slideDown(150);
        }, function() {
          $(this).find('.dropdown-menu').first().stop(true, true).slideUp(105)
        });
    

    Using Javascript in CSS

    To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):

    styles.css.php:

    body
     {
    margin: 0px;
    font-family: Verdana;
    background-color: #cccccc;
    background-image: url('<?php
    echo 'images/flag_bg/' . $user_country . '.png';
    ?>');
     }
    

    This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:

    user_theme.css.php:

    body
     {
    background-color: <?php echo $user_theme['BG_COLOR']; ?>;
    color: <?php echo $user_theme['COLOR']; ?>;
    font-family: <?php echo $user_theme['FONT']; ?>;
     }
    
    #panel
     {
    font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
    background-image: <?php echo $user_theme['PANEL_BG']; ?>;
     }
    

    Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.

    JavaScript: What are .extend and .prototype used for?

    This seems to be the clearest and simplest example to me, this just appends property or replaces existing.

    function replaceProperties(copyTo, copyFrom)  {
      for (var property in copyFrom) 
        copyTo[property] =  copyFrom[property]
      return copyTo
    }
    

    Reading RFID with Android phones

    You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/

    How can I pipe stderr, and not stdout?

    Or to swap the output from standard error and standard output over, use:

    command 3>&1 1>&2 2>&3
    

    This creates a new file descriptor (3) and assigns it to the same place as 1 (standard output), then assigns fd 1 (standard output) to the same place as fd 2 (standard error) and finally assigns fd 2 (standard error) to the same place as fd 3 (standard output).

    Standard error is now available as standard output and the old standard output is preserved in standard error. This may be overkill, but it hopefully gives more details on Bash file descriptors (there are nine available to each process).

    How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

    This worked for me. :)

    sudo keytool -importcert -file filename.cer -alias randomaliasname -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit 
    

    Combining two sorted lists in Python

    Have used merge step of the merge sort. But I have used generators. Time complexity O(n)

    def merge(lst1,lst2):
        len1=len(lst1)
        len2=len(lst2)
        i,j=0,0
        while(i<len1 and j<len2):
            if(lst1[i]<lst2[j]):
                    yield lst1[i]
                    i+=1
            else:
                    yield lst2[j]
                    j+=1
        if(i==len1):
            while(j<len2):
                    yield lst2[j]
                    j+=1
        elif(j==len2):
            while(i<len1):
                    yield lst1[i]
                    i+=1
    l1=[1,3,5,7]
    l2=[2,4,6,8,9]
    mergelst=(val for val in merge(l1,l2))
    print(*mergelst)
    

    How to subtract n days from current date in java?

    I found this perfect solution and may useful, You can directly get in format as you want:

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -90); // I just want date before 90 days. you can give that you want.
    
    SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); // you can specify your format here...
    Log.d("DATE","Date before 90 Days: " + s.format(new Date(cal.getTimeInMillis())));
    

    Thanks.

    Easiest way to convert int to string in C++

    Picking up a discussion with @v.oddou a couple of years later, C++17 has finally delivered a way to do the originally macro-based type-agnostic solution (preserved below) without going through macro uglyness.

    // variadic template
    template < typename... Args >
    std::string sstr( Args &&... args )
    {
        std::ostringstream sstr;
        // fold expression
        ( sstr << std::dec << ... << args );
        return sstr.str();
    }
    

    Usage:

    int i = 42;
    std::string s = sstr( "i is: ", i );
    puts( sstr( i ).c_str() );
    
    Foo x( 42 );
    throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
    

    Original answer:

    Since "converting ... to string" is a recurring problem, I always define the SSTR() macro in a central header of my C++ sources:

    #include <sstream>
    
    #define SSTR( x ) static_cast< std::ostringstream & >( \
            ( std::ostringstream() << std::dec << x ) ).str()
    

    Usage is as easy as could be:

    int i = 42;
    std::string s = SSTR( "i is: " << i );
    puts( SSTR( i ).c_str() );
    
    Foo x( 42 );
    throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
    

    The above is C++98 compatible (if you cannot use C++11 std::to_string), and does not need any third-party includes (if you cannot use Boost lexical_cast<>); both these other solutions have a better performance though.

    React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

    Make sure you're calling super() as the first thing in your constructor.

    You should set this for setAuthorState method

    class ManageAuthorPage extends Component {
    
      state = {
        author: { id: '', firstName: '', lastName: '' }
      };
    
      constructor(props) {
        super(props);
        this.handleAuthorChange = this.handleAuthorChange.bind(this);
      } 
    
      handleAuthorChange(event) {
        let {name: fieldName, value} = event.target;
    
        this.setState({
          [fieldName]: value
        });
      };
    
      render() {
        return (
          <AuthorForm
            author={this.state.author}
            onChange={this.handleAuthorChange}
          />
        );
      }
    }
    

    Another alternative based on arrow function:

    class ManageAuthorPage extends Component {
    
      state = {
        author: { id: '', firstName: '', lastName: '' }
      };
    
      handleAuthorChange = (event) => {
        const {name: fieldName, value} = event.target;
    
        this.setState({
          [fieldName]: value
        });
      };
    
      render() {
        return (
          <AuthorForm
            author={this.state.author}
            onChange={this.handleAuthorChange}
          />
        );
      }
    }
    

    creating batch script to unzip a file without additional zip tools

    Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

    To unzip file you can use this script :

    zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no
    

    Access to the requested object is only available from the local network phpmyadmin

    after putting "Allow from all", you need to restart your xampp to apply the setting. thanks

    How to set the current working directory?

    people using pandas package

    import os
    import pandas as pd
    
    tar = os.chdir('<dir path only>') # do not mention file name here
    print os.getcwd()# to print the path name in CLI
    

    the following syntax to be used to import the file in python CLI

    dataset(*just a variable) = pd.read_csv('new.csv')
    

    How can I find the maximum value and its index in array in MATLAB?

    For a matrix you can use this:

    [M,I] = max(A(:))
    

    I is the index of A(:) containing the largest element.

    Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

    [I_row, I_col] = ind2sub(size(A),I)
    

    source: https://www.mathworks.com/help/matlab/ref/max.html

    Understanding typedefs for function pointers in C

    This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.

        typedef double (*pf)(double x);  /*this defines a type pf */
    
        double f1(double x) { return(x+x);}
        double f2(double x) { return(x*x);}
    
        pf pa[] = {f1, f2};
    
    
        main()
        {
            pf p;
    
            p = pa[0];
            printf("%f\n", p(3.0));
            p = pa[1];
            printf("%f\n", p(3.0));
        }
    

    The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

    I know it's an old thread, but I'd like to point the possible version issue of DotNetCompilerPlatform.dll, f. ex. after an update. Please check, if the new generated Web.config file is different as your released web.config, in particular the system.codedom part. In my case it was the version change from 1.0.7 to 1.0.8. The new dll had been already copied to the server, but I didn't change the old web.config (with some server special settings):

    <pre>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
    </pre>
    

    After I update the two lines, the error disappeared.

    Unit testing with mockito for constructors

    I have used "Pattern 2 - the "factory helper pattern"

    Pattern 2 - the factory helper pattern

    One case where this pattern won't work is if MyClass is final. Most of the Mockito framework doesn't play particularly well with final classes; and this includes the use of spy(). Another case is where MyClass uses getClass() somewhere, and requires the resulting value to be MyClass. This won't work, because the class of a spy is actually a Mockito-generated subclass of the original class.

    In either of these cases, you'll need the slightly more robust factory helper pattern, as follows.

    public class MyClass{
      static class FactoryHelper{
          Foo makeFoo( A a, B b, C c ){
              return new Foo( a, b, c );
          }
      }
    
      //...
    
      private FactoryHelper helper;
      public MyClass( X x, Y y ){
          this( x, y, new FactoryHelper());
      } 
    
      MyClass( X x, Y, y, FactoryHelper helper ){
    
          //...
    
          this.helper = helper;
      } 
    
      //...
    
      Foo foo = helper.makeFoo( a, b, c );
    }
    

    So, you have a special constructor, just for testing, that has an additional argument. This is used from your test class, when creating the object that you're going to test. In your test class, you mock the FactoryHelper class, as well as the object that you want to create.

    @Mock private MyClass.FactoryHelper mockFactoryHelper;
    @Mock private Foo mockFoo;
    private MyClass toTest;
    

    and you can use it like this

    toTest = new MyClass( x, y, mockFactoryHelper ); 
    when( mockFactoryHelper.makeFoo( 
      any( A.class ), any( B.class ), any( C.class )))
      .thenReturn( mockFoo ); 
    

    Source: http://web.archive.org/web/20160322155004/http://code.google.com/p/mockito/wiki/MockingObjectCreation

    How to delete a file from SD card?

    This worked for me.

    String myFile = "/Name Folder/File.jpg";  
    
    String my_Path = Environment.getExternalStorageDirectory()+myFile;  
    
    File f = new File(my_Path);
    Boolean deleted = f.delete();
    

    How to do a Jquery Callback after form submit?

    You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

    But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

    • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
    • grab all necessary values from the form
    • fire off an HTTP request
    • handle the response to the request

    First, you'll have to cancel the form submit action like so:

    $("#myform").submit(function(event) {
        // Cancels the form's submit action.
        event.preventDefault();
    });
    

    And then, grab the value of the data. Let's just assume you have one text box.

    $("#myform").submit(function(event) {
        event.preventDefault();
        var val = $(this).find('input[type="text"]').val();
    });
    

    And then fire off a request. Let's just assume it's a POST request.

    $("#myform").submit(function(event) {
        event.preventDefault();
        var val = $(this).find('input[type="text"]').val();
    
        // I like to use defers :)
        deferred = $.post("http://somewhere.com", { val: val });
    
        deferred.success(function () {
            // Do your stuff.
        });
    
        deferred.error(function () {
            // Handle any errors here.
        });
    });
    

    And this should about do it.

    Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

    Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

    $.post("http://somewhere.com", { val: val }, function () {
        // Start partying here.
    }, function () {
        // Handle the bad news here.
    });
    

    Database Diagram Support Objects cannot be Installed ... no valid owner

    USE [ECMIS]
    GO
    EXEC dbo.sp_changedbowner @loginame = N'sa', @map = false
    GO
    

    It works.

    Should I use past or present tense in git commit messages?

    I wrote a fuller description on 365git.

    The use of the imperative, present tense is one that takes a little getting used to. When I started mentioning it, it was met with resistance. Usually along the lines of “The commit message records what I have done”. But, Git is a distributed version control system where there are potentially many places to get changes from. Rather than writing messages that say what you’ve done; consider these messages as the instructions for what applying the commit will do. Rather than having a commit with the title:

    Renamed the iVars and removed the common prefix.

    Have one like this:

    Rename the iVars to remove the common prefix

    Which tells someone what applying the commit will do, rather than what you did. Also, if you look at your repository history you will see that the Git generated messages are written in this tense as well - “Merge” not “Merged”, “Rebase” not “Rebased” so writing in the same tense keeps things consistent. It feels strange at first but it does make sense (testimonials available upon application) and eventually becomes natural.

    Having said all that - it’s your code, your repository: so set up your own guidelines and stick to them.

    If, however, you do decide to go this way then git rebase -i with the reword option would be a good thing to look into.

    Using Java with Microsoft Visual Studio 2012

    If you want to get started with Java, you will be much happier with a Java IDE. IntelliJ Community Edition, Eclipse, and Netbeans are all free.

    I know IntelliJ can be set to use Visual Studio keyboard shortcuts, so even if you are a keyboard junkie like myself, you won't feel out of place in a Java IDE.

    The differences in IDEs are minimal, and the time you will save by using a Java IDE for Java development will be huge.

    Good luck!

    pandas groupby sort within groups

    Here's other example of taking top 3 on sorted order, and sorting within the groups:

    In [43]: import pandas as pd                                                                                                                                                       
    
    In [44]:  df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})
    
    In [45]: df                                                                                                                                                                        
    Out[45]: 
       count_1  count_2  name
    0        5      100   Foo
    1       10      150   Foo
    2       12      100  Baar
    3       15       25   Foo
    4       20      250  Baar
    5       25      300   Foo
    6       30      400  Baar
    7       35      500  Baar
    
    
    ### Top 3 on sorted order:
    In [46]: df.groupby(["name"])["count_1"].nlargest(3)                                                                                                                               
    Out[46]: 
    name   
    Baar  7    35
          6    30
          4    20
    Foo   5    25
          3    15
          1    10
    dtype: int64
    
    
    ### Sorting within groups based on column "count_1":
    In [48]: df.groupby(["name"]).apply(lambda x: x.sort_values(["count_1"], ascending = False)).reset_index(drop=True)
    Out[48]: 
       count_1  count_2  name
    0       35      500  Baar
    1       30      400  Baar
    2       20      250  Baar
    3       12      100  Baar
    4       25      300   Foo
    5       15       25   Foo
    6       10      150   Foo
    7        5      100   Foo
    

    How to remove from a map while iterating it?

    In short "How do I remove from a map while iterating it?"

    • With old map impl: You can't
    • With new map impl: almost as @KerrekSB suggested. But there are some syntax issues in what he posted.

    From GCC map impl (note GXX_EXPERIMENTAL_CXX0X):

    #ifdef __GXX_EXPERIMENTAL_CXX0X__
          // _GLIBCXX_RESOLVE_LIB_DEFECTS
          // DR 130. Associative erase should return an iterator.
          /**
           *  @brief Erases an element from a %map.
           *  @param  position  An iterator pointing to the element to be erased.
           *  @return An iterator pointing to the element immediately following
           *          @a position prior to the element being erased. If no such 
           *          element exists, end() is returned.
           *
           *  This function erases an element, pointed to by the given
           *  iterator, from a %map.  Note that this function only erases
           *  the element, and that if the element is itself a pointer,
           *  the pointed-to memory is not touched in any way.  Managing
           *  the pointer is the user's responsibility.
           */
          iterator
          erase(iterator __position)
          { return _M_t.erase(__position); }
    #else
          /**
           *  @brief Erases an element from a %map.
           *  @param  position  An iterator pointing to the element to be erased.
           *
           *  This function erases an element, pointed to by the given
           *  iterator, from a %map.  Note that this function only erases
           *  the element, and that if the element is itself a pointer,
           *  the pointed-to memory is not touched in any way.  Managing
           *  the pointer is the user's responsibility.
           */
          void
          erase(iterator __position)
          { _M_t.erase(__position); }
    #endif
    

    Example with old and new style:

    #include <iostream>
    #include <map>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    typedef map<int, int> t_myMap;
    typedef vector<t_myMap::key_type>  t_myVec;
    
    int main() {
    
        cout << "main() ENTRY" << endl;
    
        t_myMap mi;
        mi.insert(t_myMap::value_type(1,1));
        mi.insert(t_myMap::value_type(2,1));
        mi.insert(t_myMap::value_type(3,1));
        mi.insert(t_myMap::value_type(4,1));
        mi.insert(t_myMap::value_type(5,1));
        mi.insert(t_myMap::value_type(6,1));
    
        cout << "Init" << endl;
        for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
            cout << '\t' << i->first << '-' << i->second << endl;
    
        t_myVec markedForDeath;
    
        for (t_myMap::const_iterator it = mi.begin(); it != mi.end() ; it++)
            if (it->first > 2 && it->first < 5)
                markedForDeath.push_back(it->first);
    
        for(size_t i = 0; i < markedForDeath.size(); i++)
            // old erase, returns void...
            mi.erase(markedForDeath[i]);
    
        cout << "after old style erase of 3 & 4.." << endl;
        for(t_myMap::const_iterator i = mi.begin(); i != mi.end(); i++)
            cout << '\t' << i->first << '-' << i->second << endl;
    
        for (auto it = mi.begin(); it != mi.end(); ) {
            if (it->first == 5)
                // new erase() that returns iter..
                it = mi.erase(it);
            else
                ++it;
        }
    
        cout << "after new style erase of 5" << endl;
        // new cend/cbegin and lambda..
        for_each(mi.cbegin(), mi.cend(), [](t_myMap::const_reference it){cout << '\t' << it.first << '-' << it.second << endl;});
    
        return 0;
    }
    

    prints:

    main() ENTRY
    Init
            1-1
            2-1
            3-1
            4-1
            5-1
            6-1
    after old style erase of 3 & 4..
            1-1
            2-1
            5-1
            6-1
    after new style erase of 5
            1-1
            2-1
            6-1
    
    Process returned 0 (0x0)   execution time : 0.021 s
    Press any key to continue.
    

    How can I get CMake to find my alternative Boost installation?

    In CMake, you can add the following to your CMakelists:

    # install boost by apt-get method
    include_directories(BEFORE SYSTEM "/usr/include") 
    
    #  or install by building from src
    # include_directories(BEFORE SYSTEM "/usr/local/include") 
    

    This method saved my serveral months. you can try it. By the way, as a temporary solution, you can rename directories you don't expect to find as below:

    sudo mv /usr/local/include/boost /usr/local/include/boost_bak
    

    Hopefully, it will help people who are in deep trouble like me.

    How to output numbers with leading zeros in JavaScript?

    function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
    

    SELECT only rows that contain only alphanumeric characters in MySQL

    Try this

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

    How to create a Java / Maven project that works in Visual Studio Code?

    I surprise no one had mentioned this possible easy approach in visual studio code.

    Install VS Code and Apache maven ( just as mentioned by @Steve Chambers)

    After installing this extension vscode:extension/vscjava.vscode-java-pack

    In the java overview page , there is a an option which reads 'Create Maven Project' which further takes to a simple wizard to generate maven project.

    Its pretty quick which is intutitive enough, even newbies can very well start with a Maven project.

    How to get a certain element in a list, given the position?

    std::list<Object> l; 
    std::list<Object>::iterator ptr;
    int i;
    
    for( i = 0 , ptr = l.begin() ; i < N && ptr != l.end() ; i++ , ptr++ );
    
    if( ptr == l.end() ) {
        // list too short  
    } else {
        // 'ptr' points to N-th element of list
    }
    

    generate random double numbers in c++

    This solution requires C++11 (or TR1).

    #include <random>
    
    int main()
    {
       double lower_bound = 0;
       double upper_bound = 10000;
       std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
       std::default_random_engine re;
       double a_random_double = unif(re);
    
       return 0;
    }
    

    For more details see John D. Cook's "Random number generation using C++ TR1".

    See also Stroustrup's "Random number generation".

    2D arrays in Python

    In Python one would usually use lists for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.

    How do I rename a column in a SQLite database table?

    While it is true that there is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of commands:

    Note: These commands have the potential to corrupt your database, so make sure you have a backup

    PRAGMA writable_schema = 1;
    UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
    PRAGMA writable_schema = 0;
    

    You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

    For example:

    Y:\> sqlite3 booktest  
    SQLite version 3.7.4  
    Enter ".help" for instructions  
    Enter SQL statements terminated with a ";"  
    sqlite> create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT NULL);  
    sqlite> insert into BOOKS VALUES ("NULLTEST",null);  
    Error: BOOKS.publication_date may not be NULL  
    sqlite> PRAGMA writable_schema = 1; 
    sqlite> UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';  
    sqlite> PRAGMA writable_schema = 0;  
    sqlite> .q  
    
    Y:\> sqlite3 booktest  
    SQLite version 3.7.4  
    Enter ".help" for instructions  
    Enter SQL statements terminated with a ";"  
    sqlite> insert into BOOKS VALUES ("NULLTEST",null);  
    sqlite> .q  
    

    REFERENCES FOLLOW:


    pragma writable_schema
    When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

    alter table
    SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

    ALTER TABLE SYNTAX

    How can we print line numbers to the log in java

    Below code is tested code for logging line no class name and method name from where logging method is called

    public class Utils {
    /*
     * debug variable enables/disables all log messages to logcat
     * Useful to disable prior to app store submission
     */
    public static final boolean debug = true;
    
    /*
     * l method used to log passed string and returns the
     * calling file as the tag, method and line number prior
     * to the string's message
     */
    public static void l(String s) {
        if (debug) {
            String[] msg = trace(Thread.currentThread().getStackTrace(), 3);
            Log.i(msg[0], msg[1] + s);
        } else {
            return;
        }
    }
    
    /*
     * l (tag, string)
     * used to pass logging messages as normal but can be disabled
     * when debug == false
     */
    public static void l(String t, String s) {
        if (debug) {
            Log.i(t, s);
        } else {
            return;
        }
    }
    
    /*
     * trace
     * Gathers the calling file, method, and line from the stack
     * returns a string array with element 0 as file name and 
     * element 1 as method[line]
     */
    public static String[] trace(final StackTraceElement e[], final int level) {
        if (e != null && e.length >= level) {
            final StackTraceElement s = e[level];
            if (s != null) { return new String[] {
                    e[level].getFileName(), e[level].getMethodName() + "[" + e[level].getLineNumber() + "]"
            };}
        }
        return null;
    }
    }
    

    XML serialization in Java?

    JAXB is part of JDK standard edition version 1.6+. So it is FREE and no extra libraries to download and manage. A simple example can be found here

    XStream seems to be dead. Last update was on Dec 6 2008. Simple seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.

    How do android screen coordinates work?

    enter image description here

    This image presents both orientation(Landscape/Portrait)

    To get MaxX and MaxY, read on.

    For Android device screen coordinates, below concept will work.

    Display mdisp = getWindowManager().getDefaultDisplay();
    Point mdispSize = new Point();
    mdisp.getSize(mdispSize);
    int maxX = mdispSize.x; 
    int maxY = mdispSize.y;
    

    EDIT:- ** **for devices supporting android api level older than 13. Can use below code.

        Display mdisp = getWindowManager().getDefaultDisplay();
        int maxX= mdisp.getWidth();
        int maxY= mdisp.getHeight();
    

    (x,y) :-

    1) (0,0) is top left corner.

    2) (maxX,0) is top right corner

    3) (0,maxY) is bottom left corner

    4) (maxX,maxY) is bottom right corner

    here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.

    Convert JS object to JSON string

    You can use JSON.stringify() method to convert JSON object to String.

    var j={"name":"binchen"};
    JSON.stringify(j)
    

    For reverse process, you can use JSON.parse() method to convert JSON String to JSON Object.

    JavaScript by reference vs. by value

    Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.

    An example:

    function changeParam(x, y, z) {
      x = 3;
      y = "new string";
      z["key2"] = "new";
      z["key3"] = "newer";
    
      z = {"new" : "object"};
    }
    
    var a = 1,
        b = "something",
        c = {"key1" : "whatever", "key2" : "original value"};
    
    changeParam(a, b, c);
    
    // at this point a is still 1
    // b is still "something"
    // c still points to the same object but its properties have been updated
    // so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
    // c definitely doesn't point to the new object created as the last line
    // of the function with z = ...
    

    How to change the background color on a Java panel?

    I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

    delete a column with awk or sed

    try this short thing:

    awk '!($3="")' file
    

    Redirecting a request using servlets and the "setHeader" method not working

    As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

    response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302
    

    How to "crop" a rectangular image into a square with CSS?

    Either use a div with square dimensions with the image inside with the .testimg class:

    .test {
    width: 307px;
    height: 307px;
    overflow:hidden
    }
    
    .testimg {
        margin-left: -76px
    
    }
    

    or a square div with a background of the image.

    .test2 {
    width: 307px;
    height: 307px;
        background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%
    }
    

    Here's some examples: http://jsfiddle.net/QqCLC/1/

    UPDATED SO THE IMAGE CENTRES

    _x000D_
    _x000D_
    .test {_x000D_
      width: 307px;_x000D_
      height: 307px;_x000D_
      overflow: hidden_x000D_
    }_x000D_
    _x000D_
    .testimg {_x000D_
      margin-left: -76px_x000D_
    }_x000D_
    _x000D_
    .test2 {_x000D_
      width: 307px;_x000D_
      height: 307px;_x000D_
      background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%_x000D_
    }
    _x000D_
    <div class="test"><img src="http://i.stack.imgur.com/GA6bB.png" width="460" height="307" class="testimg" /></div>_x000D_
    _x000D_
    <div class="test2"></div>
    _x000D_
    _x000D_
    _x000D_

    C++ Erase vector element by value rather than by position?

    You can use std::find to get an iterator to a value:

    #include <algorithm>
    std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
    if (position != myVector.end()) // == myVector.end() means the element was not found
        myVector.erase(position);
    

    How to print binary tree diagram?

    Here's a very versatile tree printer. Not the best looking, but it handles a lot of cases. Feel free to add slashes if you can figure that out. enter image description here

    package com.tomac120.NodePrinter;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    
    /**
     * Created by elijah on 6/28/16.
     */
    public class NodePrinter{
        final private List<List<PrintableNodePosition>> nodesByRow;
        int maxColumnsLeft = 0;
        int maxColumnsRight = 0;
        int maxTitleLength = 0;
        String sep = " ";
        int depth = 0;
    
        public NodePrinter(PrintableNode rootNode, int chars_per_node){
            this.setDepth(rootNode,1);
            nodesByRow = new ArrayList<>(depth);
            this.addNode(rootNode._getPrintableNodeInfo(),0,0);
            for (int i = 0;i<chars_per_node;i++){
                //sep += " ";
            }
        }
    
        private void setDepth(PrintableNode info, int depth){
            if (depth > this.depth){
                this.depth = depth;
            }
            if (info._getLeftChild() != null){
                this.setDepth(info._getLeftChild(),depth+1);
            }
            if (info._getRightChild() != null){
                this.setDepth(info._getRightChild(),depth+1);
            }
        }
    
        private void addNode(PrintableNodeInfo node, int level, int position){
            if (position < 0 && -position > maxColumnsLeft){
                maxColumnsLeft = -position;
            }
            if (position > 0 && position > maxColumnsRight){
                maxColumnsRight = position;
            }
            if (node.getTitleLength() > maxTitleLength){
               maxTitleLength = node.getTitleLength();
            }
            List<PrintableNodePosition> row = this.getRow(level);
            row.add(new PrintableNodePosition(node, level, position));
            level++;
    
            int depthToUse = Math.min(depth,6);
            int levelToUse = Math.min(level,6);
            int offset = depthToUse - levelToUse-1;
            offset = (int)(Math.pow(offset,Math.log(depthToUse)*1.4));
            offset = Math.max(offset,3);
    
    
            PrintableNodeInfo leftChild = node.getLeftChildInfo();
            PrintableNodeInfo rightChild = node.getRightChildInfo();
            if (leftChild != null){
                this.addNode(leftChild,level,position-offset);
            }
            if (rightChild != null){
                this.addNode(rightChild,level,position+offset);
            }
        }
    
        private List<PrintableNodePosition> getRow(int row){
            if (row > nodesByRow.size() - 1){
                nodesByRow.add(new LinkedList<>());
            }
            return nodesByRow.get(row);
        }
    
        public void print(){
            int max_chars = this.maxColumnsLeft+maxColumnsRight+1;
            int level = 0;
            String node_format = "%-"+this.maxTitleLength+"s";
            for (List<PrintableNodePosition> pos_arr : this.nodesByRow){
                String[] chars = this.getCharactersArray(pos_arr,max_chars);
                String line = "";
                int empty_chars = 0;
                for (int i=0;i<chars.length+1;i++){
                    String value_i = i < chars.length ? chars[i]:null;
                    if (chars.length + 1 == i || value_i != null){
                        if (empty_chars > 0) {
                            System.out.print(String.format("%-" + empty_chars + "s", " "));
                        }
                        if (value_i != null){
                            System.out.print(String.format(node_format,value_i));
                            empty_chars = -1;
                        } else{
                            empty_chars = 0;
                        }
                    } else {
                        empty_chars++;
                    }
                }
                System.out.print("\n");
    
                int depthToUse = Math.min(6,depth);
                int line_offset = depthToUse - level;
                line_offset *= 0.5;
                line_offset = Math.max(0,line_offset);
    
                for (int i=0;i<line_offset;i++){
                    System.out.println("");
                }
    
    
                level++;
            }
        }
    
        private String[] getCharactersArray(List<PrintableNodePosition> nodes, int max_chars){
            String[] positions = new String[max_chars+1];
            for (PrintableNodePosition a : nodes){
                int pos_i = maxColumnsLeft + a.column;
                String title_i = a.nodeInfo.getTitleFormatted(this.maxTitleLength);
                positions[pos_i] = title_i;
            }
            return positions;
        }
    }
    

    NodeInfo class

    package com.tomac120.NodePrinter;
    
    /**
     * Created by elijah on 6/28/16.
     */
    public class PrintableNodeInfo {
        public enum CLI_PRINT_COLOR {
            RESET("\u001B[0m"),
            BLACK("\u001B[30m"),
            RED("\u001B[31m"),
            GREEN("\u001B[32m"),
            YELLOW("\u001B[33m"),
            BLUE("\u001B[34m"),
            PURPLE("\u001B[35m"),
            CYAN("\u001B[36m"),
            WHITE("\u001B[37m");
    
            final String value;
            CLI_PRINT_COLOR(String value){
                this.value = value;
            }
    
            @Override
            public String toString() {
                return value;
            }
        }
        private final String title;
        private final PrintableNode leftChild;
        private final PrintableNode rightChild;
        private final CLI_PRINT_COLOR textColor;
    
        public PrintableNodeInfo(String title, PrintableNode leftChild, PrintableNode rightChild){
            this(title,leftChild,rightChild,CLI_PRINT_COLOR.BLACK);
        }
    
        public PrintableNodeInfo(String title, PrintableNode leftChild, PrintableNode righthild, CLI_PRINT_COLOR textColor){
            this.title = title;
            this.leftChild = leftChild;
            this.rightChild = righthild;
            this.textColor = textColor;
        }
    
        public String getTitle(){
            return title;
        }
    
        public CLI_PRINT_COLOR getTextColor(){
            return textColor;
        }
    
        public String getTitleFormatted(int max_chars){
            return this.textColor+title+CLI_PRINT_COLOR.RESET;
            /*
            String title = this.title.length() > max_chars ? this.title.substring(0,max_chars+1):this.title;
            boolean left = true;
            while(title.length() < max_chars){
                if (left){
                    title = " "+title;
                } else {
                    title = title + " ";
                }
            }
            return this.textColor+title+CLI_PRINT_COLOR.RESET;*/
        }
    
        public int getTitleLength(){
            return title.length();
        }
    
        public PrintableNodeInfo getLeftChildInfo(){
            if (leftChild == null){
                return null;
            }
            return leftChild._getPrintableNodeInfo();
        }
    
        public PrintableNodeInfo getRightChildInfo(){
            if (rightChild == null){
                return null;
            }
            return rightChild._getPrintableNodeInfo();
        }
    }
    

    NodePosition class

    package com.tomac120.NodePrinter;
    
    /**
     * Created by elijah on 6/28/16.
     */
    public class PrintableNodePosition implements Comparable<PrintableNodePosition> {
        public final int row;
        public final int column;
        public final PrintableNodeInfo nodeInfo;
        public PrintableNodePosition(PrintableNodeInfo nodeInfo, int row, int column){
            this.row = row;
            this.column = column;
            this.nodeInfo = nodeInfo;
        }
    
        @Override
        public int compareTo(PrintableNodePosition o) {
            return Integer.compare(this.column,o.column);
        }
    }
    

    And, finally, Node Interface

    package com.tomac120.NodePrinter;
    
    /**
     * Created by elijah on 6/28/16.
     */
    public interface PrintableNode {
        PrintableNodeInfo _getPrintableNodeInfo();
        PrintableNode _getLeftChild();
        PrintableNode _getRightChild();
    }
    

    How do I change column default value in PostgreSQL?

    'SET' is forgotten

    ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';
    

    No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

    Basically alter API header response by adding following additional parameters.

    Access-Control-Allow-Credentials: true

    Access-Control-Allow-Origin: *

    But this is not good solution when it comes to the security

    MySQL: ignore errors when importing?

    Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

    For example:

    mysql -u userName -p -f -D dbName < script.sql
    

    Creating a jQuery object from a big HTML-string

    I use the following for my HTML templates:

    $(".main").empty();
    
    var _template = '<p id="myelement">Your HTML Code</p>';
    var template = $.parseHTML(_template);
    var final = $(template).find("#myelement");
    
    $(".main").append(final.html());
    

    Note: Assuming if you are using jQuery

    How to compare two Dates without the time portion?

    public Date saveDateWithoutTime(Date date) {
        Calendar calendar = Calendar.getInstance();
    
        calendar.setTime( date );
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    
        return calendar.getTime();
    }
    

    This will help you to compare dates without considering the time.

    JAX-WS - Adding SOAP Headers

    The best option (for my of course) is do it yourserfl. It means you can modify programattly all parts of the SOAP message

    Binding binding = prov.getBinding();
       List<Handler> handlerChain = binding.getHandlerChain();
        handlerChain.add( new ModifyMessageHandler() );
        binding.setHandlerChain( handlerChain ); 
    

    And the ModifyMessageHandler source could be

    @Override
    public boolean handleMessage( SOAPMessageContext context )
    {
        SOAPMessage msg = context.getMessage(); 
        try
        {
    
            SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
            SOAPHeader header = envelope.addHeader();
            SOAPElement ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
            ele.addTextNode( "value_of_header" );
            ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
            ele.addTextNode( "value_of_header" );
            ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
            ele.addTextNode( "value_of_header" );
    

    ...

    I hope this helps you

    How can I make a thumbnail <img> show a full size image when clicked?

    The

    <a href="image2.gif" ><img src="image1.gif"/></a>
    

    technique has always worked for me. I used it to good effect in my Super Bowl diary, but I see that the scripts I used are broken. Once I get them fixed I will edit in the URL.

    Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

    plot(t) is in this case the same as

    plot(t[[1]], t[[2]])
    

    As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

    > length(t)
    [1] 4
    > length(1)
    [1] 1
    

    In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

    Edit:

    If you want to plot lines use

    plot(t, type="l")
    

    What is a race condition?

    Race condition is not only related with software but also related with hardware too. Actually the term was initially coined by the hardware industry.

    According to wikipedia:

    The term originates with the idea of two signals racing each other to influence the output first.

    Race condition in a logic circuit:

    enter image description here

    Software industry took this term without modification, which makes it a little bit difficult to understand.

    You need to do some replacement to map it to the software world:

    • "two signals" => "two threads"/"two processes"
    • "influence the output" => "influence some shared state"

    So race condition in software industry means "two threads"/"two processes" racing each other to "influence some shared state", and the final result of the shared state will depend on some subtle timing difference, which could be caused by some specific thread/process launching order, thread/process scheduling, etc.

    Convenient C++ struct initialisation

    Since style A is not allowed in C++ and you don't want style B then how about using style BX:

    FooBar fb = { /*.foo=*/ 12, /*.bar=*/ 3.4 };  // :)
    

    At least help at some extent.

    How do I set the visibility of a text box in SSRS using an expression?

    Twood, Visibility expression is the expressions you write on how you want the "visibility" to behave. So, if you would want to hide or show the textbox, you want to write this:

    =IIf((CountRows("ScannerStatisticsData")=0),True,False)
    

    This means, if the dataset is 0, you want to hide the textbox.

    Operand type clash: uniqueidentifier is incompatible with int

    Sounds to me like at least one of those tables has defined UserID as a uniqueidentifier, not an int. Did you check the data in each table? What does SELECT TOP 1 UserID FROM each table yield? An int or a GUID?

    EDIT

    I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership table in your script, since it's not really one of "your" tables.

    If you meant to design your tables around the aspnet_Membership database, then why are the rest of the columns int when that table clearly uses a uniqueidentifier for the UserID column?

    How to start and stop android service from a adb shell?

    To stop a service, you have to find service name using:

    adb shell dumpsys activity services <your package>
    

    for example: adb shell dumpsys activity services com.xyz.something

    This will list services running for your package.
    Output should be similar to:

    ServiceRecord{xxxxx u0 com.xyz.something.beta/xyz.something.abc.XYZService}
    

    Now select your service and run:

    adb shell am stopservice <service_name> 
    

    For example:

    adb shell am stopservice com.xyz.something.beta/xyz.something.abc.XYZService
    

    similarly, to start service:

    adb shell am startservice <service_name>
    

    To access service, your service(in AndroidManifest.xml) should set exported="true"

    <!-- Service declared in manifest -->
    <service
        android:name=".YourServiceName"
        android:exported="true"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="com.your.package.name.YourServiceName"/>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </service>
    

    #define in Java

    No, because there's no precompiler. However, in your case you could achieve the same thing as follows:

    class MyClass
    {
        private static final int PROTEINS = 0;
    
        ...
    
        MyArray[] foo = new MyArray[PROTEINS];
    
    }
    

    The compiler will notice that PROTEINS can never, ever change and so will inline it, which is more or less what you want.

    Note that the access modifier on the constant is unimportant here, so it could be public or protected instead of private, if you wanted to reuse the same constant across multiple classes.

    Iterate over array of objects in Typescript

    In Typescript and ES6 you can also use for..of:

    for (var product of products) {
         console.log(product.product_desc)
    }
    

    which will be transcoded to javascript:

    for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
        var product = products_1[_i];
        console.log(product.product_desc);
    }
    

    Automatic prune with Git fetch or pull

    git config --global fetch.prune true

    To always --prune for git fetch and git pull in all your Git repositories:

    git config --global fetch.prune true
    

    This above command appends in your global Git configuration (typically ~/.gitconfig) the following lines. Use git config -e --global to view your global configuration.

    [fetch]
        prune = true
    

    git config remote.origin.prune true

    To always --prune but from one single repository:

    git config remote.origin.prune true
                     #^^^^^^
                     #replace with your repo name
    

    This above command adds in your local Git configuration (typically .git/config) the below last line. Use git config -e to view your local configuration.

    [remote "origin"]
        url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        fetch = +refs/heads/*:refs/remotes/origin/*
        prune = true
    

    You can also use --global within the second command or use instead --local within the first command.


    git config --global gui.pruneDuringFetch true

    If you use git gui you may also be interested by:

    git config --global gui.pruneDuringFetch true
    

    that appends:

    [gui]
        pruneDuringFetch = true
    

    References

    The corresponding documentations from git help config:

    --global

      For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t.

     

    --local

      For writing options: write to the repository .git/config file. This is the default behavior.

     

    fetch.prune

      If true, fetch will automatically behave as if the --prune option was given on the command line. See also remote.<name>.prune.

     

    gui.pruneDuringFetch

      "true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".

     

    remote.<name>.prune

      When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the --prune option was given on the command line). Overrides fetch.prune settings, if any.

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

    firstly shouldn't

    data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
    

    be

    data: $(this).serialize() + '&NonFormValue=' + NonFormValue,
    

    and secondly you can use

    url: this.action + '?NonFormValue=' + NonFormValue,
    

    or if the action already contains any parameters

    url: this.action + '&NonFormValue=' + NonFormValue,
    

    You seem to not be depending on "@angular/core". This is an error

    I was getting the same error when I tried to run "ng serve" after that I saw some suggetions one of the techie told me to update my npm.I did that as well then I got this screen after entering "ng server"

    ""Versions of @angular/compiler-cli and typescript could not be determined. The most common reason for this is a broken npm install. Please make sure your package.json contains both @angular/compiler-cli and typescript in devDependencies, then delete node_module and package-lock.json(if you have one) and Run npm install again.""

    After performing all the actions now its working correctly...and getting message "Compiled Successfully."

    Java maximum memory on Windows XP

    First, using a page-file when you have 4 GB of RAM is useless. Windows can't access more than 4GB (actually, less because of memory holes) so the page file is not used.

    Second, the address space is split in 2, half for kernel, half for user mode. If you need more RAM for your applications use the /3GB option in boot.ini (make sure java.exe is marked as "large address aware" (google for more info).

    Third, I think you can't allocate the full 2 GB of address space because java wastes some memory internally (for threads, JIT compiler, VM initialization, etc). Use the /3GB switch for more.

    How to get process ID of background process?

    You can use the jobs -l command to get to a particular jobL

    ^Z
    [1]+  Stopped                 guard
    
    my_mac:workspace r$ jobs -l
    [1]+ 46841 Suspended: 18           guard
    

    In this case, 46841 is the PID.

    From help jobs:

    -l Report the process group ID and working directory of the jobs.

    jobs -p is another option which shows just the PIDs.

    Fastest way to tell if two files have the same contents in Unix/Linux?

    You can compare by checksum algorithm like sha256

    sha256sum oldFile > oldFile.sha256
    
    echo "$(cat oldFile.sha256) newFile" | sha256sum --check
    
    newFile: OK
    

    if the files are distinct the result will be

    newFile: FAILED
    sha256sum: WARNING: 1 computed checksum did NOT match
    

    Select from table by knowing only date without time (ORACLE)

    You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000

    How to show Page Loading div until the page has finished loading?

    This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading, then it will wait an optional extra few seconds.

    • Works with jQuery 3 (it has a new window load event)
    • No image needed but it's easy to add one
    • Change the delay for more branding or instructions
    • Only dependency is jQuery.

    CSS loader code from https://projects.lukehaas.me/css-loaders

    _x000D_
    _x000D_
        _x000D_
    $('body').append('<div style="" id="loadingDiv"><div class="loader">Loading...</div></div>');_x000D_
    $(window).on('load', function(){_x000D_
      setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds._x000D_
    });_x000D_
    function removeLoader(){_x000D_
        $( "#loadingDiv" ).fadeOut(500, function() {_x000D_
          // fadeOut complete. Remove the loading div_x000D_
          $( "#loadingDiv" ).remove(); //makes page more lightweight _x000D_
      });  _x000D_
    }
    _x000D_
            .loader,_x000D_
            .loader:after {_x000D_
                border-radius: 50%;_x000D_
                width: 10em;_x000D_
                height: 10em;_x000D_
            }_x000D_
            .loader {            _x000D_
                margin: 60px auto;_x000D_
                font-size: 10px;_x000D_
                position: relative;_x000D_
                text-indent: -9999em;_x000D_
                border-top: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
                border-right: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
                border-bottom: 1.1em solid rgba(255, 255, 255, 0.2);_x000D_
                border-left: 1.1em solid #ffffff;_x000D_
                -webkit-transform: translateZ(0);_x000D_
                -ms-transform: translateZ(0);_x000D_
                transform: translateZ(0);_x000D_
                -webkit-animation: load8 1.1s infinite linear;_x000D_
                animation: load8 1.1s infinite linear;_x000D_
            }_x000D_
            @-webkit-keyframes load8 {_x000D_
                0% {_x000D_
                    -webkit-transform: rotate(0deg);_x000D_
                    transform: rotate(0deg);_x000D_
                }_x000D_
                100% {_x000D_
                    -webkit-transform: rotate(360deg);_x000D_
                    transform: rotate(360deg);_x000D_
                }_x000D_
            }_x000D_
            @keyframes load8 {_x000D_
                0% {_x000D_
                    -webkit-transform: rotate(0deg);_x000D_
                    transform: rotate(0deg);_x000D_
                }_x000D_
                100% {_x000D_
                    -webkit-transform: rotate(360deg);_x000D_
                    transform: rotate(360deg);_x000D_
                }_x000D_
            }_x000D_
            #loadingDiv {_x000D_
                position:absolute;;_x000D_
                top:0;_x000D_
                left:0;_x000D_
                width:100%;_x000D_
                height:100%;_x000D_
                background-color:#000;_x000D_
            }
    _x000D_
    This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading._x000D_
    _x000D_
      <ul>_x000D_
        <li>Works with jQuery 3, which has a new window load event</li>_x000D_
        <li>No image needed but it's easy to add one</li>_x000D_
        <li>Change the delay for branding or instructions</li>_x000D_
        <li>Only dependency is jQuery.</li>_x000D_
      </ul>_x000D_
    _x000D_
    Place the script below at the bottom of the body._x000D_
    _x000D_
    CSS loader code from https://projects.lukehaas.me/css-loaders_x000D_
    _x000D_
    <!-- Place the script below at the bottom of the body -->_x000D_
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    Writing unit tests in Python: How do I start?

    The docs for unittest would be a good place to start.

    Also, it is a bit late now, but in the future please consider writing unit tests before or during the project itself. That way you can use them to test as you go along, and (in theory) you can use them as regression tests, to verify that your code changes have not broken any existing code. This would give you the full benefit of writing test cases :)

    How do you manually execute SQL commands in Ruby On Rails using NuoDB

    Reposting the answer from our forum to help others with a similar issue:

    @connection = ActiveRecord::Base.connection
    result = @connection.exec_query('select tablename from system.tables')
    result.each do |row|
    puts row
    end
    

    Remove sensitive files and their commits from Git history

    Use filter-branch:

    git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch *file_path_relative_to_git_repo*' --prune-empty --tag-name-filter cat -- --all
    
    git push origin *branch_name* -f
    

    SQL Server 2008 Row Insert and Update timestamps

    try

    CREATE TABLE [dbo].[Names]
    (
        [Name] [nvarchar](64) NOT NULL,
        [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
        [UpdateTS] [smalldatetime] NOT NULL
    
    )
    

    PS I think a smalldatetime is good enough. You may decide differently.

    Can you not do this at the "moment of impact" ?

    In Sql Server, this is common:

    Update dbo.MyTable 
    Set 
    
    ColA = @SomeValue , 
    UpdateDS = CURRENT_TIMESTAMP
    Where...........
    

    Sql Server has a "timestamp" datatype.

    But it may not be what you think.

    Here is a reference:

    http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

    Here is a little RowVersion (synonym for timestamp) example:

    CREATE TABLE [dbo].[Names]
    (
        [Name] [nvarchar](64) NOT NULL,
        RowVers rowversion ,
        [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
        [UpdateTS] [datetime] NOT NULL
    
    )
    
    
    INSERT INTO dbo.Names (Name,UpdateTS)
    select 'John' , CURRENT_TIMESTAMP
    UNION ALL select 'Mary' , CURRENT_TIMESTAMP
    UNION ALL select 'Paul' , CURRENT_TIMESTAMP
    
    select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
    
    Update dbo.Names Set Name = Name
    
    select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
    

    Maybe a complete working example:

    DROP TABLE [dbo].[Names]
    GO
    
    
    CREATE TABLE [dbo].[Names]
    (
        [Name] [nvarchar](64) NOT NULL,
        RowVers rowversion ,
        [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
        [UpdateTS] [datetime] NOT NULL
    
    )
    
    GO
    
    CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
    AFTER INSERT, UPDATE
    AS
    
    BEGIN
    
    Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
    triggerInsertedTable.Name = myAlias.Name
    
    END
    
    
    GO
    
    
    
    
    
    
    INSERT INTO dbo.Names (Name,UpdateTS)
    select 'John' , CURRENT_TIMESTAMP
    UNION ALL select 'Mary' , CURRENT_TIMESTAMP
    UNION ALL select 'Paul' , CURRENT_TIMESTAMP
    
    select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
    
    Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
    
    select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
    

    Matching on the "Name" value is probably not wise.

    Try this more mainstream example with a SurrogateKey

    DROP TABLE [dbo].[Names]
    GO
    
    
    CREATE TABLE [dbo].[Names]
    (
        SurrogateKey int not null Primary Key Identity (1001,1),
        [Name] [nvarchar](64) NOT NULL,
        RowVers rowversion ,
        [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
        [UpdateTS] [datetime] NOT NULL
    
    )
    
    GO
    
    CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
    AFTER UPDATE
    AS
    
    BEGIN
    
       UPDATE dbo.Names
        SET UpdateTS = CURRENT_TIMESTAMP
        From  dbo.Names myAlias
        WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)
    
    END
    
    
    GO
    
    
    
    
    
    
    INSERT INTO dbo.Names (Name,UpdateTS)
    select 'John' , CURRENT_TIMESTAMP
    UNION ALL select 'Mary' , CURRENT_TIMESTAMP
    UNION ALL select 'Paul' , CURRENT_TIMESTAMP
    
    select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
    
    Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
    
    select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
    

    How do I mount a host directory as a volume in docker compose

    we have to create your own docker volume mapped with the host directory before we mention in the docker-compose.yml as external

    1.Create volume named share

    docker volume create --driver local \
    --opt type=none \
    --opt device=/home/mukundhan/share \
    --opt o=bind share
    

    2.Use it in your docker-compose

    version: "3"
    
    volumes:
      share:
        external: true
    
    services:
      workstation:
        container_name: "workstation"
        image: "ubuntu"
        stdin_open: true
        tty: true
        volumes:
          - share:/share:consistent
          - ./source:/source:consistent
        working_dir: /source
        ipc: host
        privileged: true
        shm_size: '2gb'
      db:
        container_name: "db"
        image: "ubuntu"
        stdin_open: true
        tty: true
        volumes:
          - share:/share:consistent
        working_dir: /source
        ipc: host
    

    This way we can share the same directory with many services running in different containers

    Compiling simple Hello World program on OS X via command line

    Use the following for multiple .cpp files

    g++ *.cpp
    ./a.out
    

    How can I throw a general exception in Java?

    The simplest way to do it would be something like:

    throw new java.lang.Exception();
    

    However, the following lines would be unreachable in your code. So, we have two ways:


    1. Throw a generic exception at the bottom of the method.
    2. Throw a custom exception in case you don't want to do 1.

    How to make PopUp window in java

    The same answer : JOptionpane with an example :)

    package experiments;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    
    public class CreateDialogFromOptionPane {
    
        public static void main(final String[] args) {
            final JFrame parent = new JFrame();
            JButton button = new JButton();
    
            button.setText("Click me to show dialog!");
            parent.add(button);
            parent.pack();
            parent.setVisible(true);
    
            button.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    String name = JOptionPane.showInputDialog(parent,
                            "What is your name?", null);
                }
            });
        }
    }
    

    enter image description here

    What is correct media query for IPad Pro?

    This worked for me

    /* Portrait */
    @media only screen 
      and (min-device-width: 834px) 
      and (max-device-width: 834px) 
      and (orientation: portrait) 
      and (-webkit-min-device-pixel-ratio: 2) {
    
    }
    
    /* Landscape */
    @media only screen 
      and (min-width: 1112px) 
      and (max-width: 1112px) 
      and (orientation: landscape) 
      and (-webkit-min-device-pixel-ratio: 2)
     {
    
    }
    

    How to hide the border for specified rows of a table?

    Add programatically noborder class to specific row to hide it

    <style>
         .noborder
          {
            border:none;
          }
        </style>
    
    <table>
    
        <tr>
           <th>heading1</th>
           <th>heading2</th>
        </tr>
    
    
        <tr>
           <td>content1</td>
           <td>content2</td>
        </tr>
        /*no border for this row */
        <tr class="noborder">
           <td>content1</td>
           <td>content2</td>
        </tr>
    
    </table>
    

    jQuery: Change button text on click

    its work short code

    $('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
    } else { $(this).text('See Less'); } });

    How do I add a newline using printf?

    To write a newline use \n not /n the latter is just a slash and a n

    How to fix Python indentation

    Try IDLE, and use Alt + X to find indentation.

    Why does overflow:hidden not work in a <td>?

    Well here is a solution for you but I don't really understand why it works:

    <html><body>
      <div style="width: 200px; border: 1px solid red;">Test</div>
      <div style="width: 200px; border: 1px solid blue; overflow: hidden; height: 1.5em;">My hovercraft is full of eels.  These pretzels are making me thirsty.</div>
      <div style="width: 200px; border: 1px solid yellow; overflow: hidden; height: 1.5em;">
      This_is_a_terrible_example_of_thinking_outside_the_box.
      </div>
      <table style="border: 2px solid black; border-collapse: collapse; width: 200px;"><tr>
       <td style="width:200px; border: 1px solid green; overflow: hidden; height: 1.5em;"><div style="width: 200px; border: 1px solid yellow; overflow: hidden;">
        This_is_a_terrible_example_of_thinking_outside_the_box.
       </div></td>
      </tr></table>
    </body></html>
    

    Namely, wrapping the cell contents in a div.

    Sorting an Array of int using BubbleSort

    Bubble sort nested loops should be written like this:

    int n = intArray.length;
    int temp = 0;
    
    for(int i=0; i < n; i++){
       for(int j=1; j < (n-i); j++){                        
           if(intArray[j-1] > intArray[j]){
                //swap the elements!
                temp = intArray[j-1];
                intArray[j-1] = intArray[j];
                intArray[j] = temp;
           }                    
       }
    }
    

    How do I read a text file of about 2 GB?

    Try Vim, emacs (has a low maximum buffer size limit if compiled in 32-bit mode), hex tools

    React Native absolute positioning horizontal centre

    You can try the code

    <View
        style={{
          alignItems: 'center',
          justifyContent: 'center'
        }}
      >
        <View
          style={{
            position: 'absolute',
            margin: 'auto',
            width: 50,
            height: 50
          }}
        />
      </View>
    

    Difference between Amazon EC2 and AWS Elastic Beanstalk

    First off, EC2 and Elastic Compute Cloud are the same thing.

    Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

    EC2

    EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

    Elastic Beanstalk

    Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

    Running Wordpress

    For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

    What to pick?

    In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

    Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

    How to perform an SQLite query within an Android application?

    I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.

    SQLiteDatabase db = helper.getReadableDatabase();
    
    String table = "table2";
    String[] columns = {"column1", "column3"};
    String selection = "column3 =?";
    String[] selectionArgs = {"apple"};
    String groupBy = null;
    String having = null;
    String orderBy = "column3 DESC";
    String limit = "10";
    
    Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
    

    Parameters

    • table: the name of the table you want to query
    • columns: the column names that you want returned. Don't return data that you don't need.
    • selection: the row data that you want returned from the columns (This is the WHERE clause.)
    • selectionArgs: This is substituted for the ? in the selection String above.
    • groupBy and having: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.
    • orderBy: sort the data
    • limit: limit the number of results to return

    remote rejected master -> master (pre-receive hook declined)

    just in case you have this problem while trying to push a django app to heroku and then you get this error:

    ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to https://git.heroku.com/app_name.git

    simply look for this :

    Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update the application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ Heroku config:set DISABLE_COLLECTSTATIC=1

    Copy this : $ Heroku config:set DISABLE_COLLECTSTATIC=1

    and paste it in the terminal. Press Enter and after that run: $ git push Heroku master

    This should solve your problem if Django app is what you are trying to push.

    How can I get Git to follow symlinks?

    Hmmm, mount --bind doesn't seem to work on Darwin.

    Does anyone have a trick that does?

    [edited]

    OK, I found the answer on Mac OS X is to make a hardlink. Except that that API is not exposed via ln, so you have to use your own tiny program to do this. Here is a link to that program:

    Creating directory hard links in Mac OS X

    Enjoy!

    Where is android_sdk_root? and how do I set it.?

    For macOS with zshrc:

    ANDROID_HOME is depreciated, use ANDROID_SDK_ROOT instead

    1. Ensure that Android Build Tools is installed. Check if it exists in your File Directory
    2. Get the path to your SDK. Usually it is /Users/<USER>/Library/Android/sdk
    3. Add ANDROID_SDK_ROOT as a path to your Environment variables: echo 'export ANDROID_SDK_ROOT=/Users/<USER>/Library/Android/sdk' >> ~/.zshenv
    4. Apply the changes with source ~/.zshrc
    5. Check if it was saved by ...
      • ... checking the specific environment variable echo $ANDROID_SDK_ROOT
      • ... checking the complete list of environment variables on your system env

    You can apply this process to every environment variable beeing installed on your macOS system. It took me a while to comprehend it for myself

    Multiple select statements in Single query

    SELECT  (
        SELECT COUNT(*)
        FROM   user_table
    ) AS tot_user,
    (
        SELECT COUNT(*)
        FROM   cat_table
    ) AS tot_cat,
    (
        SELECT COUNT(*)
        FROM   course_table
    ) AS tot_course
    

    Swift Open Link in Safari

    In Swift 2.0:

    UIApplication.sharedApplication().openURL(NSURL(string: "http://stackoverflow.com")!)
    

    XML Document to String

    Assuming doc is your instance of org.w3c.dom.Document:

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
    

    Get the ID of a drawable in ImageView

    I think if I understand correctly this is what you are doing.

    ImageView view = (ImageView) findViewById(R.id.someImage);
    view.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageView imageView = (ImageView) view;
            assert(R.id.someImage == imageView.getId());
    
            switch(getDrawableId(imageView)) {
                case R.drawable.foo:
                    imageView.setDrawableResource(R.drawable.bar);
                    break;
                case R.drawable.bar:
                default:
                    imageView.setDrawableResource(R.drawable.foo);
                break;
            }
        });
    

    Right? So that function getDrawableId() doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags

    ImageView view = (ImageView) findViewById(R.id.someImage);
    view.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageView imageView = (ImageView) view;
            assert(R.id.someImage == imageView.getId());
    
            // See here
            Integer integer = (Integer) imageView.getTag();
            integer = integer == null ? 0 : integer;
    
            switch(integer) {
            case R.drawable.foo:
                imageView.setDrawableResource(R.drawable.bar);
                imageView.setTag(R.drawable.bar);
                break;
            case R.drawable.bar:
            default:
                imageView.setDrawableResource(R.drawable.foo);
                imageView.setTag(R.drawable.foo);
                break;
            }
        });
    

    How do I declare an array of undefined or no initial size?

    One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)

    Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).

    I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).

    FCM getting MismatchSenderId

    Actually there are many reasons for this issue. Mine was because of Invalid token passed. I was passing same token generated from one app and using same token in another app. Once token updated , it work for me.

    How to check permissions of a specific directory?

    In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.

    Also, using ls -la myFile will list & show all the facts about that file.

    "inappropriate ioctl for device"

    I tried the following code that seemed to work:

    if(open(my $FILE, "<File.txt")) {
        while(<$FILE>){
        print "$_";}
    } else {
        print "File could not be opened or did not exists\n";
    }
    

    How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

    create table employee
    (
       empid int,
       empname varchar(40),
       designation varchar(30),
       hiredate datetime, 
       Bsalary int,
       depno constraint emp_m foreign key references department(depno)
    )
    

    We should have an primary key to create foreign key or relationship between two or more table .

    How to make a 3D scatter plot in Python?

    You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.

    from matplotlib import pyplot
    from mpl_toolkits.mplot3d import Axes3D
    import random
    
    
    fig = pyplot.figure()
    ax = Axes3D(fig)
    
    sequence_containing_x_vals = list(range(0, 100))
    sequence_containing_y_vals = list(range(0, 100))
    sequence_containing_z_vals = list(range(0, 100))
    
    random.shuffle(sequence_containing_x_vals)
    random.shuffle(sequence_containing_y_vals)
    random.shuffle(sequence_containing_z_vals)
    
    ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
    pyplot.show()
    

    The code above generates a figure like:

    matplotlib 3D image

    ORDER BY date and time BEFORE GROUP BY name in mysql

    In Oracle, This work for me

    SELECT name, min(date), min(time)
        FROM table_name
    GROUP BY name
    

    iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

    Was facing a similar issue yesterday with our CI server. The app extension could not be signed with the error

    Code Sign error: No matching provisioning profiles found: No provisioning profiles with a valid signing identity (i.e. certificate and private key pair) matching the bundle identifier XXX were found.
    

    Note: I had created my provisioning profiles myself from Developer portal (not managed by Xcode).

    The error was that I had created the provisioning profiles using the Distribution certificate, but the build settings were set to use the developer certificate. Changing it to use Distribution certificate solved the issue.

    enter image description here

    Summary: Match the certificate used for creating the provisioning profile in build settings too.

    How to vertically align elements in a div?

    Wow, this problem is popular. It's based on a misunderstanding in the vertical-align property. This excellent article explains it:

    Understanding vertical-align, or "How (Not) To Vertically Center Content" by Gavin Kistner.

    “How to center in CSS” is a great web tool which helps to find the necessary CSS centering attributes for different situations.


    In a nutshell (and to prevent link rot):

    • Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example
    • For block elements, vertical alignment is harder and strongly depends on the specific situation:
      • If the inner element can have a fixed height, you can make its position absolute and specify its height, margin-top and top position. jsfiddle example
      • If the centered element consists of a single line and its parent height is fixed you can simply set the container’s line-height to fill its height. This method is quite versatile in my experience. jsfiddle example
      • … there are more such special cases.

    Why would you use String.Equals over ==?

    It's entirely likely that a large portion of the developer base comes from a Java background where using == to compare strings is wrong and doesn't work.

    In C# there's no (practical) difference (for strings) as long as they are typed as string.

    If they are typed as object or T then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.

    div with dynamic min-height based on browser window height

    If #top and #bottom have fixed heights, you can use:

    #top {
        position: absolute;
        top: 0;
        height: 200px;
    }
    #bottom {
        position: absolute;
        bottom: 0;
        height: 100px;
    }
    #central {
        margin-top: 200px;
        margin-bot: 100px;
    }
    

    update

    If you want #central to stretch down, you could:

    • Fake it with a background on parent;
    • Use CSS3's (not widely supported, most likely) calc();
    • Or maybe use javascript to dynamically add min-height.

    With calc():

    #central {
        min-height: calc(100% - 300px);
    }
    

    With jQuery it could be something like:

    $(document).ready(function() {
      var desiredHeight = $("body").height() - $("top").height() - $("bot").height();
      $("#central").css("min-height", desiredHeight );
    });
    

    Where is the default log location for SharePoint/MOSS?

    For Sharepoint 2007

    C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS