Programs & Examples On #Exit code

An exit code is signaled by a program on termination to indicate if it completed successfully, or, if it did not, what sort of failure condition occurred.

Are there any standard exit status codes in Linux?

To a first approximation, 0 is success, non-zero is failure, with 1 being general failure, and anything larger than one being a specific failure. Aside from the trivial exceptions of false and test, which are both designed to give 1 for success, there's a few other exceptions I found.

More realistically, 0 means success or maybe failure, 1 means general failure or maybe success, 2 means general failure if 1 and 0 are both used for success, but maybe sucess as well.

The diff command gives 0 if files compared are identical, 1 if they differ, and 2 if binaries are different. 2 also means failure. The less command gives 1 for failure unless you fail to supply an argument, in which case, it exits 0 despite failing.

The more command and the spell command give 1 for failure, unless the failure is a result of permission denied, nonexistent file, or attempt to read a directory. In any of these cases, they exit 0 despite failing.

Then the expr command gives 1 for success unless the output is the empty string or zero, in which case, 0 is success. 2 and 3 are failure.

Then there's cases where success or failure is ambiguous. When grep fails to find a pattern, it exits 1, but it exits 2 for a genuine failure (like permission denied). Klist also exits 1 when it fails to find a ticket, although this isn't really any more of a failure than when grep doesn't find a pattern, or when you ls an empty directory.

So, unfortunately, the unix powers that be don't seem to enforce any logical set of rules, even on very commonly used executables.

Check if process returns 0 with batch file

How to write a compound statement with if?

You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.

if %ERRORLEVEL% == 0 (
    echo ErrorLevel is zero
    echo A second statement
) else if %ERRORLEVEL% == 1 (
    echo ErrorLevel is one
    echo A second statement
) else (
   echo ErrorLevel is > 1
   echo A second statement
)

In a Bash script, how can I exit the entire script if a certain condition occurs?

A SysOps guy once taught me the Three-Fingered Claw technique:

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try() your statement and code on.

Explanation

(based on flying sheep comment).

  • yell: print the script name and all arguments to stderr:
    • $0 is the path to the script ;
    • $* are all arguments.
    • >&2 means > redirect stdout to & pipe 2. pipe 1 would be stdout itself.
  • die does the same as yell, but exits with a non-0 exit status, which means “fail”.
  • try uses the || (boolean OR), which only evaluates the right side if the left one failed.

How do I specify the exit code of a console application in .NET?

In addition to the answers covering the return int's... a plea for sanity. Please, please define your exit codes in an enum, with Flags if appropriate. It makes debugging and maintenance so much easier (and, as a bonus, you can easily print out the exit codes on your help screen - you do have one of those, right?).

enum ExitCode : int {
  Success = 0,
  InvalidLogin = 1,
  InvalidFilename = 2,
  UnknownError = 10
}

int Main(string[] args) {
   return (int)ExitCode.Success;
}

check if command was successful in a batch file

You can use

if errorlevel 1 echo Unsuccessful

in some cases. This depends on the last command returning a proper exit code. You won't be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.

Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

How do I get the application exit code from a Windows command line?

Testing ErrorLevel works for console applications, but as hinted at by dmihailescu, this won't work if you're trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.

Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt's START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel.

start /wait something.exe
echo %errorlevel%

Command /usr/bin/codesign failed with exit code 1

I just created a new project, copied all my classes and resources and then it worked!

Exit codes in Python

You're looking for calls to sys.exit() in the script. The argument to that method is returned to the environment as the exit code.

It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.

How do I get logs from all pods of a Kubernetes replication controller?

To build on the previous answer if you add -f you can tail the logs.

kubectl logs -f deployment/app

List names of all tables in a SQL Server 2012 schema

SELECT t1.name AS [Schema], t2.name AS [Table]
FROM sys.schemas t1
INNER JOIN sys.tables t2
ON t2.schema_id = t1.schema_id
ORDER BY t1.name,t2.name

How to compile a c++ program in Linux?

  1. To Compile your C++ code use:-

g++ file_name.cpp -o executable_file_name

(i) -o option is used to show error in the code (ii) if there is no error in the code_file, then it will generate an executable file.

  1. Now execute the generated executable file:

./executable_file_name

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

 jquery.ajax({
            url: `//your api url`
            type: "GET",
            dataType: "json",
            success: function(data) {
                jQuery.each(data, function(index, value) {
                        console.log(data);
                        `All you API data is here`
                    }
                }
            });     

Stop handler.postDelayed()

You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

Need to combine lots of files in a directory

There is a convenient third party tool named FileMenu Tools, that gives several right-click tools as a windows explorer extension.

One of them is Split file / Join Parts, that does and undoes exactly what you are looking for.

Check it at http://www.lopesoft.com/en/filemenutools. Of course, it is windows only, as Unixes environments already have lots of tools for that.

Django request.GET

def search(request):
if 'q' in request.GET.keys():
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'

return HttpResponse(message)

you can use if ... in too.

How do I print bytes as hexadecimal?

Well you can convert one byte (unsigned char) at a time into a array like so

char buffer [17];
buffer[16] = 0;
for(j = 0; j < 8; j++)
    sprintf(&buffer[2*j], "%02X", data[j]);

What is the difference between concurrent programming and parallel programming?

They're two phrases that describe the same thing from (very slightly) different viewpoints. Parallel programming is describing the situation from the viewpoint of the hardware -- there are at least two processors (possibly within a single physical package) working on a problem in parallel. Concurrent programming is describing things more from the viewpoint of the software -- two or more actions may happen at exactly the same time (concurrently).

The problem here is that people are trying to use the two phrases to draw a clear distinction when none really exists. The reality is that the dividing line they're trying to draw has been fuzzy and indistinct for decades, and has grown ever more indistinct over time.

What they're trying to discuss is the fact that once upon a time, most computers had only a single CPU. When you executed multiple processes (or threads) on that single CPU, the CPU was only really executing one instruction from one of those threads at a time. The appearance of concurrency was an illusion--the CPU switching between executing instructions from different threads quickly enough that to human perception (to which anything less than 100 ms or so looks instantaneous) it looked like it was doing many things at once.

The obvious contrast to this is a computer with multiple CPUs, or a CPU with multiple cores, so the machine is executing instructions from multiple threads and/or processes at exactly the same time; code executing one can't/doesn't have any effect on code executing in the other.

Now the problem: such a clean distinction has almost never existed. Computer designers are actually fairly intelligent, so they noticed a long time ago that (for example) when you needed to read some data from an I/O device such as a disk, it took a long time (in terms of CPU cycles) to finish. Instead of leaving the CPU idle while that happened, they figured out various ways of letting one process/thread make an I/O request, and let code from some other process/thread execute on the CPU while the I/O request completed.

So, long before multi-core CPUs became the norm, we had operations from multiple threads happening in parallel.

That's only the tip of the iceberg though. Decades ago, computers started providing another level of parallelism as well. Again, being fairly intelligent people, computer designers noticed that in a lot of cases, they had instructions that didn't affect each other, so it was possible to execute more than one instruction from the same stream at the same time. One early example that became pretty well known was the Control Data 6600. This was (by a fairly wide margin) the fastest computer on earth when it was introduced in 1964--and much of the same basic architecture remains in use today. It tracked the resources used by each instruction, and had a set of execution units that executed instructions as soon as the resources on which they depended became available, very similar to the design of most recent Intel/AMD processors.

But (as the commercials used to say) wait--that's not all. There's yet another design element to add still further confusion. It's been given quite a few different names (e.g., "Hyperthreading", "SMT", "CMP"), but they all refer to the same basic idea: a CPU that can execute multiple threads simultaneously, using a combination of some resources that are independent for each thread, and some resources that are shared between the threads. In a typical case this is combined with the instruction-level parallelism outlined above. To do that, we have two (or more) sets of architectural registers. Then we have a set of execution units that can execute instructions as soon as the necessary resources become available. These often combine well because the instructions from the separate streams virtually never depend on the same resources.

Then, of course, we get to modern systems with multiple cores. Here things are obvious, right? We have N (somewhere between 2 and 256 or so, at the moment) separate cores, that can all execute instructions at the same time, so we have clear-cut case of real parallelism--executing instructions in one process/thread doesn't affect executing instructions in another.

Well, sort of. Even here we have some independent resources (registers, execution units, at least one level of cache) and some shared resources (typically at least the lowest level of cache, and definitely the memory controllers and bandwidth to memory).

To summarize: the simple scenarios people like to contrast between shared resources and independent resources virtually never happen in real life. With all resources shared, we end up with something like MS-DOS, where we can only run one program at a time, and we have to stop running one before we can run the other at all. With completely independent resources, we have N computers running MS-DOS (without even a network to connect them) with no ability to share anything between them at all (because if we can even share a file, well, that's a shared resource, a violation of the basic premise of nothing being shared).

Every interesting case involves some combination of independent resources and shared resources. Every reasonably modern computer (and a lot that aren't at all modern) has at least some ability to carry out at least a few independent operations simultaneously, and just about anything more sophisticated than MS-DOS has taken advantage of that to at least some degree.

The nice, clean division between "concurrent" and "parallel" that people like to draw just doesn't exist, and almost never has. What people like to classify as "concurrent" usually still involves at least one and often more different types of parallel execution. What they like to classify as "parallel" often involves sharing resources and (for example) one process blocking another's execution while using a resource that's shared between the two.

People trying to draw a clean distinction between "parallel" and "concurrent" are living in a fantasy of computers that never actually existed.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

UPDATE: this is not the solution but it's a workaround for a problem that can cause the exception presented in the question.

I've solved changing from Release Configuration to Debug Configuration.

Comparing floating point number to zero

You can use std::nextafter with a fixed factor of the epsilon of a value like the following:

bool isNearlyEqual(double a, double b)
{
  int factor = /* a fixed factor of epsilon */;

  double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor;
  double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor;

  return min_a <= b && max_a >= b;
}

Windows Task Scheduler doesn't start batch file task

I was running this on a Windows Server OS. I worked for hours, only to find that the problem was that I had checked the "Run with highest privileges" checkbox. When checked on, it removes all drive mappings. And my .bat file was on the network.

enter image description here

In Gradle, is there a better way to get Environment Variables?

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

Subtract days, months, years from a date in JavaScript

Use the moment.js library for time and date management.

import moment = require('moment');

const now = moment();

now.subtract(7, 'seconds'); // 7 seconds ago
now.subtract(7, 'days');    // 7 days and 7 seconds ago
now.subtract(7, 'months');  // 7 months, 7 days and 7 seconds ago
now.subtract(7, 'years');   // 7 years, 7 months, 7 days and 7 seconds ago
// because `now` has been mutated, it no longer represents the current time

Using JQuery hover with HTML image map

Although jQuery Maphilight plugin does the job, it relies on the outdated verbose imagemap in your html. I would prefer to keep the mapcoordinates external. This could be as JS with the jquery imagemap plugin but it lacks hover states. A nice solution is googles geomap visualisation in flash and JS. But the opensource future for this kind of vectordata however is svg, considering svg support accross all modern browsers, and googles svgweb for a flash convert for IE, why not a jquery plugin to add links and hoverstates to a svg map, like the JS demo here? That way you also avoid the complex step of transforming a vectormap to a imagemap coordinates.

Convert Unix timestamp to a date string

Put the following in your ~/.bashrc :

function unixts() { date -d "@$1"; }

Example usage:

$ unixts 1551276383

Wed Feb 27 14:06:23 GMT 2019

How do I keep a label centered in WinForms?

The accepted answer didn't work for me for two reasons:

  1. I had BackColor set so setting AutoSize = false and Dock = Fill causes the background color to fill the whole form
  2. I couldn't have AutoSize set to false anyway because my label text was dynamic

Instead, I simply used the form's width and the width of the label to calculate the left offset:

MyLabel.Left = (this.Width - MyLabel.Width) / 2;

Euclidean distance of two vectors

try using this:

sqrt(sum((x1-x2)^2))

How to use the "required" attribute with a "radio" input field

Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:

_x000D_
_x000D_
fieldset { 
  display: block;
  margin-left: 0;
  margin-right: 0;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 0;
  padding-right: 0;
  border: none;
}
body {font-size: 15px; font-family: serif;}
input {
  background: transparent;
  border-radius: 0px;
  border: 1px solid black;
  padding: 5px;
  box-shadow: none!important;
  font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
  opacity: 0; 
  position: absolute; 
  pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
  display: block;
  border: 1px solid black;
  border-left: 0;
  padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
  <div>
    <label for="name">Name (optional)</label>
    <input id="name" type="text" name="name">
  </div>
  <fieldset>
  <legend>Gender</legend>
  <div class="checkboxes">
    <label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
    <label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
    <label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
  </div>
  </fieldset>
  <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_

Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.

Return empty cell from formula in Excel

Google brought me here with a very similar problem, I finally figured out a solution that fits my needs, it might help someone else too...

I used this formula:

=IFERROR(MID(Q2, FIND("{",Q2), FIND("}",Q2) - FIND("{",Q2) + 1), "")

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

df = pd.DataFrame({'countries':['US','UK','Germany','China']})
countries = ['UK','China']

implement in:

df[df.countries.isin(countries)]

implement not in as in of rest countries:

df[df.countries.isin([x for x in np.unique(df.countries) if x not in countries])]

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

I had the same problem and finally resolved it by changing the order of pem blocks in certificate file.

The cert block should be put in the beginning of the file, then intermediate blocks, then root block.

I realized this problem by comparing a problematic certificate file with a working certificate file.

How does one add keyboard languages and switch between them in Linux Mint 16?

For Linux Mate 17.1 Go to Menu/All applications/Keyboard/Layouts tab/Click Add/Pick out your layout by country or by language/Click Add and a language icon (US, PT and so on) will show at Panel/Close Keyboard Preferences and just click over it at Panel to switch the input language.

What is the most useful script you've written for everyday life?

I used to work at a technology summer camp, and we had to compose these write-ups for each of the kids in the group at the end of the week, which they would then receive and take home as a keepsake. Usually, these consisted of a bunch of generic sentences, and one to two personalized sentences. I wrote a python script which constructed one of these write-ups out of a bank of canned sentences, and allowed the user to add a couple of personalized sentences in the middle. This saved a huge amount of time for me and other counselors I let in on the secret. Even though so much of it was automated, our write-ups still looked better than many of the 'honest' ones, because we could put more time into the personalized parts.

How to load up CSS files using Javascript?

Below a full code using for loading JS and/or CSS

function loadScript(directory, files){
  var head = document.getElementsByTagName("head")[0]
  var done = false
  var extension = '.js'
  for (var file of files){ 
    var path = directory + file + extension 
    var script = document.createElement("script")
    script.src = path        
    script.type = "text/javascript"
    script.onload = script.onreadystatechange = function() {
        if ( !done && (!this.readyState ||
            this.readyState == "loaded" || this.readyState == "complete") ) {
            done = true
            script.onload = script.onreadystatechange = null   // cleans up a little memory:
            head.removeChild(script)  // to avoid douple loading
        }
  };
  head.appendChild(script) 
  done = false
 }
}

function loadStyle(directory, files){
  var head = document.getElementsByTagName("head")[0]
  var extension = '.css'
  for (var file of files){ 
   var path = directory + file + extension 
   var link = document.createElement("link")
   link.href = path        
   link.type = "text/css"
   link.rel = "stylesheet" 
   head.appendChild(link) 
 }
}

(() => loadScript('libraries/', ['listen','functions', 'speak', 'commands', 'wsBrowser', 'main'])) ();
(() => loadScript('scripts/', ['index'])) ();

(() => loadStyle('styles/', ['index'])) ();

How to style components using makeStyles and still have lifecycle methods in Material UI?

I used withStyles instead of makeStyle

EX :

import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";

const useStyles = theme => ({
        root: {
           flexGrow: 1,
         },
  });

class App extends Component {
       render() {
                const { classes } = this.props;
                return(
                    <div className={classes.root}>
                       Test
                </div>
                )
          }
} 

export default withStyles(useStyles)(App)

Excel 2010 VBA Referencing Specific Cells in other worksheets

I am going to give you a simplistic answer that hopefully will help you with VBA in general. The easiest way to learn how VBA works and how to reference and access elements is to record your macro then edit it in the VBA editor. This is how I learned VBA. It is based on visual basic so all the programming conventions of VB apply. Recording the macro lets you see how to access and do things.

you could use something like this:

var result = 0
Sheets("Sheet1").Select
result = Range("A1").Value * Range("B1").Value
Sheets("Sheet2").Select
Range("D1").Value = result

Alternatively you can also reference a cell using Cells(1,1).Value This way you can set variables and increment them as you wish. I think I am just not clear on exactly what you are trying to do but i hope this helps.

Swift - Integer conversion to Hours/Minutes/Seconds

NSTimeInterval is Double do do it with extension. Example:

extension Double {

    var formattedTime: String {

        var formattedTime = "0:00"

        if self > 0 {

            let hours = Int(self / 3600)
            let minutes = Int(truncatingRemainder(dividingBy: 3600) / 60)

            formattedTime = String(hours) + ":" + (minutes < 10 ? "0" + String(minutes) : String(minutes))
        }

        return formattedTime
    }
}

Search a whole table in mySQL for a string

Identify all the fields that could be related to your search and then use a query like:

SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
   OR field2 LIKE '%Mary%'
   OR field3 LIKE '%Mary%'
   OR field4 LIKE '%Mary%'
   ....
   (do that for each field you want to check)

Using LIKE '%Mary%' instead of = 'Mary' will look for the fields that contains someCaracters + 'Mary' + someCaracters.

Best way to check function arguments?

In this elongated answer, we implement a Python 3.x-specific type checking decorator based on PEP 484-style type hints in less than 275 lines of pure-Python (most of which is explanatory docstrings and comments) – heavily optimized for industrial-strength real-world use complete with a py.test-driven test suite exercising all possible edge cases.

Feast on the unexpected awesome of bear typing:

>>> @beartype
... def spirit_bear(kermode: str, gitgaata: (str, int)) -> tuple:
...     return (kermode, gitgaata, "Moksgm'ol", 'Ursus americanus kermodei')
>>> spirit_bear(0xdeadbeef, 'People of the Cane')
AssertionError: parameter kermode=0xdeadbeef not of <class "str">

As this example suggests, bear typing explicitly supports type checking of parameters and return values annotated as either simple types or tuples of such types. Golly!

O.K., that's actually unimpressive. @beartype resembles every other Python 3.x-specific type checking decorator based on PEP 484-style type hints in less than 275 lines of pure-Python. So what's the rub, bub?

Pure Bruteforce Hardcore Efficiency

Bear typing is dramatically more efficient in both space and time than all existing implementations of type checking in Python to the best of my limited domain knowledge. (More on that later.)

Efficiency usually doesn't matter in Python, however. If it did, you wouldn't be using Python. Does type checking actually deviate from the well-established norm of avoiding premature optimization in Python? Yes. Yes, it does.

Consider profiling, which adds unavoidable overhead to each profiled metric of interest (e.g., function calls, lines). To ensure accurate results, this overhead is mitigated by leveraging optimized C extensions (e.g., the _lsprof C extension leveraged by the cProfile module) rather than unoptimized pure-Python (e.g., the profile module). Efficiency really does matter when profiling.

Type checking is no different. Type checking adds overhead to each function call type checked by your application – ideally, all of them. To prevent well-meaning (but sadly small-minded) coworkers from removing the type checking you silently added after last Friday's caffeine-addled allnighter to your geriatric legacy Django web app, type checking must be fast. So fast that no one notices it's there when you add it without telling anyone. I do this all the time! Stop reading this if you are a coworker.

If even ludicrous speed isn't enough for your gluttonous application, however, bear typing may be globally disabled by enabling Python optimizations (e.g., by passing the -O option to the Python interpreter):

$ python3 -O
# This succeeds only when type checking is optimized away. See above!
>>> spirit_bear(0xdeadbeef, 'People of the Cane')
(0xdeadbeef, 'People of the Cane', "Moksgm'ol", 'Ursus americanus kermodei')

Just because. Welcome to bear typing.

What The...? Why "bear"? You're a Neckbeard, Right?

Bear typing is bare-metal type checking – that is, type checking as close to the manual approach of type checking in Python as feasible. Bear typing is intended to impose no performance penalties, compatibility constraints, or third-party dependencies (over and above that imposed by the manual approach, anyway). Bear typing may be seamlessly integrated into existing codebases and test suites without modification.

Everyone's probably familiar with the manual approach. You manually assert each parameter passed to and/or return value returned from every function in your codebase. What boilerplate could be simpler or more banal? We've all seen it a hundred times a googleplex times, and vomited a little in our mouths everytime we did. Repetition gets old fast. DRY, yo.

Get your vomit bags ready. For brevity, let's assume a simplified easy_spirit_bear() function accepting only a single str parameter. Here's what the manual approach looks like:

def easy_spirit_bear(kermode: str) -> str:
    assert isinstance(kermode, str), 'easy_spirit_bear() parameter kermode={} not of <class "str">'.format(kermode)
    return_value = (kermode, "Moksgm'ol", 'Ursus americanus kermodei')
    assert isinstance(return_value, str), 'easy_spirit_bear() return value {} not of <class "str">'.format(return_value)
    return return_value

Python 101, right? Many of us passed that class.

Bear typing extracts the type checking manually performed by the above approach into a dynamically defined wrapper function automatically performing the same checks – with the added benefit of raising granular TypeError rather than ambiguous AssertionError exceptions. Here's what the automated approach looks like:

def easy_spirit_bear_wrapper(*args, __beartype_func=easy_spirit_bear, **kwargs):
    if not (
        isinstance(args[0], __beartype_func.__annotations__['kermode'])
        if 0 < len(args) else
        isinstance(kwargs['kermode'], __beartype_func.__annotations__['kermode'])
        if 'kermode' in kwargs else True):
            raise TypeError(
                'easy_spirit_bear() parameter kermode={} not of {!r}'.format(
                args[0] if 0 < len(args) else kwargs['kermode'],
                __beartype_func.__annotations__['kermode']))

    return_value = __beartype_func(*args, **kwargs)

    if not isinstance(return_value, __beartype_func.__annotations__['return']):
        raise TypeError(
            'easy_spirit_bear() return value {} not of {!r}'.format(
                return_value, __beartype_func.__annotations__['return']))

    return return_value

It's long-winded. But it's also basically* as fast as the manual approach. * Squinting suggested.

Note the complete lack of function inspection or iteration in the wrapper function, which contains a similar number of tests as the original function – albeit with the additional (maybe negligible) costs of testing whether and how the parameters to be type checked are passed to the current function call. You can't win every battle.

Can such wrapper functions actually be reliably generated to type check arbitrary functions in less than 275 lines of pure Python? Snake Plisskin says, "True story. Got a smoke?"

And, yes. I may have a neckbeard.

No, Srsly. Why "bear"?

Bear beats duck. Duck may fly, but bear may throw salmon at duck. In Canada, nature can surprise you.

Next question.

What's So Hot about Bears, Anyway?

Existing solutions do not perform bare-metal type checking – at least, none I've grepped across. They all iteratively reinspect the signature of the type-checked function on each function call. While negligible for a single call, reinspection overhead is usually non-negligible when aggregated over all calls. Really, really non-negligible.

It's not simply efficiency concerns, however. Existing solutions also often fail to account for common edge cases. This includes most if not all toy decorators provided as stackoverflow answers here and elsewhere. Classic failures include:

  • Failing to type check keyword arguments and/or return values (e.g., sweeneyrod's @checkargs decorator).
  • Failing to support tuples (i.e., unions) of types accepted by the isinstance() builtin.
  • Failing to propagate the name, docstring, and other identifying metadata from the original function onto the wrapper function.
  • Failing to supply at least a semblance of unit tests. (Kind of critical.)
  • Raising generic AssertionError exceptions rather than specific TypeError exceptions on failed type checks. For granularity and sanity, type checking should never raise generic exceptions.

Bear typing succeeds where non-bears fail. All one, all bear!

Bear Typing Unbared

Bear typing shifts the space and time costs of inspecting function signatures from function call time to function definition time – that is, from the wrapper function returned by the @beartype decorator into the decorator itself. Since the decorator is only called once per function definition, this optimization yields glee for all.

Bear typing is an attempt to have your type checking cake and eat it, too. To do so, @beartype:

  1. Inspects the signature and annotations of the original function.
  2. Dynamically constructs the body of the wrapper function type checking the original function. Thaaat's right. Python code generating Python code.
  3. Dynamically declares this wrapper function via the exec() builtin.
  4. Returns this wrapper function.

Shall we? Let's dive into the deep end.

# If the active Python interpreter is *NOT* optimized (e.g., option "-O" was
# *NOT* passed to this interpreter), enable type checking.
if __debug__:
    import inspect
    from functools import wraps
    from inspect import Parameter, Signature

    def beartype(func: callable) -> callable:
        '''
        Decorate the passed **callable** (e.g., function, method) to validate
        both all annotated parameters passed to this callable _and_ the
        annotated value returned by this callable if any.

        This decorator performs rudimentary type checking based on Python 3.x
        function annotations, as officially documented by PEP 484 ("Type
        Hints"). While PEP 484 supports arbitrarily complex type composition,
        this decorator requires _all_ parameter and return value annotations to
        be either:

        * Classes (e.g., `int`, `OrderedDict`).
        * Tuples of classes (e.g., `(int, OrderedDict)`).

        If optimizations are enabled by the active Python interpreter (e.g., due
        to option `-O` passed to this interpreter), this decorator is a noop.

        Raises
        ----------
        NameError
            If any parameter has the reserved name `__beartype_func`.
        TypeError
            If either:
            * Any parameter or return value annotation is neither:
              * A type.
              * A tuple of types.
            * The kind of any parameter is unrecognized. This should _never_
              happen, assuming no significant changes to Python semantics.
        '''

        # Raw string of Python statements comprising the body of this wrapper,
        # including (in order):
        #
        # * A "@wraps" decorator propagating the name, docstring, and other
        #   identifying metadata of the original function to this wrapper.
        # * A private "__beartype_func" parameter initialized to this function.
        #   In theory, the "func" parameter passed to this decorator should be
        #   accessible as a closure-style local in this wrapper. For unknown
        #   reasons (presumably, a subtle bug in the exec() builtin), this is
        #   not the case. Instead, a closure-style local must be simulated by
        #   passing the "func" parameter to this function at function
        #   definition time as the default value of an arbitrary parameter. To
        #   ensure this default is *NOT* overwritten by a function accepting a
        #   parameter of the same name, this edge case is tested for below.
        # * Assert statements type checking parameters passed to this callable.
        # * A call to this callable.
        # * An assert statement type checking the value returned by this
        #   callable.
        #
        # While there exist numerous alternatives (e.g., appending to a list or
        # bytearray before joining the elements of that iterable into a string),
        # these alternatives are either slower (as in the case of a list, due to
        # the high up-front cost of list construction) or substantially more
        # cumbersome (as in the case of a bytearray). Since string concatenation
        # is heavily optimized by the official CPython interpreter, the simplest
        # approach is (curiously) the most ideal.
        func_body = '''
@wraps(__beartype_func)
def func_beartyped(*args, __beartype_func=__beartype_func, **kwargs):
'''

        # "inspect.Signature" instance encapsulating this callable's signature.
        func_sig = inspect.signature(func)

        # Human-readable name of this function for use in exceptions.
        func_name = func.__name__ + '()'

        # For the name of each parameter passed to this callable and the
        # "inspect.Parameter" instance encapsulating this parameter (in the
        # passed order)...
        for func_arg_index, func_arg in enumerate(func_sig.parameters.values()):
            # If this callable redefines a parameter initialized to a default
            # value by this wrapper, raise an exception. Permitting this
            # unlikely edge case would permit unsuspecting users to
            # "accidentally" override these defaults.
            if func_arg.name == '__beartype_func':
                raise NameError(
                    'Parameter {} reserved for use by @beartype.'.format(
                        func_arg.name))

            # If this parameter is both annotated and non-ignorable for purposes
            # of type checking, type check this parameter.
            if (func_arg.annotation is not Parameter.empty and
                func_arg.kind not in _PARAMETER_KIND_IGNORED):
                # Validate this annotation.
                _check_type_annotation(
                    annotation=func_arg.annotation,
                    label='{} parameter {} type'.format(
                        func_name, func_arg.name))

                # String evaluating to this parameter's annotated type.
                func_arg_type_expr = (
                    '__beartype_func.__annotations__[{!r}]'.format(
                        func_arg.name))

                # String evaluating to this parameter's current value when
                # passed as a keyword.
                func_arg_value_key_expr = 'kwargs[{!r}]'.format(func_arg.name)

                # If this parameter is keyword-only, type check this parameter
                # only by lookup in the variadic "**kwargs" dictionary.
                if func_arg.kind is Parameter.KEYWORD_ONLY:
                    func_body += '''
    if {arg_name!r} in kwargs and not isinstance(
        {arg_value_key_expr}, {arg_type_expr}):
        raise TypeError(
            '{func_name} keyword-only parameter '
            '{arg_name}={{}} not a {{!r}}'.format(
                {arg_value_key_expr}, {arg_type_expr}))
'''.format(
                        func_name=func_name,
                        arg_name=func_arg.name,
                        arg_type_expr=func_arg_type_expr,
                        arg_value_key_expr=func_arg_value_key_expr,
                    )
                # Else, this parameter may be passed either positionally or as
                # a keyword. Type check this parameter both by lookup in the
                # variadic "**kwargs" dictionary *AND* by index into the
                # variadic "*args" tuple.
                else:
                    # String evaluating to this parameter's current value when
                    # passed positionally.
                    func_arg_value_pos_expr = 'args[{!r}]'.format(
                        func_arg_index)

                    func_body += '''
    if not (
        isinstance({arg_value_pos_expr}, {arg_type_expr})
        if {arg_index} < len(args) else
        isinstance({arg_value_key_expr}, {arg_type_expr})
        if {arg_name!r} in kwargs else True):
            raise TypeError(
                '{func_name} parameter {arg_name}={{}} not of {{!r}}'.format(
                {arg_value_pos_expr} if {arg_index} < len(args) else {arg_value_key_expr},
                {arg_type_expr}))
'''.format(
                    func_name=func_name,
                    arg_name=func_arg.name,
                    arg_index=func_arg_index,
                    arg_type_expr=func_arg_type_expr,
                    arg_value_key_expr=func_arg_value_key_expr,
                    arg_value_pos_expr=func_arg_value_pos_expr,
                )

        # If this callable's return value is both annotated and non-ignorable
        # for purposes of type checking, type check this value.
        if func_sig.return_annotation not in _RETURN_ANNOTATION_IGNORED:
            # Validate this annotation.
            _check_type_annotation(
                annotation=func_sig.return_annotation,
                label='{} return type'.format(func_name))

            # Strings evaluating to this parameter's annotated type and
            # currently passed value, as above.
            func_return_type_expr = (
                "__beartype_func.__annotations__['return']")

            # Call this callable, type check the returned value, and return this
            # value from this wrapper.
            func_body += '''
    return_value = __beartype_func(*args, **kwargs)
    if not isinstance(return_value, {return_type}):
        raise TypeError(
            '{func_name} return value {{}} not of {{!r}}'.format(
                return_value, {return_type}))
    return return_value
'''.format(func_name=func_name, return_type=func_return_type_expr)
        # Else, call this callable and return this value from this wrapper.
        else:
            func_body += '''
    return __beartype_func(*args, **kwargs)
'''

        # Dictionary mapping from local attribute name to value. For efficiency,
        # only those local attributes explicitly required in the body of this
        # wrapper are copied from the current namespace. (See below.)
        local_attrs = {'__beartype_func': func}

        # Dynamically define this wrapper as a closure of this decorator. For
        # obscure and presumably uninteresting reasons, Python fails to locally
        # declare this closure when the locals() dictionary is passed; to
        # capture this closure, a local dictionary must be passed instead.
        exec(func_body, globals(), local_attrs)

        # Return this wrapper.
        return local_attrs['func_beartyped']

    _PARAMETER_KIND_IGNORED = {
        Parameter.POSITIONAL_ONLY, Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD,
    }
    '''
    Set of all `inspect.Parameter.kind` constants to be ignored during
    annotation- based type checking in the `@beartype` decorator.

    This includes:

    * Constants specific to variadic parameters (e.g., `*args`, `**kwargs`).
      Variadic parameters cannot be annotated and hence cannot be type checked.
    * Constants specific to positional-only parameters, which apply to non-pure-
      Python callables (e.g., defined by C extensions). The `@beartype`
      decorator applies _only_ to pure-Python callables, which provide no
      syntactic means of specifying positional-only parameters.
    '''

    _RETURN_ANNOTATION_IGNORED = {Signature.empty, None}
    '''
    Set of all annotations for return values to be ignored during annotation-
    based type checking in the `@beartype` decorator.

    This includes:

    * `Signature.empty`, signifying a callable whose return value is _not_
      annotated.
    * `None`, signifying a callable returning no value. By convention, callables
      returning no value are typically annotated to return `None`. Technically,
      callables whose return values are annotated as `None` _could_ be
      explicitly checked to return `None` rather than a none-`None` value. Since
      return values are safely ignorable by callers, however, there appears to
      be little real-world utility in enforcing this constraint.
    '''

    def _check_type_annotation(annotation: object, label: str) -> None:
        '''
        Validate the passed annotation to be a valid type supported by the
        `@beartype` decorator.

        Parameters
        ----------
        annotation : object
            Annotation to be validated.
        label : str
            Human-readable label describing this annotation, interpolated into
            exceptions raised by this function.

        Raises
        ----------
        TypeError
            If this annotation is neither a new-style class nor a tuple of
            new-style classes.
        '''

        # If this annotation is a tuple, raise an exception if any member of
        # this tuple is not a new-style class. Note that the "__name__"
        # attribute tested below is not defined by old-style classes and hence
        # serves as a helpful means of identifying new-style classes.
        if isinstance(annotation, tuple):
            for member in annotation:
                if not (
                    isinstance(member, type) and hasattr(member, '__name__')):
                    raise TypeError(
                        '{} tuple member {} not a new-style class'.format(
                            label, member))
        # Else if this annotation is not a new-style class, raise an exception.
        elif not (
            isinstance(annotation, type) and hasattr(annotation, '__name__')):
            raise TypeError(
                '{} {} neither a new-style class nor '
                'tuple of such classes'.format(label, annotation))

# Else, the active Python interpreter is optimized. In this case, disable type
# checking by reducing this decorator to the identity decorator.
else:
    def beartype(func: callable) -> callable:
        return func

And leycec said, Let the @beartype bring forth type checking fastly: and it was so.

Caveats, Curses, and Empty Promises

Nothing is perfect. Even bear typing.

Caveat I: Default Values Unchecked

Bear typing does not type check unpassed parameters assigned default values. In theory, it could. But not in 275 lines or less and certainly not as a stackoverflow answer.

The safe (...probably totally unsafe) assumption is that function implementers claim they knew what they were doing when they defined default values. Since default values are typically constants (...they'd better be!), rechecking the types of constants that never change on each function call assigned one or more default values would contravene the fundamental tenet of bear typing: "Don't repeat yourself over and oooover and oooo-oooover again."

Show me wrong and I will shower you with upvotes.

Caveat II: No PEP 484

PEP 484 ("Type Hints") formalized the use of function annotations first introduced by PEP 3107 ("Function Annotations"). Python 3.5 superficially supports this formalization with a new top-level typing module, a standard API for composing arbitrarily complex types from simpler types (e.g., Callable[[Arg1Type, Arg2Type], ReturnType], a type describing a function accepting two arguments of type Arg1Type and Arg2Type and returning a value of type ReturnType).

Bear typing supports none of them. In theory, it could. But not in 275 lines or less and certainly not as a stackoverflow answer.

Bear typing does, however, support unions of types in the same way that the isinstance() builtin supports unions of types: as tuples. This superficially corresponds to the typing.Union type – with the obvious caveat that typing.Union supports arbitrarily complex types, while tuples accepted by @beartype support only simple classes. In my defense, 275 lines.

Tests or It Didn't Happen

Here's the gist of it. Get it, gist? I'll stop now.

As with the @beartype decorator itself, these py.test tests may be seamlessly integrated into existing test suites without modification. Precious, isn't it?

Now the mandatory neckbeard rant nobody asked for.

A History of API Violence

Python 3.5 provides no actual support for using PEP 484 types. wat?

It's true: no type checking, no type inference, no type nuthin'. Instead, developers are expected to routinely run their entire codebases through heavyweight third-party CPython interpreter wrappers implementing a facsimile of such support (e.g., mypy). Of course, these wrappers impose:

  • A compatibility penalty. As the official mypy FAQ admits in response to the frequently asked question "Can I use mypy to type check my existing Python code?": "It depends. Compatibility is pretty good, but some Python features are not yet implemented or fully supported." A subsequent FAQ response clarifies this incompatibility by stating that:
    • "...your code must make attributes explicit and use a explicit protocol representation." Grammar police see your "a explicit" and raise you an implicit frown.
    • "Mypy will support modular, efficient type checking, and this seems to rule out type checking some language features, such as arbitrary runtime addition of methods. However, it is likely that many of these features will be supported in a restricted form (for example, runtime modification is only supported for classes or methods registered as dynamic or ‘patchable’)."
    • For a full list of syntactic incompatibilities, see "Dealing with common issues". It's not pretty. You just wanted type checking and now you refactored your entire codebase and broke everyone's build two days from the candidate release and the comely HR midget in casual business attire slips a pink slip through the crack in your cubicle-cum-mancave. Thanks alot, mypy.
  • A performance penalty, despite interpreting statically typed code. Fourty years of hard-boiled computer science tells us that (...all else being equal) interpreting statically typed code should be faster, not slower, than interpreting dynamically typed code. In Python, up is the new down.
  • Additional non-trivial dependencies, increasing:
    • The bug-laden fragility of project deployment, especially cross-platform.
    • The maintenance burden of project development.
    • Possible attack surface.

I ask Guido: "Why? Why bother inventing an abstract API if you weren't willing to pony up a concrete API actually doing something with that abstraction?" Why leave the fate of a million Pythonistas to the arthritic hand of the free open-source marketplace? Why create yet another techno-problem that could have been trivially solved with a 275-line decorator in the official Python stdlib?

I have no Python and I must scream.

What does '&' do in a C++ declaration?

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            *p=*p+100;
            return(*p);
}

This is invalid code on several counts. Running it through g++ gives:

crap.cpp: In function ‘int main()’:
crap.cpp:11: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int*’
crap.cpp:3: error: in passing argument 1 of ‘int add(int&)’
crap.cpp: In function ‘int add(int&)’:
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:19: error: invalid type argument of ‘unary *’
crap.cpp:20: error: invalid type argument of ‘unary *’

A valid version of the code reads:

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            p=p+100;
            return p;
}

What is happening here is that you are passing a variable "as is" to your function. This is roughly equivalent to:

int add(int *p)
{
      *p=*p+100;
      return *p;
}

However, passing a reference to a function ensures that you cannot do things like pointer arithmetic with the reference. For example:

int add(int &p)
{
            *p=*p+100;
            return p;
}

is invalid.

If you must use a pointer to a reference, that has to be done explicitly:

int add(int &p)
{
                    int* i = &p;
            i=i+100L;
            return *i;
}

Which on a test run gives (as expected) junk output:

The value of the variable number before calling the function : 5
The value of the variable number after the function is returned : 5
The value of result : 1399090792

Specifying Font and Size in HTML table

Enclose your code with the html and body tags. Size attribute does not correspond to font-size and it looks like its domain does not go beyond value 7. Furthermore font tag is not supported in HTML5. Consider this code for your case

<!DOCTYPE html>
<html>
<body>

<font size="2" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td>
    </tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td><td>master.mdf</td>
        <td>test_key_16</td><td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td>
    </tr>
</table>
</font>
<font size="5" face="Courier New" >
<table width="100%">
    <tr>
        <td><b>Client</b></td>
        <td><b>InstanceName</b></td>
        <td><b>dbname</b></td>
        <td><b>Filename</b></td>
        <td><b>KeyName</b></td>
        <td><b>Rotation</b></td>
        <td><b>Path</b></td></tr>
    <tr>
        <td>NEWDEV6</td>
        <td>EXPRESS2012</td>
        <td>master</td>
        <td>master.mdf</td>
        <td>test_key_16</td>
        <td>0</td>
        <td>d:\Program&nbsp;Files\Microsoft&nbsp;SQL&nbsp;Server\MSSQL11.EXPRESS2012\MSSQL\DATA\master.mdf</td></tr>
</table></font>
</body>
</html>

Compare a string using sh shell

eq is used to compare integers use equal '=' instead , example:

if [ 'AAA' = 'ABC' ];
then 
    echo "the same" 
else 
    echo "not the same"
fi

good luck

How to add an existing folder with files to SVN?

In Windows 7 I did this:

  1. Have you installed SVN and Tortoise SVN? If not, Google them and do so now.
  2. Go to your SVN folder where you may have other repos (short for repository) (or if you're creating one from scratch, choose a location C drive, D drive, etc or network path).
  3. Create a new folder to store your new repository. Call it the same name as your project title
  4. Right click the folder and choose Tortoise SVN -> Create Repository here
  5. Say yes to Create Folder Structure
  6. Click OK. You should see a new icon looking like a "wave" next to your new folder/repo
  7. Right Click the new repo and choose SVN Repo Browser
  8. Right click 'trunk'
  9. Choose ADD Folder... and point to your folder structure of your project in development.
  10. Click OK and SVN will ADD your folder structure in. Be patient! It looks like SVN has crashed/frozen. Don't worry. It's doing its work.

Done!

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

Find (and kill) process locking port 3000 on Mac

Here's a helper bash function to kill multiple processes by name or port

fkill() {
  for i in $@;do export q=$i;if [[ $i == :* ]];then lsof -i$i|sed -n '1!p';
  else ps aux|grep -i $i|grep -v grep;fi|awk '{print $2}'|\
  xargs -I@ sh -c 'kill -9 @&&printf "X %s->%s\n" $q @';done
}

Usage:

$ fkill [process name] [process port]

Example:

$ fkill someapp :8080 node :3333 :9000

await is only valid in async function

Yes, await / async was a great concept, but the implementation is completely broken.

For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.

Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.

This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.

If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.

So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...

  • await can only be used to CALL async functions.
  • await can appear in any kind of function, synchronous or asynchronous.
  • Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I'm using:

Eclipse Java EE IDE for Web Developers.

Version: Neon.3 Release (4.6.3) Build id: 20170314-1500

The fix/trick for me was deleting my local repository in ~/.m2/repository in order to remove local dependencies and rebuilding my project in which fresh dependencies are pulled down.

Returning an array using C

I am not saying that this is the best solution or a preferred solution to the given problem. However, it may be useful to remember that functions can return structs. Although functions cannot return arrays, arrays can be wrapped in structs and the function can return the struct thereby carrying the array with it. This works for fixed length arrays.

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

    typedef
    struct 
    {
        char v[10];
    } CHAR_ARRAY;



    CHAR_ARRAY returnArray(CHAR_ARRAY array_in, int size)
    {
        CHAR_ARRAY returned;

        /*
        . . . methods to pull values from array, interpret them, and then create new array
        */

        for (int i = 0;  i < size; i++ )
            returned.v[i] = array_in.v[i] + 1;

        return returned; // Works!
    } 




    int main(int argc, char * argv[])
    {
        CHAR_ARRAY array = {1,0,0,0,0,1,1};

        char arrayCount = 7;

        CHAR_ARRAY returnedArray = returnArray(array, arrayCount); 

        for (int i = 0; i < arrayCount; i++)
            printf("%d, ", returnedArray.v[i]);  //is this correctly formatted?

        getchar();
        return 0;
    }

I invite comments on the strengths and weaknesses of this technique. I have not bothered to do so.

How to convert text column to datetime in SQL

In SQL Server , cast text as datetime

select cast('5/21/2013 9:45:48' as datetime)

How to redraw DataTable with new data

If you want to refresh the table without adding new data then use this:

First, create the API variable of your table like this:

var myTableApi = $('#mytable').DataTable(); // D must be Capital in this.

And then use refresh code wherever you want:

myTableApi.search(jQuery('input[type="search"]').val()).draw() ;

It will search data table with current search value (even if it's blank) and refresh data,, this work even if Datatable has server-side processing enabled.

How to increase font size in NeatBeans IDE?

Tools >> Options >> Fonts & Colors >> Syntax tab. Select 'Default' from the Category list and click the ... button like you said.

It's the Default you need to select first before changing the size.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

Using WAMP is perforce option if we want to use more then one version of php.

Less than or equal to

In batch, the > is a redirection sign used to output data into a text file. The compare op's available (And recommended) for cmd are below (quoted from the if /? help):

where compare-op may be one of:

    EQU - equal
    NEQ - not equal
    LSS - less than
    LEQ - less than or equal
    GTR - greater than
    GEQ - greater than or equal

That should explain what you want. The only other compare-op is == which can be switched with the if not parameter. Other then that rely on these three letter ones.

Fixed page header overlaps in-page anchors

I had the same problem. I solved it by adding a class to the anchor element with the topbar height as the padding-top value.

<h1><a class="anchor" name="barlink">Bar</a></h1>

I used this CSS:

.anchor { padding-top: 90px; }

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

How to elegantly check if a number is within a range?

Elegant because it doesn't require you to determine which of the two boundary values is greater first. It also contains no branches.

public static bool InRange(float val, float a, float b)
{
    // Determine if val lies between a and b without first asking which is larger (a or b)
    return ( a <= val & val < b ) | ( b <= val & val < a );
}

Replacing Spaces with Underscores

Use str_replace function of PHP.

Something like:

$str = str_replace(' ', '_', $str);

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

Invert colors of an image in CSS or JavaScript

CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:

_x000D_
_x000D_
img {_x000D_
   -webkit-filter: invert(1);_x000D_
   filter: invert(1);_x000D_
   }
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
_x000D_
_x000D_

How to get the <html> tag HTML with JavaScript / jQuery?

The simplest way to get the html element natively is:

document.documentElement

Here's the reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement.

UPDATE: To then grab the html element as a string you would do:

document.documentElement.outerHTML

Edit seaborn legend

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()

enter image description here

Moreover you may combine both situations and use this code:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)

sns.plt.show()

This code works for any seaborn plot which is based on Grid class.

ASP.NET Background image

resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...

hard-size your DIV relative to your image

position your asp:login control where needed...

trying to animate a constraint in swift

With Swift 5 and iOS 12.3, according to your needs, you may choose one of the 3 following ways in order to solve your problem.


#1. Using UIView's animate(withDuration:animations:) class method

animate(withDuration:animations:) has the following declaration:

Animate changes to one or more views using the specified duration.

class func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void)

The Playground code below shows a possible implementation of animate(withDuration:animations:) in order to animate an Auto Layout constraint's constant change.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let textView = UITextView()
    lazy var heightConstraint = textView.heightAnchor.constraint(equalToConstant: 50)

    override func viewDidLoad() {
        view.backgroundColor = .white
        view.addSubview(textView)

        textView.backgroundColor = .orange
        textView.isEditable = false
        textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalToSystemSpacingBelow: view.layoutMarginsGuide.topAnchor, multiplier: 1).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
        heightConstraint.isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doIt(_:)))
        textView.addGestureRecognizer(tapGesture)
    }

    @objc func doIt(_ sender: UITapGestureRecognizer) {
        heightConstraint.constant = heightConstraint.constant == 50 ? 150 : 50
        UIView.animate(withDuration: 2) {
            self.view.layoutIfNeeded()
        }
    }

}

