Programs & Examples On #Sendinput

Synthesizes keystrokes, mouse motions, and button clicks.

Best approach to remove time part of datetime in SQL Server

I would use:

CAST
(
CAST(YEAR(DATEFIELD) as varchar(4)) + '/' CAST(MM(DATEFIELD) as varchar(2)) + '/' CAST(DD(DATEFIELD) as varchar(2)) as datetime
) 

Thus effectively creating a new field from the date field you already have.

What is a LAMP stack?

Linux operating system

Apache web server

MySQL database

and PHP

Reference: LAMP (software bundle)

The "stack" term means stack! That means if you have experience in working with these technologies/framework or not. Since all these come together in a LAMP package, which you can download and install, they call it a stack.

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

How to write a large buffer into a binary file in C++, fast?

I'd suggest trying file mapping. I used mmapin the past, in a UNIX environment, and I was impressed by the high performance I could achieve

How to change color of Toolbar back button in Android?

You can add this code into your java class. But you must create a vector asset before, so you can customize your arrow back.

actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);

Session timeout in ASP.NET

Do you have anything in machine.config that might be taking effect? Setting the session timeout in web.config should override any settings in IIS or machine.config, however, if you have a web.config file somewhere in a subfolder in your application, that setting will override the one in the root of your application.

Also, if I remember correctly, the timeout in IIS only affects .asp pages, not .aspx. Are you sure your session code in web.config is correct? It should look something like:

<sessionState
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    stateNetworkTimeout="60"
    sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
    cookieless="false"
    timeout="60"
/>

How does the Python's range function work?

When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:

for eachItem in someList:
    doSomething(eachItem)

... which, conveniently enough, is syntactically valid Python code.

The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).

So range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).

A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9

A call to range(2,12,3) would return: 2, 5, 8, 11

Notice that I said, a couple times, that Python's range() function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break" out of the loop early (after finding some particular item in which you were interested, for example).

Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.

The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."

Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.

For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators. You can just use it and be happy.

If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python. In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.

Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).

[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].

Make a phone call programmatically

Swift

if let url = NSURL(string: "tel://\(number)"), 
    UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

If you are using Samsung Device and by any chance marked your app for Samsung Knox, then you need to uninstall it from My Knox app.

Uninstalling just from General apps won't uninstall it from Knox App. It has to be done explicitly!

Ship an application with a database

Currently there is no way to precreate an SQLite database to ship with your apk. The best you can do is save the appropriate SQL as a resource and run them from your application. Yes, this leads to duplication of data (same information exists as a resrouce and as a database) but there is no other way right now. The only mitigating factor is the apk file is compressed. My experience is 908KB compresses to less than 268KB.

The thread below has the best discussion/solution I have found with good sample code.

http://groups.google.com/group/android-developers/msg/9f455ae93a1cf152

I stored my CREATE statement as a string resource to be read with Context.getString() and ran it with SQLiteDatabse.execSQL().

I stored the data for my inserts in res/raw/inserts.sql (I created the sql file, 7000+ lines). Using the technique from the link above I entered a loop, read the file line by line and concactenated the data onto "INSERT INTO tbl VALUE " and did another SQLiteDatabase.execSQL(). No sense in saving 7000 "INSERT INTO tbl VALUE "s when they can just be concactenated on.

It takes about twenty seconds on the emulator, I do not know how long this would take on a real phone, but it only happens once, when the user first starts the application.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

Passing string to a function in C - with or without pointers?

An array is a pointer. It points to the start of a sequence of "objects".

If we do this: ìnt arr[10];, then arr is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];.

How to exclude 0 from MIN formula Excel

All you have to do is to delete the "0" in the cells that contain just that and try again. That should work.

Simplest way to read json from a URL in java

I have found this to be the easiest way by far.

Use this method:

public static String getJSON(String url) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            return sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

And use it like this:

String json = getJSON(url);
JSONObject obj;
   try {
         obj = new JSONObject(json);
         JSONArray results_arr = obj.getJSONArray("results");
         final int n = results_arr.length();
            for (int i = 0; i < n; ++i) {
                // get the place id of each object in JSON (Google Search API)
                String place_id = results_arr.getJSONObject(i).getString("place_id");
            }


   }

Class has been compiled by a more recent version of the Java Environment

You can try this way

javac --release 8 yourClass.java

How to select rows from a DataFrame based on column values

Here is a simple example

from pandas import DataFrame

# Create data set
d = {'Revenue':[100,111,222], 
     'Cost':[333,444,555]}
df = DataFrame(d)


# mask = Return True when the value in column "Revenue" is equal to 111
mask = df['Revenue'] == 111

print mask

# Result:
# 0    False
# 1     True
# 2    False
# Name: Revenue, dtype: bool


# Select * FROM df WHERE Revenue = 111
df[mask]

# Result:
#    Cost    Revenue
# 1  444     111

Add/Delete table rows dynamically using JavaScript

You could just clone the first row that has the inputs, then get the nested inputs and update their ID to add the row number (and do the same with the first cell).

function deleteRow(row)
{
    var i=row.parentNode.parentNode.rowIndex;
    document.getElementById('POITable').deleteRow(i);
}


function insRow()
{
    var x=document.getElementById('POITable');
       // deep clone the targeted row
    var new_row = x.rows[1].cloneNode(true);
       // get the total number of rows
    var len = x.rows.length;
       // set the innerHTML of the first row 
    new_row.cells[0].innerHTML = len;

       // grab the input from the first cell and update its ID and value
    var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
    inp1.id += len;
    inp1.value = '';

       // grab the input from the first cell and update its ID and value
    var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
    inp2.id += len;
    inp2.value = '';

       // append the new row to the table
    x.appendChild( new_row );
}

Demo below

_x000D_
_x000D_
function deleteRow(row) {_x000D_
  var i = row.parentNode.parentNode.rowIndex;_x000D_
  document.getElementById('POITable').deleteRow(i);_x000D_
}_x000D_
_x000D_
_x000D_
function insRow() {_x000D_
  console.log('hi');_x000D_
  var x = document.getElementById('POITable');_x000D_
  var new_row = x.rows[1].cloneNode(true);_x000D_
  var len = x.rows.length;_x000D_
  new_row.cells[0].innerHTML = len;_x000D_
_x000D_
  var inp1 = new_row.cells[1].getElementsByTagName('input')[0];_x000D_
  inp1.id += len;_x000D_
  inp1.value = '';_x000D_
  var inp2 = new_row.cells[2].getElementsByTagName('input')[0];_x000D_
  inp2.id += len;_x000D_
  inp2.value = '';_x000D_
  x.appendChild(new_row);_x000D_
}
_x000D_
<div id="POItablediv">_x000D_
  <input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/>_x000D_
  <table id="POITable" border="1">_x000D_
    <tr>_x000D_
      <td>POI</td>_x000D_
      <td>Latitude</td>_x000D_
      <td>Longitude</td>_x000D_
      <td>Delete?</td>_x000D_
      <td>Add Rows?</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td><input size=25 type="text" id="latbox" /></td>_x000D_
      <td><input size=25 type="text" id="lngbox" readonly=true/></td>_x000D_
      <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>_x000D_
      <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td>_x000D_
    </tr>_x000D_
  </table>
_x000D_
_x000D_
_x000D_

JQuery wait for page to finish loading before starting the slideshow?

you can try

$(function()
{

$(window).bind('load', function()
{

// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...

});
});

i had the same problem and this code worked for me. how it works for you too!

How to get indices of a sorted array in Python

myList = [1, 2, 3, 100, 5]    
sorted(range(len(myList)),key=myList.__getitem__)

[0, 1, 2, 4, 3]

How to get the sign, mantissa and exponent of a floating point number

  1. Don't make functions that do multiple things.
  2. Don't mask then shift; shift then mask.
  3. Don't mutate values unnecessarily because it's slow, cache-destroying and error-prone.
  4. Don't use magic numbers.
/* NaNs, infinities, denormals unhandled */
/* assumes sizeof(float) == 4 and uses ieee754 binary32 format */
/* assumes two's-complement machine */
/* C99 */
#include <stdint.h>

#define SIGN(f) (((f) <= -0.0) ? 1 : 0)

#define AS_U32(f) (*(const uint32_t*)&(f))
#define FLOAT_EXPONENT_WIDTH 8
#define FLOAT_MANTISSA_WIDTH 23
#define FLOAT_BIAS ((1<<(FLOAT_EXPONENT_WIDTH-1))-1) /* 2^(e-1)-1 */
#define MASK(width)  ((1<<(width))-1) /* 2^w - 1 */
#define FLOAT_IMPLICIT_MANTISSA_BIT (1<<FLOAT_MANTISSA_WIDTH)

/* correct exponent with bias removed */
int float_exponent(float f) {
  return (int)((AS_U32(f) >> FLOAT_MANTISSA_WIDTH) & MASK(FLOAT_EXPONENT_WIDTH)) - FLOAT_BIAS;
}

/* of non-zero, normal floats only */
int float_mantissa(float f) {
  return (int)(AS_U32(f) & MASK(FLOAT_MANTISSA_BITS)) | FLOAT_IMPLICIT_MANTISSA_BIT;
}

/* Hacker's Delight book is your friend. */

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

Converting dict to OrderedDict

You are creating a dictionary first, then passing that dictionary to an OrderedDict. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict is inherently not ordered.

Pass in a sequence of tuples instead:

ship = [("NAME", "Albatross"),
        ("HP", 50),
        ("BLASTERS", 13),
        ("THRUSTERS", 18),
        ("PRICE", 250)]
ship = collections.OrderedDict(ship)

What you see when you print the OrderedDict is it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)]) just shows you, in a reproducable representation, what the contents are of the OrderedDict.


(*): In the CPython 3.6 implementation, the dict type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict() for certain cases.

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get file URL using Storage facade in laravel 5?

First get file url/link then path, as below:

$url = Storage::disk('public')->url($filename);
$path = public_path($url);

Set value of hidden input with jquery

var test = $('input[name="testing"]:hidden');
test.val('work!');

How to repeat a char using printf?

If you have a compiler that supports the alloca() function, then this is possible solution (quite ugly though):

printf("%s", (char*)memset(memset(alloca(10), '\0', 10), 'x', 9));

It basically allocates 10 bytes on the stack which are filled with '\0' and then the first 9 bytes are filled with 'x'.

If you have a C99 compiler, then this might be a neater solution:

for (int i = 0;  i < 10;  i++, printf("%c", 'x'));

jQuery checkbox onChange

$('input[type=checkbox]').change(function () {
    alert('changed');
});

Add newline to VBA or Visual Basic 6

There are actually two ways of doing this:

  1. st = "Line 1" + vbCrLf + "Line 2"

  2. st = "Line 1" + vbNewLine + "Line 2"

These even work for message boxes (and all other places where strings are used).

How to align input forms in HTML

css I used to solve this problem, similar to Gjaa but styled better

p
{
    text-align:center;
        }
.styleform label
{
    float:left;
    width: 40%;
    text-align:right;
    }
.styleform input
{
    float:left;
    width: 30%;
    }

Here is my HTML, used specifically for a simple registration form with no php code

