Programs & Examples On #Uiimagejpegrepresentation

For questions related to the UIImageJPEGRepresentation method for the UIImage class on the iOS platform, a method commonly used to convert images to JPEG.

How to zoom in/out an UIImage object when user pinches screen?

Another easy way to do this is to place your UIImageView within a UIScrollView. As I describe here, you need to set the scroll view's contentSize to be the same as your UIImageView's size. Set your controller instance to be the delegate of the scroll view and implement the viewForZoomingInScrollView: and scrollViewDidEndZooming:withView:atScale: methods to allow for pinch-zooming and image panning. This is effectively what Ben's solution does, only in a slightly more lightweight manner, as you don't have the overhead of a full web view.

One issue you may run into is that the scaling within the scroll view comes in the form of transforms applied to the image. This may lead to blurriness at high zoom factors. For something that can be redrawn, you can follow my suggestions here to provide a crisper display after the pinch gesture is finished. hniels' solution could be used at that point to rescale your image.

HttpURLConnection timeout settings

HttpURLConnection has a setConnectTimeout method.

Just set the timeout to 5000 milliseconds, and then catch java.net.SocketTimeoutException

Your code should look something like this:


try {
   HttpURLConnection.setFollowRedirects(false);
   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds

   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}


What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.

How much data can a List can hold at the maximum?

As much as your available memory will allow. There's no size limit except for the heap.

How to count the number of columns in a table using SQL?

Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:

SELECT t.owner, 
       t.table_name, 
       t.num_rows, 
       Count(*) 
FROM   all_tables t 
       LEFT JOIN all_tab_columns c 
              ON t.table_name = c.table_name 
WHERE  num_rows IS NOT NULL 
GROUP  BY t.owner, 
          t.table_name, 
          t.num_rows 
ORDER  BY t.num_rows DESC; 

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

Dynamic creation of table with DOM

In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.

<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">


<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div class="dataGridForItem">
        </div>
    </div>
</div>

//Call Function From Button click Event

var counts = 1;
function add(){ 
    var Weightage = $('#Weightage').val();
    var ItemName = $('#ItemName option:selected').text();  
    var ItemNamenum = $('#ItemName').val();
    generateTable(Weightage,ItemName,ItemNamenum);
     $('#Weightage').val('');
     $('#ItemName').val(-1);
     return true;
 } 


function generateTable(Weightage,ItemName,ItemNamenum){
    var tableHtml = '';
    if($("#rDataTable").html() == undefined){
        tableHtml = generateHeader();
    }else{
        tableHtml = $("#rDataTable");
    } 
    var temp = $("<div/>");
    var row = addToRow(Weightage,ItemName,ItemNamenum);
    $(temp).append($(row));
    $("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}


//Generate Header


function generateHeader(){
        var html = "<table id='rDataTable' class='table table-striped'>";
        html+="<tr class=''>";
        html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
        html+="</tr></table>";
        return html; 
}

//Add New Row


function addToRow(Weightage,ItemName,ItemNamenum){
    var html="<tr class='trObj'>";
    html+="<td>"+counts+"</td>";
    html+="<td>"+ItemName+"</td>";
    html+="<td>"+Weightage+"</td>";
    html+="</tr>";
    counts++;
    return html;
}

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

How to import cv2 in python3?

Your screenshot shows you doing a pip install from the python terminal which is wrong. Do that outside the python terminal. Also the package I believe you want is:

pip install opencv-python

Since you're running on Windows, I might look at the official install manual: https://breakthrough.github.io/Installing-OpenCV

opencv2 is ONLY compatible with Python3 if you do so by compiling the source code. See the section under opencv supported python versions: https://pypi.org/project/opencv-python

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

Run cURL commands from Windows console

I am may be bit late for this, but I am able to resolve my issue of curl at cmd for windows 10.

I got help from below video tutorial https://www.youtube.com/watch?v=qlTVMuONazs

Here is some explanation

Step 1: go to https://curl.haxx.se/download.html

Step 2: Search "Win64 - Generic" and download "Win64 x86_64 7zip" by "Darren Owen"

Step 3: unzip the download file and install the certificate "ca-bundle.crt" do not touch curl.exe

Step 4: in windows go to "Control Panel" -> "System" -> "Advance system settings " Step 5: click on Envirnoment variables

Step 6: In System variable click on "Path" and paste the path of the file folder in my case it is "C:\curl\curl_7_53_1_openssl_nghttp2_x64"

And you are done.

Don't Forgot to restart you system for one time

Mime type for WOFF fonts?

It will be application/font-woff.

see http://www.w3.org/TR/WOFF/#appendix-b (W3C Candidate Recommendation 04 August 2011)

and http://www.w3.org/2002/06/registering-mediatype.html

From Mozilla css font-face notes

In Gecko, web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless HTTP access controls are used to relax this restriction. Note: Because there are no defined MIME types for TrueType, OpenType, and WOFF fonts, the MIME type of the file specified is not considered.

source: https://developer.mozilla.org/en/CSS/@font-face#Notes

java- reset list iterator to first element of the list

This is an alternative solution, but one could argue it doesn't add enough value to make it worth it:

import com.google.common.collect.Iterables;
...
Iterator<String> iter = Iterables.cycle(list).iterator();
if(iter.hasNext()) {
    str = iter.next();
}

Calling hasNext() will reset the iterator cursor to the beginning if it's a the end.

MySQL LEFT JOIN 3 tables

Select 
    p.Name,
    p.SS,
    f.fear
From
    Persons p
left join
        Person_Fear pf
    inner join
        Fears f
    on
        pf.fearID = f.fearID
 on
    p.personID = pf.PersonID

Find document with array that contains a specific value

If you'd want to use something like a "contains" operator through javascript, you can always use a Regular expression for that...

eg. Say you want to retrieve a customer having "Bartolomew" as name

async function getBartolomew() {
    const custStartWith_Bart = await Customers.find({name: /^Bart/ }); // Starts with Bart
    const custEndWith_lomew = await Customers.find({name: /lomew$/ }); // Ends with lomew
    const custContains_rtol = await Customers.find({name: /.*rtol.*/ }); // Contains rtol

    console.log(custStartWith_Bart);
    console.log(custEndWith_lomew);
    console.log(custContains_rtol);
}

Tar a directory, but don't store full absolute paths in the archive

tar -cjf site1.tar.bz2 -C /var/www/site1 .

In the above example, tar will change to directory /var/www/site1 before doing its thing because the option -C /var/www/site1 was given.

From man tar:

OTHER OPTIONS

  -C, --directory DIR
       change to directory DIR

How to install Ruby 2.1.4 on Ubuntu 14.04

Best is to install it using rvm(ruby version manager).
Run following commands in a terminal:

sudo apt-get update
sudo apt-get install build-essential make curl
\curl -L https://get.rvm.io | bash -s stable
source ~/.bash_profile
rvm install ruby-2.1.4

Then check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

Also you can directly add ruby bin path to PATH variable. Ruby is installed in

$HOME/.rvm/rubies export PATH=$PATH:$HOME/.rvm/rubies/ruby-2.1.4/bin

What is the largest possible heap size with a 64-bit JVM?

For a 64-bit JVM running in a 64-bit OS on a 64-bit machine, is there any limit besides the theoretical limit of 2^64 bytes or 16 exabytes?

You also have to take hardware limits into account. While pointers may be 64bit current CPUs can only address a less than 2^64 bytes worth of virtual memory.

With uncompressed pointers the hotspot JVM needs a continuous chunk of virtual address space for its heap. So the second hurdle after hardware is the operating system providing such a large chunk, not all OSes support this.

And the third one is practicality. Even if you can have that much virtual memory it does not mean the CPUs support that much physical memory, and without physical memory you will end up swapping, which will adversely affect the performance of the JVM because the GCs generally have to touch a large fraction of the heap.

As other answers mention compressed oops: By bumping the object alignment higher than 8 bytes the limits with compressed oops can be increased beyond 32GB

How do you set, clear, and toggle a single bit?

Setting the nth bit to x (bit value) without using -1

Sometimes when you are not sure what -1 or the like will result in, you may wish to set the nth bit without using -1:

number = (((number | (1 << n)) ^ (1 << n))) | (x << n);

Explanation: ((number | (1 << n) sets the nth bit to 1 (where | denotes bitwise OR), then with (...) ^ (1 << n) we set the nth bit to 0, and finally with (...) | x << n) we set the nth bit that was 0, to (bit value) x.

This also works in golang.

How to ignore parent css style

This got bumped to the top because of an edit ... The answers have gotten a bit stale, and not as useful today as another solution has been added to the standard.

There is now an "all" shorthand property.

#elementId select.funTimes {
   all: initial;
}

This sets all css properties to their initial value ... note some of the initial values are inherit; Resulting in some formatting still taking place on the element.

Because of that pause required when reading the code or reviewing it in the future, don't use it unless you most as the review process is a point where errors/bugs can be made! when editing the page. But clearly if there are a large number of properties that need to be reset, then "all" is the way to go.

Standard is online here: https://drafts.csswg.org/css-cascade/#all-shorthand

Set type for function parameters?

Explanation

I'm not sure if my answer is direct answer to original question, but as I suppose a lot of people come here to just find a way to tell their IDEs to understand types, I'll share what I found.

If you want to tell VSCode to understand your types, do as follows. Please pay attention that js runtime and NodeJS does not care about these types at all.

Solution

1- Create a file with .d.ts ending: e.g: index.d.ts. You can create this file in another folder. for example: types/index.d.ts
2- Suppose we want to have a function called view. Add these lines to index.d.ts:

/**
 * Use express res.render function to render view file inside layout file.
 *
 * @param {string} view The path of the view file, relative to view root dir.
 * @param {object} options The options to send to view file for ejs to use when rendering.
 * @returns {Express.Response.render} .
 */
view(view: string, options?: object): Express.Response.render;

3- Create a jsconfig.json file in you project's root. (It seems that just creating this file is enough for VSCode to search for your types).

A bit more

Now suppose we want to add this type to another library types. (As my own situation). We can use some ts keywords. And as long as VSCode understands ts we have no problem with it.
For example if you want to add this view function to response from expressjs, change index.d.ts file as follows:

export declare global {
  namespace Express {
    interface Response {
      /**
       * Use express res.render function to render view file inside layout file.
       *
       * @param {string} view The path of the view file, relative to view root dir.
       * @param {object} options The options to send to view file for ejs to use when rendering.
       * @returns {Express.Response.render} .
       */
      view(view: string, options?: object): Express.Response.render;
    }
  }
}

Result

enter image description here

enter image description here

Adding Lombok plugin to IntelliJ project

You need to Enable Annotation Processing on IntelliJ IDEA

> Settings > Build, Execution, Deployment > Compiler > Annotation Processors

enter image description here

NTFS performance and large volumes of files and directories

For local access, large numbers of directories/files doesn't seem to be an issue. However, if you're accessing it across a network, there's a noticeable performance hit after a few hundred (especially when accessed from Vista machines (XP to Windows Server w/NTFS seemed to run much faster in that regard)).

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

python pip on Windows - command 'cl.exe' failed

  1. Install Microsoft visual c++ 14.0 build tool.(Windows 7)
  2. create a virtual environment using conda.
  3. Activate the environment and use conda to install the necessary package.

For example: conda install -c conda-forge spacy

"Cannot instantiate the type..."

java.util.Queue is an interface so you cannot instantiate it directly. You can instantiate a concrete subclass, such as LinkedList:

Queue<T> q = new LinkedList<T>;

How to print a list with integers without the brackets, commas and no quotes?

Using .format from Python 2.6 and higher:

>>> print '{}{}{}{}'.format(*[7,7,7,7])
7777
>>> data = [7, 7, 7, 7] * 3
>>> print ('{}'*len(data)).format(*data)
777777777777777777777777

For Python 3:

>>> print(('{}'*len(data)).format(*data))
777777777777777777777777

MySQL query String contains

You probably are looking for find_in_set function:

Where find_in_set($needle,'column') > 0

This function acts like in_array function in PHP

pdftk compression option

I had the same problem and found two different solutions (see this thread for more details). Both reduced the size of my uncompressed PDF dramatically.

  • Pixelated (lossy):

    convert input.pdf -compress Zip output.pdf
    
  • Unpixelated (lossless, but may display slightly differently):

    gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH  -dQUIET -sOutputFile=output.pdf input.pdf
    

Edit: I just discovered another option (for lossless compression), which avoids the nasty gs command. qpdf is a neat tool that converts PDFs (compression/decompression, encryption/decryption), and is much faster than the gs command:

qpdf --linearize input.pdf output.pdf

SQL DROP TABLE foreign key constraint

Slightly more generic version of what @mark_s posted, this helped me

SELECT 
'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(k.parent_object_id) +
'.[' + OBJECT_NAME(k.parent_object_id) + 
'] DROP CONSTRAINT ' + k.name
FROM sys.foreign_keys k
WHERE referenced_object_id = object_id('your table')

just plug your table name, and execute the result of it.

enable/disable zoom in Android WebView

Ive modifiet Lukas Knuth's solution a little:

1) There's no need to subclass the webview,

2) the code will crash during bytecode verification on some Android 1.6 devices if you don't put nonexistant methods in seperate classes

3) Zoom controls will still appear if the user scrolls up/down a page. I simply set the zoom controller container to visibility GONE

  wv.getSettings().setSupportZoom(true);
  wv.getSettings().setBuiltInZoomControls(true);
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
    // Use the API 11+ calls to disable the controls
    // Use a seperate class to obtain 1.6 compatibility
    new Runnable() {
      public void run() {
        wv.getSettings().setDisplayZoomControls(false);
      }
    }.run();
  } else {
    final ZoomButtonsController zoom_controll =
        (ZoomButtonsController) wv.getClass().getMethod("getZoomButtonsController").invoke(wv, null);
    zoom_controll.getContainer().setVisibility(View.GONE);
  }

JPA : How to convert a native query result set to POJO class collection

Use DTO Design Pattern. It was used in EJB 2.0. Entity was container managed. DTO Design Pattern is used to solve this problem. But, it might be use now, when the application is developed Server Side and Client Side separately.DTO is used when Server side doesn't want to pass/return Entity with annotation to Client Side.

DTO Example :

PersonEntity.java