PlaygroundPage.current.liveView = ViewController()

#2. Using UIViewPropertyAnimator's init(duration:curve:animations:) initialiser and startAnimation() method

init(duration:curve:animations:) has the following declaration:

Initializes the animator with a built-in UIKit timing curve.

convenience init(duration: TimeInterval, curve: UIViewAnimationCurve, animations: (() -> Void)? = nil)

The Playground code below shows a possible implementation of init(duration:curve:animations:) and startAnimation() in order to animate an Auto Layout constraint's constant change.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let textView = UITextView()
    lazy var heightConstraint = textView.heightAnchor.constraint(equalToConstant: 50)

    override func viewDidLoad() {
        view.backgroundColor = .white
        view.addSubview(textView)

        textView.backgroundColor = .orange
        textView.isEditable = false
        textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalToSystemSpacingBelow: view.layoutMarginsGuide.topAnchor, multiplier: 1).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
        heightConstraint.isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doIt(_:)))
        textView.addGestureRecognizer(tapGesture)
    }

    @objc func doIt(_ sender: UITapGestureRecognizer) {
        heightConstraint.constant = heightConstraint.constant == 50 ? 150 : 50
        let animator = UIViewPropertyAnimator(duration: 2, curve: .linear, animations: {
            self.view.layoutIfNeeded()
        })
        animator.startAnimation()
    }

}