<form id="registration">
    <h1>Register</h1>
    <div class="styleform">
    <fieldset id="inputs">
        <p><label>Name:</label> 
          <input id="name" type="text" placeholder="Name" autofocus required>
        </p>
        <p><label>Email:</label>   
          <input id="email" type="text" placeholder="Email Address" required>
        </p>
        <p><label>Username:</label>
          <input id="username" type="text" placeholder="Username" autofocus required>
        </p>
        <p>   
          <label>Password:</label>
          <input id="password" type="password" placeholder="Password" required>
        </p>
    </fieldset>
    <fieldset id="actions">

    </fieldset>
    </div>
    <p>
          <input type="submit" id="submit" value="Register">
          </p>

It's very simple, and I'm just beginning, but it worked quite nicely

cleanest way to skip a foreach if array is empty

Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.

foreach (is_array($Items) || is_object($Items) ? $Items : array()  as $Item) {

It is a bit of a pain to write, but is the safest way to handle it.

Insert data using Entity Framework model

I'm using EF6, and I find something strange,

Suppose Customer has constructor with parameter ,

if I use new Customer(id, "name"), and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name") );
    db.SaveChanges();
 }

It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,

But if I add the curly brackets, use new Customer(id, "name"){} and do

 using (var db = new EfContext("name=EfSample"))
 {
    db.Customers.Add( new Customer(id, "name"){} );
    db.SaveChanges();
 }

the data will then actually BE Inserted,

seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

In case you came to this question but related to newer Angular version >= 2.0.

<div [id]="element.id"></div>

How do I kill a process using Vb.NET or C#?

You can bypass the security concerns, and create a much politer application by simply checking if the Word process is running, and asking the user to close it, then click a 'Continue' button in your app. This is the approach taken by many installers.

private bool isWordRunning() 
{
    return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0;
}

Of course, you can only do this if your app has a GUI

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

String contains another two strings

With the code d.Contains(b + a) you check if "You hit someone for 50 damage" contains "someonedamage". And this (i guess) you don't want.

The + concats the two string of b and a.

You have to check it by

if(d.Contains(b) && d.Contains(a))

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

I had the same error on my Angular6 project. none of those solutions seemed to work out for me. turned out that the problem was due to an element which was specified as dropdown but it didn't have dropdown options in it. take a look at code below:

<span class="nav-link" id="navbarDropdownMenuLink" data-toggle="dropdown"
                          aria-haspopup="true" aria-expanded="false">
                        <i class="material-icons "
                           style="font-size: 2rem">notifications</i>
                        <span class="notification"></span>
                        <p>
                            <span class="d-lg-none d-md-block">Some Actions</span>
                        </p>
                    </span>
                    <div class="dropdown-menu dropdown-menu-left"
                         *ngIf="global.localStorageItem('isInSadHich')"
                         aria-labelledby="navbarDropdownMenuLink">
                                        <a class="dropdown-item" href="#">You have 5 new tasks</a>
                                        <a class="dropdown-item" href="#">You're now friend with Andrew</a>
                                        <a class="dropdown-item" href="#">Another Notification</a>
                                        <a class="dropdown-item" href="#">Another One</a>
                    </div>

removing the code data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" solved the problem.

I myself think that by each click on the first span element, the scope expected to set style for dropdown children which did not existed in the parent span, so it threw error.

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

Passing just a type as a parameter in C#

There are two common approaches. First, you can pass System.Type

object GetColumnValue(string columnName, Type type)
{
    // Here, you can check specific types, as needed:

    if (type == typeof(int)) { // ...

This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));

The other option would be to use generics:

T GetColumnValue<T>(string columnName)
{
    // If you need the type, you can use typeof(T)...

This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);

Converting string to Date and DateTime

You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

That way you are not at the whims of a certain interpretation.

DOM element to corresponding vue.js component

Exactly what Kamil said,

element = this.$el

But make sure you don't have fragment instances.

PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

Error: Unexpected value 'undefined' imported by the module

For me the problem was solved by changing the import sequence :

One with I got the error :

imports: [ 
 BrowserModule, HttpClientModule, AppRoutingModule, 
 CommonModule
],

Changed this to :

   imports: [
    BrowserModule, CommonModule, HttpClientModule,
    AppRoutingModule
  ],

How to write to files using utl_file in oracle

Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.

PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS

              vLine VARCHAR2(30000);
              vFile UTL_FILE.file_type; 
              vExists boolean;
              vLength number;
              vBlockSize number;
    BEGIN

        UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);

                 FETCH p_Input INTO vLine;
         IF p_input%ROWCOUNT > 0
         THEN
            IF vExists THEN
               vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
            ELSE
               --even if the append flag is passed if the file doesn't exist open it with W.
                vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
            END IF;
            --GET HANDLE TO FILE
            IF p_Header IS NOT NULL THEN 
              UTL_FILE.PUT_LINE(vFile, p_Header);
            END IF;
            UTL_FILE.PUT_LINE(vFile, vLine);
            DBMS_OUTPUT.PUT_LINE('Record count > 0');

             --LOOP THROUGH CURSOR VAR
             LOOP
                FETCH p_Input INTO vLine;

                EXIT WHEN p_Input%NOTFOUND;

                UTL_FILE.PUT_LINE(vFile, vLine);

             END LOOP;


             IF p_Footer IS NOT NULL THEN 
                UTL_FILE.PUT_LINE(vFile, p_Footer);
             END IF;

             CLOSE p_Input;
             UTL_FILE.FCLOSE(vFile);
        ELSE
          DBMS_OUTPUT.PUT_LINE('Record count = 0');

        END IF; 


    EXCEPTION
       WHEN UTL_FILE.INVALID_PATH THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_path'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_MODE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_mode'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_FILEHANDLE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_filehandle'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_OPERATION THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_operation'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.READ_ERROR THEN  
           DBMS_OUTPUT.PUT_LINE ('read_error');
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.WRITE_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('write_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INTERNAL_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('internal_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;            
       WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE ('other write error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;
    END;

What's the easiest way to install a missing Perl module?

Otto made a good suggestion. This works for Debian too, as well as any other Debian derivative. The missing piece is what to do when apt-cache search doesn't find something.

$ sudo apt-get install dh-make-perl build-essential apt-file
$ sudo apt-file update

Then whenever you have a random module you wish to install:

$ cd ~/some/path
$ dh-make-perl --build --cpan Some::Random::Module
$ sudo dpkg -i libsome-random-module-perl-0.01-1_i386.deb

This will give you a deb package that you can install to get Some::Random::Module. One of the big benefits here is man pages and sample scripts in addition to the module itself will be placed in your distro's location of choice. If the distro ever comes out with an official package for a newer version of Some::Random::Module, it will automatically be installed when you apt-get upgrade.

Why the switch statement cannot be applied on strings?

In C++ and C switches only work on integer types. Use an if else ladder instead. C++ could obviously have implemented some sort of swich statement for strings - I guess nobody thought it worthwhile, and I agree with them.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

How do I center a window onscreen in C#?

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

Run a mySQL query as a cron job?

This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.

I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.

I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.

So I turned to embedding the SQL script in a PHP file. I used the example [here][1]

[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.

All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.

my cron is set to run once per day and looks like this, modified for security.

00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php

For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.

Hope this helps.

What is "X-Content-Type-Options=nosniff"?

Prevent content sniffing where no mimetype is sent

Configuration on Ubuntu 20.04 - apache 2.4.41:

Enable the headers module $ sudo a2enmod headers

Edit file /etc/apache2/conf-available/security.conf and add:

Header always set X-Content-Type-Options: nosniff

Restart Apache $ sudo systemctl restart apache2

$ culr -I localhost

HTTP/1.1 200 OK
Date: Fri, 23 Oct 2020 06:12:16 GMT
Server:  
X-Content-Type-Options: nosniff
Last-Modified: Thu, 22 Oct 2020 08:06:06 GMT

CSS performance relative to translateZ(0)

If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg); worked just fine.

I don't believe we ever figured out why.

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

AngularJS routing without the hash '#'

In Angular 6, with your router you can use:

RouterModule.forRoot(routes, { useHash: false })

java.net.UnknownHostException: Invalid hostname for server: local

I was having the same issue on my mac. I found the issue when I pinged my $HOSTNAME from terminal and it returned ping: cannot resolve myHostName: Unknown host.

To resolve:

  1. Do echo $HOSTNAME on your terminal.
  2. Whatever hostname it shows (lets say myHostName), try to ping it : ping myHostName. If it returns ping: cannot resolve myHostName: Unknown host then add an entry into your /etc/hosts file.
  3. For that edit /etc/hosts file and add following:

    127.0.0.1 myHostName

Hope it helps.

Static class initializer in PHP

Sounds like you'd be better served by a singleton rather than a bunch of static methods

class Singleton
{
  /**
   * 
   * @var Singleton
   */
  private static $instance;

  private function __construct()
  {
    // Your "heavy" initialization stuff here
  }

  public static function getInstance()
  {
    if ( is_null( self::$instance ) )
    {
      self::$instance = new self();
    }
    return self::$instance;
  }

  public function someMethod1()
  {
    // whatever
  }

  public function someMethod2()
  {
    // whatever
  }
}

And then, in usage

// As opposed to this
Singleton::someMethod1();

// You'd do this
Singleton::getInstance()->someMethod1();

jQuery DataTables: control table width

Well, I'm not familiar with that plugin, but could you reset the style after adding the datatable? Something like

$("#querydatatablesets").css("width","100%")

after the .dataTable call?

How to make picturebox transparent?

I've had a similar problem like this. You can not make Transparent picturebox easily such as picture that shown at top of this page, because .NET Framework and VS .NET objects are created by INHERITANCE! (Use Parent Property).

I solved this problem by RectangleShape and with the below code I removed background, if difference between PictureBox and RectangleShape is not important and doesn't matter, you can use RectangleShape easily.

private void CreateBox(int X, int Y, int ObjectType)
{
    ShapeContainer canvas = new ShapeContainer();
    RectangleShape box = new RectangleShape();
    box.Parent = canvas;
    box.Size = new System.Drawing.Size(100, 90);
    box.Location = new System.Drawing.Point(X, Y);
    box.Name = "Box" + ObjectType.ToString();
    box.BackColor = Color.Transparent;
    box.BorderColor = Color.Transparent;
    box.BackgroundImage = img.Images[ObjectType];// Load from imageBox Or any resource
    box.BackgroundImageLayout = ImageLayout.Stretch;
    box.BorderWidth = 0;
    canvas.Controls.Add(box);   // For feature use 
}

jQuery: how to trigger anchor link's click event

You cannot open in a new tab programmatically, it's a browser functionality. You can open a link in an external window . Have a look here

Can Google Chrome open local links?

Hopefully this helps others in an enterprise setting looking for a solution. My solution after much tinkering was the following:

Follow the steps in the following link to install legacy browser extension and gpo settings: https://support.google.com/chrome/a/answer/3019558?hl=en&ref_topic=3062034

Enabled legacy browser redirect for "file://" through chrome gpo configuration Google Chrome -> Legacy Browser Support -> "Websites to open in alternative browser"

Configure gpo to also install extension: https://chrome.google.com/webstore/detail/enable-local-file-links/nikfmfgobenbhmocjaaboihbeocackld that redirects file:// links to bypass chrome file:// link block.

The extension opens the links which then triggers google chrome to open the link in internet explorer. The result is IE opens a window, then opens the file/folder for the user, then IE closes itself.

R Apply() function on specific dataframe columns

lapply is probably a better choice than apply here, as apply first coerces your data.frame to an array which means all the columns must have the same type. Depending on your context, this could have unintended consequences.

The pattern is:

df[cols] <- lapply(df[cols], FUN)

The 'cols' vector can be variable names or indices. I prefer to use names whenever possible (it's robust to column reordering). So in your case this might be:

wifi[4:9] <- lapply(wifi[4:9], A)

An example of using column names:

wifi <- data.frame(A=1:4, B=runif(4), C=5:8)
wifi[c("B", "C")] <- lapply(wifi[c("B", "C")], function(x) -1 * x)

How to copy and paste code without rich text formatting?

I usually work with Notepad2, all the text I copy from the web are pasted there and then reused, that allows me to clean it (from format and make modifications).

You can download Notepad2 here

CSS - center two images in css side by side

You can't have two elements with the same ID.

Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.

Instead, try something like this:

<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>

CSS:

.link {
    width: 50%;
    float: left;
    text-align: center;
}

Find the number of columns in a table

It's working (mysql) :

SELECT TABLE_NAME , count(COLUMN_NAME)
FROM information_schema.columns
GROUP BY TABLE_NAME 

How to generate an MD5 file hash in JavaScript?

CryptoJS is a crypto library which can generate md5 hash among others:

Usage with Script tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
<script>
   var hash = CryptoJS.MD5("Message");
   alert(hash);
</script>

Alternatively with ES6:

npm install crypto-js

import MD5 from "crypto-js/md5";
console.log(MD5("Message").toString());

You can also use modular imports:

var MD5 = require("crypto-js/md5");
console.log(MD5("Message").toString());

Github: https://github.com/brix/crypto-js

CDN: https://cdnjs.com/libraries/crypto-js

How to output in CLI during execution of PHP Unit tests?

UPDATE

Just realized another way to do this that works much better than the --verbose command line option:

class TestSomething extends PHPUnit_Framework_TestCase {
    function testSomething() {
        $myDebugVar = array(1, 2, 3);
        fwrite(STDERR, print_r($myDebugVar, TRUE));
    }
}

This lets you dump anything to your console at any time without all the unwanted output that comes along with the --verbose CLI option.


As other answers have noted, it's best to test output using the built-in methods like:

$this->expectOutputString('foo');

However, sometimes it's helpful to be naughty and see one-off/temporary debugging output from within your test cases. There is no need for the var_dump hack/workaround, though. This can easily be accomplished by setting the --verbose command line option when running your test suite. For example:

$ phpunit --verbose -c phpunit.xml

This will display output from inside your test methods when running in the CLI environment.

See: Writing Tests for PHPUnit - Testing Output.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Neither one of the solutions worked form me. The only one that worked for me in Spring form is:

action="./upload?${_csrf.parameterName}=${_csrf.token}"

REPLACED WITH:

action="./upload?_csrf=${_csrf.token}"

(Spring 5 with enabled csrf in java configuration)

configuring project ':app' failed to find Build Tools revision

also try to increase gradle version in your project's build.gradle. It helped me

Pycharm does not show plot

Change import to:

import matplotlib.pyplot as plt

or use this line:

plt.pyplot.show()

Format date in a specific timezone

I was having the same issue with Moment.js. I've installed moment-timezone, but the issue wasn't resolved. Then, I did just what here it's exposed, set the timezone and it works like a charm:

moment(new Date({your_date})).zone("+08:00")

Thanks a lot!

Extract file name from path, no matter what the os/path format

If you have a number of files in a directory and want to store those file names into a list. Use the below code.

import os as os
import glob as glob
path = 'mypath'
file_list= []
for file in glob.glob(path):
    data_file_list = os.path.basename(file)
    file_list.append(data_file_list)

How to get Django and ReactJS to work together?

As others answered you, if you are creating a new project, you can separate frontend and backend and use any django rest plugin to create rest api for your frontend application. This is in the ideal world.

If you have a project with the django templating already in place, then you must load your react dom render in the page you want to load the application. In my case I had already django-pipeline and I just added the browserify extension. (https://github.com/j0hnsmith/django-pipeline-browserify)

As in the example, I loaded the app using django-pipeline:

PIPELINE = {
    # ...
    'javascript':{
        'browserify': {
            'source_filenames' : (
                'js/entry-point.browserify.js',
            ),
            'output_filename': 'js/entry-point.js',
        },
    }
}

Your "entry-point.browserify.js" can be an ES6 file that loads your react app in the template:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app.js';
import "babel-polyfill";

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise';
import reducers from './reducers/index.js';

const createStoreWithMiddleware = applyMiddleware(
  promise
)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App/>
  </Provider>
  , document.getElementById('my-react-app')
);

In your django template, you can now load your app easily:

{% load pipeline %}

{% comment %} 
`browserify` is a PIPELINE key setup in the settings for django 
 pipeline. See the example above
{% endcomment %}

{% javascript 'browserify' %}

{% comment %} 
the app will be loaded here thanks to the entry point you created 
in PIPELINE settings. The key is the `entry-point.browserify.js` 
responsable to inject with ReactDOM.render() you react app in the div 
below
{% endcomment %}
<div id="my-react-app"></div>

The advantage of using django-pipeline is that statics get processed during the collectstatic.

FirstOrDefault: Default value other than null

Use DefaultIfEmpty() instead of FirstOrDefault().

No resource found - Theme.AppCompat.Light.DarkActionBar

In my case, I took an android project from one computer to another and had this problem. What worked for me was a combination of some of the answers I've seen:

  • Remove the copy of the appcompat library that was in the libs folder of the workspace
  • Install sdk 21
  • Change the project properties to use that sdk build enter image description here
  • Set up and start an emulator compatible with sdks 21
  • Update the Run Configuration to prompt for device to run on & choose Run

Mine ran fine after these steps.

json_decode returns NULL after webservice call

i had a similar problem, got it to work after adding '' (single quotes) around the json_encode string. Following from my js file:

var myJsVar  = <?php echo json_encode($var); ?> ;    -------> NOT WORKING  
var myJsVar = '<?php echo json_encode($var); ?>' ;    -------> WORKING

just thought of posting it in case someone stumbles upon this post like me :)

Check if a string matches a regex in Bash script

I would use expr match instead of =~:

expr match "$date" "[0-9]\{8\}" >/dev/null && echo yes

This is better than the currently accepted answer of using =~ because =~ will also match empty strings, which IMHO it shouldn't. Suppose badvar is not defined, then [[ "1234" =~ "$badvar" ]]; echo $? gives (incorrectly) 0, while expr match "1234" "$badvar" >/dev/null ; echo $? gives correct result 1.

We have to use >/dev/null to hide expr match's output value, which is the number of characters matched or 0 if no match found. Note its output value is different from its exit status. The exit status is 0 if there's a match found, or 1 otherwise.

Generally, the syntax for expr is:

expr match "$string" "$lead"

Or:

expr "$string" : "$lead"

where $lead is a regular expression. Its exit status will be true (0) if lead matches the leading slice of string (Is there a name for this?). For example expr match "abcdefghi" "abc"exits true, but expr match "abcdefghi" "bcd" exits false. (Credit to @Carlo Wood for pointing out this.

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

Difference between objectForKey and valueForKey?

I'll try to provide a comprehensive answer here. Much of the points appear in other answers, but I found each answer incomplete, and some incorrect.

First and foremost, objectForKey: is an NSDictionary method, while valueForKey: is a KVC protocol method required of any KVC complaint class - including NSDictionary.

Furthermore, as @dreamlax wrote, documentation hints that NSDictionary implements its valueForKey: method USING its objectForKey: implementation. In other words - [NSDictionary valueForKey:] calls on [NSDictionary objectForKey:].

This implies, that valueForKey: can never be faster than objectForKey: (on the same input key) although thorough testing I've done imply about 5% to 15% difference, over billions of random access to a huge NSDictionary. In normal situations - the difference is negligible.

Next: KVC protocol only works with NSString * keys, hence valueForKey: will only accept an NSString * (or subclass) as key, whilst NSDictionary can work with other kinds of objects as keys - so that the "lower level" objectForKey: accepts any copy-able (NSCopying protocol compliant) object as key.

Last, NSDictionary's implementation of valueForKey: deviates from the standard behavior defined in KVC's documentation, and will NOT emit a NSUnknownKeyException for a key it can't find - unless this is a "special" key - one that begins with '@' - which usually means an "aggregation" function key (e.g. @"@sum, @"@avg"). Instead, it will simply return a nil when a key is not found in the NSDictionary - behaving the same as objectForKey:

Following is some test code to demonstrate and prove my notes.

- (void) dictionaryAccess {
    NSLog(@"Value for Z:%@", [@{@"X":@(10), @"Y":@(20)} valueForKey:@"Z"]); // prints "Value for Z:(null)"

    uint32_t testItemsCount = 1000000;
    // create huge dictionary of numbers
    NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:testItemsCount];
    for (long i=0; i<testItemsCount; ++i) {
        // make new random key value pair:
        NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
        NSNumber *value = @(arc4random_uniform(testItemsCount));
        [d setObject:value forKey:key];
    }
    // create huge set of random keys for testing.
    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:testItemsCount];
    for (long i=0; i<testItemsCount; ++i) {
        NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
        [keys addObject:key];
    }

    NSDictionary *dict = [d copy];
    NSTimeInterval vtotal = 0.0, ototal = 0.0;

    NSDate *start;
    NSTimeInterval elapsed;

    for (int i = 0; i<10; i++) {

        start = [NSDate date];
        for (NSString *key in keys) {
            id value = [dict valueForKey:key];
        }
        elapsed = [[NSDate date] timeIntervalSinceDate:start];
        vtotal+=elapsed;
        NSLog (@"reading %lu values off dictionary via valueForKey took: %10.4f seconds", keys.count, elapsed);

        start = [NSDate date];
        for (NSString *key in keys) {
            id obj = [dict objectForKey:key];
        }
        elapsed = [[NSDate date] timeIntervalSinceDate:start];
        ototal+=elapsed;
        NSLog (@"reading %lu objects off dictionary via objectForKey took: %10.4f seconds", keys.count, elapsed);
    }

    NSString *slower = (vtotal > ototal) ? @"valueForKey" : @"objectForKey";
    NSString *faster = (vtotal > ototal) ? @"objectForKey" : @"valueForKey";
    NSLog (@"%@ takes %3.1f percent longer then %@", slower, 100.0 * ABS(vtotal-ototal) / MAX(ototal,vtotal), faster);
}

How do I center text vertically and horizontally in Flutter?

Put the Text in a Center:

Container(
      height: 45,
      color: Colors.black,
      child: Center(
        child: Text(
            'test',
            style: TextStyle(color: Colors.white),
        ),
      ),
    );

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

How to get JQuery.trigger('click'); to initiate a mouse click

Just use this:

$(function() {
 $('#watchButton').trigger('click');
});

How to make the corners of a button round?

You can also use the card layout like below

  <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:cardCornerRadius="30dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="Template"

                />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

How can I send and receive WebSocket messages on the server side?

C# Implementation

Browser -> Server

    private String DecodeMessage(Byte[] bytes)
    {
        String incomingData = String.Empty;
        Byte secondByte = bytes[1];
        Int32 dataLength = secondByte & 127;
        Int32 indexFirstMask = 2;
        if (dataLength == 126)
            indexFirstMask = 4;
        else if (dataLength == 127)
            indexFirstMask = 10;

        IEnumerable<Byte> keys = bytes.Skip(indexFirstMask).Take(4);
        Int32 indexFirstDataByte = indexFirstMask + 4;

        Byte[] decoded = new Byte[bytes.Length - indexFirstDataByte];
        for (Int32 i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++)
        {
            decoded[j] = (Byte)(bytes[i] ^ keys.ElementAt(j % 4));
        }

        return incomingData = Encoding.UTF8.GetString(decoded, 0, decoded.Length);
    }

Server -> Browser

    private static Byte[] EncodeMessageToSend(String message)
    {
        Byte[] response;
        Byte[] bytesRaw = Encoding.UTF8.GetBytes(message);
        Byte[] frame = new Byte[10];

        Int32 indexStartRawData = -1;
        Int32 length = bytesRaw.Length;

        frame[0] = (Byte)129;
        if (length <= 125)
        {
            frame[1] = (Byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (Byte)126;
            frame[2] = (Byte)((length >> 8) & 255);
            frame[3] = (Byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (Byte)127;
            frame[2] = (Byte)((length >> 56) & 255);
            frame[3] = (Byte)((length >> 48) & 255);
            frame[4] = (Byte)((length >> 40) & 255);
            frame[5] = (Byte)((length >> 32) & 255);
            frame[6] = (Byte)((length >> 24) & 255);
            frame[7] = (Byte)((length >> 16) & 255);
            frame[8] = (Byte)((length >> 8) & 255);
            frame[9] = (Byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new Byte[indexStartRawData + length];

        Int32 i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }

Loop through all elements in XML using NodeList

Here is another way to loop through XML elements using JDOM.

        List<Element> nodeNodes = inputNode.getChildren();
        if (nodeNodes != null) {
            for (Element nodeNode : nodeNodes) {
                List<Element> elements = nodeNode.getChildren(elementName);
                if (elements != null) {
                    elements.size();
                    nodeNodes.removeAll(elements);
                }
            }

How can I one hot encode in Python?

Here is a solution using DictVectorizer and the Pandas DataFrame.to_dict('records') method.

>>> import pandas as pd
>>> X = pd.DataFrame({'income': [100000,110000,90000,30000,14000,50000],
                      'country':['US', 'CAN', 'US', 'CAN', 'MEX', 'US'],
                      'race':['White', 'Black', 'Latino', 'White', 'White', 'Black']
                     })

>>> from sklearn.feature_extraction import DictVectorizer
>>> v = DictVectorizer()
>>> qualitative_features = ['country','race']
>>> X_qual = v.fit_transform(X[qualitative_features].to_dict('records'))
>>> v.vocabulary_
{'country=CAN': 0,
 'country=MEX': 1,
 'country=US': 2,
 'race=Black': 3,
 'race=Latino': 4,
 'race=White': 5}

>>> X_qual.toarray()
array([[ 0.,  0.,  1.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  1.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  1.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  1.,  1.,  0.,  0.]])

using c# .net libraries to check for IMAP messages from gmail servers

Cross posted from the other similar question. See what happens when they get so similar?

I've been searching for an IMAP solution for a while now, and after trying quite a few, I'm going with AE.Net.Mail.

There is no documentation, which I consider a downside, but I was able to whip this up by looking at the source code (yay for open source!) and using Intellisense. The below code connects specifically to Gmail's IMAP server:

// Connect to the IMAP server. The 'true' parameter specifies to use SSL
// which is important (for Gmail at least)
ImapClient ic = new ImapClient("imap.gmail.com", "[email protected]", "pass",
                ImapClient.AuthMethods.Login, 993, true);
// Select a mailbox. Case-insensitive
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message;
// and it also includes the 10th message, which is really the eleventh ;)
// MailMessage represents, well, a message in your mailbox
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm)
{
    Console.WriteLine(m.Subject);
}
// Probably wiser to use a using statement
ic.Dispose();

I'm not affiliated with this library or anything, but I've found it very fast and stable.

How to inflate one view with a layout

Even simpler way is to use

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item

Handling a timeout error in python sockets

I had enough success just catchig socket.timeout and socket.error; although socket.error can be raised for lots of reasons. Be careful.

import socket
import logging

hostname='google.com'
port=443

try:
    sock = socket.create_connection((hostname, port), timeout=3)

except socket.timeout as err:
    logging.error(err)

except socket.error as err:
    logging.error(err)

Upload folder with subfolders using S3 and the AWS console

You can't upload nested structures like that through the online tool. I'd recommend using something like Bucket Explorer for more complicated uploads.

How to change credentials for SVN repository in Eclipse?

In windows :

  1. Open run type %APPDATA%\Subversion\auth\svn.simple
  2. This will open svn.simple folder
  3. you will find a file e.g. Big Alpha Numeric file
  4. Delete that file.
  5. Restart eclipse.
  6. Try to edit file from project and commit it
  7. you can see dialog asking userName password

It worked for me.... ;)

How to center links in HTML

you would put them inside a <p> or a <div>

<p style="text-align:center">
    <a href="http//www.google.com">Search</a> 
    <a href="Contact Us">Contact Us</a>
</p>

sample: http://jsfiddle.net/X8HM4/1/

how to put focus on TextBox when the form load?

Textbox.Focus() "Tries" to set focus on the textbox element. In case of the element visibility is hidden for example, Focus() will not work. So make sure that your element is visible before calling Focus().

Docker is in volume in use, but there aren't any Docker containers

I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q), but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use.

I did a docker system prune and it cleaned up what was needed to remove the last volume:

[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated

Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER              VOLUME NAME
local              uuid
[0]$ docker volume rm uuid
uuid
[0]$

docker system prune

The client and daemon API must both be at least 1.25 to use this command. Use the docker version command on the client to check your client and daemon API versions.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

This worked for me:

dict = {1: 'a', 2: '', 3: 'b', 4: '', 5: '', 6: 'c'}
for key, value in list(dict.items()):
    if (value == ''):
        del dict[key]
print(dict)
# dict = {1: 'a', 3: 'b', 6: 'c'}  

Casting the dictionary items to list creates a list of its items, so you can iterate over it and avoid the RuntimeError.

Save multiple sheets to .pdf

I recommend adding the following line after the export to PDF:

ThisWorkbook.Sheets("Sheet1").Select

(where eg. Sheet1 is the single sheet you want to be active afterwards)

Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)

IIS Request Timeout on long ASP.NET operation

I'm posting this here, because I've spent like 3 and 4 hours on it, and I've only found answers like those one above, that say do add the executionTime, but it doesn't solve the problem in the case that you're using ASP .NET Core. For it, this would work:

At web.config file, add the requestTimeout attribute at aspNetCore node.

<system.webServer>
  <aspNetCore requestTimeout="00:10:00" ... (other configs goes here) />
</system.webServer>

In this example, I'm setting the value for 10 minutes.

Reference: https://docs.microsoft.com/en-us/aspnet/core/hosting/aspnet-core-module#configuring-the-asp-net-core-module

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

If any other solution is in the debug mode then first stop them all and after that restart the visual studio. It worked for me.

Scale iFrame css width 100% like an image

I like this solution best. Simple, scalable, responsive. The idea here is to create a zero-height outer div with bottom padding set to the aspect ratio of the video. The iframe is scaled to 100% in both width and height, completely filling the outer container. The outer container automatically adjusts its height according to its width, and the iframe inside adjusts itself accordingly.

<div style="position:relative; width:100%; height:0px; padding-bottom:56.25%;">
    <iframe style="position:absolute; left:0; top:0; width:100%; height:100%"
        src="http://www.youtube.com/embed/RksyMaJiD8Y">
    </iframe>
</div>

The only variable here is the padding-bottom value in the outer div. It's 75% for 4:3 aspect ratio videos, and 56.25% for widescreen 16:9 aspect ratio videos.

Sleeping in a batch file

Over at Server Fault, a similar question was asked, and the solution there was:

choice /d y /t 5 > nul

Object creation on the stack/heap?

Actually, neither statement says anything about heap or stack. The code

Object o;

creates one of the following, depending on its context:

  • a local variable with automatic storage,
  • a static variable at namespace or file scope,
  • a member variable that designates the subobject of another object.

This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack vs heap storage. Instead, it talks about storage duration, which can be either automatic, dynamic, static or thread-local. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.

Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.

To illustrate this with an example:

struct Foo {
    Object o;
};

Foo foo;

int main() {
    Foo f;
    Foo* p = new Foo;
    Foo* pf = &f;
}

Now where is the object Foo::o (that is, the subobject o of an object of class Foo) created? It depends:

  • foo.o has static storage because foo has static storage, and therefore lives neither on the stack nor on the heap.
  • f.o has automatic storage since f has automatic storage (= it lives on the stack).
  • p->o has dynamic storage since *p has dynamic storage (= it lives on the heap).
  • pf->o is the same object as f.o because pf points to f.

In fact, both p and pf in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.

The pointee (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: *p is dynamic, whereas *pf is automatic.

how to know status of currently running jobs

EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,''

Notice the column Running, obviously 1 means that it is currently running, and [Current Step]. This returns job_id to you, so you'll need to look these up, e.g.:

SELECT top 100 *
 FROM   msdb..sysjobs
 WHERE  job_id IN (0x9DAD1B38EB345D449EAFA5C5BFDC0E45, 0xC00A0A67D109B14897DD3DFD25A50B80, 0xC92C66C66E391345AE7E731BFA68C668)

Python error: AttributeError: 'module' object has no attribute

More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12

An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

>>> from lib.pkg1 import mod11

Then reference the function as simply mod11.mod12().

Align HTML input fields by :

Working JS Fiddle

HTML:

  <div>
      <label>Name:</label><input type="text">
      <label>Email Address:</label><input type = "text">
      <label>Description of the input value:</label><input type="text">
  </div>

CSS:

label{
    display: inline-block;
    float: left;
    clear: left;
    width: 250px;
    text-align: right;
}
input {
  display: inline-block;
  float: left;
}

Why use the 'ref' keyword when passing an object?

In .NET when you pass any parameter to a method, a copy is created. In value types means that any modification you make to the value is at the method scope, and is lost when you exit the method.

When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object. So, if you use the reference to modify the object, it gets modified. But if you modify the reference itself - we must remember it is a copy - then any changes are also lost upon exiting the method.

As people have said before, an assignment is a modification of the reference, thus is lost:

public void Method1(object obj) {   
 obj = new Object(); 
}

public void Method2(object obj) {  
 obj = _privateObject; 
}

The methods above does not modifies the original object.

A little modification of your example

 using System;

    class Program
        {
            static void Main(string[] args)
            {
                TestRef t = new TestRef();
                t.Something = "Foo";

                DoSomething(t);
                Console.WriteLine(t.Something);

            }

            static public void DoSomething(TestRef t)
            {
                t = new TestRef();
                t.Something = "Bar";
            }
        }



    public class TestRef
    {
    private string s;
        public string Something 
        { 
            get {return s;} 
            set { s = value; }
        }
    }

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

You can use plt.subplots_adjust to change the spacing between the subplots Link

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots
hspace = 0.2   # the amount of height reserved for white space between subplots

$.focus() not working

Make sure the element and its parents are visible. You cannot use focus on hidden elements

Change New Google Recaptcha (v2) Width

For more compatibility:

  -webkit-transform: scale(0.77);
     -moz-transform: scale(0.77);
      -ms-transform: scale(0.77);
       -o-transform: scale(0.77);
          transform: scale(0.77);
   -webkit-transform-origin: 0 0;
      -moz-transform-origin: 0 0;
       -ms-transform-origin: 0 0;
        -o-transform-origin: 0 0;
           transform-origin: 0 0;

Passing environment-dependent variables in webpack

There are two basic ways to achieve this.

DefinePlugin

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),

Note that this will just replace the matches "as is". That's why the string is in the format it is. You could have a more complex structure, such as an object there but you get the idea.

EnvironmentPlugin

new webpack.EnvironmentPlugin(['NODE_ENV'])

EnvironmentPlugin uses DefinePlugin internally and maps the environment values to code through it. Terser syntax.

Alias

Alternatively you could consume configuration through an aliased module. From consumer side it would look like this:

var config = require('config');

Configuration itself could look like this:

resolve: {
    alias: {
        config: path.join(__dirname, 'config', process.env.NODE_ENV)
    }
}

Let's say process.env.NODE_ENV is development. It would map into ./config/development.js then. The module it maps to can export configuration like this:

module.exports = {
    testing: 'something',
    ...
};

How can I run a program from a batch file without leaving the console open after the program starts?

Loads of answers for this question already, but I am posting this to clarify something important, though this might not always be the case:

Start "C:\Program Files\someprog.exe"

Might cause issues in some windows versions as Start actually expects the first set of quotation marks to be a windows title. So it is best practice to first double quote a comment, or a blank comment:

Start "" "C:\Program Files\someprog.exe"

or

Start "Window Title" "C:\Program Files\someprog.exe"

Simple example of threading in C++

#include <thread>
#include <iostream>
#include <vector>
using namespace std;

void doSomething(int id) {
    cout << id << "\n";
}

/**
 * Spawns n threads
 */
void spawnThreads(int n)
{
    std::vector<thread> threads(n);
    // spawn n threads:
    for (int i = 0; i < n; i++) {
        threads[i] = thread(doSomething, i + 1);
    }

    for (auto& th : threads) {
        th.join();
    }
}

int main()
{
    spawnThreads(10);
}

How to send objects through bundle

another simple way to pass object using a bundle:

  • in the class object, create a static list or another data structure with a key
  • when you create the object, put it in the list/data structure with the key (es. the long timestamp when the object is created)
  • create the method static getObject(long key) to get the object from the list
  • in the bundle pass the key, so you can get the object later from another point in the code

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

Is there an ignore command for git like there is for svn?

There is no special git ignore command.

Edit a .gitignore file located in the appropriate place within the working copy. You should then add this .gitignore and commit it. Everyone who clones that repo will than have those files ignored.

Note that only file names starting with / will be relative to the directory .gitignore resides in. Everything else will match files in whatever subdirectory.

You can also edit .git/info/exclude to ignore specific files just in that one working copy. The .git/info/exclude file will not be committed, and will thus only apply locally in this one working copy.

You can also set up a global file with patterns to ignore with git config --global core.excludesfile. This will locally apply to all git working copies on the same user's account.

Run git help gitignore and read the text for the details.

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

how to convert integer to string?

If you really want to use String:

NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];

But I would recommend using NSNumber:

NSNumber *number = [[NSNumber alloc] initWithInt:123];

Then just add it to the array.

[array addObject:number];

Don't forget to release it after that, since you created it above.

[number release];

Display fullscreen mode on Tkinter

This creates a fullscreen window. Pressing Escape resizes the window to '200x200+0+0' by default. If you move or resize the window, Escape toggles between the current geometry and the previous geometry.

import Tkinter as tk

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

root=tk.Tk()
app=FullScreenApp(root)
root.mainloop()

"git rm --cached x" vs "git reset head --? x"?

There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.

When you do something like git add file you add it to the index. And when you commit it, you add it to the tree as well.

It will probably help you to know the three more common flags in git reset:

git reset [--<mode>] [<commit>]

This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>, which must be one of the following:
--soft

Does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

Now, when you do something like git reset HEAD, what you are actually doing is git reset HEAD --mixed and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD is the exact opposite of git add.

git rm, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add was used to add a new (previously untracked) file, then git rm --cached is the exact opposite of git add (and is pretty much identical to git reset HEAD).

Git 2.25 introduced a new command for these cases, git restore, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

Slack clean all messages (~8K) in a channel

!!UPDATE!!

as @niels-van-reijmersdal metioned in comment.

This feature has been removed. See this thread for more info: twitter.com/slackhq/status/467182697979588608?lang=en

!!END UPDATE!!

Here is a nice answer from SlackHQ in twitter, and it works without any third party stuff. https://twitter.com/slackhq/status/467182697979588608?lang=en

You can bulk delete via the archives (http://my.slack.com/archives ) page for a particular channel: look for "delete messages" in menu

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

How do I open a URL from C++?

Create a function and copy the code using winsock which is mentioned already by Software_Developer.

For Instance:

#ifdef _WIN32

// this is required only for windows

if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{

  //...

}

#endif

winsock code here

#ifdef _WIN32

WSACleanup();

#endif

Is object empty?

For ECMAScript5 (not supported in all browsers yet though), you can use:

Object.keys(obj).length === 0

How to make padding:auto work in CSS?

You should just scope your * selector to the specific areas that need the reset. .legacy * { }, etc.

Recursively looping through an object to build a property list

UPDATE: JUST USE JSON.stringify to print objects on screen!

All you need is this line:

document.body.innerHTML = '<pre>' + JSON.stringify(ObjectWithSubObjects, null, "\t") + '</pre>';

This is my older version of printing objects recursively on screen:

 var previousStack = '';
    var output = '';
    function objToString(obj, stack) {
        for (var property in obj) {
            var tab = '&nbsp;&nbsp;&nbsp;&nbsp;';
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] === 'object' && typeof stack === 'undefined') {
                    config = objToString(obj[property], property);
                } else {
                    if (typeof stack !== 'undefined' && stack !== null && stack === previousStack) {
                        output = output.substring(0, output.length - 1);  // remove last }
                        output += tab + '<span>' + property + ': ' + obj[property] + '</span><br />'; // insert property
                        output += '}';   // add last } again
                    } else {
                        if (typeof stack !== 'undefined') {
                            output += stack + ': {  <br />' + tab;
                        }
                        output += '<span>' + property + ': ' + obj[property] + '</span><br />';
                        if (typeof stack !== 'undefined') {
                            output += '}';
                        }
                    }
                    previousStack = stack;
                }
            }
        }
        return output;
    }