@Entity
public class PersonEntity {
    @Id
    private String id;
    private String address;

    public PersonEntity(){

    }
    public PersonEntity(String id, String address) {
        this.id = id;
        this.address = address;
    }
    //getter and setter

}

PersonDTO.java

public class PersonDTO {
    private String id;
    private String address;

    public PersonDTO() {
    }
    public PersonDTO(String id, String address) {
        this.id = id;
        this.address = address;
    }

    //getter and setter 
}

DTOBuilder.java

public class DTOBuilder() {
    public static PersonDTO buildPersonDTO(PersonEntity person) {
        return new PersonDTO(person.getId(). person.getAddress());
    }
}

EntityBuilder.java <-- it mide be need

public class EntityBuilder() {
    public static PersonEntity buildPersonEntity(PersonDTO person) {
        return new PersonEntity(person.getId(). person.getAddress());
    }
}

If Radio Button is selected, perform validation on Checkboxes

Full validation example with javascript:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Radio button: full validation example with javascript</title>
        <script>
            function send() {
                var genders = document.getElementsByName("gender");
                if (genders[0].checked == true) {
                    alert("Your gender is male");
                } else if (genders[1].checked == true) {
                    alert("Your gender is female");
                } else {
                    // no checked
                    var msg = '<span style="color:red;">You must select your gender!</span><br /><br />';
                    document.getElementById('msg').innerHTML = msg;
                    return false;
                }
                return true;
            }

            function reset_msg() {
                document.getElementById('msg').innerHTML = '';
            }
        </script>
    </head>
    <body>
        <form action="" method="POST">
            <label>Gender:</label>
            <br />
            <input type="radio" name="gender" value="m" onclick="reset_msg();" />Male
            <br />
            <input type="radio" name="gender" value="f" onclick="reset_msg();" />Female
            <br />
            <div id="msg"></div>
            <input type="submit" value="send>>" onclick="return send();" />
        </form>
    </body>
</html>

Regards,

Fernando

How to export DataTable to Excel

One way of doing it would be also with ACE OLEDB Provider (see also connection strings for Excel). Of course you'd have to have the provider installed and registered. You should have it, if you have Excel installed, but this is something you have to consider when deploying the app.

This is the example of calling the helper method from ExportHelper: ExportHelper.CreateXlsFromDataTable(myDataTable, @"C:\tmp\export.xls");

The helper for exporting to Excel file using ACE OLEDB:

public class ExportHelper
{
    private const string ExcelOleDbConnectionStringTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";";

    /// <summary>
    /// Creates the Excel file from items in DataTable and writes them to specified output file.
    /// </summary>
    public static void CreateXlsFromDataTable(DataTable dataTable, string fullFilePath)
    {
        string createTableWithHeaderScript = GenerateCreateTableCommand(dataTable);

        using (var conn = new OleDbConnection(String.Format(ExcelOleDbConnectionStringTemplate, fullFilePath)))
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            OleDbCommand cmd = new OleDbCommand(createTableWithHeaderScript, conn);
            cmd.ExecuteNonQuery();

            foreach (DataRow dataExportRow in dataTable.Rows)
            {
                AddNewRow(conn, dataExportRow);
            }
        }
    }

    private static void AddNewRow(OleDbConnection conn, DataRow dataRow)
    {
        string insertCmd = GenerateInsertRowCommand(dataRow);

        using (OleDbCommand cmd = new OleDbCommand(insertCmd, conn))
        {
            AddParametersWithValue(cmd, dataRow);
            cmd.ExecuteNonQuery();
        }
    }

    /// <summary>
    /// Generates the insert row command.
    /// </summary>
    private static string GenerateInsertRowCommand(DataRow dataRow)
    {
        var stringBuilder = new StringBuilder();
        var columns = dataRow.Table.Columns.Cast<DataColumn>().ToList();
        var columnNamesCommaSeparated = string.Join(",", columns.Select(x => x.Caption));
        var questionmarkCommaSeparated = string.Join(",", columns.Select(x => "?"));

        stringBuilder.AppendFormat("INSERT INTO [{0}] (", dataRow.Table.TableName);
        stringBuilder.Append(columnNamesCommaSeparated);
        stringBuilder.Append(") VALUES(");
        stringBuilder.Append(questionmarkCommaSeparated);
        stringBuilder.Append(")");
        return stringBuilder.ToString();
    }

    /// <summary>
    /// Adds the parameters with value.
    /// </summary>
    private static void AddParametersWithValue(OleDbCommand cmd, DataRow dataRow)
    {
        var paramNumber = 1;

        for (int i = 0; i <= dataRow.Table.Columns.Count - 1; i++)
        {
            if (!ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(int)) && !ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(decimal)))
            {
                cmd.Parameters.AddWithValue("@p" + paramNumber, dataRow[i].ToString().Replace("'", "''"));
            }
            else
            {
                object value = GetParameterValue(dataRow[i]);
                OleDbParameter parameter = cmd.Parameters.AddWithValue("@p" + paramNumber, value);
                if (value is decimal)
                {
                    parameter.OleDbType = OleDbType.Currency;
                }
            }

            paramNumber = paramNumber + 1;
        }
    }

    /// <summary>
    /// Gets the formatted value for the OleDbParameter.
    /// </summary>
    private static object GetParameterValue(object value)
    {
        if (value is string)
        {
            return value.ToString().Replace("'", "''");
        }
        return value;
    }

    private static string GenerateCreateTableCommand(DataTable tableDefination)
    {
        StringBuilder stringBuilder = new StringBuilder();
        bool firstcol = true;

        stringBuilder.AppendFormat("CREATE TABLE [{0}] (", tableDefination.TableName);

        foreach (DataColumn tableColumn in tableDefination.Columns)
        {
            if (!firstcol)
            {
                stringBuilder.Append(", ");
            }
            firstcol = false;

            string columnDataType = "CHAR(255)";

            switch (tableColumn.DataType.Name)
            {
                case "String":
                    columnDataType = "CHAR(255)";
                    break;
                case "Int32":
                    columnDataType = "INTEGER";
                    break;
                case "Decimal":
                    // Use currency instead of decimal because of bug described at 
                    // http://social.msdn.microsoft.com/Forums/vstudio/en-US/5d6248a5-ef00-4f46-be9d-853207656bcc/localization-trouble-with-oledbparameter-and-decimal?forum=csharpgeneral
                    columnDataType = "CURRENCY";
                    break;
            }

            stringBuilder.AppendFormat("{0} {1}", tableColumn.ColumnName, columnDataType);
        }
        stringBuilder.Append(")");

        return stringBuilder.ToString();
    }
}

TypeError: p.easing[this.easing] is not a function

use the latest one for bootstrap 4 and above, this won't affect your UI

How do you format a Date/Time in TypeScript?

For Angular you should simply use formatDate instead of the DatePipe.

import {formatDate} from '@angular/common';

constructor(@Inject(LOCALE_ID) private locale: string) { 
    this.dateString = formatDate(Date.now(),'yyyy-MM-dd',this.locale);
}

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.

How to hide a navigation bar from first ViewController in Swift?

In IOS 8 do it like

navigationController?.hidesBarsOnTap = true

but only when it's part of a UINavigationController

make it false when you want it back

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

Maybe something like this ?

Create a batch to connect to telnet and run a script to issue commands ? source

Batch File (named Script.bat ):

     :: Open a Telnet window
   start telnet.exe 192.168.1.1
   :: Run the script 
    cscript SendKeys.vbs 

Command File (named SendKeys.vbs ):