PlaygroundPage.current.liveView = ViewController()

#3. Using UIViewPropertyAnimator's runningPropertyAnimator(withDuration:delay:options:animations:completion:) class method

runningPropertyAnimator(withDuration:delay:options:animations:completion:) has the following declaration:

Creates and returns an animator object that begins running its animations immediately.

class func runningPropertyAnimator(withDuration duration: TimeInterval, delay: TimeInterval, options: UIViewAnimationOptions = [], animations: @escaping () -> Void, completion: ((UIViewAnimatingPosition) -> Void)? = nil) -> Self

The Playground code below shows a possible implementation of runningPropertyAnimator(withDuration:delay:options:animations:completion:) in order to animate an Auto Layout constraint's constant change.

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let textView = UITextView()
    lazy var heightConstraint = textView.heightAnchor.constraint(equalToConstant: 50)

    override func viewDidLoad() {
        view.backgroundColor = .white
        view.addSubview(textView)

        textView.backgroundColor = .orange
        textView.isEditable = false
        textView.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalToSystemSpacingBelow: view.layoutMarginsGuide.topAnchor, multiplier: 1).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
        heightConstraint.isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(doIt(_:)))
        textView.addGestureRecognizer(tapGesture)
    }

    @objc func doIt(_ sender: UITapGestureRecognizer) {
        heightConstraint.constant = heightConstraint.constant == 50 ? 150 : 50
        UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 2, delay: 0, options: [], animations: {
            self.view.layoutIfNeeded()
        })
    }

}

PlaygroundPage.current.liveView = ViewController()

Amazon S3 - HTTPS/SSL - Is it possible?

This is a response I got from their Premium Services

Hello,

This is actually a issue with the way SSL validates names containing a period, '.', > character. We've documented this behavior here:

http://docs.amazonwebservices.com/AmazonS3/latest/dev/BucketRestrictions.html

The only straight-forward fix for this is to use a bucket name that does not contain that character. You might instead use a bucket named 'furniture-retailcatalog-us'. This would allow you use HTTPS with

https://furniture-retailcatalog-us.s3.amazonaws.com/

You could, of course, put a CNAME DNS record to make that more friendly. For example,

images-furniture.retailcatalog.us IN CNAME furniture-retailcatalog-us.s3.amazonaws.com.

Hope that helps. Let us know if you have any other questions.

Amazon Web Services

Unfortunately your "friendly" CNAME will cause host name mismatch when validating the certificate, therefore you cannot really use it for a secure connection. A big missing feature of S3 is accepting custom certificates for your domains.


UPDATE 10/2/2012

From @mpoisot:

The link Amazon provided no longer says anything about https. I poked around in the S3 docs and finally found a small note about it on the Virtual Hosting page: http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html


UPDATE 6/17/2013

From @Joseph Lust:

Just got it! Check it out and sign up for an invite: http://aws.amazon.com/cloudfront/custom-ssl-domains

Anaconda Navigator won't launch (windows 10)

So none of the above answers worked for me.

I performed the following steps in order to make it work for me : OS : Windows 10 Home 64 Bit

Open Anaconda Prompt

conda remove anaconda-navigator
conda install anaconda-navigator

conda install -c anaconda pywin32 // Had to install since I got a module not found error // with just the above two commands

And it worked for me!!

how to convert binary string to decimal?

ES6 supports binary numeric literals for integers, so if the binary string is immutable, as in the example code in the question, one could just type it in as it is with the prefix 0b or 0B:

var binary = 0b1101000; // code for 104
console.log(binary); // prints 104

Android emulator: How to monitor network traffic?

You can monitor network traffic from Android Studio. Go to Android Monitor and open Network tab.

http://developer.android.com/tools/debugging/ddms.html

UPDATE: ?? Android Device Monitor was deprecated in Android Studio 3.1. See more in https://developer.android.com/studio/profile/monitor

Access-Control-Allow-Origin and Angular.js $http

I'm new to AngularJS and I came across this CORS problem, almost lost my mind! Luckily i found a way to fix this. So here it goes....

My problem was, when I use AngularJS $resource in sending API requests I'm getting this error message XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. Yup, I already added callback="JSON_CALLBACK" and it didn't work.

What I did to fix it the problem, instead of using GET method or resorting to $http.get, I've used JSONP. Just replace GET method with JSONP and change the api response format to JSONP as well.

    myApp.factory('myFactory', ['$resource', function($resource) {

           return $resource( 'http://website.com/api/:apiMethod',
                        { callback: "JSON_CALLBACK", format:'jsonp' }, 
                        { 
                            method1: { 
                                method: 'JSONP', 
                                params: { 
                                            apiMethod: 'hello world'
                                        } 
                            },
                            method2: { 
                                method: 'JSONP', 
                                params: { 
                                            apiMethod: 'hey ho!'
                                        } 
                            }
            } );

    }]);

I hope someone find this helpful. :)

Fastest way to get the first n elements of a List into an Array

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);
}

What's the difference between xsd:include and xsd:import?

Direct quote from MSDN: <xsd:import> Element, Remarks section

The difference between the include element and the import element is that import element allows references to schema components from schema documents with different target namespaces and the include element adds the schema components from other schema documents that have the same target namespace (or no specified target namespace) to the containing schema. In short, the import element allows you to use schema components from any schema; the include element allows you to add all the components of an included schema to the containing schema.

How to get HTTP response code for a URL in Java?

import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;

public class API{
    public static void main(String args[]) throws IOException
    {
        URL url = new URL("http://www.google.com");
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        int statusCode = http.getResponseCode();
        System.out.println(statusCode);
    }
}

How to set a variable to current date and date-1 in linux?

You can also use the shorter format

From the man page:

%F     full date; same as %Y-%m-%d

Example:

#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

To prevent the flex items from shrinking, set the flex shrink factor to 0:

The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.

.boxcontainer .box {
  flex-shrink: 0;
}

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
  width: 200px;_x000D_
  background-color: #EEEEEE;_x000D_
  border: 2px solid #DDDDDD;_x000D_
  padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  border: 2px solid #BDC3C7;_x000D_
  transition: all 0.4s ease;_x000D_
  display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
  width: 100%;_x000D_
  padding: 1rem;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
  background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
  background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
  left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
  <div class="boxcontainer">_x000D_
    <div class="box">_x000D_
      First bunch of content._x000D_
    </div>_x000D_
    <div class="box">_x000D_
      Second load  of content._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Object comparison in JavaScript

If you work without the JSON library, maybe this will help you out:

Object.prototype.equals = function(b) {
    var a = this;
    for(i in a) {
        if(typeof b[i] == 'undefined') {
            return false;
        }
        if(typeof b[i] == 'object') {
            if(!b[i].equals(a[i])) {
                return false;
            }
        }
        if(b[i] != a[i]) {
            return false;
        }
    }
    for(i in b) {
        if(typeof a[i] == 'undefined') {
            return false;
        }
        if(typeof a[i] == 'object') {
            if(!a[i].equals(b[i])) {
                return false;
            }
        }
        if(a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

Importing a function from a class in another file?

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose(a):
  from random import randint
  b = randint(0, len(a) - 1)
  c = a[b]
  return(c)

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

Android update activity UI from service

Callback from service to activity to update UI.
ResultReceiver receiver = new ResultReceiver(new Handler()) {
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        //process results or update UI
    }
}

Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);
context.startService(instructionServiceIntent);

Ruby on Rails generates model field:type - what are the options for field:type?

There are lots of data types you can mention while creating model, some examples are:

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean, :references

syntax:

field_type:data_type

How to embed fonts in CSS?

I used Ataturk's font like this. I didn't use "TTF" version. I translated orginal font version ("otf" version) to "eot" and "woof" version. Then It works in local but not working when I uploaded the files to server. So I added "TTF" version too like this. Now, It's working on Chrome and Firefox but Internet Explorer still defence. When you installed on your computer "Ataturk" font, then working IE too. But I wanted to use this font without installing.

@font-face {
    font-family: 'Ataturk';
    font-style: normal;
    font-weight: normal;
    src: url('font/ataturk.eot');
    src: local('Ataturk Regular'), url('font/ataturk.ttf') format('truetype'), 
    url('font/ataturk.woff') format('woff');
}

You can see it on my website here: http://www.canotur.com

Change collations of all columns of all tables in SQL Server

Sorry late to the party, but here is mine - cater for table with a schema and funny column and table names. Yes I had some of them.

SELECT 
    'ALTER TABLE [' +  TABLE_SCHEMA + '].[' + TABLE_NAME  
    + '] ALTER COLUMN [' + COLUMN_NAME + '] ' + DATA_TYPE 
    + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS nvarchar(100)) 
    + ') COLLATE ' + 'Latin1_General_CI_AS' 
    + CASE WHEN IS_NULLABLE = 'YES' THEN ' NULL' ELSE ' NOT NULL' END 
FROM 
    INFORMATION_SCHEMA.COLUMNS 
WHERE 
    DATA_TYPE like '%char'

Command-line Unix ASCII-based charting / plotting tool