Usage:

document.body.innerHTML = objToString(ObjectWithSubObjects);

Example output:

cache: false
position: fixed
effect: { 
    fade: false
    fall: true
}

Obviously this can be improved by adding comma's when needed and quotes from string values. But this was good enough for my case.

Store List to session

Try this..

    List<Cat> cats = new List<Cat>
    {
        new Cat(){ Name = "Sylvester", Age=8 },
        new Cat(){ Name = "Whiskers", Age=2 },
        new Cat(){ Name = "Sasha", Age=14 }
    };
    Session["data"] = cats;
    foreach (Cat c in cats)
        System.Diagnostics.Debug.WriteLine("Cats>>" + c.Name);     //DEBUGGG

How to get the MD5 hash of a file in C++?

There is a pretty library at http://256stuff.com/sources/md5/, with example of use. This is the simplest library for MD5.

JavaScript: Get image dimensions

naturalWidth and naturalHeight

var img = document.createElement("img");
img.onload = function (event)
{
    console.log("natural:", img.naturalWidth, img.naturalHeight);
    console.log("width,height:", img.width, img.height);
    console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);

// css for tests
img { width:50%;height:50%; }

How to change the server port from 3000?

Using Angular 4 and the cli that came with it I was able to start the server with $npm start -- --port 8000. That worked ok: ** NG Live Development Server is listening on localhost:8000, open your browser on http://localhost:8000 **