set OBJECT=WScript.CreateObject("WScript.Shell")
WScript.sleep 50 
OBJECT.SendKeys "mylogin{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys "mypassword{ENTER}"
WScript.sleep 50 
OBJECT.SendKeys " cd /var/tmp{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys " rm log_web_activity{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys " ln -s /dev/null log_web_activity{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys "exit{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys " "

How to pass a user / password in ansible command

As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.

read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"

Get Image Height and Width as integer values?

getimagesize('image.jpg') function works only if allow_url_fopen is set to 1 or On inside php.ini file on the server, if it is not enabled, one should use ini_set('allow_url_fopen',1); on top of the file where getimagesize() function is used.

ArrayList of String Arrays

I wouldn't use arrays. They're problematic for several reasons and you can't declare it in terms of a specific array size anyway. Try:

List<List<String>> addresses = new ArrayList<List<String>>();

But honestly for addresses, I'd create a class to model them.

If you were to use arrays it would be:

List<String[]> addresses = new ArrayList<String[]>();

ie you can't declare the size of the array.

Lastly, don't declare your types as concrete types in instances like this (ie for addresses). Use the interface as I've done above. This applies to member variables, return types and parameter types.

Android OnClickListener - identify a button

I prefer:

class MTest extends Activity implements OnClickListener {
    public void onCreate(Bundle savedInstanceState) {
    ...
    Button b1 = (Button) findViewById(R.id.b1);
    Button b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    ...
}

And then:

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.b1:
            ....
            break;
        case R.id.b2:
            ....
            break;
    }   
}

Switch-case is easier to maintain than if-else, and this implementation doesn't require making many class variables.

how to rotate text left 90 degree and cell size is adjusted according to text in html

Without calculating height. Strict CSS and HTML. <span/> only for Chrome, because the chrome isn't able change text direction for <th/>.

_x000D_
_x000D_
th _x000D_
{_x000D_
  vertical-align: bottom;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
th span _x000D_
{_x000D_
  -ms-writing-mode: tb-rl;_x000D_
  -webkit-writing-mode: vertical-rl;_x000D_
  writing-mode: vertical-rl;_x000D_
  transform: rotate(180deg);_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <th><span>Rotated text by 90 deg.</span></th>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

A column-vector y was passed when a 1d array was expected

use below code:

model = forest.fit(train_fold, train_y.ravel())

if you are still getting slap by error as identical as below ?

Unknown label type: %r" % y

use this code:

y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

How to know what the 'errno' means?

This is faster than looking up the code in errno.h, shorter than most solutions posted here and it does not require installation of third party tools:

perl -E 'say $!=shift' 2

yields

No such file or directory

React Native android build failed. SDK location not found

There are 2 ways to solve this issue:

  1. Simple run your react native Android project in the android studio it will automatically generate your local.properties file in react native Android project.

  2. a. Go to React-native Project -> Android
    b. Create a file local.properties
    c. Open the file
    d. Paste your Android SDK path like below

Eclipse: How to build an executable jar with external jar?

How to include the jars of your project into your runnable jar:

I'm using Eclipse Version: 3.7.2 running on Ubuntu 12.10. I'll also show you how to make the build.xml so you can do the ant jar from command line and create your jar with other imported jars extracted into it.

Basically you ask Eclipse to construct the build.xml that imports your libraries into your jar for you.

  1. Fire up Eclipse and make a new Java project, make a new package 'mypackage', add your main class: Runner Put this code in there.

    enter image description here

  2. Now include the mysql-connector-java-5.1.28-bin.jar from Oracle which enables us to write Java to connect to the MySQL database. Do this by right clicking the project -> properties -> java build path -> Add External Jar -> pick mysql-connector-java-5.1.28-bin.jar.

  3. Run the program within eclipse, it should run, and tell you that the username/password is invalid which means Eclipse is properly configured with the jar.

  4. In Eclipse go to File -> Export -> Java -> Runnable Jar File. You will see this dialog:

    enter image description here

    Make sure to set up the 'save as ant script' checkbox. That is what makes it so you can use the commandline to do an ant jar later.

  5. Then go to the terminal and look at the ant script:

    enter image description here

So you see, I ran the jar and it didn't error out because it found the included mysql-connector-java-5.1.28-bin.jar embedded inside Hello.jar.

Look inside Hello.jar: vi Hello.jar and you will see many references to com/mysql/jdbc/stuff.class

To do ant jar on the commandline to do all this automatically: Rename buildant.xml to build.xml, and change the target name from create_run_jar to jar.

Then, from within MyProject you type ant jar and boom. You've got your jar inside MyProject. And you can invoke it using java -jar Hello.jar and it all works.

How to write a basic swap function in Java

You cannot use references in Java, so a swap function is impossible, but you can use the following code snippet per each use of swap operations:

T t = p
p = q
q = t

where T is the type of p and q

However, swapping mutable objects may be possible by rewriting properties:

void swap(Point a, Point b) {
  int tx = a.x, ty = a.y;
  a.x = b.x; a.y = b.y;
  b.x = t.x; b.y = t.y;
}

No signing certificate "iOS Distribution" found

Tried the above solutions with no luck ... restarted my mac solved the issue...

How do I tokenize a string in C++?

Check this example. It might help you..

#include <iostream>
#include <sstream>

using namespace std;

int main ()
{
    string tmps;
    istringstream is ("the dellimiter is the space");
    while (is.good ()) {
        is >> tmps;
        cout << tmps << "\n";
    }
    return 0;
}

Generate a range of dates using SQL

Date range between 12/31/1996 and 12/31/2020

SELECT dt, to_char(dt, 'MM/DD/YYYY') as date_name, 
  EXTRACT(year from dt) as year, 
  EXTRACT(year from fiscal_dt) as fiscal_year,
  initcap(to_char(dt, 'MON')) as month,
  to_char(dt, 'YYYY')        || ' ' || initcap(to_char(dt, 'MON')) as year_month,
  to_char(fiscal_dt, 'YYYY') || ' ' || initcap(to_char(dt, 'MON')) as fiscal_year_month,
  EXTRACT(year from dt)*100        + EXTRACT(month from dt) as year_month_id,
  EXTRACT(year from fiscal_dt)*100 + EXTRACT(month from fiscal_dt) as fiscal_year_month_id,
  to_char(dt, 'YYYY')        || ' Q' || to_char(dt, 'Q') as quarter,
  to_char(fiscal_dt, 'YYYY') || ' Q' || to_char(fiscal_dt, 'Q') as fiscal_quarter
  --, EXTRACT(day from dt) as day_of_month, to_char(dt, 'YYYY-WW') as week_of_year, to_char(dt, 'D') as day_of_week
  FROM (
    SELECT dt, add_months(dt, 6) as fiscal_dt --starts July 1st
    FROM (
      SELECT TO_DATE('12/31/1996', 'mm/dd/yyyy') + ROWNUM as dt 
      FROM DUAL CONNECT BY ROWNUM < 366 * 30 --30 years
    )
    WHERE dt <= TO_DATE('12/31/2020', 'mm/dd/yyyy')
  )

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

SELECT TO_DATE(TO_CHAR(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD')
FROM table;

How to wait in a batch script?

What about:

@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs

How to update cursor limit for ORA-01000: maximum open cursors exceed

RUn the following query to find if you are running spfile or not:

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type" 
       FROM sys.v_$parameter WHERE name = 'spfile';

If the result is "SPFILE", then use the following command:

alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor

if the result is "PFILE", then use the following command:

alter system set open_cursors = 1000 ;

You can read about SPFILE vs PFILE here,

http://www.orafaq.com/node/5

Java SecurityException: signer information does not match

  1. After sign, access: dist\lib
  2. Find extra .jar
  3. Using Winrar, You extract for a folder (extract to "folder name") option
  4. Access: META-INF/MANIFEST.MF
  5. Delete each signature like that:

Name: net/sf/jasperreports/engine/util/xml/JaxenXPathExecuterFactory.c lass SHA-256-Digest: q3B5wW+hLX/+lP2+L0/6wRVXRHq1mISBo1dkixT6Vxc=

  1. Save the file
  2. Zip again
  3. Renaime ext to .jar back
  4. Already

WCF - How to Increase Message Size Quota

For HTTP:

<bindings>
  <basicHttpBinding>
    <binding name="basicHttp" allowCookies="true"
             maxReceivedMessageSize="20000000" 
             maxBufferSize="20000000"
             maxBufferPoolSize="20000000">
        <readerQuotas maxDepth="200" 
             maxArrayLength="200000000"
             maxBytesPerRead="4096"
             maxStringContentLength="200000000"
             maxNameTableCharCount="16384"/>
    </binding>
  </basicHttpBinding>
</bindings>

For TCP:

<bindings>
  <netTcpBinding>
    <binding name="tcpBinding"
             maxReceivedMessageSize="20000000"
             maxBufferSize="20000000"
             maxBufferPoolSize="20000000">
      <readerQuotas maxDepth="200"
           maxArrayLength="200000000"
           maxStringContentLength="200000000"
           maxBytesPerRead="4096"
           maxNameTableCharCount="16384"/>
    </binding>
  </netTcpBinding>
</bindings>

IMPORTANT:

If you try to pass complex object that has many connected objects (e.g: a tree data structure, a list that has many objects...), the communication will fail no matter how you increased the Quotas. In such cases, you must increase the containing objects count:

<behaviors>
  <serviceBehaviors>
    <behavior name="NewBehavior">
      ...
      <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

Counter in foreach loop in C#

From MSDN:

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

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

Can regular expressions be used to match nested patterns?

as zsolt mentioned, some regex engines support recursion -- of course, these are typically the ones that use a backtracking algorithm so it won't be particularly efficient. example: /(?>[^{}]*){(?>[^{}]*)(?R)*(?>[^{}]*)}/sm

How do I get IntelliJ to recognize common Python modules?

Even my Intellisense in Pycharm was not working for modules like time Problem in my system was no Interpreter was selected Go to File --> Settings... (Ctrl+Alt+S) Open Project Interpreter

Project Interpreter In my case was selected. I selected the available python interpreter. If not available you can add a new interpreter.

NSDictionary - Need to check whether dictionary contains key-value pair or not

With literal syntax you can check as follows

static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
  NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
 NSLog(@"Key pair do not exits for key: %@", kKeyToCheck); 

AddRange to a Collection

Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.

public static void AddRange<T>(this ICollection<T> destination,
                               IEnumerable<T> source)
{
    List<T> list = destination as List<T>;

    if (list != null)
    {
        list.AddRange(source);
    }
    else
    {
        foreach (T item in source)
        {
            destination.Add(item);
        }
    }
}

Add new row to dataframe, at specific row-index, not appended?

for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

allEdges <- data.frame(c(edges$V1,edges$V2))

Why is my power operator (^) not working?

In C ^ is the bitwise XOR:

0101 ^ 1100 = 1001 // in binary

There's no operator for power, you'll need to use pow function from math.h (or some other similar function):

result = pow( a, i );

Print array elements on separate lines in Bash?

I tried the answers here in a giant for...if loop, but didn't get any joy - so I did it like this, maybe messy but did the job:

 # EXP_LIST2 is iterated    
 # imagine a for loop
     EXP_LIST="List item"    
     EXP_LIST2="$EXP_LIST2 \n $EXP_LIST"
 done 
 echo -e $EXP_LIST2

although that added a space to the list, which is fine - I wanted it indented a bit. Also presume the "\n" could be printed in the original $EP_LIST.

Where does Anaconda Python install on Windows?

where conda

F:\Users\christos\Anaconda3\Library\bin\conda.bat

F:\Users\christos\Anaconda3\Scripts\conda.exe

F:\Users\christos\Anaconda3\condabin\conda.bat

F:\Users\christos\Anaconda3\Scripts\conda.exe --version

conda 4.6.11

this worked for me

R - Markdown avoiding package loading messages

This is an old question, but here's another way to do it.

You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```

You can also put those functions around your library() calls inside the "source.R" script.

Laravel Eloquent Sum of relation's column

this is not your answer but is for those come here searching solution for another problem. I wanted to get sum of a column of related table conditionally. In my database Deals has many Activities I wanted to get the sum of the "amount_total" from Activities table where activities.deal_id = deal.id and activities.status = paid so i did this.

$query->withCount([
'activity AS paid_sum' => function ($query) {
            $query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
        }
    ]);

it returns

"paid_sum_count" => "320.00"

in Deals attribute.

This it now the sum which i wanted to get not the count.

C#: How would I get the current time into a string?

You can use format strings as well.

string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros

or some shortcuts if the format works for you

string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();

Either should work.

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

What are the integrity and crossorigin attributes?

Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.

Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.

Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.

In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.

Source: https://yon.fun/what-is-link-integrity-and-crossorigin/

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

How do I remove diacritics (accents) from a string in .NET?

I've not used this method, but Michael Kaplan describes a method for doing so in his blog post (with a confusing title) that talks about stripping diacritics: Stripping is an interesting job (aka On the meaning of meaningless, aka All Mn characters are non-spacing, but some are more non-spacing than others)

static string RemoveDiacritics(string text) 
{
    var normalizedString = text.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder();

    foreach (var c in normalizedString)
    {
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}

Note that this is a followup to his earlier post: Stripping diacritics....

The approach uses String.Normalize to split the input string into constituent glyphs (basically separating the "base" characters from the diacritics) and then scans the result and retains only the base characters. It's just a little complicated, but really you're looking at a complicated problem.

Of course, if you're limiting yourself to French, you could probably get away with the simple table-based approach in How to remove accents and tilde in a C++ std::string, as recommended by @David Dibben.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Just in case you want to try something else. This is what worked for me:

Based on Ternary Operator which has following structure:

condition ? value-if-true : value-if-false

As result:

{{gallery.date?(gallery.date | date:'mediumDate'):"Various" }}

Simplest way to detect a mobile device in PHP

You could also use a third party api to do device detection via user agent string. One such service is www.useragentinfo.co. Just sign up and get your api token and below is how you get the device info via PHP:

<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
// get api token at https://www.useragentinfo.co/
$token = "<api-token>";
$url = "https://www.useragentinfo.co/api/v1/device/";

$data = array('useragent' => $useragent);

$headers = array();
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Token " . $token;

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status != 200 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

echo $json_response;
?>

And here is the sample response if the visitor is using an iPhone:

{
  "device_type":"SmartPhone",
  "browser_version":"5.1",
  "os":"iOS",
  "os_version":"5.1",
  "device_brand":"Apple",
  "bot":false,
  "browser":"Mobile Safari",
  "device_model":"iPhone"
}

Setting background colour of Android layout element

Android studio 2.1.2 (or possibly earlier) will let you pick from a color wheel:

Color Wheel in Android Studio

I got this by adding the following to my layout:

android:background="#FFFFFF"

Then I clicked on the FFFFFF color and clicked on the lightbulb that appeared.

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is non-standard and only supported by Internet Explorer on Windows.

There is no native cross browser way to write to the file system without using plugins, even the draft File API gives read only access.

If you want to work cross platform, then you need to look at such things as signed Java applets (keeping in mind that that will only work on platforms for which the Java runtime is available).

How do I print colored output with Python 3?

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def colour_print(text,colour):
    if colour == 'OKBLUE':
        string = bcolors.OKBLUE + text + bcolors.ENDC
        print(string)
    elif colour == 'HEADER':
        string = bcolors.HEADER + text + bcolors.ENDC
        print(string)
    elif colour == 'OKCYAN':
        string = bcolors.OKCYAN + text + bcolors.ENDC
        print(string)
    elif colour == 'OKGREEN':
        string = bcolors.OKGREEN + text + bcolors.ENDC
        print(string)
    elif colour == 'WARNING':
        string = bcolors.WARNING + text + bcolors.ENDC
        print(string)
    elif colour == 'FAIL':
        string = bcolors.HEADER + text + bcolors.ENDC
        print(string)
    elif colour == 'BOLD':
        string = bcolors.BOLD + text + bcolors.ENDC
        print(string)
    elif colour == 'UNDERLINE':
        string = bcolors.UNDERLINE + text + bcolors.ENDC
        print(string)

just copy the above code. just call them easily

colour_print('Hello world','OKBLUE')
colour_print('easy one','OKCYAN')
colour_print('copy and paste','OKGREEN')
colour_print('done','OKBLUE')

Hope it would help

Rebase array keys after unsetting elements

Or you can make your own function that passes the array by reference.

function array_unset($unsets, &$array) {
  foreach ($array as $key => $value) {
    foreach ($unsets as $unset) {
      if ($value == $unset) {
        unset($array[$key]);
        break;
      }
    }
  }
  $array = array_values($array);
}

So then all you have to do is...

$unsets = array(1,2);
array_unset($unsets, $array);

... and now your $array is without the values you placed in $unsets and the keys are reset

How to pip or easy_install tkinter on Windows

Easiest way to do this:

cd C:\Users\%User%\AppData\Local\Programs\Python\Python37\Scripts> 
pip install pythonds 

Screenshot of installing

cv2.imshow command doesn't work properly in opencv-python

Doesn't need any additional methods after waitKey(0) (reply for above code)

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)
cv2.waitKey(0)

Window appears -> Click on the Window & Click on Enter. Window will close.

How can I write to the console in PHP?

Here is my solution, the good thing about this one is that you can pass as many params as you like.

function console_log()
{
    $js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
        ');';
    $js_code = '<script>' . $js_code . '</script>';
    echo $js_code;
}

Call it this way

console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);

Now you should be able to see output in your console, happy coding :)

How to generate different random numbers in a loop in C++?

Don't know men. I found the best way for me after testing different ways like 10 minutes. ( Change the numbers in code to get big or small random number.)

    int x;
srand ( time(NULL) );
x = rand() % 1000 * rand() % 10000 ;
cout<<x;

Could not open ServletContext resource

Mark sure propertie file is in "/WEB-INF/classes" try to use

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>/WEB-INF/classes/social.properties</value>
    </property>
</bean>

How to terminate a process in vbscript

Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.

Connect to mysql in a docker container from the host

I do this by running a temporary docker container against my server so I don't have to worry about what is installed on my host. First, I define what I need (which you should modify for your purposes):

export MYSQL_SERVER_CONTAINER=mysql-db
export MYSQL_ROOT_PASSWORD=pswd 
export DB_DOCKER_NETWORK=db-net
export MYSQL_PORT=6604

I always create a new docker network which any other containers will need:

docker network create --driver bridge $DB_DOCKER_NETWORK

Start a mySQL database server:

docker run --detach --name=$MYSQL_SERVER_CONTAINER --net=$DB_DOCKER_NETWORK --env="MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD" -p ${MYSQL_PORT}:3306 mysql

Capture IP address of the new server container

export DBIP="$(docker inspect ${MYSQL_SERVER_CONTAINER} | grep -i 'ipaddress' | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])')"

Open a command line interface to the server:

docker run -it -v ${HOST_DATA}:/data --net=$DB_DOCKER_NETWORK --link ${MYSQL_SERVER_CONTAINER}:mysql --rm mysql sh -c "exec mysql -h${DBIP} -uroot -p"

This last container will remove itself when you exit the mySQL interface, while the server will continue running. You can also share a volume between the server and host to make it easier to import data or scripts. Hope this helps!

How to show alert message in mvc 4 controller?

TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])

Set Matplotlib colorbar size to match graph

When you create the colorbar try using the fraction and/or shrink parameters.

From the documents:

fraction 0.15; fraction of original axes to use for colorbar

shrink 1.0; fraction by which to shrink the colorbar

How to send post request with x-www-form-urlencoded body

As you set application/x-www-form-urlencoded as content type so data sent must be like this format.

String urlParameters  = "param1=data1&param2=data2&param3=data3";

Sending part now is quite straightforward.

byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
   wr.write( postData );
}

Or you can create a generic method to build key value pattern which is required for application/x-www-form-urlencoded.

private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");    
        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }    
    return result.toString();
}

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}

How to change FontSize By JavaScript?

Please never do this in real projects:

_x000D_
_x000D_
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
_x000D_
_x000D_

Format price in the current locale and currency

I think Google could have answered your question ;-) See http://blog.chapagain.com.np/magento-format-price/.

You can do it with

$formattedPrice = Mage::helper('core')->currency($finalPrice, true, false);

How to get the request parameters in Symfony 2?

Most of the cases like getting query string or form parameters are covered in answers above.

When working with raw data, like a raw JSON string in the body that you would like to give as an argument to json_decode(), the method Request::getContent() can be used.

$content = $request->getContent();

Additional useful informations on HTTP requests in Symfony can be found on the HttpFoundation package's documentation.

changing minDate option in JQuery DatePicker not working

How to dynamically alter the minDate (after init)

The above answers address how to set the default minDate at init, but the question was actually how to dynamically alter the minDate, below I also clarify How to set the default minDate.

All that was wrong with the original question was that the minDate value being set should have been a string (don't forget the quotes):

$('#datePickerId').datepicker('option', 'minDate', '3');

minDate also accepts a date object and a common use is to have an end date you are trying to calculate so something like this could be useful:

$('#datePickerId').datepicker(
    'option', 'minDate', new Date($(".datePop.start").val())
);

How to set the default minDate (at init)

Just answering this for best practice; the minDate option expects one of:

  1. a string in the current dateFormat OR
  2. number of days from today (e.g. +7) OR
  3. string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '-1y -1m')

@bogart setting the string to "0" is a solution as it satisfies option 2 above

$('#datePickerId').datepicker('minDate': '3');

jQuery UI docs for minDate

Flutter - Wrap text on overflow, like insert ellipsis or fade

Using Ellipsis

Text(
  "This is a long text",
  overflow: TextOverflow.ellipsis,
),

enter image description here


Using Fade

Text(
  "This is a long text",
  overflow: TextOverflow.fade,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Using Clip

Text(
  "This is a long text",
  overflow: TextOverflow.clip,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Note:

If you are using Text inside a Row, you can put above Text inside Expanded like:

Expanded(
  child: AboveText(),
)

When is it appropriate to use C# partial classes?

I note two usages which I couldn't find explicitly in the answers.

Grouping Class Items

Some developers use comments to separate different "parts" of their class. For example, a team might use the following convention:

public class MyClass{  
  //Member variables
  //Constructors
  //Properties
  //Methods
}

With partial classes, we can go a step further, and split the sections into separate files. As a convention, a team might suffix each file with the section corresponding to it. So in the above we would have something like: MyClassMembers.cs, MyClassConstructors.cs, MyClassProperties.cs, MyClassMethods.cs.

As other answers alluded to, whether or not it's worth splitting the class up probably depends on how big the class is in this case. If it's small, it's probably easier to have everything in one master class. But if any of those sections get too big, its content can be moved to a separate partial class, in order to keep the master class neat. A convention in that case might be to leave a comment in saying something like "See partial class" after the section heading e.g.:

//Methods - See partial class

Managing Scope of Using statements / Namespace

This is probably a rare occurrence, but there might be a namespace collision between two functions from libraries that you want to use. In a single class, you could at most use a using clause for one of these. For the other you'd need a fully qualified name or an alias. With partial classes, since each namespace & using statements list is different, one could separate the two sets of functions into two separate files.

Laravel Escaping All HTML in Blade Template

{{html_entity_decode ($post->content())}} saved the issue for me with Laravel 4.0. Now My HTML content is interpreted as it should.

Implementing two interfaces in a class with same method. Which interface method is overridden?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error. This is the general rule of inheritance, method overriding, hiding, and declarations, and applies also to possible conflicts not only between 2 inherited interface methods, but also an interface and a super class method, or even just conflicts due to type erasure of generics.


Compatibility example

Here's an example where you have an interface Gift, which has a present() method (as in, presenting gifts), and also an interface Guest, which also has a present() method (as in, the guest is present and not absent).

Presentable johnny is both a Gift and a Guest.

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }

    interface Presentable extends Gift, Guest { }

    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
            @Override public void present() {
                System.out.println("Heeeereee's Johnny!!!");
            }
        };
        johnny.present();                     // "Heeeereee's Johnny!!!"

        ((Gift) johnny).present();            // "Heeeereee's Johnny!!!"
        ((Guest) johnny).present();           // "Heeeereee's Johnny!!!"

        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();               // "Heeeereee's Johnny!!!"

        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();              // "Heeeereee's Johnny!!!"
    }
}

The above snippet compiles and runs.

Note that there is only one @Override necessary!!!. This is because Gift.present() and Guest.present() are "@Override-equivalent" (JLS 8.4.2).

Thus, johnny only has one implementation of present(), and it doesn't matter how you treat johnny, whether as a Gift or as a Guest, there is only one method to invoke.


Incompatibility example

Here's an example where the two inherited methods are NOT @Override-equivalent:

public class InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { boolean present(); }

    interface Presentable extends Gift, Guest { } // DOES NOT COMPILE!!!
    // "types InterfaceTest.Guest and InterfaceTest.Gift are incompatible;
    //  both define present(), but with unrelated return types"
}

This further reiterates that inheriting members from an interface must obey the general rule of member declarations. Here we have Gift and Guest define present() with incompatible return types: one void the other boolean. For the same reason that you can't an void present() and a boolean present() in one type, this example results in a compilation error.


Summary

You can inherit methods that are @Override-equivalent, subject to the usual requirements of method overriding and hiding. Since they ARE @Override-equivalent, effectively there is only one method to implement, and thus there's nothing to distinguish/select from.

The compiler does not have to identify which method is for which interface, because once they are determined to be @Override-equivalent, they're the same method.

Resolving potential incompatibilities may be a tricky task, but that's another issue altogether.

References

how can I Update top 100 records in sql server

Try:

UPDATE Dispatch_Post
SET isSync = 1
WHERE ChallanNo 
IN (SELECT TOP 1000 ChallanNo FROM dbo.Dispatch_Post ORDER BY 
CreatedDate DESC)

How to append data to a json file?

Append entry to the file contents if file exists, otherwise append the entry to an empty list and write in in the file:

a = []
if not os.path.isfile(fname):
    a.append(entry)
    with open(fname, mode='w') as f:
        f.write(json.dumps(a, indent=2))
else:
    with open(fname) as feedsjson:
        feeds = json.load(feedsjson)

    feeds.append(entry)
    with open(fname, mode='w') as f:
        f.write(json.dumps(feeds, indent=2))

How to convert Blob to String and String to Blob in java

Use this to convert String to Blob. Where connection is the connection to db object.

    String strContent = s;
    byte[] byteConent = strContent.getBytes();
    Blob blob = connection.createBlob();//Where connection is the connection to db object. 
    blob.setBytes(1, byteContent);

JPA: how do I persist a String into a database field, type MYSQL Text

Since you're using JPA, use the Lob annotation (and optionally the Column annotation). Here is what the JPA specification says about it:

9.1.19 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.

So declare something like this:

@Lob 
@Column(name="CONTENT", length=512)
private String content;

References

  • JPA 1.0 specification:
    • Section 9.1.19 "Lob Annotation"

List the queries running on SQL Server

If you're running SQL Server 2005 or 2008, you could use the DMV's to find this...

SELECT  *
FROM    sys.dm_exec_requests  
        CROSS APPLY sys.dm_exec_sql_text(sql_handle)  

How to create a collapsing tree table in html/css/js?

jquery is your friend here.

http://docs.jquery.com/UI/Tree

If you want to make your own, here is some high level guidance:

Display all of your data as <ul /> elements with the inner data as nested <ul />, and then use the jquery:

$('.ulClass').click(function(){ $(this).children().toggle(); });

I believe that is correct. Something like that.

EDIT:

Here is a complete example.

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
</head>
                                                                                                                                                                                <body>
<ul>
    <li><span class="Collapsable">item 1</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span><ul>
            <li><span class="Collapsable">item 1</span></li>
            <li><span class="Collapsable">item 2</span></li>
            <li><span class="Collapsable">item 3</span></li>
            <li><span class="Collapsable">item 4</span></li>
        </ul>
        </li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span><ul>
            <li><span class="Collapsable">item 1</span></li>
            <li><span class="Collapsable">item 2</span></li>
            <li><span class="Collapsable">item 3</span></li>
            <li><span class="Collapsable">item 4</span></li>
        </ul>
        </li>
    </ul>
    </li>
    <li><span class="Collapsable">item 2</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span></li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span></li>
    </ul>
    </li>
    <li><span class="Collapsable">item 3</span><ul>
        <li><span class="Collapsable">item 1</span></li>
        <li><span class="Collapsable">item 2</span></li>
        <li><span class="Collapsable">item 3</span></li>
        <li><span class="Collapsable">item 4</span></li>
    </ul>
    </li>
    <li><span class="Collapsable">item 4</span></li>
</ul>
<script type="text/javascript">
    $(".Collapsable").click(function () {

        $(this).parent().children().toggle();
        $(this).toggle();

    });

</script>

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

How to search for string in an array

You could use the following without the wrapper function, but it provides a nicer API:

Function IsInArray(ByVal findString as String, ByVal arrayToSearch as Variant) as Boolean
  IsInArray = UBound(Filter(arrayToSearch,findString)) >= 0
End Function

The Filter function has the following signature:

Filter(sourceArray, stringToMatch, [Include As Boolean = True], [Compare as VbCompareMethod = vbBinaryCompare])

Java Class.cast() vs. cast operator

I've only ever used Class.cast(Object) to avoid warnings in "generics land". I often see methods doing things like this:

@SuppressWarnings("unchecked")
<T> T doSomething() {
    Object o;
    // snip
    return (T) o;
}

It's often best to replace it by:

<T> T doSomething(Class<T> cls) {
    Object o;
    // snip
    return cls.cast(o);
}

That's the only use case for Class.cast(Object) I've ever come across.

Regarding compiler warnings: I suspect that Class.cast(Object) isn't special to the compiler. It could be optimized when used statically (i.e. Foo.class.cast(o) rather than cls.cast(o)) but I've never seen anybody using it - which makes the effort of building this optimization into the compiler somewhat worthless.

How to update Identity Column in SQL Server?

If got your question right you want to do something like

update table
set identity_column_name = some value

Let me tell you, it is not an easy process and it is not advisable to use it, as there may be some foreign key associated on it.

But here are steps to do it, Please take a back-up of table

Step 1- Select design view of the table

enter image description here

Step 2- Turn off the identity column

enter image description here

Now you can use the update query.

Now redo the step 1 and step 2 and Turn on the identity column

Reference

How to Load Ajax in Wordpress

Firstly, you should read this page thoroughly http://codex.wordpress.org/AJAX_in_Plugins

Secondly, ajax_script is not defined so you should change to: url: ajaxurl. I don't see your function1() in the above code but you might already define it in other file.

And finally, learn how to debug ajax call using Firebug, network and console tab will be your friends. On the PHP side, print_r() or var_dump() will be your friends.

How to change the order of DataFrame columns?

This question has been answered before but reindex_axis is deprecated now so I would suggest to use:

df = df.reindex(sorted(df.columns), axis=1)

For those who want to specify the order they want instead of just sorting them, here's the solution spelled out:

df = df.reindex(['the','order','you','want'], axis=1)

Now, how you want to sort the list of column names is really not a pandas question, that's a Python list manipulation question. There are many ways of doing that, and I think this answer has a very neat way of doing it.

Python: subplot within a loop: first panel appears in wrong position

Using your code with some random data, this would work:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(10):

    axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
    axs[i].set_title(str(250+i))

The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).

enter image description here

Storing Data in MySQL as JSON

I know this is really late but I did have a similar situation where I used a hybrid approach of maintaining RDBMS standards of normalizing tables upto a point and then storing data in JSON as text value beyond that point. So for example I store data in 4 tables following RDBMS rules of normalization. However in the 4th table to accomodate dynamic schema I store data in JSON format. Every time I want to retrieve data I retrieve the JSON data, parse it and display it in Java. This has worked for me so far and to ensure that I am still able to index the fields I transform to json data in the table to a normalized manner using an ETL. This ensures that while the user is working on the application he faces minimal lag and the fields are transformed to a RDBMS friendly format for data analysis etc. I see this approach working well and believe that given MYSQL (5.7+) also allows parsing of JSON this approach gives you the benefits of both RDBMS and NOSQL databases.

How to push object into an array using AngularJS

'Push' is for arrays.

You can do something like this:

app.js:

(function() {

var app = angular.module('myApp', []);

 app.controller('myController', ['$scope', function($scope) {

    $scope.myText = "Let's go";

    $scope.arrayText = [
            'Hello',
            'world'
        ];

    $scope.addText = function() {
        $scope.arrayText.push(this.myText);
    }

 }]);

})();

index.html

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <div>
      <form ng-controller="myController" ng-submit="addText()">
           <input type="text" ng-model="myText" value="Lets go">
           <input type="submit" id="submit"/>
           <pre>list={{arrayText}}</pre>
      </form>
    </div>
  </body>
</html>

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

Since no answers were posted, I found the following here:

The Web server (running the Web site) thinks that the request submitted by the client (e.g. your Web browser or our CheckUpDown robot) can not be completed because it conflicts with some rule already established. For example, you may get a 409 error if you try to upload a file to the Web server which is older than the one already there - resulting in a version control conflict.

Someone on a similar question right here on stackoverflow, said the answer was:

I've had this issue when I was referencing the url of the document library and not the destination file itself.

i.e. try http://server name/document library name/new file name.doc

However I am 100% sure this was not my case, since I checked the WebRequest's URI property several times and the URI was complete with filename, and all the folders in the path existed on the sharepoint site.

Anyways, I hope this helps someone.

Trim string in JavaScript?

use simply code

var str = "       Hello World!        ";
alert(str.trim());

Browser support

Feature         Chrome  Firefox Internet Explorer   Opera   Safari  Edge
Basic support   (Yes)   3.5     9                   10.5    5       ?

For old browser add prototype

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Generating a drop down list of timezones with PHP

America Country - Time with Timezones List in Array Format.

$america_timezones_list = array(
        '+00:00||America/Danmarkshavn'=>'(+00:00) Danmarkshavn',
        '-01:00||America/Scoresbysund'=>'(-01:00) Scoresbysund',
        '-02:00||America/Miquelon'=>'(-02:00) Miquelon',
        '-02:00||America/Noronha'=>'(-02:00) Noronha',
        '-02:30||America/St_Johns'=>'(-02:30) St_Johns',
        '-03:00||America/Araguaina'=>'(-03:00) Araguaina',
        '-03:00||America/Argentina/Buenos_Aires'=>'(-03:00) Argentina/Buenos_Aires',
        '-03:00||America/Argentina/Catamarca'=>'(-03:00) Argentina/Catamarca',
        '-03:00||America/Argentina/Cordoba'=>'(-03:00) Argentina/Cordoba',
        '-03:00||America/Argentina/Jujuy'=>'(-03:00) Argentina/Jujuy',
        '-03:00||America/Argentina/La_Rioja'=>'(-03:00) Argentina/La_Rioja',
        '-03:00||America/Argentina/Mendoza'=>'(-03:00) Argentina/Mendoza',
        '-03:00||America/Argentina/Rio_Gallegos'=>'(-03:00) Argentina/Rio_Gallegos',
        '-03:00||America/Argentina/Salta'=>'(-03:00) Argentina/Salta',
        '-03:00||America/Argentina/San_Juan'=>'(-03:00) Argentina/San_Juan',
        '-03:00||America/Argentina/San_Luis'=>'(-03:00) Argentina/San_Luis',
        '-03:00||America/Argentina/Tucuman'=>'(-03:00) Argentina/Tucuman',
        '-03:00||America/Argentina/Ushuaia'=>'(-03:00) Argentina/Ushuaia',
        '-03:00||America/Asuncion'=>'(-03:00) Asuncion',
        '-03:00||America/Bahia'=>'(-03:00) Bahia',
        '-03:00||America/Belem'=>'(-03:00) Belem',
        '-03:00||America/Cayenne'=>'(-03:00) Cayenne',
        '-03:00||America/Fortaleza'=>'(-03:00) Fortaleza',
        '-03:00||America/Glace_Bay'=>'(-03:00) Glace_Bay',
        '-03:00||America/Godthab'=>'(-03:00) Godthab',
        '-03:00||America/Goose_Bay'=>'(-03:00) Goose_Bay',
        '-03:00||America/Halifax'=>'(-03:00) Halifax',
        '-03:00||America/Maceio'=>'(-03:00) Maceio',
        '-03:00||America/Moncton'=>'(-03:00) Moncton',
        '-03:00||America/Montevideo'=>'(-03:00) Montevideo',
        '-03:00||America/Paramaribo'=>'(-03:00) Paramaribo',
        '-03:00||America/Punta_Arenas'=>'(-03:00) Punta_Arenas',
        '-03:00||America/Recife'=>'(-03:00) Recife',
        '-03:00||America/Santarem'=>'(-03:00) Santarem',
        '-03:00||America/Santiago'=>'(-03:00) Santiago',
        '-03:00||America/Sao_Paulo'=>'(-03:00) Sao_Paulo',
        '-03:00||America/Thule'=>'(-03:00) Thule',
        '-04:00||America/Anguilla'=>'(-04:00) Anguilla',
        '-04:00||America/Antigua'=>'(-04:00) Antigua',
        '-04:00||America/Aruba'=>'(-04:00) Aruba',
        '-04:00||America/Barbados'=>'(-04:00) Barbados',
        '-04:00||America/Blanc-Sablon'=>'(-04:00) Blanc-Sablon',
        '-04:00||America/Boa_Vista'=>'(-04:00) Boa_Vista',
        '-04:00||America/Campo_Grande'=>'(-04:00) Campo_Grande',
        '-04:00||America/Caracas'=>'(-04:00) Caracas',
        '-04:00||America/Cuiaba'=>'(-04:00) Cuiaba',
        '-04:00||America/Curacao'=>'(-04:00) Curacao',
        '-04:00||America/Detroit'=>'(-04:00) Detroit',
        '-04:00||America/Dominica'=>'(-04:00) Dominica',
        '-04:00||America/Grand_Turk'=>'(-04:00) Grand_Turk',
        '-04:00||America/Grenada'=>'(-04:00) Grenada',
        '-04:00||America/Guadeloupe'=>'(-04:00) Guadeloupe',
        '-04:00||America/Guyana'=>'(-04:00) Guyana',
        '-04:00||America/Havana'=>'(-04:00) Havana',
        '-04:00||America/Indiana/Indianapolis'=>'(-04:00) Indiana/Indianapolis',
        '-04:00||America/Indiana/Marengo'=>'(-04:00) Indiana/Marengo',
        '-04:00||America/Indiana/Petersburg'=>'(-04:00) Indiana/Petersburg',
        '-04:00||America/Indiana/Vevay'=>'(-04:00) Indiana/Vevay',
        '-04:00||America/Indiana/Vincennes'=>'(-04:00) Indiana/Vincennes',
        '-04:00||America/Indiana/Winamac'=>'(-04:00) Indiana/Winamac',
        '-04:00||America/Iqaluit'=>'(-04:00) Iqaluit',
        '-04:00||America/Kentucky/Louisville'=>'(-04:00) Kentucky/Louisville',
        '-04:00||America/Kentucky/Monticello'=>'(-04:00) Kentucky/Monticello',
        '-04:00||America/Kralendijk'=>'(-04:00) Kralendijk',
        '-04:00||America/La_Paz'=>'(-04:00) La_Paz',
        '-04:00||America/Lower_Princes'=>'(-04:00) Lower_Princes',
        '-04:00||America/Manaus'=>'(-04:00) Manaus',
        '-04:00||America/Marigot'=>'(-04:00) Marigot',
        '-04:00||America/Martinique'=>'(-04:00) Martinique',
        '-04:00||America/Montserrat'=>'(-04:00) Montserrat',
        '-04:00||America/Nassau'=>'(-04:00) Nassau',
        '-04:00||America/New_York'=>'(-04:00) New_York',
        '-04:00||America/Nipigon'=>'(-04:00) Nipigon',
        '-04:00||America/Pangnirtung'=>'(-04:00) Pangnirtung',
        '-04:00||America/Port-au-Prince'=>'(-04:00) Port-au-Prince',
        '-04:00||America/Port_of_Spain'=>'(-04:00) Port_of_Spain',
        '-04:00||America/Porto_Velho'=>'(-04:00) Porto_Velho',
        '-04:00||America/Puerto_Rico'=>'(-04:00) Puerto_Rico',
        '-04:00||America/Santo_Domingo'=>'(-04:00) Santo_Domingo',
        '-04:00||America/St_Barthelemy'=>'(-04:00) St_Barthelemy',
        '-04:00||America/St_Kitts'=>'(-04:00) St_Kitts',
        '-04:00||America/St_Lucia'=>'(-04:00) St_Lucia',
        '-04:00||America/St_Thomas'=>'(-04:00) St_Thomas',
        '-04:00||America/St_Vincent'=>'(-04:00) St_Vincent',
        '-04:00||America/Thunder_Bay'=>'(-04:00) Thunder_Bay',
        '-04:00||America/Toronto'=>'(-04:00) Toronto',
        '-04:00||America/Tortola'=>'(-04:00) Tortola',
        '-05:00||America/Atikokan'=>'(-05:00) Atikokan',
        '-05:00||America/Bogota'=>'(-05:00) Bogota',
        '-05:00||America/Cancun'=>'(-05:00) Cancun',
        '-05:00||America/Cayman'=>'(-05:00) Cayman',
        '-05:00||America/Chicago'=>'(-05:00) Chicago',
        '-05:00||America/Eirunepe'=>'(-05:00) Eirunepe',
        '-05:00||America/Guayaquil'=>'(-05:00) Guayaquil',
        '-05:00||America/Indiana/Knox'=>'(-05:00) Indiana/Knox',
        '-05:00||America/Indiana/Tell_City'=>'(-05:00) Indiana/Tell_City',
        '-05:00||America/Jamaica'=>'(-05:00) Jamaica',
        '-05:00||America/Lima'=>'(-05:00) Lima',
        '-05:00||America/Matamoros'=>'(-05:00) Matamoros',
        '-05:00||America/Menominee'=>'(-05:00) Menominee',
        '-05:00||America/North_Dakota/Beulah'=>'(-05:00) North_Dakota/Beulah',
        '-05:00||America/North_Dakota/Center'=>'(-05:00) North_Dakota/Center',
        '-05:00||America/North_Dakota/New_Salem'=>'(-05:00) North_Dakota/New_Salem',
        '-05:00||America/Panama'=>'(-05:00) Panama',
        '-05:00||America/Rainy_River'=>'(-05:00) Rainy_River',
        '-05:00||America/Rankin_Inlet'=>'(-05:00) Rankin_Inlet',
        '-05:00||America/Resolute'=>'(-05:00) Resolute',
        '-05:00||America/Rio_Branco'=>'(-05:00) Rio_Branco',
        '-05:00||America/Winnipeg'=>'(-05:00) Winnipeg',
        '-06:00||America/Bahia_Banderas'=>'(-06:00) Bahia_Banderas',
        '-06:00||America/Belize'=>'(-06:00) Belize',
        '-06:00||America/Boise'=>'(-06:00) Boise',
        '-06:00||America/Cambridge_Bay'=>'(-06:00) Cambridge_Bay',
        '-06:00||America/Costa_Rica'=>'(-06:00) Costa_Rica',
        '-06:00||America/Denver'=>'(-06:00) Denver',
        '-06:00||America/Edmonton'=>'(-06:00) Edmonton',
        '-06:00||America/El_Salvador'=>'(-06:00) El_Salvador',
        '-06:00||America/Guatemala'=>'(-06:00) Guatemala',
        '-06:00||America/Inuvik'=>'(-06:00) Inuvik',
        '-06:00||America/Managua'=>'(-06:00) Managua',
        '-06:00||America/Merida'=>'(-06:00) Merida',
        '-06:00||America/Mexico_City'=>'(-06:00) Mexico_City',
        '-06:00||America/Monterrey'=>'(-06:00) Monterrey',
        '-06:00||America/Ojinaga'=>'(-06:00) Ojinaga',
        '-06:00||America/Regina'=>'(-06:00) Regina',
        '-06:00||America/Swift_Current'=>'(-06:00) Swift_Current',
        '-06:00||America/Tegucigalpa'=>'(-06:00) Tegucigalpa',
        '-06:00||America/Yellowknife'=>'(-06:00) Yellowknife',
        '-07:00||America/Chihuahua'=>'(-07:00) Chihuahua',
        '-07:00||America/Creston'=>'(-07:00) Creston',
        '-07:00||America/Dawson'=>'(-07:00) Dawson',
        '-07:00||America/Dawson_Creek'=>'(-07:00) Dawson_Creek',
        '-07:00||America/Fort_Nelson'=>'(-07:00) Fort_Nelson',
        '-07:00||America/Hermosillo'=>'(-07:00) Hermosillo',
        '-07:00||America/Los_Angeles'=>'(-07:00) Los_Angeles',
        '-07:00||America/Mazatlan'=>'(-07:00) Mazatlan',
        '-07:00||America/Phoenix'=>'(-07:00) Phoenix',
        '-07:00||America/Tijuana'=>'(-07:00) Tijuana',
        '-07:00||America/Vancouver'=>'(-07:00) Vancouver',
        '-07:00||America/Whitehorse'=>'(-07:00) Whitehorse',
        '-08:00||America/Anchorage'=>'(-08:00) Anchorage',
        '-08:00||America/Juneau'=>'(-08:00) Juneau',
        '-08:00||America/Metlakatla'=>'(-08:00) Metlakatla',
        '-08:00||America/Nome'=>'(-08:00) Nome',
        '-08:00||America/Sitka'=>'(-08:00) Sitka',
        '-08:00||America/Yakutat'=>'(-08:00) Yakutat',
        '-09:00||America/Adak'=>'(-09:00) Adak'
    );

I have used it in many projects, sharing to help you. Thanks for asking this question.

Map a network drive to be used by a service

You wan't to either change the user that the Service runs under from "System" or find a sneaky way to run your mapping as System.

The funny thing is that this is possible by using the "at" command, simply schedule your drive mapping one minute into the future and it will be run under the System account making the drive visible to your service.

Linux Script to check if process is running and act on the result

If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:

#! /bin/bash

logfile="/var/oscamlog/oscam1check.log"

case "$(pidof oscam1 | wc -w)" in

0)  echo "oscam1 not running, restarting oscam1:     $(date)" >> $logfile
    /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
    ;;
2)  echo "oscam1 running, all OK:     $(date)" >> $logfile
    ;;
*)  echo "multiple instances of oscam1 running. Stopping & restarting oscam1:     $(date)" >> $logfile
    kill $(pidof oscam1 | awk '{ $1=""; print $0}')
    ;;
esac

It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like

root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript

Just an FYI

Best way to "negate" an instanceof

I agree that in most cases the if (!(x instanceof Y)) {...} is the best approach, but in some cases creating an isY(x) function so you can if (!isY(x)) {...} is worthwhile.

I'm a typescript novice, and I've bumped into this S/O question a bunch of times over the last few weeks, so for the googlers the typescript way to do this is to create a typeguard like this:

typeGuards.ts

export function isHTMLInputElement (value: any): value is HTMLInputElement {
  return value instanceof HTMLInputElement
}

usage

if (!isHTMLInputElement(x)) throw new RangeError()
// do something with an HTMLInputElement

I guess the only reason why this might be appropriate in typescript and not regular js is that typeguards are a common convention, so if you're writing them for other interfaces, it's reasonable / understandable / natural to write them for classes too.

There's more detail about user defined type guards like this in the docs

SQL - HAVING vs. WHERE

You can not use where clause with aggregate functions because where fetch records on the basis of condition, it goes into table record by record and then fetch record on the basis of condition we have give. So that time we can not where clause. While having clause works on the resultSet which we finally get after running a query.

Example query:

select empName, sum(Bonus) 
from employees 
order by empName 
having sum(Bonus) > 5000;

This will store the resultSet in a temporary memory, then having clause will perform its work. So we can easily use aggregate functions here.

Response::json() - Laravel 5.1

From a controller you can also return an Object/Array and it will be sent as a JSON response (including the correct HTTP headers).

public function show($id)
{
    return Customer::find($id);
}

What is the use of BindingResult interface in spring MVC?

BindingResult is used for validation..

Example:-

 public @ResponseBody String nutzer(@ModelAttribute(value="nutzer") Nutzer nutzer, BindingResult ergebnis){
        String ergebnisText;
        if(!ergebnis.hasErrors()){
            nutzerList.add(nutzer);
            ergebnisText = "Anzahl: " + nutzerList.size();
        }else{
            ergebnisText = "Error!!!!!!!!!!!";
        }
        return ergebnisText;
    }

CSS3 :unchecked pseudo-class

:unchecked is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.

In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked), it's safe to assume that there is no corresponding :unchecked pseudo. Browser support for :not() and :checked is identical, so that shouldn't be a problem.

This may seem inconsistent with the :enabled and :disabled states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.

(:indeterminate does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

Timing Delays in VBA

Another variant of Steve Mallorys answer, I specifically needed excel to run off and do stuff while waiting and 1 second was too long.

'Wait for the specified number of milliseconds while processing the message pump
'This allows excel to catch up on background operations
Sub WaitFor(milliseconds As Single)

    Dim finish As Single
    Dim days As Integer

    'Timer is the number of seconds since midnight (as a single)
    finish = Timer + (milliseconds / 1000)
    'If we are near midnight (or specify a very long time!) then finish could be
    'greater than the maximum possible value of timer. Bring it down to sensible
    'levels and count the number of midnights
    While finish >= 86400
        finish = finish - 86400
        days = days + 1
    Wend

    Dim lastTime As Single
    lastTime = Timer

    'When we are on the correct day and the time is after the finish we can leave
    While days >= 0 And Timer < finish
        DoEvents
        'Timer should be always increasing except when it rolls over midnight
        'if it shrunk we've gone back in time or we're on a new day
        If Timer < lastTime Then
            days = days - 1
        End If
        lastTime = Timer
    Wend

End Sub

XDocument or XmlDocument

I believe that XDocument makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument will be faster.

One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument.

How to write multiple line string using Bash with variables?

The heredoc solutions are certainly the most common way to do this. Other common solutions are:

echo 'line 1, '"${kernel}"'
line 2,
line 3, '"${distro}"'
line 4' > /etc/myconfig.conf

and

exec 3>&1 # Save current stdout
exec > /etc/myconfig.conf
echo line 1, ${kernel}
echo line 2, 
echo line 3, ${distro}
...
exec 1>&3  # Restore stdout

Laravel orderBy on a relationship

I believe you can also do:

$sortDirection = 'desc';

$user->with(['comments' => function ($query) use ($sortDirection) {
    $query->orderBy('column', $sortDirection);
}]);

That allows you to run arbitrary logic on each related comment record. You could have stuff in there like:

$query->where('timestamp', '<', $someTime)->orderBy('timestamp', $sortDirection);

Javascript change Div style

you may check the color before you click to change it.

function abc(){
     var color = document.getElementById("test").style.color;
     if(color==''){
         //change
     }else{
         //change back
     }
}

count distinct values in spreadsheet

This is similar to Solution 1 from @JSuar...

Assume your original city data is a named range called dataCity. In a new sheet, enter the following:

    A                 | B
  ----------------------------------------------------------
1 | =UNIQUE(dataCity) | Count
2 |                   | =DCOUNTA(dataCity,"City",{"City";$A2})
3 |                   | [copy down the formula above]
4 |                   | ...
5 |                   | ...

Getting Current date, time , day in laravel

FOR LARAVEL 5.x

I think you were looking for this

$errorLog->timestamps = false;
$errorLog->created_at = date("Y-m-d H:i:s");

How to pass arguments to entrypoint in docker-compose.yml

To override the default entrypoint, use entrypoint option. To pass the arguments use command.

Here is the example of replacing bash with sh in ubuntu image:

version: '3'
services:
  sh:
    entrypoint: /bin/sh
    command: -c "ps $$(echo $$$$)"
    image: ubuntu
    tty: true
  bash:
    entrypoint: /bin/bash
    command: -c "ps $$(echo $$$$)"
    image: ubuntu
    tty: true

Here is the output:

$ docker-compose up   
Starting test_sh_1                ... done
Starting 020211508a29_test_bash_1 ... done
Attaching to test_sh_1, 020211508a29_test_bash_1
sh_1    |   PID TTY      STAT   TIME COMMAND
sh_1    |     1 pts/0    Ss+    0:00 /bin/sh -c ps $(echo $$)
020211508a29_test_bash_1 |   PID TTY      STAT   TIME COMMAND
020211508a29_test_bash_1 |     1 pts/0    Rs+    0:00 ps 1

disable all form elements inside div

Only text type

$(".form-edit-account :input[type=text]").attr("disabled", "disabled");

Only Password type

$(".form-edit-account :input[type=password]").attr("disabled", "disabled");

Only Email Type

$(".form-edit-account :input[type=email]").attr("disabled", "disabled");

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Handling ExecuteScalar() when no results are returned

Alternatively, you can use DataTable to check if there's any row:

SqlCommand cmd = new SqlCommand("select username from usermst where userid=2", conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
string getusername = "";
// assuming userid is unique
if (dt.Rows.Count > 0)
    getusername = dt.Rows[0]["username"].ToString();

Failing to run jar file from command line: “no main manifest attribute”

Export you Java Project as an Runnable Jar file rather than Jar.

I exported my project as Jar and even though the Manifest was present it gave me the error no main manifest attribute in jar even though the Manifest file was present in the Jar. However there is only one entry in the Manifest file and it didn't specify the Main class or Function to execute or any dependent JAR's

After exporting it as Runnable Jar file it works as expected.

Efficient way to insert a number into a sorted array of numbers?

TypeScript version with custom compare method:

const { compare } = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: "base"
});

const insert = (items: string[], item: string) => {
    let low = 0;
    let high = items.length;

    while (low < high) {
        const mid = (low + high) >> 1;
        compare(items[mid], item) > 0
            ? (high = mid)
            : (low = mid + 1);
    }

    items.splice(low, 0, item);
};

Use:

const items = [];

insert(items, "item 12");
insert(items, "item 1");
insert(items, "item 2");
insert(items, "item 22");

console.log(items);

// ["item 1", "item 2", "item 12", "item 22"]

SpringMVC RequestMapping for GET parameters

You can add @RequestMapping like so:

@RequestMapping("/userGrid")
public @ResponseBody GridModel getUsersForGrid(
   @RequestParam("_search") String search,
   @RequestParam String nd,
   @RequestParam int rows,
   @RequestParam int page,
   @RequestParam String sidx) 
   @RequestParam String sord) {

Given URL is not permitted by the application configuration

Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.

Count Vowels in String Python

Simplest Answer:

inputString = str(input("Please type a sentence: "))

vowel_count = 0

inputString =inputString.lower()

vowel_count+=inputString.count("a")
vowel_count+=inputString.count("e")
vowel_count+=inputString.count("i")
vowel_count+=inputString.count("o")
vowel_count+=inputString.count("u")

print(vowel_count)

Using %s in C correctly - very basic level

For both *printf and *scanf, %s expects the corresponding argument to be of type char *, and for scanf, it had better point to a writable buffer (i.e., not a string literal).

char *str_constant = "I point to a string literal";
char str_buf[] = "I am an array of char initialized with a string literal";

printf("string literal = %s\n", "I am a string literal");
printf("str_constant = %s\n", str_constant);
printf("str_buf = %s\n", str_buf);

scanf("%55s", str_buf);

Using %s in scanf without an explcit field width opens the same buffer overflow exploit that gets did; namely, if there are more characters in the input stream than the target buffer is sized to hold, scanf will happily write those extra characters to memory outside the buffer, potentially clobbering something important. Unfortunately, unlike in printf, you can't supply the field with as a run time argument:

printf("%*s\n", field_width, string);

One option is to build the format string dynamically:

char fmt[10];
sprintf(fmt, "%%%lus", (unsigned long) (sizeof str_buf) - 1);
...
scanf(fmt, target_buffer); // fmt = "%55s"

EDIT

Using scanf with the %s conversion specifier will stop scanning at the first whitespace character; for example, if your input stream looks like

"This is a test"

then scanf("%55s", str_buf) will read and assign "This" to str_buf. Note that the field with specifier doesn't make a difference in this case.

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

Pandas group-by and sum

df.groupby(['Fruit','Name'])['Number'].sum()

You can select different columns to sum numbers.

Where do I configure log4j in a JUnit test class?

The LogManager class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:

  1. If you specify log4j.defaultInitOverride to false, it will not configure log4j at all.
  2. Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java:

    -Dlog4j.configuration=<path to properties file>

    in your test runner configuration.

  3. Allow log4j to scan the classpath for a log4j config file during your test. (the default)

See also the online documentation.

How do I align a label and a textarea?

Try setting a height on your td elements.

vertical-align: middle; 

means the element the style is applied to will be aligned within the parent element. The height of the td may be only as high as the text inside.

How to find MAC address of an Android device programmatically

Recent update from Developer.Android.com

Don't work with MAC addresses MAC addresses are globally unique, not user-resettable, and survive factory resets. For these reasons, it's generally not recommended to use MAC address for any form of user identification. Devices running Android 10 (API level 29) and higher report randomized MAC addresses to all apps that aren't device owner apps.

Between Android 6.0 (API level 23) and Android 9 (API level 28), local device MAC addresses, such as Wi-Fi and Bluetooth, aren't available via third-party APIs. The WifiInfo.getMacAddress() method and the BluetoothAdapter.getDefaultAdapter().getAddress() method both return 02:00:00:00:00:00.

Additionally, between Android 6.0 and Android 9, you must hold the following permissions to access MAC addresses of nearby external devices available via Bluetooth and Wi-Fi scans:

Method/Property Permissions Required

ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION

Source: https://developer.android.com/training/articles/user-data-ids.html#version_specific_details_identifiers_in_m

How to use group by with union in t-sql

GROUP BY 1

I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).

There's no need to run GROUP BY on the contents when you're using UNION - UNION ensures that duplicates are removed; UNION ALL is faster because it doesn't - and in that case you would need the GROUP BY...

Your query only needs to be:

SELECT a.id,
       a.time
  FROM dbo.TABLE_A a
UNION
SELECT b.id,
       b.time
  FROM dbo.TABLE_B b

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Handling MySQL datetimes and timestamps in Java

In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date. It is basically backed by the Epoch time in flavor of a long, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.

In SQL side, there are several standard date and time types, DATE, TIME and TIMESTAMP (at some DB's also called DATETIME), which are represented in JDBC as java.sql.Date, java.sql.Time and java.sql.Timestamp, all subclasses of java.util.Date. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.

In contrary to java.util.Date, the java.sql.Date contains only information about the date part (year, month, day). The Time contains only information about the time part (hours, minutes, seconds) and the Timestamp contains information about the both parts, like as java.util.Date does.

The normal practice to store a timestamp in the DB (thus, java.util.Date in Java side and java.sql.Timestamp in JDBC side) is to use PreparedStatement#setTimestamp().

java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);

The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp().

Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.

Limiting double to 3 decimal places

double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));

How to generate random positive and negative numbers in Java

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

What is a lambda expression in C++11?

One problem it solves: Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member

You can initialize a const member of your class, with a call to a function that sets its value by giving back its output as an output parameter.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

As complement to Mark's answer, the compile function does not have access to scope, but the link function does.

I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).

How to pad a string to a fixed length with spaces in Python?

This is super simple with format:

>>> a = "John"
>>> "{:<15}".format(a)
'John           '

MySQL: What's the difference between float and double?

Float has 32 bit (4 bytes) with 8 places accuracy. Double has 64 bit (8 bytes) with 16 places accuracy.

If you need better accuracy, use Double instead of Float.

What does the line "#!/bin/sh" mean in a UNIX shell script?

The first line tells the shell that if you execute the script directly (./run.sh; as opposed to /bin/sh run.sh), it should use that program (/bin/sh in this case) to interpret it.

You can also use it to pass arguments, commonly -e (exit on error), or use other programs (/bin/awk, /usr/bin/perl, etc).

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

I always use this my function to generate a custom random alphanumeric string... Hope this help.

<?php
  function random_alphanumeric($length) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
    $my_string = '';
    for ($i = 0; $i < $length; $i++) {
      $pos = mt_rand(0, strlen($chars) -1);
      $my_string .= substr($chars, $pos, 1);
    }
    return $my_string;
  }
  echo random_alphanumeric(50); // 50 characters
?>

It generates for example: Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86g

If you want compare with another string to be sure that is a unique sequence you can use this trick...

$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
  $string_1 = random_alphanumeric(50);
  $string_2 = random_alphanumeric(50);
  if ($string_1 != $string_2) {
     break;
  }
}
echo $string_1;
echo "<br>\n";
echo $string_2;

it generate two unique strings:

qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi

Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF

Hope this is what you are looking for...

remove first element from array and return the array minus the first element

Why not use ES6?

_x000D_
_x000D_
 var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
 const [, ...rest] = myarray;_x000D_
 console.log(rest)
_x000D_
_x000D_
_x000D_

UPDATE with CASE and IN - Oracle

"The list are variables/paramaters that is pre-defined as comma separated lists". Do you mean that your query is actually

UPDATE tab1   SET budgpost_gr1=     
CASE  WHEN (budgpost in ('1001,1012,50055'))  THEN 'BP_GR_A'   
      WHEN (budgpost in ('5,10,98,0'))  THEN 'BP_GR_B'  
      WHEN (budgpost in ('11,876,7976,67465'))     
      ELSE 'Missing' END`

If so, you need a function to take a string and parse it into a list of numbers.

create type tab_num is table of number;

create or replace function f_str_to_nums (i_str in varchar2) return tab_num is
  v_tab_num tab_num := tab_num();
  v_start   number := 1;
  v_end     number;
  v_delim   VARCHAR2(1) := ',';
  v_cnt     number(1) := 1;
begin
  v_end := instr(i_str||v_delim,v_delim,1, v_start);
  WHILE v_end > 0 LOOP
    v_cnt := v_cnt + 1;
    v_tab_num.extend;
    v_tab_num(v_tab_num.count) := 
                  substr(i_str,v_start,v_end-v_start);
    v_start := v_end + 1;
    v_end := instr(i_str||v_delim,v_delim,v_start);
  END LOOP;
  RETURN v_tab_num;
end;
/

Then you can use the function like so:

select column_id, 
   case when column_id in 
     (select column_value from table(f_str_to_nums('1,2,3,4'))) then 'red' 
   else 'blue' end
from  user_tab_columns
where table_name = 'EMP'

Java Comparator class to sort arrays

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

CSS: How to remove pseudo elements (after, before,...)?

This depends on what's actually being added by the pseudoselectors. In your situation, setting content to "" will get rid of it, but if you're setting borders or backgrounds or whatever, you need to zero those out specifically. As far as I know, there's no one cure-all for removing everything about a before/after element regardless of what it is.

LINQ: combining join and group by

We did it like this:

from p in Products                         
join bp in BaseProducts on p.BaseProductId equals bp.Id                    
where !string.IsNullOrEmpty(p.SomeId) && p.LastPublished >= lastDate                         
group new { p, bp } by new { p.SomeId } into pg    
let firstproductgroup = pg.FirstOrDefault()
let product = firstproductgroup.p
let baseproduct = firstproductgroup.bp
let minprice = pg.Min(m => m.p.Price)
let maxprice = pg.Max(m => m.p.Price)
select new ProductPriceMinMax
{
SomeId = product.SomeId,
BaseProductName = baseproduct.Name,
CountryCode = product.CountryCode,
MinPrice = minprice, 
MaxPrice = maxprice
};

EDIT: we used the version of AakashM, because it has better performance

Update query using Subquery in Sql Server

you can join both tables even on UPDATE statements,

UPDATE  a
SET     a.marks = b.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

for faster performance, define an INDEX on column marks on both tables.

using SUBQUERY

UPDATE  tempDataView 
SET     marks = 
        (
          SELECT marks 
          FROM tempData b 
          WHERE tempDataView.Name = b.Name
        )

How to build minified and uncompressed bundle with webpack?

You can create two configs for webpack, one that minifies the code and one that doesn't (just remove the optimize.UglifyJSPlugin line) and then run both configurations at the same time $ webpack && webpack --config webpack.config.min.js

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Using getopts to process long and short command line options

getopts "could be used" for parsing long options as long as you don't expect them to have arguments...

Here's how to:

$ cat > longopt
while getopts 'e:-:' OPT; do
  case $OPT in
    e) echo echo: $OPTARG;;
    -) #long option
       case $OPTARG in
         long-option) echo long option;;
         *) echo long option: $OPTARG;;
       esac;;
  esac
done

$ bash longopt -e asd --long-option --long1 --long2 -e test
echo: asd
long option
long option: long1
long option: long2
echo: test

If you try to use OPTIND for getting a parameter for the long option, getopts will treat it as the first no optional positional parameter and will stop parsing any other parameters. In such a case you'll be better off handling it manually with a simple case statement.

This will "always" work:

$ cat >longopt2
while (($#)); do
    OPT=$1
    shift
    case $OPT in
        --*) case ${OPT:2} in
            long1) echo long1 option;;
            complex) echo comples with argument $1; shift;;
        esac;;

        -*) case ${OPT:1} in
            a) echo short option a;;
            b) echo short option b with parameter $1; shift;;
        esac;;
    esac