feedgnuplot is another front end to gnuplot, which handles piping in data.

    $ seq 5 | awk '{print 2*$1, $1*$1}' |
      feedgnuplot --lines --points --legend 0 "data 0" --title "Test plot" --y2 1
                  --terminal 'dumb 80,40' --exit

                                     Test plot

     10 ++------+--------+-------+-------+-------+--------+-------+------*A 25
        +       +        +       +       +       +        +       +    **#+
        |       :        :       :       :       :        : data 0+**A*** |
        |       :        :       :       :       :        :       :** #   |
      9 ++.......................................................**.##....|
        |       :        :       :       :       :        :    ** :#      |
        |       :        :       :       :       :        :  **   #       |
        |       :        :       :       :       :        :**   ##:      ++ 20
      8 ++................................................A....#..........|
        |       :        :       :       :       :      **:   #   :       |
        |       :        :       :       :       :    **  : ##    :       |
        |       :        :       :       :       :  **    :#      :       |
        |       :        :       :       :       :**      B       :       |
      7 ++......................................**......##................|
        |       :        :       :       :    ** :    ##  :       :      ++ 15
        |       :        :       :       :  **   :   #    :       :       |
        |       :        :       :       :**     : ##     :       :       |
      6 ++..............................*A.......##.......................|
        |       :        :       :    ** :     ##:        :       :       |
        |       :        :       :  **   :    #  :        :       :       |
        |       :        :       :**     :  ##   :        :       :      ++ 10
      5 ++......................**........##..............................|
        |       :        :    ** :      #B       :        :       :       |
        |       :        :  **   :    ## :       :        :       :       |
        |       :        :**     :  ##   :       :        :       :       |
      4 ++...............A.......###......................................|
        |       :      **:     ##:       :       :        :       :       |
        |       :    **  :   ##  :       :       :        :       :      ++ 5
        |       :  **    : ##    :       :       :        :       :       |
        |       :**    ##B#      :       :       :        :       :       |
      3 ++.....**..####...................................................|
        |    **####      :       :       :       :        :       :       |
        |  **## :        :       :       :       :        :       :       |
        B**     +        +       +       +       +        +       +       +
      2 A+------+--------+-------+-------+-------+--------+-------+------++ 0
        1      1.5       2      2.5      3      3.5       4      4.5      5

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

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

  } @else {

    display: inline-block;
    width: $width;

  }
}

How to clear the Entry widget after a button is pressed in Tkinter?

if none of the above is working you can use this->

idAssignedToEntryWidget.delete(first = 0, last = UpperLimitAssignedToEntryWidget)

for e.g. ->

id assigned is = en then

en.delete(first =0, last =100)

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

integrating barcode scanner into php application?

I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.

In jQuery, how do I select an element by its name attribute?

another way

$('input:radio[name=theme]').filter(":checked").val()

Height equal to dynamic width (CSS fluid layout)

Simple and neet : use vw units for a responsive height/width according to the viewport width.

vw : 1/100th of the width of the viewport. (Source MDN)

DEMO

HTML:

<div></div>

CSS for a 1:1 aspect ratio:

div{
    width:80vw;
    height:80vw; /* same as width */
}

Table to calculate height according to the desired aspect ratio and width of element.

   aspect ratio  |  multiply width by
    -----------------------------------
         1:1      |         1
         1:3      |         3
         4:3      |        0.75
        16:9      |       0.5625

This technique allows you to :

  • insert any content inside the element without using position:absolute;
  • no unecessary HTML markup (only one element)
  • adapt the elements aspect ratio according to the height of the viewport using vh units
  • you can make a responsive square or other aspect ratio that alway fits in viewport according to the height and width of the viewport (see this answer : Responsive square according to width and height of viewport or this demo)

These units are supported by IE9+ see canIuse for more info

How to change the MySQL root account password on CentOS7?

For me work like this: 1. Stop mysql: systemctl stop mysqld

  1. Set the mySQL environment option systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

  2. Start mysql usig the options you just set systemctl start mysqld

  3. Login as root mysql -u root

  4. After login I use FLUSH PRIVILEGES; tell the server to reload the grant tables so that account-management statements work. If i don't do that i receive this error trying to update the password: "Can't find any matching row in the user table"

When should I use a struct rather than a class in C#?

In addition to the "it is a value" answer, one specific scenario for using structs is when you know that you have a set of data that is causing garbage collection issues, and you have lots of objects. For example, a large list/array of Person instances. The natural metaphor here is a class, but if you have large number of long-lived Person instance, they can end up clogging GEN-2 and causing GC stalls. If the scenario warrants it, one potential approach here is to use an array (not list) of Person structs, i.e. Person[]. Now, instead of having millions of objects in GEN-2, you have a single chunk on the LOH (I'm assuming no strings etc here - i.e. a pure value without any references). This has very little GC impact.

Working with this data is awkward, as the data is probably over-sized for a struct, and you don't want to copy fat values all the time. However, accessing it directly in an array does not copy the struct - it is in-place (contrast to a list indexer, which does copy). This means lots of work with indexes:

int index = ...
int id = peopleArray[index].Id;

Note that keeping the values themselves immutable will help here. For more complex logic, use a method with a by-ref parameter:

void Foo(ref Person person) {...}
...
Foo(ref peopleArray[index]);

Again, this is in-place - we have not copied the value.

In very specific scenarios, this tactic can be very successful; however, it is a fairly advanced scernario that should be attempted only if you know what you are doing and why. The default here would be a class.

How can I get a precise time, for example in milliseconds in Objective-C?

You can get current time in milliseconds since January 1st, 1970 using an NSDate:

- (double)currentTimeInMilliseconds {
    NSDate *date = [NSDate date];
    return [date timeIntervalSince1970]*1000;
}

Why can't DateTime.Parse parse UTC date

It's not a valid format, however "Tue, 1 Jan 2008 00:00:00 GMT" is.

The documentation says like this:

A string that includes time zone information and conforms to ISO 8601. For example, the first of the following two strings designates the Coordinated Universal Time (UTC); the second designates the time in a time zone seven hours earlier than UTC:

2008-11-01T19:35:00.0000000Z

A string that includes the GMT designator and conforms to the RFC 1123 time format. For example:

Sat, 01 Nov 2008 19:35:00 GMT

A string that includes the date and time along with time zone offset information. For example:

03/01/2009 05:42:00 -5:00

Render HTML string as real HTML in a React component

I could not get npm build to work with react-html-parser. However, in my case, I was able to successfully make use of https://reactjs.org/docs/fragments.html. I had a requirement to show few html unicode characters , but they should not be directly embedded in the JSX. Within the JSX, it had to be picked from the Component's state. Component code snippet is given below :

constructor() 
{
this.state = {
      rankMap : {"5" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9733;</Fragment> , 
                 "4" : <Fragment>&#9733; &#9733; &#9733; &#9733; &#9734;</Fragment>, 
                 "3" : <Fragment>&#9733; &#9733; &#9733; &#9734; &#9734;</Fragment> , 
                 "2" : <Fragment>&#9733; &#9733; &#9734; &#9734; &#9734;</Fragment>, 
                 "1" : <Fragment>&#9733; &#9734; &#9734; &#9734; &#9734;</Fragment>}
                };
}

render() 
{
       return (<div class="card-footer">
                    <small class="text-muted">{ this.state.rankMap["5"] }</small>
               </div>);
}

Where can I find the TypeScript version installed in Visual Studio?

Based in the response of basarat, I give here a little more information how to run this in Visual Studio 2013.

  • Go to Windows Start button -> All Programs -> Visual Studio 2013 -> Visual Studio Tools A windows is open with a list of tool.

Menu path for Visual Studio Tools

  • Select Developer Command Prompt for VS2013
  • In the opened Console write: tsc -v
  • You get the version: See Image

enter image description here

[UPDATE]

If you update your Visual Studio to a new version of Typescript as 1.0.x you don't see the last version here. To see the last version:

  • Go to: C:\Program Files (x86)\Microsoft SDKs\TypeScript, there you see directories of type 0.9, 1.0 1.1
  • Enter the high number that you have (in this case 1.1)
  • Copy the directory and run in CMD the command tsc -v, you get the version.

enter image description here

NOTE: Typescript 1.3 install in directory 1.1, for that it is important to run the command to know the last version that you have installed.

NOTE: It is possible that you have installed a version 1.3 and your code use 1.0.3. To avoid this if you have your Typescript in a separate(s) project(s) unload the project and see if the Typescript tag:

<TypeScriptToolsVersion>1.1</TypeScriptToolsVersion> 

is set to 1.1.

[UPDATE 2]

TypeScript version 1.4, 1.5 .. 1.7 install in 1.4, 1.5... 1.7 directories. they are not problem to found version. if you have typescript in separate project and you migrate from a previous typescript your project continue to use the old version. to solve this:

unload the project file and change the typescript version to 1.x at:

  <TypeScriptToolsVersion>1.x</TypeScriptToolsVersion>

If you installed the typescript using the visual studio installer file, the path to the new typescript compiler should be automatically updated to point to 1.x directory. If you have problem, review that you environment variable Path include

C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.x\

SUGGESTION TO MICROSOFT :-) Because Typescript run side by side with other version, maybe is good to have in the project properties have a combo box to select the typescript compiler (similar to select the net version)

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

Git - push current branch shortcut

You can configure git to push to the current branch using the following command

git config --global push.default current

then just do

git push 

this will push the code to your current branch.

Detecting endianness programmatically in a C++ program

You can also do this via the preprocessor using something like boost header file which can be found boost endian

How to replace a string in multiple files in linux command line

Really lame, but I couldn't get any of the sed commands to work right on OSX, so I did this dumb thing instead:

:%s/foo/bar/g
:wn

^- copy these three lines into my clipboard (yes, include the ending newline), then:

vi *

and hold down command-v until it says there's no files left.

Dumb...hacky...effective...

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

TypeError: Cannot read property 'then' of undefined

You need to return your promise to the calling function.

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}

REST API 404: Bad URI, or Missing Resource?

The Uniform Resource Identifier is a unique pointer to the resource. A poorly form URI doesn't point to the resource and therefore performing a GET on it will not return a resource. 404 means The server has not found anything matching the Request-URI. If you put in the wrong URI or bad URI that is your problem and the reason you didn't get to a resource whether a HTML page or IMG.

Create instance of generic type whose constructor requires a parameter?

You can't use any parameterised constructor. You can use a parameterless constructor if you have a "where T : new()" constraint.

It's a pain, but such is life :(

This is one of the things I'd like to address with "static interfaces". You'd then be able to constrain T to include static methods, operators and constructors, and then call them.

In MySQL, how to copy the content of one table to another table within the same database?

If table1 is large and you don't want to lock it for the duration of the copy process, you can do a dump-and-load instead:

CREATE TABLE table2 LIKE table1;

SELECT * INTO OUTFILE '/tmp/table1.txt' FROM table1;
LOAD DATA INFILE '/tmp/table1.txt' INTO TABLE table2;

Do you need to dispose of objects and set them to null?

You never need to set objects to null in C#. The compiler and runtime will take care of figuring out when they are no longer in scope.

Yes, you should dispose of objects that implement IDisposable.

batch script - read line by line

For those with spaces in the path, you are going to want something like this: n.b. It expands out to an absolute path, rather than relative, so if your running directory path has spaces in, these count too.

set SOURCE=path\with spaces\to\my.log
FOR /F "usebackq delims=" %%A IN ("%SOURCE%") DO (
    ECHO %%A
)

To explain:

(path\with spaces\to\my.log)

Will not parse, because spaces. If it becomes:

("path\with spaces\to\my.log")

It will be handled as a string rather than a file path.

"usebackq delims=" 

See docs will allow the path to be used as a path (thanks to Stephan).

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How do the major C# DI/IoC frameworks compare?

Actually there are tons of IoC frameworks. It seems like every programmer tries to write one at some point of their career. Maybe not to publish it, but to learn the inner workings.

I personally prefer autofac since it's quite flexible and have syntax that suits me (although I really hate that all register methods are extension methods).

Some other frameworks:

How to loop through elements of forms with JavaScript?

$(function() {
    $('form button').click(function() {
        var allowSubmit = true;
        $.each($('form input:text'), function(index, formField) {
            if($(formField).val().trim().length == 0) {
                alert('field is empty!');
                allowSubmit = false;
            }
        });
        return allowSubmit;
    });
});

DEMO

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

In Perl, how do I create a hash whose keys come from a given array?

If you do a lot of set theoretic operations - you can also use Set::Scalar or similar module. Then $s = Set::Scalar->new( @array ) will build the Set for you - and you can query it with: $s->contains($m).

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

Checking whether a String contains a number value in Java

You could use a regex to find out if the String contains a number. Take a look at the matches() method.

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

How can I enable or disable the GPS programmatically on Android?

This code works on ROOTED phones:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] cmds = {"cd /system/bin" ,"settings put secure location_providers_allowed +gps"};
        try {
            Process p = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            for (String tmpCmd : cmds) {
                os.writeBytes(tmpCmd + "\n");
            }
            os.writeBytes("exit\n");
            os.flush();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

For turning off GPS you can use this command instead

settings put secure location_providers_allowed -gps

You can also toggle network accuracy using the following commands: for turning on use:

settings put secure location_providers_allowed +network

and for turning off you can use:

settings put secure location_providers_allowed -network

Permission denied error on Github Push

For some reason my push and pull origin was changed to HTTPS-url in stead of SSH-url (probably a copy-paste error on my end), but trying to push would give me the following error after trying to login:

Username for 'https://github.com': xxx
Password for 'https://[email protected]': 
remote: Invalid username or password.

Updating the remote origin with the SSH url, solved the problem:

git remote set-url origin [email protected]:<username>/<repo>.git

Hope this helps!

passing form data to another HTML page

Another option is to use "localStorage". You can easealy request the value with javascript in another page.

On the first page, you use the following snippet of javascript code to set the localStorage:

<script>    
   localStorage.setItem("serialNumber", "abc123def456");
</script>

On the second page, you can retrieve the value with the following javascript code snippet:

<script>    
   console.log(localStorage.getItem("serialNumber"));
</script>

On Google Chrome You can vizualize the values pressing F12 > Application > Local Storage.

Source: https://www.w3schools.com/jsref/prop_win_localstorage.asp

TypeError: window.initMap is not a function

Actually the error is being generated by the initMap in the Google's api script

 <script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

so basically when the Google Map API is loaded then the initMap function is executed. If you don't have an initMap function, then the initMap is not a function error is generated.

So basically what you have to do is one of the following options:

  1. to create an initMap function
  2. replace the callback function with one of your own that created for the same purpose but named it something else
  3. replace the &callback=angular.noop if you just want an empty function() (only if you use angular)

CodeIgniter: How to get Controller, Action, URL information

Use This Code anywhere in class or libraries

    $current_url =& get_instance(); //  get a reference to CodeIgniter
    $current_url->router->fetch_class(); // for Class name or controller
    $current_url->router->fetch_method(); // for method name

Date object to Calendar [Java]

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

However, another approach is to not use Date at all. You could use an approach like this:

private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

Put request with simple string as request body

I was having trouble sending plain text and found that I needed to surround the body's value with double quotes:

const request = axios.put(url, "\"" + values.guid + "\"", {
    headers: {
        "Accept": "application/json",
        "Content-type": "application/json",
        "Authorization": "Bearer " + sessionStorage.getItem('jwt')
    }
})

My webapi server method signature is this:

public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)

How to update Android Studio automatically?

For this task, I recommend using Android Studio IDE and choose the automatic installation program, and not the compressed file.

  1. On the top menu, select Help -> Check for Update...
  2. Upon the updates dialog below, select Updates link to configure your IDE settings.

Platform and Plugin Updates

  1. For checking updates, my suggestion is to select the Dev channel. I

don't recommend Beta or Canary

channel which is the unstable version and they are not automatic installation, instead a zip file is provided in that case.