Got the tip from Here

enter image description here enter image description here

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

pip cannot install anything

This problem is most-likely caused by DNS setup: server cannot resolve the Domain Name, so cannot download the package.

Solution:

     sudo nano /etc/network/interface

add a line: dns-nameservers 8.8.8.8

save file and exit

     sudo ifdown eth0 && sudo ifup eth0

Then pip install should be working now.

How to change a particular element of a C++ STL vector

I prefer

l.at(4)= -1;

while [4] is your index

Is it possible to get the index you're sorting over in Underscore.js?

Index is actually available like;

_.sortBy([1, 4, 2, 66, 444, 9], function(num, index){  });

Check if a varchar is a number (TSQL)

ISNUMERIC will do

Check the NOTES section too in the article.

Which font is used in Visual Studio Code Editor and how to change fonts?

Open vscode.

Press ctrl,.

The setting is "editor.fontFamily".

On Linux to get a list of fonts (and their names which you have to use) run this in another shell:

fc-list | awk '{$1=""}1' | cut -d: -f1 | sort| uniq

You can specify a list of fonts, to have fallback values in case a font is missing.

How do I limit the number of results returned from grep?

Another option is just using head:

grep ...parameters... yourfile | head

This won't require searching the entire file - it will stop when the first ten matching lines are found. Another advantage with this approach is that will return no more than 10 lines even if you are using grep with the -o option.

For example if the file contains the following lines:

112233
223344
123123

Then this is the difference in the output:

$ grep -o '1.' yourfile | head -n2
11
12

$ grep -m2 -o '1.'
11
12
12

Using head returns only 2 results as desired, whereas -m2 returns 3.

HTML5 - mp4 video does not play in IE9

From what I've heard, video support is minimal at best.

From http://diveintohtml5.ep.io/video.html#what-works:

As of this writing, this is the landscape of HTML5 video:

  • Mozilla Firefox (3.5 and later) supports Theora video and Vorbis audio in an Ogg container. Firefox 4 also supports WebM.

  • Opera (10.5 and later) supports Theora video and Vorbis audio in an Ogg container. Opera 10.60 also supports WebM.

  • Google Chrome (3.0 and later) supports Theora video and Vorbis audio in an Ogg container. Google Chrome 6.0 also supports WebM.

  • Safari on Macs and Windows PCs (3.0 and later) will support anything that QuickTime supports. In theory, you could require your users to install third-party QuickTime plugins. In practice, few users are going to do that. So you’re left with the formats that QuickTime supports “out of the box.” This is a long list, but it does not include WebM, Theora, Vorbis, or the Ogg container. However, QuickTime does ship with support for H.264 video (main profile) and AAC audio in an MP4 container.

  • Mobile phones like Apple’s iPhone and Google Android phones support H.264 video (baseline profile) and AAC audio (“low complexity” profile) in an MP4 container.

  • Adobe Flash (9.0.60.184 and later) supports H.264 video (all profiles) and AAC audio (all profiles) in an MP4 container.

  • Internet Explorer 9 supports all profiles of H.264 video and either AAC or MP3 audio in an MP4 container. It will also play WebM video if you install a third-party codec, which is not installed by default on any version of Windows. IE9 does not support other third-party codecs (unlike Safari, which will play anything QuickTime can play).

  • Internet Explorer 8 has no HTML5 video support at all, but virtually all Internet Explorer users will have the Adobe Flash plugin. Later in this chapter, I’ll show you how you can use HTML5 video but gracefully fall back to Flash.

As well, you should note this section just below on the same page:

There is no single combination of containers and codecs that works in all HTML5 browsers.

This is not likely to change in the near future.

To make your video watchable across all of these devices and platforms, you’re going to need to encode your video more than once.

Using jQuery Fancybox or Lightbox to display a contact form

you'll probably want to look into jquery-ui dialog. it's highly customizable and can be made to work exactly like lightbox/fancybox and supports everything you would need for a contact form from a regular link.

there is even an example with a form.

Bash loop ping successful

You don't need to use echo or grep. You could do this:

ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"

Query to display all tablespaces in a database and datafiles

SELECT a.file_name,
       substr(A.tablespace_name,1,14) tablespace_name,
       trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
       trunc(a.bytes/1024/1024) allocated_mb,
       trunc(A.MAXSIZE/1024/1024) capacity,
       a.autoextensible ae
FROM (
     SELECT file_id, file_name,
            tablespace_name,
            autoextensible,
            bytes,
            decode(autoextensible,'YES',maxbytes,bytes) maxsize
     FROM   dba_data_files
     GROUP BY file_id, file_name,
              tablespace_name,
              autoextensible,
              bytes,
              decode(autoextensible,'YES',maxbytes,bytes)
     ) a,
     (SELECT file_id,
             tablespace_name,
             sum(bytes) free
      FROM   dba_free_space
      GROUP BY file_id,
               tablespace_name
      ) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC; 

How do I add slashes to a string in Javascript?

if (!String.prototype.hasOwnProperty('addSlashes')) {
    String.prototype.addSlashes = function() {
        return this.replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
             .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
             .replace(/"/g, '&quot;')
             .replace(/\\/g, '\\\\')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
        }
}

Usage: alert(str.addSlashes());

ref: https://stackoverflow.com/a/9756789/3584667

What primitive data type is time_t?

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));

How can I get current date in Android?

Calendar cal = Calendar.getInstance();      
Calendar dt = Calendar.getInstance(); 
dt.clear();
dt.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),cal.get(Calendar.DATE)); 
return dt.getTime();        

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

Consider following code

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

Now, here goes the difference

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

Now, what if we add a myTask again?

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

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

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

Summary:

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

Python - difference between two strings

I like the ndiff answer, but if you want to spit it all into a list of only the changes, you could do something like:

import difflib

case_a = 'afrykbnerskojezyczny'
case_b = 'afrykanerskojezycznym'

output_list = [li for li in difflib.ndiff(case_a, case_b) if li[0] != ' ']

How to convert Base64 String to javascript file object like as from file input form?

Way 1: only works for dataURL, not for other types of url.

_x000D_
_x000D_
 function dataURLtoFile(dataurl, filename) {_x000D_
 _x000D_
        var arr = dataurl.split(','),_x000D_
            mime = arr[0].match(/:(.*?);/)[1],_x000D_
            bstr = atob(arr[1]), _x000D_
            n = bstr.length, _x000D_
            u8arr = new Uint8Array(n);_x000D_
            _x000D_
        while(n--){_x000D_
            u8arr[n] = bstr.charCodeAt(n);_x000D_
        }_x000D_
        _x000D_
        return new File([u8arr], filename, {type:mime});_x000D_
    }_x000D_
    _x000D_
    //Usage example:_x000D_
    var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');_x000D_
    console.log(file);
_x000D_
_x000D_
_x000D_

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

_x000D_
_x000D_
 //return a promise that resolves with a File instance_x000D_
    function urltoFile(url, filename, mimeType){_x000D_
        return (fetch(url)_x000D_
            .then(function(res){return res.arrayBuffer();})_x000D_
            .then(function(buf){return new File([buf], filename,{type:mimeType});})_x000D_
        );_x000D_
    }_x000D_
    _x000D_
    //Usage example:_x000D_
    urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')_x000D_
    .then(function(file){ console.log(file);});
_x000D_
_x000D_
_x000D_

How do I measure a time interval in C?

Great answers for GNU environments above and below...

But... what if you're not running on an OS? (or a PC for that matter, or you need to time your timer interrupts themselves?) Here's a solution that uses the x86 CPU timestamp counter directly... Not because this is good practice, or should be done, ever, when running under an OS...

  • Caveat: Only works on x86, with frequency scaling disabled.
  • Under Linux, only works on non-tickless kernels

rdtsc.c:

#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef unsigned long long int64;

static __inline__ int64 getticks(void)
{
     unsigned a, d;
     asm volatile("rdtsc" : "=a" (a), "=d" (d));
     return (((int64)a) | (((int64)d) << 32));
}

int main(){

     int64 tick,tick1;
     unsigned time=0,mt;

     // mt is the divisor to give microseconds

     FILE *pf;
     int i,r,l,n=0;
     char s[100];

     // time how long it takes to get the divisors, as a test 
     tick = getticks();

     // get the divisors  - todo: for max performance this can 
     // output a new binary or library with these values hardcoded 
     // for the relevant CPU - if you use the equivalent assembler for
     // that CPU
     pf = fopen("/proc/cpuinfo","r");
     do {
      r=fscanf(pf,"%s",&s[0]);
      if (r<0) {
       n=5; break;
      } else if (n==0) {
       if (strcmp("MHz",s)==0) n=1;
      } else if (n==1) {
       if (strcmp(":",s)==0) n=2;
      } else if (n==2) {
       n=3;
      };
     } while (n<3);
     fclose(pf);

     s[9]=(char)0;
     strcpy(&s[4],&s[5]);
     mt=atoi(s);

     printf("#define mt %u // (%s Hz) hardcode this for your a CPU-specific binary ;-)\n",mt,s);

     tick1 = getticks();
     time = (unsigned)((tick1-tick)/mt);
     printf("%u ms\n",time);

     // time the duration of sleep(1) - plus overheads ;-)
     tick = getticks();

     sleep(1);

     tick1 = getticks();
     time = (unsigned)((tick1-tick)/mt);
     printf("%u ms\n",time);

     return 0;
}

compile and run with

$ gcc rdtsc.c -o rdtsc && ./rdtsc

It reads the divisor for your CPU from /proc/cpuinfo and shows how long it took to read that in microseconds, as well as how long it takes to execute sleep(1) in microseconds... Assuming the Mhz rating in /proc/cpuinfo always contains 3 decimal places :-o

OnClick Send To Ajax

Tried and working. you are using,

<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

I am using javascript , (don't know about php), use id ="status" in textarea like

<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>

then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag

<srcipt>
function UpdateStatus(){

//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({

        type:"GET",//or POST
        url:'http://localhost:7080/ajaxforjson/Testajax',
                           //  (or whatever your url is)
        data:{data1:var1},
        //can send multipledata like {data1:var1,data2:var2,data3:var3
        //can use dataType:'text/html' or 'json' if response type expected 
        success:function(responsedata){
               // process on data
               alert("got response as "+"'"+responsedata+"'");

        }
     })

}
</script>

and jsp is like

the servlet will look like:   //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")

public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
    super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String data1=request.getParameter("data1");
    //do processing on datas pass in other java class to add to DB
    // i am adding or concatenate
    String data="i Got : "+"'"+data1+"' ";
    System.out.println(" data1 : "+data1+"\n data "+data);
    response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
}

}

Class 'ViewController' has no initializers in swift

The error could be improved, but the problem with your first version is you have a member variable, delegate, that does not have a default value. All variables in Swift must always have a value. That means that you have to set it up in an initializer which you do not have or you could provide it a default value in-line.

When you make it optional, you allow it to be nil by default, removing the need to explicitly give it a value or initialize it.

How do I activate C++ 11 in CMake?

I am using

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

But if you want to play with C++11, g++ 4.6.1 is pretty old. Try to get a newer g++ version.

Alternative to file_get_contents?

If you have it available, using curl is your best option.

You can see if it is enabled by doing phpinfo() and searching the page for curl.

If it is enabled, try this:

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php');
$xml_file = curl_exec($curl_handle);
curl_close($curl_handle);

JavaScript window resize event

The following blog post may be useful to you: Fixing the window resize event in IE

It provides this code:

Sys.Application.add_load(function(sender, args) {
    $addHandler(window, 'resize', window_resize);
});

var resizeTimeoutId;

function window_resize(e) {
     window.clearTimeout(resizeTimeoutId);
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10);
}

How to stop VBA code running?

I do this a lot. A lot. :-)

I have got used to using "DoEvents" more often, but still tend to set things running without really double checking a sure stop method.

Then, today, having done it again, I thought, "Well just wait for the end in 3 hours", and started paddling around in the ribbon. Earlier, I had noticed in the "View" section of the Ribbon a "Macros" pull down, and thought I have a look to see if I could see my interminable Macro running....

I now realise you can also get this up using Alt-F8.