done


$ bash longopt2 --complex abc -a --long -b test
comples with argument abc
short option a
short option b with parameter test

Albeit is not as flexible as getopts and you have to do much of the error checking code yourself within the case instances...

But it is an option.

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

This is a sledgehammer approach to replacing raw UNICODE with HTML. I haven't seen any other place to put this solution, but I assume others have had this problem.

Apply this str_replace function to the RAW JSON, before doing anything else.

function unicode2html($str){
    $i=65535;
    while($i>0){
        $hex=dechex($i);
        $str=str_replace("\u$hex","&#$i;",$str);
        $i--;
     }
     return $str;
}

This won't take as long as you think, and this will replace ANY unicode with HTML.

Of course this can be reduced if you know the unicode types that are being returned in the JSON.

For example my code was getting lots of arrows and dingbat unicode. These are between 8448 an 11263. So my production code looks like:

$i=11263;
while($i>08448){
    ...etc...

You can look up the blocks of Unicode by type here: http://unicode-table.com/en/ If you know you're translating Arabic or Telegu or whatever, you can just replace those codes, not all 65,000.

You could apply this same sledgehammer to simple encoding:

 $str=str_replace("\u$hex",chr($i),$str);

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

PHP XML Extension: Not installed

Had the same problem running PHP 7.2. I had to do the following :

sudo apt-get install php7.2-xml

What ports does RabbitMQ use?

Port Access

Firewalls and other security tools may prevent RabbitMQ from binding to a port. When that happens, RabbitMQ will fail to start. Make sure the following ports can be opened:

4369: epmd, a peer discovery service used by RabbitMQ nodes and CLI tools

5672, 5671: used by AMQP 0-9-1 and 1.0 clients without and with TLS

25672: used by Erlang distribution for inter-node and CLI tools communication and is allocated from a dynamic range (limited to a single port by default, computed as AMQP port + 20000). See networking guide for details.

15672: HTTP API clients and rabbitmqadmin (only if the management plugin is enabled)

61613, 61614: STOMP clients without and with TLS (only if the STOMP plugin is enabled)

1883, 8883: (MQTT clients without and with TLS, if the MQTT plugin is enabled

15674: STOMP-over-WebSockets clients (only if the Web STOMP plugin is enabled)

15675: MQTT-over-WebSockets clients (only if the Web MQTT plugin is enabled)

Reference doc: https://www.rabbitmq.com/install-windows-manual.html

Why should I prefer to use member initialization lists?

  1. Initialization of base class

One important reason for using constructor initializer list which is not mentioned in answers here is initialization of base class.

As per the order of construction, base class should be constructed before child class. Without constructor initializer list, this is possible if your base class has default constructor which will be called just before entering the constructor of child class.

But, if your base class has only parameterized constructor, then you must use constructor initializer list to ensure that your base class is initialized before child class.

  1. Initialization of Subobjects which only have parameterized constructors

  2. Efficiency

Using constructor initializer list, you initialize your data members to exact state which you need in your code rather than first initializing them to their default state & then changing their state to the one you need in your code.

  1. Initializing non-static const data members

If non-static const data members in your class have default constructors & you don't use constructor initializer list, you won't be able to initialize them to intended state as they will be initialized to their default state.

  1. Initialization of reference data members

Reference data members must be intialized when compiler enters constructor as references can't be just declared & initialized later. This is possible only with constructor initializer list.

How do I get the offset().top value of an element without using jQuery?

For Angular 2+ to get the offset of the current element (this.el.nativeElement is equvalent of $(this) in jquery):

export class MyComponent implements  OnInit {

constructor(private el: ElementRef) {}

    ngOnInit() {
      //This is the important line you can use in your function in the code
      //-------------------------------------------------------------------------- 
        let offset = this.el.nativeElement.getBoundingClientRect().top;
      //--------------------------------------------------------------------------    

        console.log(offset);
    }

}

How do I change the IntelliJ IDEA default JDK?

I am using IntelliJ 2020.3.1 and the File > Other Settings... menu option has disappeared. I went to Settings in the usual way and searched for "jdk". Under Build, Execution, Deployment > Build Tools > Maven > Importing I found the the setting that will solve my specific issue:

JDK for importer.

IntelliJ 2020.3 Settings dialog

What is "String args[]"? parameter in main method Java

I would break up

public static void main(String args[])

in parts.

"public" means that main() can be called from anywhere.

"static" means that main() doesn't belong to a specific object

"void" means that main() returns no value

"main" is the name of a function. main() is special because it is the start of the program.

"String[]" means an array of String.

"args" is the name of the String[] (within the body of main()). "args" is not special; you could name it anything else and the program would work the same.

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

JavaFX and OpenJDK

Try obuildfactory.

There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.

Until then enjoy, sir :)

JQuery show/hide when hover

('.cat').hover(
  function () {
    $(this).show();
  }, 
  function () {
    $(this).hide();
  }
);

It's the same for the others.

For the smooth fade in you can use fadeIn and fadeOut

Mysql: Select rows from a table that are not in another

Try this simple query. It works perfectly.

select * from Table1 where (FirstName,LastName,BirthDate) not in (select * from Table2);

Detecting a redirect in ajax request?

The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648

Finding what branch a Git commit came from

As an experiment, I made a post-commit hook that stores information about the currently checked out branch in the commit metadata. I also slightly modified gitk to show that information.

You can check it out here: https://github.com/pajp/branch-info-commits

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

For our application, we had a client server architecture and we only allowed decrypting/encrypting data in the server level. Hence the JCE files are only needed there.

We had another problem where we needed to update a security jar on the client machines, through JNLP, it overwrites the libraries in${java.home}/lib/security/ and the JVM on first run.

That made it work.

MongoDB: Combine data from multiple collections into one..how?

use multiple $lookup for multiple collections in aggregation

query:

db.getCollection('servicelocations').aggregate([
  {
    $match: {
      serviceLocationId: {
        $in: ["36728"]
      }
    }
  },
  {
    $lookup: {
      from: "orders",
      localField: "serviceLocationId",
      foreignField: "serviceLocationId",
      as: "orders"
    }
  },
  {
    $lookup: {
      from: "timewindowtypes",
      localField: "timeWindow.timeWindowTypeId",
      foreignField: "timeWindowTypeId",
      as: "timeWindow"
    }
  },
  {
    $lookup: {
      from: "servicetimetypes",
      localField: "serviceTimeTypeId",
      foreignField: "serviceTimeTypeId",
      as: "serviceTime"
    }
  },
  {
    $unwind: "$orders"
  },
  {
    $unwind: "$serviceTime"
  },
  {
    $limit: 14
  }
])

result:

{
    "_id" : ObjectId("59c3ac4bb7799c90ebb3279b"),
    "serviceLocationId" : "36728",
    "regionId" : 1.0,
    "zoneId" : "DXBZONE1",
    "description" : "AL HALLAB REST EMIRATES MALL",
    "locationPriority" : 1.0,
    "accountTypeId" : 1.0,
    "locationType" : "SERVICELOCATION",
    "location" : {
        "makani" : "",
        "lat" : 25.119035,
        "lng" : 55.198694
    },
    "deliveryDays" : "MTWRFSU",
    "timeWindow" : [ 
        {
            "_id" : ObjectId("59c3b0a3b7799c90ebb32cde"),
            "timeWindowTypeId" : "1",
            "Description" : "MORNING",
            "timeWindow" : {
                "openTime" : "06:00",
                "closeTime" : "08:00"
            },
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b0a3b7799c90ebb32cdf"),
            "timeWindowTypeId" : "1",
            "Description" : "MORNING",
            "timeWindow" : {
                "openTime" : "09:00",
                "closeTime" : "10:00"
            },
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b0a3b7799c90ebb32ce0"),
            "timeWindowTypeId" : "1",
            "Description" : "MORNING",
            "timeWindow" : {
                "openTime" : "10:30",
                "closeTime" : "11:30"
            },
            "accountId" : 1.0
        }
    ],
    "address1" : "",
    "address2" : "",
    "phone" : "",
    "city" : "",
    "county" : "",
    "state" : "",
    "country" : "",
    "zipcode" : "",
    "imageUrl" : "",
    "contact" : {
        "name" : "",
        "email" : ""
    },
    "status" : "ACTIVE",
    "createdBy" : "",
    "updatedBy" : "",
    "updateDate" : "",
    "accountId" : 1.0,
    "serviceTimeTypeId" : "1",
    "orders" : [ 
        {
            "_id" : ObjectId("59c3b291f251c77f15790f92"),
            "orderId" : "AQ18O1704264",
            "serviceLocationId" : "36728",
            "orderNo" : "AQ18O1704264",
            "orderDate" : "18-Sep-17",
            "description" : "AQ18O1704264",
            "serviceType" : "Delivery",
            "orderSource" : "Import",
            "takenBy" : "KARIM",
            "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
            "plannedDeliveryTime" : "",
            "actualDeliveryDate" : "",
            "actualDeliveryTime" : "",
            "deliveredBy" : "",
            "size1" : 296.0,
            "size2" : 3573.355,
            "size3" : 240.811,
            "jobPriority" : 1.0,
            "cancelReason" : "",
            "cancelDate" : "",
            "cancelBy" : "",
            "reasonCode" : "",
            "reasonText" : "",
            "status" : "",
            "lineItems" : [ 
                {
                    "ItemId" : "BNWB020",
                    "size1" : 15.0,
                    "size2" : 78.6,
                    "size3" : 6.0
                }, 
                {
                    "ItemId" : "BNWB021",
                    "size1" : 20.0,
                    "size2" : 252.0,
                    "size3" : 11.538
                }, 
                {
                    "ItemId" : "BNWB023",
                    "size1" : 15.0,
                    "size2" : 285.0,
                    "size3" : 16.071
                }, 
                {
                    "ItemId" : "CPMW112",
                    "size1" : 3.0,
                    "size2" : 25.38,
                    "size3" : 1.731
                }, 
                {
                    "ItemId" : "MMGW001",
                    "size1" : 25.0,
                    "size2" : 464.375,
                    "size3" : 46.875
                }, 
                {
                    "ItemId" : "MMNB218",
                    "size1" : 50.0,
                    "size2" : 920.0,
                    "size3" : 60.0
                }, 
                {
                    "ItemId" : "MMNB219",
                    "size1" : 50.0,
                    "size2" : 630.0,
                    "size3" : 40.0
                }, 
                {
                    "ItemId" : "MMNB220",
                    "size1" : 50.0,
                    "size2" : 416.0,
                    "size3" : 28.846
                }, 
                {
                    "ItemId" : "MMNB270",
                    "size1" : 50.0,
                    "size2" : 262.0,
                    "size3" : 20.0
                }, 
                {
                    "ItemId" : "MMNB302",
                    "size1" : 15.0,
                    "size2" : 195.0,
                    "size3" : 6.0
                }, 
                {
                    "ItemId" : "MMNB373",
                    "size1" : 3.0,
                    "size2" : 45.0,
                    "size3" : 3.75
                }
            ],
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b291f251c77f15790f9d"),
            "orderId" : "AQ137O1701240",
            "serviceLocationId" : "36728",
            "orderNo" : "AQ137O1701240",
            "orderDate" : "18-Sep-17",
            "description" : "AQ137O1701240",
            "serviceType" : "Delivery",
            "orderSource" : "Import",
            "takenBy" : "KARIM",
            "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
            "plannedDeliveryTime" : "",
            "actualDeliveryDate" : "",
            "actualDeliveryTime" : "",
            "deliveredBy" : "",
            "size1" : 28.0,
            "size2" : 520.11,
            "size3" : 52.5,
            "jobPriority" : 1.0,
            "cancelReason" : "",
            "cancelDate" : "",
            "cancelBy" : "",
            "reasonCode" : "",
            "reasonText" : "",
            "status" : "",
            "lineItems" : [ 
                {
                    "ItemId" : "MMGW001",
                    "size1" : 25.0,
                    "size2" : 464.38,
                    "size3" : 46.875
                }, 
                {
                    "ItemId" : "MMGW001-F1",
                    "size1" : 3.0,
                    "size2" : 55.73,
                    "size3" : 5.625
                }
            ],
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b291f251c77f15790fd8"),
            "orderId" : "AQ110O1705036",
            "serviceLocationId" : "36728",
            "orderNo" : "AQ110O1705036",
            "orderDate" : "18-Sep-17",
            "description" : "AQ110O1705036",
            "serviceType" : "Delivery",
            "orderSource" : "Import",
            "takenBy" : "KARIM",
            "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
            "plannedDeliveryTime" : "",
            "actualDeliveryDate" : "",
            "actualDeliveryTime" : "",
            "deliveredBy" : "",
            "size1" : 60.0,
            "size2" : 1046.0,
            "size3" : 68.0,
            "jobPriority" : 1.0,
            "cancelReason" : "",
            "cancelDate" : "",
            "cancelBy" : "",
            "reasonCode" : "",
            "reasonText" : "",
            "status" : "",
            "lineItems" : [ 
                {
                    "ItemId" : "MMNB218",
                    "size1" : 50.0,
                    "size2" : 920.0,
                    "size3" : 60.0
                }, 
                {
                    "ItemId" : "MMNB219",
                    "size1" : 10.0,
                    "size2" : 126.0,
                    "size3" : 8.0
                }
            ],
            "accountId" : 1.0
        }
    ],
    "serviceTime" : {
        "_id" : ObjectId("59c3b07cb7799c90ebb32cdc"),
        "serviceTimeTypeId" : "1",
        "serviceTimeType" : "nohelper",
        "description" : "",
        "fixedTime" : 30.0,
        "variableTime" : 0.0,
        "accountId" : 1.0
    }
}

PHPExcel Make first row bold

Try this

    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                 ->setLastModifiedBy("Maarten Balliauw")
                                 ->setTitle("Office 2007 XLSX Test Document")
                                 ->setSubject("Office 2007 XLSX Test Document")
                                 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                 ->setKeywords("office 2007 openxml php")
                                 ->setCategory("Test result file");
    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValue('A1', 'No');
    $sheet->setCellValue('B1', 'Job ID');
    $sheet->setCellValue('C1', 'Job completed Date');
    $sheet->setCellValue('D1', 'Job Archived Date');
    $styleArray = array(
        'font' => array(
        'bold' => true
        )
    );
    $sheet->getStyle('A1')->applyFromArray($styleArray);
    $sheet->getStyle('B1')->applyFromArray($styleArray);
    $sheet->getStyle('C1')->applyFromArray($styleArray);
    $sheet->getStyle('D1')->applyFromArray($styleArray);
    $sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
    

This is give me output like below link.(https://www.screencast.com/t/ZkKFHbDq1le)

Difference between wait and sleep

wait() is given inside a synchronized method whereas sleep() is given inside a non-synchronized method because wait() method release the lock on the object but sleep() or yield() does release the lock().

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists represent a sequential ordering of elements. Maps are used to represent a collection of key / value pairs.

While you could use a map as a list, there are some definite downsides of doing so.

Maintaining order: - A list by definition is ordered. You add items and then you are able to iterate back through the list in the order that you inserted the items. When you add items to a HashMap, you are not guaranteed to retrieve the items in the same order you put them in. There are subclasses of HashMap like LinkedHashMap that will maintain the order, but in general order is not guaranteed with a Map.

Key/Value semantics: - The purpose of a map is to store items based on a key that can be used to retrieve the item at a later point. Similar functionality can only be achieved with a list in the limited case where the key happens to be the position in the list.

Code readability Consider the following examples.

    // Adding to a List
    list.add(myObject);         // adds to the end of the list
    map.put(myKey, myObject);   // sure, you can do this, but what is myKey?
    map.put("1", myObject);     // you could use the position as a key but why?

    // Iterating through the items
    for (Object o : myList)           // nice and easy
    for (Object o : myMap.values())   // more code and the order is not guaranteed

Collection functionality Some great utility functions are available for lists via the Collections class. For example ...

    // Randomize the list
    Collections.shuffle(myList);

    // Sort the list
    Collections.sort(myList, myComparator);  

Hope this helps,

Understanding __get__ and __set__ and Python descriptors

I am trying to understand what Python's descriptors are and what they can be useful for.

Descriptors are class attributes (like properties or methods) with any of the following special methods:

  • __get__ (non-data descriptor method, for example on a method/function)
  • __set__ (data descriptor method, for example on a property instance)
  • __delete__ (data descriptor method)

These descriptor objects can be used as attributes on other object class definitions. (That is, they live in the __dict__ of the class object.)

Descriptor objects can be used to programmatically manage the results of a dotted lookup (e.g. foo.descriptor) in a normal expression, an assignment, and even a deletion.

Functions/methods, bound methods, property, classmethod, and staticmethod all use these special methods to control how they are accessed via the dotted lookup.

A data descriptor, like property, can allow for lazy evaluation of attributes based on a simpler state of the object, allowing instances to use less memory than if you precomputed each possible attribute.

Another data descriptor, a member_descriptor, created by __slots__, allow memory savings by allowing the class to store data in a mutable tuple-like datastructure instead of the more flexible but space-consuming __dict__.

Non-data descriptors, usually instance, class, and static methods, get their implicit first arguments (usually named cls and self, respectively) from their non-data descriptor method, __get__.

Most users of Python need to learn only the simple usage, and have no need to learn or understand the implementation of descriptors further.

In Depth: What Are Descriptors?

A descriptor is an object with any of the following methods (__get__, __set__, or __delete__), intended to be used via dotted-lookup as if it were a typical attribute of an instance. For an owner-object, obj_instance, with a descriptor object:

  • obj_instance.descriptor invokes
    descriptor.__get__(self, obj_instance, owner_class) returning a value
    This is how all methods and the get on a property work.

  • obj_instance.descriptor = value invokes
    descriptor.__set__(self, obj_instance, value) returning None
    This is how the setter on a property works.

  • del obj_instance.descriptor invokes
    descriptor.__delete__(self, obj_instance) returning None
    This is how the deleter on a property works.

obj_instance is the instance whose class contains the descriptor object's instance. self is the instance of the descriptor (probably just one for the class of the obj_instance)

To define this with code, an object is a descriptor if the set of its attributes intersects with any of the required attributes:

def has_descriptor_attrs(obj):
    return set(['__get__', '__set__', '__delete__']).intersection(dir(obj))

def is_descriptor(obj):
    """obj can be instance of descriptor or the descriptor class"""
    return bool(has_descriptor_attrs(obj))

A Data Descriptor has a __set__ and/or __delete__.
A Non-Data-Descriptor has neither __set__ nor __delete__.

def has_data_descriptor_attrs(obj):
    return set(['__set__', '__delete__']) & set(dir(obj))

def is_data_descriptor(obj):
    return bool(has_data_descriptor_attrs(obj))

Builtin Descriptor Object Examples:

  • classmethod
  • staticmethod
  • property
  • functions in general

Non-Data Descriptors

We can see that classmethod and staticmethod are Non-Data-Descriptors:

>>> is_descriptor(classmethod), is_data_descriptor(classmethod)
(True, False)
>>> is_descriptor(staticmethod), is_data_descriptor(staticmethod)
(True, False)

Both only have the __get__ method:

>>> has_descriptor_attrs(classmethod), has_descriptor_attrs(staticmethod)
(set(['__get__']), set(['__get__']))

Note that all functions are also Non-Data-Descriptors:

>>> def foo(): pass
... 
>>> is_descriptor(foo), is_data_descriptor(foo)
(True, False)

Data Descriptor, property

However, property is a Data-Descriptor:

>>> is_data_descriptor(property)
True
>>> has_descriptor_attrs(property)
set(['__set__', '__get__', '__delete__'])

Dotted Lookup Order

These are important distinctions, as they affect the lookup order for a dotted lookup.

obj_instance.attribute
  1. First the above looks to see if the attribute is a Data-Descriptor on the class of the instance,
  2. If not, it looks to see if the attribute is in the obj_instance's __dict__, then
  3. it finally falls back to a Non-Data-Descriptor.

The consequence of this lookup order is that Non-Data-Descriptors like functions/methods can be overridden by instances.

Recap and Next Steps

We have learned that descriptors are objects with any of __get__, __set__, or __delete__. These descriptor objects can be used as attributes on other object class definitions. Now we will look at how they are used, using your code as an example.


Analysis of Code from the Question

Here's your code, followed by your questions and answers to each:

class Celsius(object):
    def __init__(self, value=0.0):
        self.value = float(value)
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = float(value)

class Temperature(object):
    celsius = Celsius()
  1. Why do I need the descriptor class?

Your descriptor ensures you always have a float for this class attribute of Temperature, and that you can't use del to delete the attribute:

>>> t1 = Temperature()
>>> del t1.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __delete__

Otherwise, your descriptors ignore the owner-class and instances of the owner, instead, storing state in the descriptor. You could just as easily share state across all instances with a simple class attribute (so long as you always set it as a float to the class and never delete it, or are comfortable with users of your code doing so):

class Temperature(object):
    celsius = 0.0

This gets you exactly the same behavior as your example (see response to question 3 below), but uses a Pythons builtin (property), and would be considered more idiomatic:

class Temperature(object):
    _celsius = 0.0
    @property
    def celsius(self):
        return type(self)._celsius
    @celsius.setter
    def celsius(self, value):
        type(self)._celsius = float(value)
  1. What is instance and owner here? (in get). What is the purpose of these parameters?

instance is the instance of the owner that is calling the descriptor. The owner is the class in which the descriptor object is used to manage access to the data point. See the descriptions of the special methods that define descriptors next to the first paragraph of this answer for more descriptive variable names.

  1. How would I call/use this example?

Here's a demonstration:

>>> t1 = Temperature()
>>> t1.celsius
0.0
>>> t1.celsius = 1
>>> 
>>> t1.celsius
1.0
>>> t2 = Temperature()
>>> t2.celsius
1.0

You can't delete the attribute:

>>> del t2.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __delete__

And you can't assign a variable that can't be converted to a float:

>>> t1.celsius = '0x02'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __set__
ValueError: invalid literal for float(): 0x02

Otherwise, what you have here is a global state for all instances, that is managed by assigning to any instance.

The expected way that most experienced Python programmers would accomplish this outcome would be to use the property decorator, which makes use of the same descriptors under the hood, but brings the behavior into the implementation of the owner class (again, as defined above):

class Temperature(object):
    _celsius = 0.0
    @property
    def celsius(self):
        return type(self)._celsius
    @celsius.setter
    def celsius(self, value):
        type(self)._celsius = float(value)

Which has the exact same expected behavior of the original piece of code:

>>> t1 = Temperature()
>>> t2 = Temperature()
>>> t1.celsius
0.0
>>> t1.celsius = 1.0
>>> t2.celsius
1.0
>>> del t1.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't delete attribute
>>> t1.celsius = '0x02'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in celsius
ValueError: invalid literal for float(): 0x02

Conclusion

We've covered the attributes that define descriptors, the difference between data- and non-data-descriptors, builtin objects that use them, and specific questions about use.

So again, how would you use the question's example? I hope you wouldn't. I hope you would start with my first suggestion (a simple class attribute) and move on to the second suggestion (the property decorator) if you feel it is necessary.

How to pass all arguments passed to my bash script to a function of mine?

Here's a simple script:

#!/bin/bash

args=("$@")

echo Number of arguments: $#
echo 1st argument: ${args[0]}
echo 2nd argument: ${args[1]}

$# is the number of arguments received by the script. I find easier to access them using an array: the args=("$@") line puts all the arguments in the args array. To access them use ${args[index]}.

Error: Jump to case label

Declaration of new variables in case statements is what causing problems. Enclosing all case statements in {} will limit the scope of newly declared variables to the currently executing case which solves the problem.

switch(choice)
{
    case 1: {
       // .......
    }break;
    case 2: {
       // .......
    }break;
    case 3: {
       // .......
    }break;
}    

How to restrict user to type 10 digit numbers in input element?

Add a maxlength attribute to your input.

<input type="text" id="phone" name="phone" maxlength="10">

See this working example on JSFiddle.

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

Container is running beyond memory limits

I haven't personally checked, but hadoop-yarn-container-virtual-memory-understanding-and-solving-container-is-running-beyond-virtual-memory-limits-errors sounds very reasonable

I solved the issue by changing yarn.nodemanager.vmem-pmem-ratio to a higher value , and I would agree that:

Another less recommended solution is to disable the virtual memory check by setting yarn.nodemanager.vmem-check-enabled to false.

What's the environment variable for the path to the desktop?

you could also open a DOS command prompt and execute the set command.

This will give you an idea what environment variables are available on your system.

E.g. - since you where specifically asking for a non-english Windows - heres is an example of my own German Edition (Window7-64bit) :

set > env.txt
type env.txt

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\SOF\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=VMSOF
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\SOF
LOCALAPPDATA=C:\Users\SOF\AppData\Local
LOGONSERVER=\\VMSOF
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\CMake 2.8\bin;C:\Program Files (x86)\emacs-22.3\bin;C:\Program Files (x86)\GnuWin32\bin;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 15 Model 67 Stepping 3, AuthenticAMD
PROCESSOR_LEVEL=15
PROCESSOR_REVISION=4303
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\SOF\AppData\Local\Temp
TMP=C:\Users\SOF\AppData\Local\Temp
USERDOMAIN=VMSOF
USERNAME=SOF
USERPROFILE=C:\Users\SOF
VBOX_INSTALL_PATH=C:\Program Files\Sun\VirtualBox\
VS90COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
windir=C:\Windows

Get day of week in SQL Server 2005/2008

With SQL Server 2012 and onward you can use the FORMAT function

SELECT FORMAT(GETDATE(), 'dddd')

Finish an activity from another activity

I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me

I overrode onPause and called finish() inside that method.

How can I remount my Android/system as read-write in a bash script using adb?

In addition to all the other answers you received, I want to explain the unknown option -- o error: Your command was

$ adb shell 'su -c  mount -o rw,remount /system'

which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell. However, su -c <cmd> also needs you to quote the command with arguments it shall pass to the shell's -c option. (YMMV depending on su variants.) Therefore, you might want to try

$ adb shell 'su -c "mount -o rw,remount /system"'

(and potentially add the actual device listed in the output of mount | grep system before the /system arg – see the other answers.)