Updates dialog

  1. When finished with the configuration, select Update and Restart for downloading the installation EXE.
  2. Run the installation.

Warning: Among different version of Android Studio, the steps may be different. But hopefully you get the idea, as I try to be clear on my intentions.

Extra info: If you want, check for Android Studio updates @ Android Tools Project Site - Recent Builds. This web page seems to be more accurate than other Android pages about tool updates.

How to pass an event object to a function in Javascript?

I would change your binding to be:

<button type="button" value="click me" onclick="check_me" />

I would then change your check_me() function declaration to be:

function check_me() {   
  //event.preventDefault();
  var hello = document.myForm.username.value;
  var err = '';

  if(hello == '' || hello == null) {
    err = 'User name required';
  }

  if(err != '') { 
     alert(err); 
     $('username').focus(); 
     event.preventDefault(); 
   } else { 
    return true; }
}

How to install SQL Server Management Studio 2008 component only

I found some articles to be of major use:

This link is an experience someone else had: http://goneale.com/2009/05/24/cant-install-microsoft-sql-server-2008-management-studio-express/

This link has the exact steps involved to install everything properly: http://www.codefrenzy.net/2011/06/03/how-to-install-sql-server-2008-management-studio/

This link confirms the previous link: https://superuser.com/questions/88244/installing-sql-server-management-studio-when-vs2010-beta-2-is-already-installed

My Instructions

I am not sure if my instructions will be 100% accurate, but in my instance, because I installed VS2010 on a fresh copy of Windows 7, the VS2010 installer installs SQL Server 2008 Express for you, so from this point I just need the Management Studio.

What I gathered from these explanations is to do the following:

  1. Download the SQL Server Management Studio install from http://www.microsoft.com/download/en/details.aspx?id=22973

  2. Run the setup, when you get to the point where it asks you to "Perform a new installation of SQL Server 2008" or "Add features to an existing instance of SQL Server 2008", this part is the CONFUSING PART (HEY MICROSOFT TAKE NOTES, DON'T DO THIS KIND OF STUFF).

    As much as you want to select "Add features to an existing instance of SQL Server 2008" DON'T!!!!

    You need to select "Perform a new installation of SQL Server 2008". It doesn't sound right I know - it is very confusing and counter intuitive, but this seems to be the way to install management studio. :(

  3. Press next until you see the features selection portion. Heeeeeyyyy look at that, it has a check box for Management Studio. It should be selected already, if not then select it of course and press next.

  4. Press Next next next next next next... basically just install it at this point.

  5. Enjoy, it has installed.

How to check if a view controller is presented modally or pushed on a navigation stack?

For some one who's wondering, How to tell ViewController that it is being presented

if A is presenting/pushing B

  1. Define an enum and property in B

    enum ViewPresentationStyle {
        case Push
        case Present
    }
    
    //and write property 
    
    var vcPresentationStyle : ViewPresentationStyle = .Push //default value, considering that B is pushed 
    
  2. Now in A view controller, tell B if it is being presented/pushed by assigning presentationStyle

    func presentBViewController() {
        let bViewController = B()
        bViewController.vcPresentationStyle = .Present //telling B that it is being presented
        self.presentViewController(bViewController, animated: true, completion: nil)
    }
    
  3. Usage in B View Controller

    override func viewDidLoad() {
        super.viewDidLoad()
    
        if self.vcPresentationStyle == .Present {
            //is being presented 
        }
        else {
            //is being pushed
        }
    
    }
    

How to create PDF files in Python

I believe that matplotlib has the ability to serialize graphics, text and other objects to a pdf document.

How can I install the Beautiful Soup module on the Mac?

I think the current right way to do this is by pip like Pramod comments

pip install beautifulsoup4

because of last changes in Python, see discussion here. This was not so in the past.

Best way to do multiple constructors in PHP

As has already been shown here, there are many ways of declaring multiple constructors in PHP, but none of them are the correct way of doing so (since PHP technically doesn't allow it). But it doesn't stop us from hacking this functionality... Here's another example:

<?php

class myClass {
    public function __construct() {
        $get_arguments       = func_get_args();
        $number_of_arguments = func_num_args();

        if (method_exists($this, $method_name = '__construct'.$number_of_arguments)) {
            call_user_func_array(array($this, $method_name), $get_arguments);
        }
    }

    public function __construct1($argument1) {
        echo 'constructor with 1 parameter ' . $argument1 . "\n";
    }

    public function __construct2($argument1, $argument2) {
        echo 'constructor with 2 parameter ' . $argument1 . ' ' . $argument2 . "\n";
    }

    public function __construct3($argument1, $argument2, $argument3) {
        echo 'constructor with 3 parameter ' . $argument1 . ' ' . $argument2 . ' ' . $argument3 . "\n";
    }
}

$object1 = new myClass('BUET');
$object2 = new myClass('BUET', 'is');
$object3 = new myClass('BUET', 'is', 'Best.');

Source: The easiest way to use and understand multiple constructors:

Hope this helps. :)

Node.js – events js 72 throw er unhandled 'error' event

Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).

How do I get a list of files in a directory in C++?

You have to use operating system calls (e.g. the Win32 API) or a wrapper around them. I tend to use Boost.Filesystem as it is superior interface compared to the mess that is the Win32 API (as well as being cross platform).

If you are looking to use the Win32 API, Microsoft has a list of functions and examples on msdn.

How to set timeout in Retrofit library?

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }`enter code here`

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

How can I check a C# variable is an empty string "" or null?

if (string.IsNullOrEmpty(myString)) {
   //
}

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

Very often this error appears if you use incompatible versions of Selenium and ChromeDriver.

Selenium 3.0.1 for Maven project:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.0.1</version>
    </dependency>

ChromeDriver 2.27: https://sites.google.com/a/chromium.org/chromedriver/downloads

Appending a vector to a vector

If you would like to add vector to itself both popular solutions will fail:

std::vector<std::string> v, orig;

orig.push_back("first");
orig.push_back("second");

// BAD:
v = orig;
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "", "" }

// BAD:
v = orig;
std::copy(v.begin(), v.end(), std::back_inserter(v));
// std::bad_alloc exception is generated

// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "first", "second" }

// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
std::copy(v.begin(), v.end(), std::back_inserter(v));
// Now v contains: { "first", "second", "first", "second" }

// GOOD (best):
v = orig;
v.insert(v.end(), orig.begin(), orig.end()); // note: we use different vectors here
// Now v contains: { "first", "second", "first", "second" }

Reset C int array to zero : the fastest way?

From memset():

memset(myarray, 0, sizeof(myarray));

You can use sizeof(myarray) if the size of myarray is known at compile-time. Otherwise, if you are using a dynamically-sized array, such as obtained via malloc or new, you will need to keep track of the length.

How to initialize all members of an array to the same value?

I see no requirements in the question, so the solution must be generic: initialization of an unspecified possibly multidimensional array built from unspecified possibly structure elements with an initial member value:

#include <string.h> 

void array_init( void *start, size_t element_size, size_t elements, void *initval ){
  memcpy(        start,              initval, element_size              );
  memcpy( (char*)start+element_size, start,   element_size*(elements-1) );
}

// testing
#include <stdio.h> 

struct s {
  int a;
  char b;
} array[2][3], init;

int main(){
  init = (struct s){.a = 3, .b = 'x'};
  array_init( array, sizeof(array[0][0]), 2*3, &init );

  for( int i=0; i<2; i++ )
    for( int j=0; j<3; j++ )
      printf("array[%i][%i].a = %i .b = '%c'\n",i,j,array[i][j].a,array[i][j].b);
}

Result:

array[0][0].a = 3 .b = 'x'
array[0][1].a = 3 .b = 'x'
array[0][2].a = 3 .b = 'x'
array[1][0].a = 3 .b = 'x'
array[1][1].a = 3 .b = 'x'
array[1][2].a = 3 .b = 'x'

EDIT: start+element_size changed to (char*)start+element_size

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

No such keg: /usr/local/Cellar/git

Os X Mojave 10.14 has:

Error: The Command Line Tools header package must be installed on Mojave.

Solution. Go to

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

location and install the package manually. And brew will start working and we can run:

brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git

How can I get the client's IP address in ASP.NET MVC?

Request.ServerVariables["REMOTE_ADDR"] should work - either directly in a view or in the controller action method body (Request is a property of Controller class in MVC, not Page).

It is working.. but you have to publish on a real IIS not the virtual one.

How do I print the key-value pairs of a dictionary in python

In addition to ways already mentioned.. can use 'viewitems', 'viewkeys', 'viewvalues'

>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]

Or

>>> list(d.iteritems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.iterkeys())
[320, 321, 322]
>>> list(d.itervalues())
[1, 0, 3]

or using itemgetter

>>> from operator import itemgetter
>>> map(itemgetter(0), dd.items())     ####  for keys
['323', '332']
>>> map(itemgetter(1), dd.items())     ####  for values
['3323', 232]

For loop example in MySQL

You can exchange this local variable for a global, it would be easier.

DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      SET @a = 0;
      simple_loop: LOOP
         SET @a=@a+1;
         select @a;
         IF @a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

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

Although you can't do this real-time, you can run map-reduce multiple times to merge data together by using the "reduce" out option in MongoDB 1.8+ map/reduce (see http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Outputoptions). You need to have some key in both collections that you can use as an _id.

For example, let's say you have a users collection and a comments collection and you want to have a new collection that has some user demographic info for each comment.

Let's say the users collection has the following fields:

  • _id
  • firstName
  • lastName
  • country
  • gender
  • age

And then the comments collection has the following fields:

  • _id
  • userId
  • comment
  • created

You would do this map/reduce:

var mapUsers, mapComments, reduce;
db.users_comments.remove();

// setup sample data - wouldn't actually use this in production
db.users.remove();
db.comments.remove();
db.users.save({firstName:"Rich",lastName:"S",gender:"M",country:"CA",age:"18"});
db.users.save({firstName:"Rob",lastName:"M",gender:"M",country:"US",age:"25"});
db.users.save({firstName:"Sarah",lastName:"T",gender:"F",country:"US",age:"13"});
var users = db.users.find();
db.comments.save({userId: users[0]._id, "comment": "Hey, what's up?", created: new ISODate()});
db.comments.save({userId: users[1]._id, "comment": "Not much", created: new ISODate()});
db.comments.save({userId: users[0]._id, "comment": "Cool", created: new ISODate()});
// end sample data setup

mapUsers = function() {
    var values = {
        country: this.country,
        gender: this.gender,
        age: this.age
    };
    emit(this._id, values);
};
mapComments = function() {
    var values = {
        commentId: this._id,
        comment: this.comment,
        created: this.created
    };
    emit(this.userId, values);
};
reduce = function(k, values) {
    var result = {}, commentFields = {
        "commentId": '', 
        "comment": '',
        "created": ''
    };
    values.forEach(function(value) {
        var field;
        if ("comment" in value) {
            if (!("comments" in result)) {
                result.comments = [];
            }
            result.comments.push(value);
        } else if ("comments" in value) {
            if (!("comments" in result)) {
                result.comments = [];
            }
            result.comments.push.apply(result.comments, value.comments);
        }
        for (field in value) {
            if (value.hasOwnProperty(field) && !(field in commentFields)) {
                result[field] = value[field];
            }
        }
    });
    return result;
};
db.users.mapReduce(mapUsers, reduce, {"out": {"reduce": "users_comments"}});
db.comments.mapReduce(mapComments, reduce, {"out": {"reduce": "users_comments"}});
db.users_comments.find().pretty(); // see the resulting collection

At this point, you will have a new collection called users_comments that contains the merged data and you can now use that. These reduced collections all have _id which is the key you were emitting in your map functions and then all of the values are a sub-object inside the value key - the values aren't at the top level of these reduced documents.

This is a somewhat simple example. You can repeat this with more collections as much as you want to keep building up the reduced collection. You could also do summaries and aggregations of data in the process. Likely you would define more than one reduce function as the logic for aggregating and preserving existing fields gets more complex.

You'll also note that there is now one document for each user with all of that user's comments in an array. If we were merging data that has a one-to-one relationship rather than one-to-many, it would be flat and you could simply use a reduce function like this:

reduce = function(k, values) {
    var result = {};
    values.forEach(function(value) {
        var field;
        for (field in value) {
            if (value.hasOwnProperty(field)) {
                result[field] = value[field];
            }
        }
    });
    return result;
};

If you want to flatten the users_comments collection so it's one document per comment, additionally run this:

var map, reduce;
map = function() {
    var debug = function(value) {
        var field;
        for (field in value) {
            print(field + ": " + value[field]);
        }
    };
    debug(this);
    var that = this;
    if ("comments" in this.value) {
        this.value.comments.forEach(function(value) {
            emit(value.commentId, {
                userId: that._id,
                country: that.value.country,
                age: that.value.age,
                comment: value.comment,
                created: value.created,
            });
        });
    }
};
reduce = function(k, values) {
    var result = {};
    values.forEach(function(value) {
        var field;
        for (field in value) {
            if (value.hasOwnProperty(field)) {
                result[field] = value[field];
            }
        }
    });
    return result;
};
db.users_comments.mapReduce(map, reduce, {"out": "comments_with_demographics"});

This technique should definitely not be performed on the fly. It's suited for a cron job or something like that which updates the merged data periodically. You'll probably want to run ensureIndex on the new collection to make sure queries you perform against it run quickly (keep in mind that your data is still inside a value key, so if you were to index comments_with_demographics on the comment created time, it would be db.comments_with_demographics.ensureIndex({"value.created": 1});

Using margin / padding to space <span> from the rest of the <p>

JSFiddle

HTML:

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa omnis obcaecati dolore reprehenderit praesentium. Nisi eius deleniti voluptates quis esse deserunt magni eum commodi nostrum facere pariatur sed eos voluptatum?

</p><span class="small-text">George Nelson 1955</span>

CSS:

p       {font-size:24px; font-weight: 300; -webkit-font-smoothing: subpixel-antialiased;}
p span  {font-size:16px; font-style: italic; margin-top:50px;}

.small-text{
font-size: 12px;
font-style: italic;
}

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);

Using C#:

private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);

Manually put files to Android emulator SD card

If you are using Eclipse you can move files to and from the SD Card through the Android Perspective (it is called DDMS in Eclipse). Just select the Emulator in the left part of the screen and then choose the File Explorer tab. Above the list with your files should be two symbols, one with an arrow pointing at a phone, clicking this will allow you to choose a file to move to phone memory.

Replace \n with actual new line in Sublime Text

On Mac, Shift+CMD+F for search and replace. Search for '\n' and replace with Shift+Enter.

How to print the data in byte array as characters?

Well if you're happy printing it in decimal, you could just make it positive by masking:

int positive = bytes[i] & 0xff;

If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

How do I make an HTTP request in Swift?