Then I thought, well what if I "Step into" a different Macro, would that rescue me? It did :-) It also works if you step into your running Macro (but you still lose where you're upto), unless you are a very lazy programmer like me and declare lots of "Global" variables, in which case the Global data is retained :-)

K

How To Set Up GUI On Amazon EC2 Ubuntu server

This can be done. Following are the steps to setup the GUI

Create new user with password login

sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui

sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes

sudo /etc/init.d/ssh restart

Setting up ui based ubuntu machine on AWS.

In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:

sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server

Then run following commands and enter the login password for vnc connection:

su - awsgui

vncserver

vncserver -kill :1

vim /home/awsgui/.vnc/xstartup

Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads

exec sh /etc/X11/xinit/xinitrc. 

When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.

Then start vnc server again.

vncserver

You can download xtightvncviewer to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients

In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.

Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html

Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/

Port opening on console

sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT

If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.

vncserver

PHP: How do I display the contents of a textfile on my page?

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>

Try this to open a file in php

Refer this: (http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Should work for any collection except Map, but it's easy to support, too. Modify code to pass these 3 chars as arguments if needed.

static <T> String seqToString(Iterable<T> items) {
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    boolean needSeparator = false;
    for (T x : items) {
        if (needSeparator)
            sb.append(' ');
        sb.append(x.toString());
        needSeparator = true;
    }
    sb.append(']');
    return sb.toString();
}

how to set JAVA_OPTS for Tomcat in Windows?

This is because, the amount of memory you wish to assign for JVM is not available or may be you are assigning more than available memory. Try small size then u can see the difference.
Try:

set JAVA_OPTS=-Xms128m -Xmx512m -XX:PermSize=128m

How to fix Error: laravel.log could not be opened?

This is work for me.

Essa foi a única solução que funcionou para mim. Estou usando Docker e Laradock

chmod -Rvc 775 storage

Selected value for JSP drop down using JSTL

You can try one even more simple:

<option value="1" ${item.quantity == 1 ? "selected" : ""}>1</option>

Lock, mutex, semaphore... what's the difference?

Using C programming on a Linux variant as a base case for examples.

Lock:

• Usually a very simple construct binary in operation either locked or unlocked

• No concept of thread ownership, priority, sequencing etc.

• Usually a spin lock where the thread continuously checks for the locks availability.

• Usually relies on atomic operations e.g. Test-and-set, compare-and-swap, fetch-and-add etc.

• Usually requires hardware support for atomic operation.

File Locks:

• Usually used to coordinate access to a file via multiple processes.

• Multiple processes can hold the read lock however when any single process holds the write lock no other process is allowed to acquire a read or write lock.

• Example : flock, fcntl etc..

Mutex:

• Mutex function calls usually work in kernel space and result in system calls.

• It uses the concept of ownership. Only the thread that currently holds the mutex can unlock it.

• Mutex is not recursive (Exception: PTHREAD_MUTEX_RECURSIVE).

• Usually used in Association with Condition Variables and passed as arguments to e.g. pthread_cond_signal, pthread_cond_wait etc.

• Some UNIX systems allow mutex to be used by multiple processes although this may not be enforced on all systems.

Semaphore:

• This is a kernel maintained integer whose values is not allowed to fall below zero.

• It can be used to synchronize processes.

• The value of the semaphore may be set to a value greater than 1 in which case the value usually indicates the number of resources available.

• A semaphore whose value is restricted to 1 and 0 is referred to as a binary semaphore.

Remove all line breaks from a long string of text

You can split the string with no separator arg, which will treat consecutive whitespace as a single separator (including newlines and tabs). Then join using a space:

In : " ".join("\n\nsome    text \r\n with multiple whitespace".split())
Out: 'some text with multiple whitespace'

https://docs.python.org/2/library/stdtypes.html#str.split

ActiveX component can't create object

I know this is an old thread, but has anyone checked if their Antivirus is blocking Win32API and Scripting on their systems? I have CylanceProtect installed on my office system and i found the same issues occurring as listed by others. This can be confirmed if you check the Windows Logs in Event Viewer.

twitter bootstrap navbar fixed top overlapping site

For handling wrapping lines in menu-bar, apply an id to the navbar, like this:

<div class="navbar navbar-default navbar-fixed-top" role="navigation" id="topnavbar">

and add this small script in the head after including the jquery, like this:

<script>
    $(document).ready(function(){
        $(document.body).css('padding-top', $('#topnavbar').height() + 10);
        $(window).resize(function(){
            $(document.body).css('padding-top', $('#topnavbar').height() + 10);
        });
    });
</script>

That way, the top-padding of the body gets automatically adjusted.

Create a directory if it doesn't exist

Use the WINAPI CreateDirectory() function to create a folder.

You can use this function without checking if the directory already exists as it will fail but GetLastError() will return ERROR_ALREADY_EXISTS:

if (CreateDirectory(OutputFolder.c_str(), NULL) ||
    ERROR_ALREADY_EXISTS == GetLastError())
{
    // CopyFile(...)
}
else
{
     // Failed to create directory.
}

The code for constructing the target file is incorrect:

string(OutputFolder+CopiedFile).c_str()

this would produce "D:\testEmploi Nam.docx": there is a missing path separator between the directory and the filename. Example fix:

string(OutputFolder+"\\"+CopiedFile).c_str()

How to schedule a task to run when shutting down windows

I posted this answer too over on superuser.


To do this you will need to set up a custom event filter in Task Scheduler.

Triggers > New > Custom > Edit Event > XML

and paste the following:

<QueryList>
  <Query Id="0" Path="System">
    <Select Path="System">
    *[System[Provider[@Name='User32'] and (Level=4 or Level=0) and (EventID=1074)]]
   and 
     *[EventData[Data[@Name='param5'] and (Data='power off')]]
    </Select>
  </Query>
</QueryList>

This will filter out the power off event only.

If you look in the event viewer you can see under Windows Logs > System under Details tab>XML View that there's this.

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="User32" Guid="{xxxxx-xxxxxxxxxxx-xxxxxxxxxxxxxx-x-x}" EventSourceName="User32" /> 
  <EventID Qualifiers="32768">1074</EventID> 
  <Version>0</Version> 
  <Level>4</Level> 
  <Task>0</Task> 
  <Opcode>0</Opcode> 
  <Keywords>0x8080000000000000</Keywords> 
  <TimeCreated SystemTime="2021-01-19T18:23:32.6133523Z" /> 
  <EventRecordID>26696</EventRecordID> 
  <Correlation /> 
  <Execution ProcessID="1056" ThreadID="11288" /> 
  <Channel>System</Channel> 
  <Computer>DESKTOP-REDACTED</Computer> 
  <Security UserID="x-x-x-xx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxx" /> 
  </System>
- <EventData>
  <Data Name="param1">Explorer.EXE</Data> 
  <Data Name="param2">DESKTOP-REDACTED</Data> 
  <Data Name="param3">Other (Unplanned)</Data> 
  <Data Name="param4">0x0</Data> 
  <Data Name="param5">power off</Data> 
  <Data Name="param6" /> 
  <Data Name="param7">DESKTOP-REDACTED\username</Data> 
  </EventData>
  </Event>

You can test the query with the query list code above in the event viewer by clicking

Create Custom View... > XML > Edit query manually

and pasting the code, giving it a name Power Off Events Only before you try it in the Task Scheduler.

What is an Endpoint?

Endpoint, in the OpenID authentication lingo, is the URL to which you send (POST) the authentication request.

Excerpts from Google authentication API

To get the Google OpenID endpoint, perform discovery by sending either a GET or HEAD HTTP request to https://www.google.com/accounts/o8/id. When using a GET, we recommend setting the Accept header to "application/xrds+xml". Google returns an XRDS document containing an OpenID provider endpoint URL.The endpoint address is annotated as:

<Service priority="0">
<Type>http://specs.openid.net/auth/2.0/server</Type> 
<URI>{Google's login endpoint URI}</URI> 
</Service>

Once you've acquired the Google endpoint, you can send authentication requests to it, specifying the appropriate parameters (available at the linked page). You connect to the endpoint by sending a request to the URL or by making an HTTP POST request.

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Replace invalid values with None in Pandas DataFrame

df = pd.DataFrame(['-',3,2,5,1,-5,-1,'-',9])
df = df.where(df!='-', None)

Changing Vim indentation behavior by file type

While you can configure Vim's indentation just fine using the indent plugin or manually using the settings, I recommend using a python script called Vindect that automatically sets the relevant settings for you when you open a python file. Use this tip to make using Vindect even more effective. When I first started editing python files created by others with various indentation styles (tab vs space and number of spaces), it was incredibly frustrating. But Vindect along with this indent file

Also recommend:

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

How can I find the number of days between two Date objects in Ruby?

all of these steered me to the correct result, but I wound up doing

DateTime.now.mjd - DateTime.parse("01-01-1995").mjd

How to connect to Mysql Server inside VirtualBox Vagrant?

Well, since neither of the given replies helped me, I had to look more, and found solution in this article.

And the answer in a nutshell is the following:

Connecting to MySQL using MySQL Workbench

Connection Method: Standard TCP/IP over SSH
SSH Hostname: <Local VM IP Address (set in PuPHPet)>
SSH Username: vagrant (the default username)
SSH Password: vagrant (the default password)
MySQL Hostname: 127.0.0.1
MySQL Server Port: 3306
Username: root
Password: <MySQL Root Password (set in PuPHPet)>

Using given approach I was able to connect to mysql database in vagrant from host Ubuntu machine using MySQL Workbench and also using Valentina Studio.

How to move a file?

Based on the answer described here, using subprocess is another option.

Something like this:

subprocess.call("mv %s %s" % (source_files, destination_folder), shell=True)

I am curious to know the pro's and con's of this method compared to shutil. Since in my case I am already using subprocess for other reasons and it seems to work I am inclined to stick with it.

Is it system dependent maybe?

Center fixed div with dynamic width (CSS)

Here's another method if you can safely use CSS3's transform property:

.fixed-horizontal-center
{
    position: fixed;
    top: 100px; /* or whatever top you need */
    left: 50%;
    width: auto;
    -webkit-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    transform: translateX(-50%);
}

...or if you want both horizontal AND vertical centering:

.fixed-center
{
    position: fixed;
    top: 50%;
    left: 50%;
    width: auto;
    height: auto;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

What is the difference between a symbolic link and a hard link?

Underneath the file system, files are represented by inodes. (Or is it multiple inodes? Not sure.)

A file in the file system is basically a link to an inode.
A hard link, then, just creates another file with a link to the same underlying inode.

When you delete a file, it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted.

A symbolic link is a link to another name in the file system.

Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.

Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file.

How to remove padding around buttons in Android?

That's not padding, it's the shadow around the button in its background drawable. Create your own background and it will disappear.

How to get a variable value if variable name is stored as string?

X=foo
Y=X
eval "Z=\$$Y"

sets Z to "foo"

Take care using eval since this may allow accidential excution of code through values in ${Y}. This may cause harm through code injection.

For example

Y="\`touch /tmp/eval-is-evil\`"

would create /tmp/eval-is-evil. This could also be some rm -rf /, of course.

How to empty (clear) the logcat buffer in Android

For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)

Create a list with initial capacity in Python

The Pythonic way for this is:

x = [None] * numElements

Or whatever default value you wish to prepopulate with, e.g.

bottles = [Beer()] * 99
sea = [Fish()] * many
vegetarianPizzas = [None] * peopleOrderingPizzaNotQuiche

(Caveat Emptor: The [Beer()] * 99 syntax creates one Beer and then populates an array with 99 references to the same single instance)

Python's default approach can be pretty efficient, although that efficiency decays as you increase the number of elements.

Compare

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # Millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    result = []
    i = 0
    while i < Elements:
        result.append(i)
        i += 1

def doAllocate():
    result = [None] * Elements
    i = 0
    while i < Elements:
        result[i] = i
        i += 1

def doGenerator():
    return list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        x = 0
        while x < Iterations:
            fn()
            x += 1


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

with

#include <vector>
typedef std::vector<unsigned int> Vec;

static const unsigned int Elements = 100000;
static const unsigned int Iterations = 144;

void doAppend()
{
    Vec v;
    for (unsigned int i = 0; i < Elements; ++i) {
        v.push_back(i);
    }
}

void doReserve()
{
    Vec v;
    v.reserve(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v.push_back(i);
    }
}

void doAllocate()
{
    Vec v;
    v.resize(Elements);
    for (unsigned int i = 0; i < Elements; ++i) {
        v[i] = i;
    }
}

#include <iostream>
#include <chrono>
using namespace std;

void test(const char* name, void(*fn)(void))
{
    cout << name << ": ";

    auto start = chrono::high_resolution_clock::now();
    for (unsigned int i = 0; i < Iterations; ++i) {
        fn();
    }
    auto end = chrono::high_resolution_clock::now();

    auto elapsed = end - start;
    cout << chrono::duration<double, milli>(elapsed).count() << "ms\n";
}

int main()
{
    cout << "Elements: " << Elements << ", Iterations: " << Iterations << '\n';

    test("doAppend", doAppend);
    test("doReserve", doReserve);
    test("doAllocate", doAllocate);
}

On my Windows 7 Core i7, 64-bit Python gives

Elements: 100000, Iterations: 144
doAppend: 3587.204933ms
doAllocate: 2701.154947ms
doGenerator: 1721.098185ms

While C++ gives (built with Microsoft Visual C++, 64-bit, optimizations enabled)

Elements: 100000, Iterations: 144
doAppend: 74.0042ms
doReserve: 27.0015ms
doAllocate: 5.0003ms

C++ debug build produces:

Elements: 100000, Iterations: 144
doAppend: 2166.12ms
doReserve: 2082.12ms
doAllocate: 273.016ms

The point here is that with Python you can achieve a 7-8% performance improvement, and if you think you're writing a high-performance application (or if you're writing something that is used in a web service or something) then that isn't to be sniffed at, but you may need to rethink your choice of language.

Also, the Python code here isn't really Python code. Switching to truly Pythonesque code here gives better performance:

import time

class Timer(object):
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, *args):
        end = time.time()
        secs = end - self.start
        msecs = secs * 1000  # millisecs
        print('%fms' % msecs)

Elements   = 100000
Iterations = 144

print('Elements: %d, Iterations: %d' % (Elements, Iterations))


def doAppend():
    for x in range(Iterations):
        result = []
        for i in range(Elements):
            result.append(i)

def doAllocate():
    for x in range(Iterations):
        result = [None] * Elements
        for i in range(Elements):
            result[i] = i

def doGenerator():
    for x in range(Iterations):
        result = list(i for i in range(Elements))


def test(name, fn):
    print("%s: " % name, end="")
    with Timer() as t:
        fn()


test('doAppend', doAppend)
test('doAllocate', doAllocate)
test('doGenerator', doGenerator)

Which gives

Elements: 100000, Iterations: 144
doAppend: 2153.122902ms
doAllocate: 1346.076965ms
doGenerator: 1614.092112ms

(in 32-bit, doGenerator does better than doAllocate).

Here the gap between doAppend and doAllocate is significantly larger.

Obviously, the differences here really only apply if you are doing this more than a handful of times or if you are doing this on a heavily loaded system where those numbers are going to get scaled out by orders of magnitude, or if you are dealing with considerably larger lists.

The point here: Do it the Pythonic way for the best performance.

But if you are worrying about general, high-level performance, Python is the wrong language. The most fundamental problem being that Python function calls has traditionally been up to 300x slower than other languages due to Python features like decorators, etc. (PythonSpeed/PerformanceTips, Data Aggregation).

How to change default format at created_at and updated_at value laravel

You could use

protected $casts = [
    'created_at' => "datetime:Y-m-d\TH:iPZ",
];

in your model class or any format following this link https://www.php.net/manual/en/datetime.format.php

Unicode character in PHP string

I wonder why no one has mentioned this yet, but you can do an almost equivalent version using escape sequences in double quoted strings:

\x[0-9A-Fa-f]{1,2}

The sequence of characters matching the regular expression is a character in hexadecimal notation.

ASCII example:

<?php
    echo("\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21");
?>

Hello World!

So for your case, all you need to do is $str = "\x30\xA2";. But these are bytes, not characters. The byte representation of the Unicode codepoint coincides with UTF-16 big endian, so we could print it out directly as such:

<?php
    header('content-type:text/html;charset=utf-16be');
    echo("\x30\xA2");
?>

?

If you are using a different encoding, you'll need alter the bytes accordingly (mostly done with a library, though possible by hand too).

UTF-16 little endian example:

<?php
    header('content-type:text/html;charset=utf-16le');
    echo("\xA2\x30");
?>

?

UTF-8 example:

<?php
    header('content-type:text/html;charset=utf-8');
    echo("\xE3\x82\xA2");
?>

?

There is also the pack function, but you can expect it to be slow.

How to get Android crash logs?

You can use ACRA from this. Including this library to your projects and configuring it, you could receive (into your email or gdocs) their crash reports. Sorry for my bad English.

Select a row from html table and send values onclick of a button

check http://jsfiddle.net/Z22NU/12/

function fnselect(){

    alert($("tr.selected td:first" ).html());
}

Kotlin's List missing "add", "remove", Map missing "put", etc?

https://kotlinlang.org/docs/reference/collections.html

According to above link List<E> is immutable in Kotlin. However this would work:

var list2 = ArrayList<String>()
list2.removeAt(1)

How do I copy SQL Azure database to my local development server?

I just wanted to add a simplified version of dumbledad's answer, since it is the correct one.

  1. Export the Azure SQL Database to a BACPAC file on blob storage.
  2. From inside SQL Management studio, right-click your database, click "import data-tier application".
  3. You'll be prompted to enter the information to get to the BACPAC file on your Azure blob storage.
  4. Hit next a couple times and... Done!

Handling a Menu Item Click Event - Android

This code is work for me

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

     if (id == R.id.action_settings) {
  // add your action here that you want
        return true;
    }

    else if (id==R.id.login)
     {
         // add your action here that you want
     }


    return super.onOptionsItemSelected(item);
}

Why does the jquery change event not trigger when I set the value of a select using val()?

Because the change event requires an actual browser event initiated by the user instead of via javascript code.

Do this instead:

$("#single").val("Single2").trigger('change');

or

$("#single").val("Single2").change();

Favorite Visual Studio keyboard shortcuts

I like my code clean and arranged so my favorite keyboard shortcuts are the following:

Ctrl+K,D - Format document

Ctrl+K,F - Format selected code

Ctrl+E,S - Show white spaces

Ctrl+L - Cut line

Alt+Enter - Insert line below

Can you force Vue.js to reload/re-render?

sorry guys, except page reload method(flickering), none of them works for me (:key didn't worked).

and i found this method from old vue.js forum which is works for me:

https://github.com/vuejs/Discussion/issues/356

<template>
    <div v-if="show">
       <button @click="rerender">re-render</button>
    </div>
</template>
<script>
    export default {
        data(){
            return {show:true}
        },
        methods:{
            rerender(){
                this.show = false
                this.$nextTick(() => {
                    this.show = true
                    console.log('re-render start')
                    this.$nextTick(() => {
                        console.log('re-render end')
                    })
                })
            }
        }
    }
</script>

How do I convert from int to Long in Java?

I have this little toy, that also deals with non generic interfaces. I'm OK with it throwing a ClassCastException if feed wrong (OK and happy)

public class TypeUtil {
    public static long castToLong(Object o) {
        Number n = (Number) o;
        return n.longValue();
    }
}

Android Studio and Gradle build error

I used a local distribution of gradle downloaded from gradle website and used it in android studio.

It fixed the gradle build error.

Passing variables through handlebars partial

Not sure if this is helpful but here's an example of Handlebars template with dynamic parameters passed to an inline RadioButtons partial and the client(browser) rendering the radio buttons in the container.

For my use it's rendered with Handlebars on the server and lets the client finish it up. With it a forms tool can provide inline data within Handlebars without helpers.

Note : This example requires jQuery

{{#*inline "RadioButtons"}}
{{name}} Buttons<hr>
<div id="key-{{{name}}}"></div>
<script>
  {{{buttons}}}.map((o)=>{
    $("#key-{{name}}").append($(''
      +'<button class="checkbox">'
      +'<input name="{{{name}}}" type="radio" value="'+o.value+'" />'+o.text
      +'</button>'
    ));
  });
  // A little test script
  $("#key-{{{name}}} .checkbox").on("click",function(){
      alert($("input",this).val());
  });
</script>
{{/inline}}
{{>RadioButtons name="Radio" buttons='[
 {value:1,text:"One"},
 {value:2,text:"Two"}, 
 {value:3,text:"Three"}]' 
}}

Remove excess whitespace from within a string

To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this

? productID =26%20via%20@LFS

Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.

$productID=preg_replace('/[\s]+.*/','',$productID);

I look for a space in the URL and then remove everything after it.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

A few things to check:

  1. Make sure that you have the .NET Framework 4 installed.
  2. Ensure that version 4 of the .NET Framework is selected for your website & virtual directory (if applicable).
  3. Ensure that you have MVC installed or have the appropriate DLLs in your bin directory.
  4. Might need to allow ASP.NET 4.0 web service extensions
  5. Put the application in it's own app pool.
  6. Make sure the directory has at least "Scripts Only" execute permissions.

IPC performance: Named Pipe vs Socket

If you do not need speed, sockets are the easiest way to go!

If what you are looking at is speed, the fastest solution is shared Memory, not named pipes.

Reshape an array in NumPy

numpy has a great tool for this task ("numpy.reshape") link to reshape documentation

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

`numpy.reshape(a,(3,3))`

you can also use the "-1" trick

`a = a.reshape(-1,3)`

the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3

so yes.. this would also work: a = a.reshape(3,-1)

and this: a = a.reshape(-1,2) would do nothing

and this: a = a.reshape(-1,9) would change the shape to (2,9)

Does Typescript support the ?. operator? (And, what's it called?)

This is defined in the ECMAScript Optional Chaining specification, so we should probably refer to optional chaining when we discuss this. Likely implementation:

const result = a?.b?.c;

The long and short of this one is that the TypeScript team are waiting for the ECMAScript specification to get tightened up, so their implementation can be non-breaking in the future. If they implemented something now, it would end up needing major changes if ECMAScript redefine their specification.

See Optional Chaining Specification

Where something is never going to be standard JavaScript, the TypeScript team can implement as they see fit, but for future ECMAScript additions, they want to preserve semantics even if they give early access, as they have for so many other features.

Short Cuts

So all of JavaScripts funky operators are available, including the type conversions such as...

var n: number = +myString; // convert to number
var b: bool = !!myString; // convert to bool

Manual Solution

But back to the question. I have an obtuse example of how you can do a similar thing in JavaScript (and therefore TypeScript) although I'm definitely not suggesting it is a graceful as the feature you are really after.

(foo||{}).bar;

So if foo is undefined the result is undefined and if foo is defined and has a property named bar that has a value, the result is that value.

I put an example on JSFiddle.

This looks quite sketchy for longer examples.

var postCode = ((person||{}).address||{}).postcode;

Chain Function

If you are desperate for a shorter version while the specification is still up in the air, I use this method in some cases. It evaluates the expression and returns a default if the chain can't be satisfied or ends up null/undefined (note the != is important here, we don't want to use !== as we want a bit of positive juggling here).

function chain<T>(exp: () => T, d: T) {
    try {
        let val = exp();
        if (val != null) {
            return val;
        }
    } catch { }
    return d;
}

let obj1: { a?: { b?: string }} = {
    a: {
        b: 'c'
    }
};

// 'c'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = {
    a: {}
};

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = {};

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));

obj1 = null;

// 'Nothing'
console.log(chain(() => obj1.a.b, 'Nothing'));