Swift 4 and above : Data Request using URLSession API

   //create the url with NSURL
   let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url

   //create the session object
   let session = URLSession.shared

   //now create the URLRequest object using the url object
   let request = URLRequest(url: url)

   //create dataTask using the session object to send data to the server
   let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

       guard error == nil else {
           return
       }

       guard let data = data else {
           return
       }

      do {
         //create json object from data
         if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            print(json)
         }
      } catch let error {
        print(error.localizedDescription)
      }
   })

   task.resume()

Swift 4 and above, Decodable and Result enum

//APPError enum which shows all possible errors
enum APPError: Error {
    case networkError(Error)
    case dataNotFound
    case jsonParsingError(Error)
    case invalidStatusCode(Int)
}

//Result enum to show success or failure
enum Result<T> {
    case success(T)
    case failure(APPError)
}

//dataRequest which sends request to given URL and convert to Decodable Object
func dataRequest<T: Decodable>(with url: String, objectType: T.Type, completion: @escaping (Result<T>) -> Void) {

    //create the url with NSURL
    let dataURL = URL(string: url)! //change the url

    //create the session object
    let session = URLSession.shared

    //now create the URLRequest object using the url object
    let request = URLRequest(url: dataURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            completion(Result.failure(AppError.networkError(error!)))
            return
        }

        guard let data = data else {
            completion(Result.failure(APPError.dataNotFound))
            return
        }

        do {
            //create decodable object from data
            let decodedObject = try JSONDecoder().decode(objectType.self, from: data)
            completion(Result.success(decodedObject))
        } catch let error {
            completion(Result.failure(APPError.jsonParsingError(error as! DecodingError)))
        }
    })

    task.resume()
}

example:

//if we want to fetch todo from placeholder API, then we define the ToDo struct and call dataRequest and pass "https://jsonplaceholder.typicode.com/todos/1" string url.

struct ToDo: Decodable {
    let id: Int
    let userId: Int
    let title: String
    let completed: Bool

}

dataRequest(with: "https://jsonplaceholder.typicode.com/todos/1", objectType: ToDo.self) { (result: Result) in
    switch result {
    case .success(let object):
        print(object)
    case .failure(let error):
        print(error)
    }
}

//this prints the result:

ToDo(id: 1, userId: 1, title: "delectus aut autem", completed: false)

Convert hours:minutes:seconds into total minutes in excel

Just use the formula

120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60

Giving height to table and row in Bootstrap

The simple solution that worked for me as below, wrap the table with a div and change the line-height, this line-height is taken as a ratio.

_x000D_
_x000D_
<div class="col-md-6" style="line-height: 0.5">_x000D_
                                <table class="table table-striped" >_x000D_
                                    <thead>_x000D_
                                    <tr>_x000D_
                                        <th>Parameter</th>_x000D_
                                        <th>Recorded Value</th>_x000D_
                                        <th>Individual Score</th>_x000D_
                                    </tr>_x000D_
                                    </thead>_x000D_
                                    <tbody>_x000D_
                                    <tr>_x000D_
                                        <td>Respiratory Rate</td>_x000D_
                                        <td>Doe</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    <tr>_x000D_
                                        <td>Respiratory Effort</td>_x000D_
                                        <td>Moe</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    <tr>_x000D_
                                        <td>Oxygon Saturation</td>_x000D_
                                        <td>Dooley</td>_x000D_
                                        <td>[email protected]</td>_x000D_
                                    </tr>_x000D_
                                    </tbody>_x000D_
                                </table>_x000D_
                            </div>
_x000D_
_x000D_
_x000D_

Try changing the value as it fits for you.

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

How can I remove or replace SVG content?

I had two charts.

<div id="barChart"></div>
<div id="bubbleChart"></div>

This removed all charts.

d3.select("svg").remove(); 

This worked for removing the existing bar chart, but then I couldn't re-add the bar chart after

d3.select("#barChart").remove();

Tried this. It not only let me remove the existing bar chart, but also let me re-add a new bar chart.

d3.select("#barChart").select("svg").remove();

var svg = d3.select('#barChart')
       .append('svg')
       .attr('width', width + margins.left + margins.right)
       .attr('height', height + margins.top + margins.bottom)
       .append('g')
       .attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');

Not sure if this is the correct way to remove, and re-add a chart in d3. It worked in Chrome, but have not tested in IE.

Module is not available, misspelled or forgot to load (but I didn't)

I got this error when my service declaration was inside a non-invoked function (IIFE). The last line below did NOT have the extra () to run and define the service.

(function() {
    "use strict";

    angular.module("reviewService", [])
        .service("reviewService", reviewService);

    function reviewService($http, $q, $log) {
        //
    }
}());

How to export data to an excel file using PHPExcel

I currently use this function in my project after a series of googling to download excel file from sql statement

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }

find vs find_by vs where

The accepted answer generally covers it all, but I'd like to add something, just incase you are planning to work with the model in a way like updating, and you are retrieving a single record(whose id you do not know), Then find_by is the way to go, because it retrieves the record and does not put it in an array

irb(main):037:0> @kit = Kit.find_by(number: "3456")
  Kit Load (0.9ms)  SELECT "kits".* FROM "kits" WHERE "kits"."number" = 
 '3456' LIMIT 1
=> #<Kit id: 1, number: "3456", created_at: "2015-05-12 06:10:56",   
updated_at: "2015-05-12 06:10:56", job_id: nil>

irb(main):038:0> @kit.update(job_id: 2)
(0.2ms)  BEGIN Kit Exists (0.4ms)  SELECT 1 AS one FROM "kits" WHERE  
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.5ms)   
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE  "kits"."id" = 
1  [["job_id", 2], ["updated_at", Tue, 12 May 2015 07:16:58 UTC +00:00]] 
(0.6ms)  COMMIT => true

but if you use where then you can not update it directly

irb(main):039:0> @kit = Kit.where(number: "3456")
Kit Load (1.2ms)  SELECT "kits".* FROM "kits" WHERE "kits"."number" =  
'3456' => #<ActiveRecord::Relation [#<Kit id: 1, number: "3456", 
created_at: "2015-05-12 06:10:56", updated_at: "2015-05-12 07:16:58", 
job_id: 2>]>

irb(main):040:0> @kit.update(job_id: 3)
ArgumentError: wrong number of arguments (1 for 2)

in such a case you would have to specify it like this

irb(main):043:0> @kit[0].update(job_id: 3)
(0.2ms)  BEGIN Kit Exists (0.6ms)  SELECT 1 AS one FROM "kits" WHERE 
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.6ms)   
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE "kits"."id" = 1  
[["job_id", 3], ["updated_at", Tue, 12 May 2015 07:28:04 UTC +00:00]]
(0.5ms)  COMMIT => true

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

Disable asp.net button after click to prevent double clicking

Check this link, the most simplest way and it does not disable the validations.

http://aspsnippets.com/Articles/Disable-Button-before-Page-PostBack-in-ASP.Net.aspx

If you have e.g.

  <form id="form1" runat="server">
      <asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
  </form>

Then you can use

  <script type = "text/javascript">
  function DisableButton() {
      document.getElementById("<%=Button1.ClientID %>").disabled = true;
  }
  window.onbeforeunload = DisableButton;
  </script>

To disable the button if and after validation has succeeded, just as the page is doing a server postback.

How to delete rows in tables that contain foreign keys to other tables

If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.

Ex:

--id is primary key of MainTable
    declare @id int
    set @id = 1
    declare theMain cursor for select FK from MainTable where MainID = @id
    declare @fk_Id int
    open theMain
    fetch next from theMain into @fk_Id
    while @@fetch_status=0
    begin
        --fkid is the foreign key 
        --Must delete from Main Table first then child.
        delete from MainTable where fkid = @fk_Id
        delete from ReferencingTable where fkid = @fk_Id
        fetch next from theMain into @fk_Id
    end
    close theMain
    deallocate theMain

hope is useful

How do I run msbuild from the command line using Windows SDK 7.1?

Using the "Developer Command Prompt for Visual Studio 20XX" instead of "cmd" will set the path for msbuild automatically without having to add it to your environment variables.

How to set OnClickListener on a RadioButton in Android?

For Kotlin Here is added the lambda expression and Optimized the Code.

   radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
        run {
            when (optionId) {
                R.id.radioButton1 -> {
                    // do something when radio button 1 is selected
                }
                R.id.radioButton2 -> {
                    // do something when radio button 2 is selected
                }
                // add more cases here to handle other buttons in the your RadioGroup
            }
        }
    }

Hope this will help you. Thanks!

Vue - Deep watching an array of objects and calculating the change?

It is well defined behaviour. You cannot get the old value for a mutated object. That's because both the newVal and oldVal refer to the same object. Vue will not keep an old copy of an object that you mutated.

Had you replaced the object with another one, Vue would have provided you with correct references.

Read the Note section in the docs. (vm.$watch)

More on this here and here.

How can I convert spaces to tabs in Vim or Linux?

To use Vim to retab a set of files (e.g. all the *.ts files in a directory hierarchy) from say 2 spaces to 4 spaces you can try this from the command line:

find . -name '*.ts' -print0 | xargs -0 -n1 vim -e '+set ts=2 noet | retab! | set ts=4 et | retab | wq'

What this is doing is using find to pass all the matching files to xargs (the -print0 option on find works with the -0 option to xargs in order to handle files w/ spaces in the name).

xargs runs vim in ex mode (-e) on each file executing the given ex command which is actually several commands, to change the existing leading spaces to tabs, resetting the tab stop and changing the tabs back to spaces and finally saving and exiting.

Running in ex mode prevents this: Vim: Warning: Input is not from a terminal for each file.

How to get the separate digits of an int number?

Java 8 solution to get digits as int[] from an integer that you have as a String:

int[] digits = intAsString.chars().map(i -> i - '0').toArray();

Fatal error: Cannot use object of type stdClass as array in

CodeIgniter returns result rows as objects, not arrays. From the user guide:

result()


This function returns the query result as an array of objects, or an empty array on failure.

You'll have to access the fields using the following notation:

foreach ($getvidids->result() as $row) {
    $vidid = $row->videoid;
}

How do I fire an event when a iframe has finished loading in jQuery?

The solution I have applied to this situation is to simply place an absolute loading image in the DOM, which will be covered by the iframe layer after the iframe is loaded.

The z-index of the iframe should be (loading's z-index + 1), or just higher.

For example:

.loading-image { position: absolute; z-index: 0; }
.iframe-element { position: relative; z-index: 1; }

Hope this helps if no javaScript solution did. I do think that CSS is best practice for these situations.

Best regards.

How to extract text from a PDF file?

I am adding code to accomplish this: It is working fine for me:

# This works in python 3
# required python packages
# tabula-py==1.0.0
# PyPDF2==1.26.0
# Pillow==4.0.0
# pdfminer.six==20170720

import os
import shutil
import warnings
from io import StringIO

import requests
import tabula
from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage

warnings.filterwarnings("ignore")


def download_file(url):
    local_filename = url.split('/')[-1]
    local_filename = local_filename.replace("%20", "_")
    r = requests.get(url, stream=True)
    print(r)
    with open(local_filename, 'wb') as f:
        shutil.copyfileobj(r.raw, f)

    return local_filename


class PDFExtractor():
    def __init__(self, url):
        self.url = url

    # Downloading File in local
    def break_pdf(self, filename, start_page=-1, end_page=-1):
        pdf_reader = PdfFileReader(open(filename, "rb"))
        # Reading each pdf one by one
        total_pages = pdf_reader.numPages
        if start_page == -1:
            start_page = 0
        elif start_page < 1 or start_page > total_pages:
            return "Start Page Selection Is Wrong"
        else:
            start_page = start_page - 1

        if end_page == -1:
            end_page = total_pages
        elif end_page < 1 or end_page > total_pages - 1:
            return "End Page Selection Is Wrong"
        else:
            end_page = end_page

        for i in range(start_page, end_page):
            output = PdfFileWriter()
            output.addPage(pdf_reader.getPage(i))
            with open(str(i + 1) + "_" + filename, "wb") as outputStream:
                output.write(outputStream)

    def extract_text_algo_1(self, file):
        pdf_reader = PdfFileReader(open(file, 'rb'))
        # creating a page object
        pageObj = pdf_reader.getPage(0)

        # extracting extract_text from page
        text = pageObj.extractText()
        text = text.replace("\n", "").replace("\t", "")
        return text

    def extract_text_algo_2(self, file):
        pdfResourceManager = PDFResourceManager()
        retstr = StringIO()
        la_params = LAParams()
        device = TextConverter(pdfResourceManager, retstr, codec='utf-8', laparams=la_params)
        fp = open(file, 'rb')
        interpreter = PDFPageInterpreter(pdfResourceManager, device)
        password = ""
        max_pages = 0
        caching = True
        page_num = set()

        for page in PDFPage.get_pages(fp, page_num, maxpages=max_pages, password=password, caching=caching,
                                      check_extractable=True):
            interpreter.process_page(page)

        text = retstr.getvalue()
        text = text.replace("\t", "").replace("\n", "")

        fp.close()
        device.close()
        retstr.close()
        return text

    def extract_text(self, file):
        text1 = self.extract_text_algo_1(file)
        text2 = self.extract_text_algo_2(file)

        if len(text2) > len(str(text1)):
            return text2
        else:
            return text1

    def extarct_table(self, file):

        # Read pdf into DataFrame
        try:
            df = tabula.read_pdf(file, output_format="csv")
        except:
            print("Error Reading Table")
            return

        print("\nPrinting Table Content: \n", df)
        print("\nDone Printing Table Content\n")

    def tiff_header_for_CCITT(self, width, height, img_size, CCITT_group=4):
        tiff_header_struct = '<' + '2s' + 'h' + 'l' + 'h' + 'hhll' * 8 + 'h'
        return struct.pack(tiff_header_struct,
                           b'II',  # Byte order indication: Little indian
                           42,  # Version number (always 42)
                           8,  # Offset to first IFD
                           8,  # Number of tags in IFD
                           256, 4, 1, width,  # ImageWidth, LONG, 1, width
                           257, 4, 1, height,  # ImageLength, LONG, 1, lenght
                           258, 3, 1, 1,  # BitsPerSample, SHORT, 1, 1
                           259, 3, 1, CCITT_group,  # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding
                           262, 3, 1, 0,  # Threshholding, SHORT, 1, 0 = WhiteIsZero
                           273, 4, 1, struct.calcsize(tiff_header_struct),  # StripOffsets, LONG, 1, len of header
                           278, 4, 1, height,  # RowsPerStrip, LONG, 1, lenght
                           279, 4, 1, img_size,  # StripByteCounts, LONG, 1, size of extract_image
                           0  # last IFD
                           )

    def extract_image(self, filename):
        number = 1
        pdf_reader = PdfFileReader(open(filename, 'rb'))

        for i in range(0, pdf_reader.numPages):

            page = pdf_reader.getPage(i)

            try:
                xObject = page['/Resources']['/XObject'].getObject()
            except:
                print("No XObject Found")
                return

            for obj in xObject:

                try:

                    if xObject[obj]['/Subtype'] == '/Image':
                        size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
                        data = xObject[obj]._data
                        if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
                            mode = "RGB"
                        else:
                            mode = "P"

                        image_name = filename.split(".")[0] + str(number)

                        print(xObject[obj]['/Filter'])

                        if xObject[obj]['/Filter'] == '/FlateDecode':
                            data = xObject[obj].getData()
                            img = Image.frombytes(mode, size, data)
                            img.save(image_name + "_Flate.png")
                            # save_to_s3(imagename + "_Flate.png")
                            print("Image_Saved")

                            number += 1
                        elif xObject[obj]['/Filter'] == '/DCTDecode':
                            img = open(image_name + "_DCT.jpg", "wb")
                            img.write(data)
                            # save_to_s3(imagename + "_DCT.jpg")
                            img.close()
                            number += 1
                        elif xObject[obj]['/Filter'] == '/JPXDecode':
                            img = open(image_name + "_JPX.jp2", "wb")
                            img.write(data)
                            # save_to_s3(imagename + "_JPX.jp2")
                            img.close()
                            number += 1
                        elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
                            if xObject[obj]['/DecodeParms']['/K'] == -1:
                                CCITT_group = 4
                            else:
                                CCITT_group = 3
                            width = xObject[obj]['/Width']
                            height = xObject[obj]['/Height']
                            data = xObject[obj]._data  # sorry, getData() does not work for CCITTFaxDecode
                            img_size = len(data)
                            tiff_header = self.tiff_header_for_CCITT(width, height, img_size, CCITT_group)
                            img_name = image_name + '_CCITT.tiff'
                            with open(img_name, 'wb') as img_file:
                                img_file.write(tiff_header + data)

                            # save_to_s3(img_name)
                            number += 1
                except:
                    continue

        return number

    def read_pages(self, start_page=-1, end_page=-1):

        # Downloading file locally
        downloaded_file = download_file(self.url)
        print(downloaded_file)

        # breaking PDF into number of pages in diff pdf files
        self.break_pdf(downloaded_file, start_page, end_page)

        # creating a pdf reader object
        pdf_reader = PdfFileReader(open(downloaded_file, 'rb'))

        # Reading each pdf one by one
        total_pages = pdf_reader.numPages

        if start_page == -1:
            start_page = 0
        elif start_page < 1 or start_page > total_pages:
            return "Start Page Selection Is Wrong"
        else:
            start_page = start_page - 1

        if end_page == -1:
            end_page = total_pages
        elif end_page < 1 or end_page > total_pages - 1:
            return "End Page Selection Is Wrong"
        else:
            end_page = end_page

        for i in range(start_page, end_page):
            # creating a page based filename
            file = str(i + 1) + "_" + downloaded_file

            print("\nStarting to Read Page: ", i + 1, "\n -----------===-------------")

            file_text = self.extract_text(file)
            print(file_text)
            self.extract_image(file)

            self.extarct_table(file)
            os.remove(file)
            print("Stopped Reading Page: ", i + 1, "\n -----------===-------------")

        os.remove(downloaded_file)


# I have tested on these 3 pdf files
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Healthcare-January-2017.pdf"
url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sample_Test.pdf"
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sazerac_FS_2017_06_30%20Annual.pdf"
# creating the instance of class
pdf_extractor = PDFExtractor(url)

# Getting desired data out
pdf_extractor.read_pages(15, 23)

How to uninstall Golang?

Use this command to uninstall Golang for Ubuntu.

This will remove just the golang-go package itself.

sudo apt-get remove golang-go

Uninstall golang-go and its dependencies:

sudo apt-get remove --auto-remove golang-go

JQuery show and hide div on mouse click (animate)

I would do something like this

DEMO in JsBin: http://jsbin.com/ofiqur/1/

  <a href="#" id="showmenu">Click Here</a>
  <div class="menu">
    <ul>
      <li><a href="#">Button 1</a></li>
      <li><a href="#">Button 2</a></li>
      <li><a href="#">Button 3</a></li>
    </ul>
  </div>

and in jQuery as simple as

var min = "-100px", // remember to set in css the same value
    max = "0px";

$(function() {
  $("#showmenu").click(function() {

    if($(".menu").css("marginLeft") == min) // is it left?
      $(".menu").animate({ marginLeft: max }); // move right
    else
      $(".menu").animate({ marginLeft: min }); // move left

  });
});

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

What is the preferred syntax for defining enums in JavaScript?

If you're using Backbone, you can get full-blown enum functionality (find by id, name, custom members) for free using Backbone.Collection.

// enum instance members, optional
var Color = Backbone.Model.extend({
    print : function() {
        console.log("I am " + this.get("name"))
    }
});

// enum creation
var Colors = new Backbone.Collection([
    { id : 1, name : "Red", rgb : 0xFF0000},
    { id : 2, name : "Green" , rgb : 0x00FF00},
    { id : 3, name : "Blue" , rgb : 0x0000FF}
], {
    model : Color
});

// Expose members through public fields.
Colors.each(function(color) {
    Colors[color.get("name")] = color;
});

// using
Colors.Red.print()

How to "inverse match" with regex?

If you want to do this in RegexBuddy, there are two ways to get a list of all lines not matching a regex.

On the toolbar on the Test panel, set the test scope to "Line by line". When you do that, an item List All Lines without Matches will appear under the List All button on the same toolbar. (If you don't see the List All button, click the Match button in the main toolbar.)

On the GREP panel, you can turn on the "line-based" and the "invert results" checkboxes to get a list of non-matching lines in the files you're grepping through.

Find index of a value in an array

Just posted my implementation of IndexWhere() extension method (with unit tests):

http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

Example usage:

int index = myList.IndexWhere(item => item.Something == someOtherThing);

How to use GROUP BY to concatenate strings in MySQL?

The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024 characters, so we first do:

SET group_concat_max_len=100000000;

and then, for example:

SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id

Get gateway ip address in android

This solution will give you the Network parameters. Check out this solution

Save plot to image file instead of displaying it using Matplotlib

The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:

with open('some_file.pkl', "wb") as fp:
    pickle.dump(fig, fp, protocol=4)

Like this, I can later load the figure object and manipulate the settings as I please.

I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.

NB: Be careful, as sometimes this method generates huge files.

Multiline for WPF TextBox

Enable TextWrapping="Wrap" and AcceptsReturn="True" on your TextBox.

You might also wish to enable AcceptsTab and SpellCheck.IsEnabled too.

In Perl, how to remove ^M from a file?

I prefer a more general solution that will work with either DOS or Unix input. Assuming the input is from STDIN:

while (defined(my $ln = <>))
  {
    chomp($ln);
    chop($ln) if ($ln =~ m/\r$/);

    # filter and write
  }

How to enable scrolling on website that disabled scrolling?

You can paste the following code to the console to scroll up/down using the a/z keyboard keys. If you want to set your own keys you can visit this page to get the keycodes

function KeyPress(e) {
  var evtobj = window.event? event : e
  if (evtobj.keyCode == 90) {
    window.scrollBy(0, 100) 
  }
  if (evtobj.keyCode == 65) {
    window.scrollBy(0, -100) 
  }
}

document.onkeydown = KeyPress;

How to get a random value from dictionary?

Since this is homework:

Check out random.sample() which will select and return a random element from an list. You can get a list of dictionary keys with dict.keys() and a list of dictionary values with dict.values().

How to send data in request body with a GET when using jQuery $.ajax()

You can send your data like the "POST" request through the "HEADERS".

Something like this:

$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   headers: ['id1':1, 'id2':2, 'id3':3],
   data: "",
   contentType: "text/plain",
   dataType: "json",
   success: onSuccess,
   error: onError
});

C# getting its own class name

Get Current class name of Asp.net

string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

A non-zero exit status code, usually indicates abnormal termination. if n != 0, its up to the programmer to apply a meaning to the various n's.

From https://docs.oracle.com/javase/7/docs/api/java/lang/System.html.

Selecting data frame rows based on partial string match in a column

Another option would be to simply use grepl function:

df[grepl('er', df$name), ]
CO2[grepl('non', CO2$Treatment), ]

df <- data.frame(name = c('bob','robert','peter'),
                 id = c(1,2,3)
                 )

# name id
# 2 robert  2
# 3  peter  3

How to listen for changes to a MongoDB collection?

MongoDB has what is called capped collections and tailable cursors that allows MongoDB to push data to the listeners.

A capped collection is essentially a collection that is a fixed size and only allows insertions. Here's what it would look like to create one:

db.createCollection("messages", { capped: true, size: 100000000 })

MongoDB Tailable cursors (original post by Jonathan H. Wage)

Ruby

coll = db.collection('my_collection')
cursor = Mongo::Cursor.new(coll, :tailable => true)
loop do
  if doc = cursor.next_document
    puts doc
  else
    sleep 1
  end
end

PHP

$mongo = new Mongo();
$db = $mongo->selectDB('my_db')
$coll = $db->selectCollection('my_collection');
$cursor = $coll->find()->tailable(true);
while (true) {
    if ($cursor->hasNext()) {
        $doc = $cursor->getNext();
        print_r($doc);
    } else {
        sleep(1);
    }
}

Python (by Robert Stewart)

from pymongo import Connection
import time

db = Connection().my_db
coll = db.my_collection
cursor = coll.find(tailable=True)
while cursor.alive:
    try:
        doc = cursor.next()
        print doc
    except StopIteration:
        time.sleep(1)

Perl (by Max)

use 5.010;

use strict;
use warnings;
use MongoDB;

my $db = MongoDB::Connection->new;
my $coll = $db->my_db->my_collection;
my $cursor = $coll->find->tailable(1);
for (;;)
{
    if (defined(my $doc = $cursor->next))
    {
        say $doc;
    }
    else
    {
        sleep 1;
    }
}

Additional Resources:

Ruby/Node.js Tutorial which walks you through creating an application that listens to inserts in a MongoDB capped collection.

An article talking about tailable cursors in more detail.

PHP, Ruby, Python, and Perl examples of using tailable cursors.

Disabling contextual LOB creation as createClob() method threw error

Update to this for using Hibernate 4.3.x / 5.0.x - you could just set this property to true:

<prop key="hibernate.jdbc.lob.non_contextual_creation">true</prop>

to get rid of that error message. Same effect but without the "threw exception" detail. See LobCreatorBuilder source for details.

ReferenceError: variable is not defined

Got the error (in the function init) with the following code ;

"use strict" ;

var hdr ;

function init(){ // called on load
    hdr = document.getElementById("hdr");
}

... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The fix for this was to change

var hdr ;

to

var hdr = null ;

Excel tab sheet names vs. Visual Basic sheet names

I think I may have an alternative solution. It's a little ugly, but it seems to work.

Function GetAnyNameValue(NameofName) As String
    Dim nm, ws, rng As String
    nm = ActiveWorkbook.Names(NameofName).Value
    ws = CStr(Split(nm, "!")(0))
    ws = Replace(ws, "'", "")
    ws = Replace(ws, "=", "")
    rng = CStr(Split(nm, "!")(1))
    GetAnyNameValue = CStr(Worksheets(ws).Range(rng).Value)
End Function

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

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

This is how I did it on macOS:

vim ~/.bash_profile  # macOS 10.14 Mojave and older
vim ~/.zshrc         # macOS 10.15 Catalina and newer (using zsh by default)

And added the following environment variables:

export ANDROID_HOME=/Users/{{your user}}/Library/Android/sdk
export ANDROID_SDK_ROOT=/Users/{{your user}}/Library/Android/sdk
export ANDROID_AVD_HOME=/Users/{{your user}}/.android/avd

Android path might be different, if so change it accordingly. At last, to refresh the terminal to apply changes:

source ~/.bash_profile  # macOS 10.14 Mojave and older
source ~/.zshrc         # macOS 10.15 Catalina and newer (using zsh by default)

(Excel) Conditional Formatting based on Adjacent Cell Value

You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula

=$B2>$C2

by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Why is the time complexity of both DFS and BFS O( V + E )

Short but simple explanation:

I the worst case you would need to visit all the vertex and edge hence the time complexity in the worst case is O(V+E)

How to programmatically click a button in WPF?

if you want to call click event:

SomeButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

And if you want the button looks like it is pressed:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { true });

and unpressed after that:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { false });

or use the ToggleButton

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

to convert a TimestampTZ in oracle, you do

TO_TIMESTAMP_TZ('2012-10-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') 
  at time zone 'region'

see here: http://docs.oracle.com/cd/E11882_01/server.112/e10729/ch4datetime.htm#NLSPG264

and here for regions: http://docs.oracle.com/cd/E11882_01/server.112/e10729/applocaledata.htm#NLSPG0141

eg:

SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
09-APR-13 01.10.21.000000000 -05:00


SQL> select a, sys_extract_utc(a), a at time zone '-05:00' from (select TO_TIMESTAMP_TZ('2013-03-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'-05:00'
---------------------------------------------------------------------------
09-MAR-13 01.10.21.000000000 CST
09-MAR-13 07.10.21.000000000
09-MAR-13 02.10.21.000000000 -05:00

SQL> select a, sys_extract_utc(a), a at time zone 'America/Los_Angeles' from (select TO_TIMESTAMP_TZ('2013-04-09 1:10:21 CST','YYYY-MM-DD HH24:MI:SS TZR') a from dual);

A
---------------------------------------------------------------------------
SYS_EXTRACT_UTC(A)
---------------------------------------------------------------------------
AATTIMEZONE'AMERICA/LOS_ANGELES'
---------------------------------------------------------------------------
09-APR-13 01.10.21.000000000 CST
09-APR-13 06.10.21.000000000
08-APR-13 23.10.21.000000000 AMERICA/LOS_ANGELES

Shell script to copy files from one location to another location and rename add the current date to every file

In bash, provided you files names have no spaces:

cd /home/webapps/project1/folder1
for f in *.csv
do 
   cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

Passing no-sandbox to exec seems important for jenkins on windows in foreground or as service. Here's my solution

chromedriver fails on windows jenkins slave running in foreground

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

How do you add an ActionListener onto a JButton in Java

I don't know if this works but I made the variable names

public abstract class beep implements ActionListener {
    public static void main(String[] args) {
        JFrame f = new JFrame("beeper");
        JButton button = new JButton("Beep me");
        f.setVisible(true);
        f.setSize(300, 200);
        f.add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Insert code here
            }
        });
    }
}

How to use a ViewBag to create a dropdownlist?

hope it will work

 @Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })

Here String.Empty will be the empty as a default selector.

Is there a way to have printf() properly print out an array (of floats, say)?

You need to go for a loop:

for (int i = 0; i < sizeof(foo) / sizeof(float); ++i)
   printf("%f", foo[i]);
printf("\n");