Programs & Examples On #Data comparison

JOptionPane Yes or No window

"if(true)" will always be true and it will never make it to the else. If you want it to work correctly you have to do this:

int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
    JOptionPane.showMessageDialog(null, "HELLO");
} else {
    JOptionPane.showMessageDialog(null, "GOODBYE");
    System.exit(0);
}

Converting between datetime and Pandas Timestamp objects

To answer the question of going from an existing python datetime to a pandas Timestamp do the following:

    import time, calendar, pandas as pd
    from datetime import datetime
    
    def to_posix_ts(d: datetime, utc:bool=True) -> float:
        tt=d.timetuple()
        return (calendar.timegm(tt) if utc else time.mktime(tt)) + round(d.microsecond/1000000, 0)
    
    def pd_timestamp_from_datetime(d: datetime) -> pd.Timestamp:
        return pd.to_datetime(to_posix_ts(d), unit='s')
    
    dt = pd_timestamp_from_datetime(datetime.now())
    print('({}) {}'.format(type(dt), dt))

Output:

(<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2020-09-05 23:38:55

I was hoping for a more elegant way to do this but the to_posix_ts is already in my standard tool chain so I'm moving on.

How can I get the baseurl of site?

This works for me.

Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
  • Request.Url.OriginalString: return the complete path same as browser showing.
  • Request.Url.PathAndQuery: return the (complete path) - (domain name + PORT).
  • Request.ApplicationPath: return "/" on hosted server and "application name" on local IIS deploy.

So if you want to access your domain name do consider to include the application name in case of:

  1. IIS deployment
  2. If your application deployed on the sub-domain.

====================================

For the dev.x.us/web

it return this strong text

Redirecting unauthorized controller in ASP.NET MVC

Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.

EDIT: I have a couple of blog posts that go into more detail:

Example:

    [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
    public class MasterEventAuthorizationAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// The name of the master page or view to use when rendering the view on authorization failure.  Default
        /// is null, indicating to use the master page of the specified view.
        /// </summary>
        public virtual string MasterName { get; set; }

        /// <summary>
        /// The name of the view to render on authorization failure.  Default is "Error".
        /// </summary>
        public virtual string ViewName { get; set; }

        public MasterEventAuthorizationAttribute()
            : base()
        {
            this.ViewName = "Error";
        }

        protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
        {
            validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
        }

        public override void OnAuthorization( AuthorizationContext filterContext )
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException( "filterContext" );
            }

            if (AuthorizeCore( filterContext.HttpContext ))
            {
                SetCachePolicy( filterContext );
            }
            else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                // auth failed, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
            {
                // is authenticated and is in the SuperUser role
                SetCachePolicy( filterContext );
            }
            else
            {
                ViewDataDictionary viewData = new ViewDataDictionary();
                viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
                filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
            }

        }

        protected void SetCachePolicy( AuthorizationContext filterContext )
        {
            // ** IMPORTANT **
            // Since we're performing authorization at the action level, the authorization code runs
            // after the output caching module. In the worst case this could allow an authorized user
            // to cause the page to be cached, then an unauthorized user would later be served the
            // cached page. We work around this by telling proxies not to cache the sensitive page,
            // then we hook our custom authorization code into the caching mechanism so that we have
            // the final say on whether a page should be served from the cache.
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
            cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
            cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
        }


    }

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

You probably want to have a list of supported encodings. For each file, try each encoding in turn, maybe starting with UTF-8. Every time you catch the MalformedInputException, try the next encoding.

How can I create a dynamically sized array of structs?

If you want to dynamically allocate arrays, you can use malloc from stdlib.h.

If you want to allocate an array of 100 elements using your words struct, try the following:

words* array = (words*)malloc(sizeof(words) * 100);

The size of the memory that you want to allocate is passed into malloc and then it will return a pointer of type void (void*). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*.

The sizeof keyword is used here to find out the size of the words struct, then that size is multiplied by the number of elements you want to allocate.

Once you are done, be sure to use free() to free up the heap memory you used in order to prevent memory leaks:

free(array);

If you want to change the size of the allocated array, you can try to use realloc as others have mentioned, but keep in mind that if you do many reallocs you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many reallocs.

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

Remove an item from a dictionary when its key is unknown

a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']

How to load CSS Asynchronously

you can try to get it in a lot of ways :

1.Using media="bogus" and a <link> at the foot

<head>
    <!-- unimportant nonsense -->
    <link rel="stylesheet" href="style.css" media="bogus">
</head>
<body>
    <!-- other unimportant nonsense, such as content -->
    <link rel="stylesheet" href="style.css">
</body>

2.Inserting DOM in the old way

<script type="text/javascript">
(function(){
  var bsa = document.createElement('script');
     bsa.type = 'text/javascript';
     bsa.async = true;
     bsa.src = 'https://s3.buysellads.com/ac/bsa.js';
  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa);
})();
</script>

3.if you can try plugins you could try loadCSS

<script>
  // include loadCSS here...
  function loadCSS( href, before, media ){ ... }
  // load a file
  loadCSS( "path/to/mystylesheet.css" );
</script>

How to split a string, but also keep the delimiters?

You want to use lookarounds, and split on zero-width matches. Here are some examples:

public class SplitNDump {
    static void dump(String[] arr) {
        for (String s : arr) {
            System.out.format("[%s]", s);
        }
        System.out.println();
    }
    public static void main(String[] args) {
        dump("1,234,567,890".split(","));
        // "[1][234][567][890]"
        dump("1,234,567,890".split("(?=,)"));   
        // "[1][,234][,567][,890]"
        dump("1,234,567,890".split("(?<=,)"));  
        // "[1,][234,][567,][890]"
        dump("1,234,567,890".split("(?<=,)|(?=,)"));
        // "[1][,][234][,][567][,][890]"

        dump(":a:bb::c:".split("(?=:)|(?<=:)"));
        // "[][:][a][:][bb][:][:][c][:]"
        dump(":a:bb::c:".split("(?=(?!^):)|(?<=:)"));
        // "[:][a][:][bb][:][:][c][:]"
        dump(":::a::::b  b::c:".split("(?=(?!^):)(?<!:)|(?!:)(?<=:)"));
        // "[:::][a][::::][b  b][::][c][:]"
        dump("a,bb:::c  d..e".split("(?!^)\\b"));
        // "[a][,][bb][:::][c][  ][d][..][e]"

        dump("ArrayIndexOutOfBoundsException".split("(?<=[a-z])(?=[A-Z])"));
        // "[Array][Index][Out][Of][Bounds][Exception]"
        dump("1234567890".split("(?<=\\G.{4})"));   
        // "[1234][5678][90]"

        // Split at the end of each run of letter
        dump("Boooyaaaah! Yippieeee!!".split("(?<=(?=(.)\\1(?!\\1))..)"));
        // "[Booo][yaaaa][h! Yipp][ieeee][!!]"
    }
}

And yes, that is triply-nested assertion there in the last pattern.

Related questions

See also

What’s the difference between Response.Write() andResponse.Output.Write()?

Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.

Here is example:

protected void Button1_Click(object sender, EventArgs e)
    {
       Response.Write ("hi good morning!"+"is it right?");//only strings are allowed        
       Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
       Response.Output.Write("\nhi goood morning!");//works fine
       Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
    }

Android Horizontal RecyclerView scroll Direction

XML approach using androidx:

<androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:id="@+id/my_recycler_view"
        android:orientation="horizontal"
        tools:listitem="@layout/my_item"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" 
        android:layout_height="wrap_content">

How do I compile and run a program in Java on my Mac?

Other solutions are good enough to answer your query. However, if you are looking for just one command to do that for you -

Create a file name "run", in directory where your Java files are. And save this in your file -

javac "$1.java"
if [ $? -eq 0 ]; then
  echo "--------Run output-------"
  java "$1"
fi

give this file run permission by running -

chmod 777 

Now you can run any of your files by merely running -

./run <yourfilename> (don't add .java in filename)

How to stop a goroutine

Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.

quit := make(chan bool)
go func() {
    for {
        select {
        case <- quit:
            return
        default:
            // Do other stuff
        }
    }
}()

// Do stuff

// Quit goroutine
quit <- true

How to get the HTML for a DOM element in javascript

as outerHTML is IE only, use this function:

function getOuterHtml(node) {
    var parent = node.parentNode;
    var element = document.createElement(parent.tagName);
    element.appendChild(node);
    var html = element.innerHTML;
    parent.appendChild(node);
    return html;
}

creates a bogus empty element of the type parent and uses innerHTML on it and then reattaches the element back into the normal dom

JavaScript single line 'if' statement - best syntax, this alternative?

As has already been stated, you can use:

&& style

lemons && document.write("foo gave me a bar");  

or

bracket-less style

if (lemons) document.write("foo gave me a bar");

short-circuit return

If, however, you wish to use the one line if statement to short-circuit a function though, you'd need to go with the bracket-less version like so:

if (lemons) return "foo gave me a bar";

as

lemons && return "foo gave me a bar"; // does not work!

will give you a SyntaxError: Unexpected keyword 'return'

How to disable the parent form when a child form is active?

Have you tried using Form.ShowDialog() instead of Form.Show()?

ShowDialog shows your window as modal, which means you cannot interact with the parent form until it closes.

What does Html.HiddenFor do?

Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.

So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.

To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting

Ansible: filter a list by its attributes

To filter a list of dicts you can use the selectattr filter together with the equalto test:

network.addresses.private_man | selectattr("type", "equalto", "fixed")

The above requires Jinja2 v2.8 or later (regardless of Ansible version).


Ansible also has the tests match and search, which take regular expressions:

match will require a complete match in the string, while search will require a match inside of the string.

network.addresses.private_man | selectattr("type", "match", "^fixed$")

To reduce the list of dicts to a list of strings, so you only get a list of the addr fields, you can use the map filter:

... | map(attribute='addr') | list

Or if you want a comma separated string:

... | map(attribute='addr') | join(',')

Combined, it would look like this.

- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}

Is mathematics necessary for programming?

I would argue that having advanced logic (discrete) math can really help. That along with set theory. When dealing with common computer programs, these disciplines can help a lot. However, a lot of the other math I took in university was calculus, which as far as I can see, had very limited usage. Since 90% (or something like that) of programming is doing business apps with very simple math, I would say that for the most part, you can get by with very little math knowledge. However, a good understanding of boolean algebra, logic, discrete math, and set theory can really put you up to that next level.

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

How to compare 2 files fast using .NET?

If you only need to compare two files, I guess the fastest way would be (in C, I don't know if it's applicable to .NET)

  1. open both files f1, f2
  2. get the respective file length l1, l2
  3. if l1 != l2 the files are different; stop
  4. mmap() both files
  5. use memcmp() on the mmap()ed files

OTOH, if you need to find if there are duplicate files in a set of N files, then the fastest way is undoubtedly using a hash to avoid N-way bit-by-bit comparisons.

How to pass credentials to the Send-MailMessage command for sending emails

PSH> $cred = Get-Credential

PSH> $cred | Export-CliXml c:\temp\cred.clixml

PSH> $cred2 = Import-CliXml c:\temp\cred.clixml

That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.

Log all queries in mysql

Besides what I came across here, running the following was the simplest way to dump queries to a log file without restarting

SET global log_output = 'FILE';
SET global general_log_file='/Applications/MAMP/logs/mysql_general.log';
SET global general_log = 1;

can be turned off with

SET global general_log = 0;

concatenate char array in C

Have a look at the strcat function.

In particular, you could try this:

const char* name = "hello";
const char* extension = ".txt";

char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */

ActionController::InvalidAuthenticityToken

Running rails dev:cache in my console fixed this for me! (Rails 6)

I think it might be something to do with Turbolinks, but CSRF only seems to work when local caching is enabled.

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

Adding an onclick event to a table row

Try changing the this.getElementsByTagName("td")[0]) line to read row.getElementsByTagName("td")[0];. That should capture the row reference in a closure, and it should work as expected.

Edit: The above is wrong, since row is a global variable -- as others have said, allocate a new variable and then use THAT in the closure.

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

When you decorate a model property with [DataType(DataType.Date)] the default template in ASP.NET MVC 4 generates an input field of type="date":

<input class="text-box single-line" 
       data-val="true" 
       data-val-date="The field EstPurchaseDate must be a date."
       id="EstPurchaseDate" 
       name="EstPurchaseDate" 
       type="date" value="9/28/2012" />

Browsers that support HTML5 such Google Chrome render this input field with a date picker.

In order to correctly display the date, the value must be formatted as 2012-09-28. Quote from the specification:

value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.

You could enforce this format using the DisplayFormat attribute:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EstPurchaseDate { get; set; }

Adding whitespace in Java

If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.

messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,
                        KeyEvent.KEYCODE_ENDCALL));

How can I scroll to a specific location on the page using jquery?

jQuery Scroll Plugin

since this is a question tagged with jquery i have to say, that this library has a very nice plugin for smooth scrolling, you can find it here: http://plugins.jquery.com/scrollTo/

Excerpts from Documentation:

$('div.pane').scrollTo(...);//all divs w/class pane

or

$.scrollTo(...);//the plugin will take care of this

Custom jQuery function for scrolling

you can use a very lightweight approach by defining your custom scroll jquery function

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

and use it like:

$('#your-div').scrollView();

Scroll to a page coordinates

Animate html and body elements with scrollTop or scrollLeft attributes

$('html, body').animate({
    scrollTop: 0,
    scrollLeft: 300
}, 1000);

Plain javascript

scrolling with window.scroll

window.scroll(horizontalOffset, verticalOffset);

only to sum up, use the window.location.hash to jump to element with ID

window.location.hash = '#your-page-element';

Directly in HTML (accesibility enhancements)

<a href="#your-page-element">Jump to ID</a>

<div id="your-page-element">
    will jump here
</div>

Is it possible to write data to file using only JavaScript?

Yes its possible Here the code is

_x000D_
_x000D_
const fs = require('fs') 
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => { 
      
    // In case of a error throw err. 
    if (err) throw err; 
}) 
_x000D_
_x000D_
_x000D_

How to develop Android app completely using python?

To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.

checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application

How it works

Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.

VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.

Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.

Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:

  • Mac
  • Windows
  • Linux
  • iPhone/iPad
  • Android
  • AppleTV
  • tvOS.

You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub

in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.

and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.

I hope this has been helpful

get the titles of all open windows

you should use the EnumWindow API.

there are plenty of examples on how to use it from C#, I found something here:

Get Application's Window Handles

Issue with EnumWindows

Bootstrap 4 File Input

Updated 2021

Bootstrap 5

Custom file input no longer exists so to change Choose file... you'd need to use JS or some CSS like this.

Bootstrap 4.4

Displaying the selected filename can also be done with plain JavaScript. Here's an example that assumes the standard custom-file-input with label that is the next sibling element to the input...

document.querySelector('.custom-file-input').addEventListener('change',function(e){
  var fileName = document.getElementById("myInput").files[0].name;
  var nextSibling = e.target.nextElementSibling
  nextSibling.innerText = fileName
})

https://codeply.com/p/LtpNZllird

Bootstrap 4.1+

Now in Bootstrap 4.1 the "Choose file..." placeholder text is set in the custom-file-label:

<div class="custom-file" id="customFile" lang="es">
        <input type="file" class="custom-file-input" id="exampleInputFile" aria-describedby="fileHelp">
        <label class="custom-file-label" for="exampleInputFile">
           Select file...
        </label>
</div>

Changing the "Browse" button text requires a little extra CSS or SASS. Also notice how language translation works using the lang="" attribute.

.custom-file-input ~ .custom-file-label::after {
    content: "Button Text";
}

https://codeply.com/go/gnVCj66Efp (CSS)
https://codeply.com/go/2Mo9OrokBQ (SASS)

Another Bootstrap 4.1 Option

Alternatively you can use this custom file input plugin

https://www.codeply.com/go/uGJOpHUd8L/file-input


Bootstrap 4 Alpha 6 (Original Answer)

I think there are 2 separate issues here..

<label class="custom-file" id="customFile">
        <input type="file" class="custom-file-input">
        <span class="custom-file-control form-control-file"></span>
</label>

1 - How the change the initial placeholder and button text

In Bootstrap 4, the initial placeholder value is set on the custom-file-control with a CSS pseudo ::after element based on the HTML language. The initial file button (which isn't really a button but looks like one) is set with a CSS pseudo ::before element. These values can be overridden with CSS..

#customFile .custom-file-control:lang(en)::after {
  content: "Select file...";
}

#customFile .custom-file-control:lang(en)::before {
  content: "Click me";
}

2 - How to get the selected filename value, and update the input to show the value.

Once a file is selected, the value can be obtained using JavaScript/jQuery.

$('.custom-file-input').on('change',function(){
    var fileName = $(this).val();
})

However, since the placeholder text for the input is a pseudo element, there's no easy way to manipulate this with Js/jQuery. You can however, have a another CSS class that hides the pseudo content once the file is selected...

.custom-file-control.selected:lang(en)::after {
  content: "" !important;
}

Use jQuery to toggle the .selected class on the .custom-file-control once the file is selected. This will hide the initial placeholder value. Then put the filename value in the .form-control-file span...

$('.custom-file-input').on('change',function(){
  var fileName = $(this).val();
  $(this).next('.form-control-file').addClass("selected").html(fileName);
})

You can then handle the file upload or re-selection as needed.

Demo on Codeply (alpha 6)

Compare two files line by line and generate the difference in another file

The Unix utility diff is meant for exactly this purpose.

$ diff -u file1 file2 > file3

See the manual and the Internet for options, different output formats, etc.

Using R to download zipped data file, extract, and import data

I found that the following worked for me. These steps come from BTD's YouTube video, Managing Zipfile's in R:

zip.url <- "url_address.zip"

dir <- getwd()

zip.file <- "file_name.zip"

zip.combine <- as.character(paste(dir, zip.file, sep = "/"))

download.file(zip.url, destfile = zip.combine)

unzip(zip.file)

RegEx for matching UK Postcodes

I've been looking for a UK postcode regex for the last day or so and stumbled on this thread. I worked my way through most of the suggestions above and none of them worked for me so I came up with my own regex which, as far as I know, captures all valid UK postcodes as of Jan '13 (according to the latest literature from the Royal Mail).

The regex and some simple postcode checking PHP code is posted below. NOTE:- It allows for lower or uppercase postcodes and the GIR 0AA anomaly but to deal with the, more than likely, presence of a space in the middle of an entered postcode it also makes use of a simple str_replace to remove the space before testing against the regex. Any discrepancies beyond that and the Royal Mail themselves don't even mention them in their literature (see http://www.royalmail.com/sites/default/files/docs/pdf/programmers_guide_edition_7_v5.pdf and start reading from page 17)!

Note: In the Royal Mail's own literature (link above) there is a slight ambiguity surrounding the 3rd and 4th positions and the exceptions in place if these characters are letters. I contacted Royal Mail directly to clear it up and in their own words "A letter in the 4th position of the Outward Code with the format AANA NAA has no exceptions and the 3rd position exceptions apply only to the last letter of the Outward Code with the format ANA NAA." Straight from the horse's mouth!

<?php

    $postcoderegex = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';

    $postcode2check = str_replace(' ','',$postcode2check);

    if (preg_match($postcoderegex, $postcode2check)) {

        echo "$postcode2check is a valid postcode<br>";

    } else {

        echo "$postcode2check is not a valid postcode<br>";

    }

?>

I hope it helps anyone else who comes across this thread looking for a solution.

Multiple inputs with same name through POST in php

For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.

The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval] (string or int) which then allows you to refer to an existing record.

Lambda function in list comprehensions

The big difference is that the first example actually invokes the lambda f(x), while the second example doesn't.

Your first example is equivalent to [(lambda x: x*x)(x) for x in range(10)] while your second example is equivalent to [f for x in range(10)].

How to get 2 digit year w/ Javascript?

var d = new Date();
var n = d.getFullYear();

Yes, n will give you the 4 digit year, but you can always use substring or something similar to split up the year, thus giving you only two digits:

var final = n.toString().substring(2);

This will give you the last two digits of the year (2013 will become 13, etc...)

If there's a better way, hopefully someone posts it! This is the only way I can think of. Let us know if it works!

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

While a comprehensive answer to this question takes up hundreds of pages of my book, here's a quick comparison chart that I'm still working on:

A table explaining difference between several DICs

Responsive css background images

#container {
    background-image: url("../images/layout/bg.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 100vh;
    margin: 3px auto 0;
    position: relative;
}

What is ADT? (Abstract Data Type)

To solve problems we combine the data structure with their operations. An ADT consists of two parts:

  1. Declaration of Data.
  2. Declaration of Operation.

Commonly used ADT's are Linked Lists, Stacks, Queues, Priority Queues, Trees etc. While defining ADTs we don't need to worry about implementation detals. They come into picture only when we want to use them.

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

Use getJSON

$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){                     
    $.each(data, function(key, value){
        console.log(key + ":" + value)
    })
});

Detail look here http://api.jquery.com/jQuery.getJSON/

InputStream from a URL

(a) wwww.somewebsite.com/a.txt isn't a 'file URL'. It isn't a URL at all. If you put http:// on the front of it it would be an HTTP URL, which is clearly what you intend here.

(b) FileInputStream is for files, not URLs.

(c) The way to get an input stream from any URL is via URL.openStream(), or URL.getConnection().getInputStream(), which is equivalent but you might have other reasons to get the URLConnection and play with it first.

Why is SQL Server 2008 Management Studio Intellisense not working?

I ended up fixing it by reinstalling SQL Server 2008. This wasn't at all optimal, but if someone comes across a similar problem be sure to know this route will probably work.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Also you can define ids.xml in res/values. You can see an exact example in android's sample code.

samples/ApiDemos/src/com/example/android/apis/RadioGroup1.java
samples/ApiDemp/res/values/ids.xml

angularjs getting previous route path

Use the $locationChangeStart or $locationChangeSuccess events, 3rd parameter:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
   console.log('success', evt, absNewUrl, absOldUrl);
});

ArrayAdapter in android to create simple listview

ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString() method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.

For your use, I would suggest that you use the constructor:

ArrayAdapter(Context context, int resource, T[] objects). 

In your case, this would be:

ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)

and it should be fine. This will bind each string to the default TextView display - plain and simple white background.

So to answer your question, you do not have to use the textViewResourceId.

Bootstrap 3 offset on right not left

Bootstrap rows always contain their floats and create new lines. You don't need to worry about filling blank columns, just make sure they don't add up to more than 12.

_x000D_
_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-3 col-xs-offset-9">_x000D_
      I'm a right column of 3_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-3">_x000D_
      I'm a left column of 3_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="panel panel-default">_x000D_
    <div class="panel-body">_x000D_
      And I'm some content below both columns_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hosting ASP.NET in IIS7 gives Access is denied?

For me, nothing worked except the following, which solved the problem: open IIS, select the site, open Authentication (in the IIS section), right click Anonymous Authentication and select Edit, select Application Pool Identity.

How to show the text on a ImageButton?

Best way to show Text on button(with image)

example of text on button with image background

Your Question: How to show text on imagebutton?

Answer: You can not display text with imageButton. Method that tell in Accepted answer also not work.

because

If you use android:drawableLeft="@drawable/buttonok" then you can not set drawable in center of button.

If you use android:background="@drawable/button_bg" then color of your drawable will be changed.

In android world there are thousands of option to do this. But here i provide best alternate according to my point of view. (see below)

Solution: Use cardView with LinearLayout

Your drawable/image use in LinearLayout because it shows in center. And with help of textView you can set text on this. We makes cardView background to transparent.

<androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="99dp"
                android:layout_margin="16dp"
                app:cardBackgroundColor="@android:color/transparent"
                app:cardElevation="0dp"
                app:cardUseCompatPadding="true">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@drawable/your_selected_image"
                    >

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:text="Happy Coding"
                        android:textSize="33sp"
                        android:gravity="center"
                        >
                    </TextView>

                </LinearLayout>
            </androidx.cardview.widget.CardView>

here i explain some terms:

app:cardBackgroundColor="@android:color/transparent" for make transparent background of cardView

app:cardElevation="0dp" for hide evelation lines around cardView

app:cardUseCompatPadding="true" its provide actual size of cardView. Always use this when you use cardView

set your image/drawable in LinearLayout as a background.

Sorry, for my Bad English.

Happy Coding:)

How do I see what character set a MySQL database / table / column is?

show global variables where variable_name like 'character_set_%' or variable_name like 'collation%'

undefined reference to `WinMain@16'

My situation was that I did not have a main function.

Skip the headers when editing a csv file using Python

Another way of solving this is to use the DictReader class, which "skips" the header row and uses it to allowed named indexing.

Given "foo.csv" as follows:

FirstColumn,SecondColumn
asdf,1234
qwer,5678

Use DictReader like this:

import csv
with open('foo.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        print(row['FirstColumn'])  # Access by column header instead of column number
        print(row['SecondColumn'])

how to use sqltransaction in c#

You have to tell your SQLCommand objects to use the transaction:

cmd1.Transaction = transaction;

or in the constructor:

SqlCommand cmd1 = new SqlCommand("select...", connectionsql, transaction);

Make sure to have the connectionsql object open, too.

But all you are doing are SELECT statements. Transactions would benefit more when you use INSERT, UPDATE, etc type actions.

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

I know this is an old question, but if you ever want ot fix the malformed '&' signs in your HTML. You can use code similar to this:

$page = file_get_contents('http://www.example.com');
$page = preg_replace('/\s+/', ' ', trim($page));
fixAmps($page, 0);
$dom->loadHTML($page);


function fixAmps(&$html, $offset) {
    $positionAmp = strpos($html, '&', $offset);
    $positionSemiColumn = strpos($html, ';', $positionAmp+1);

    $string = substr($html, $positionAmp, $positionSemiColumn-$positionAmp+1);

    if ($positionAmp !== false) { // If an '&' can be found.
        if ($positionSemiColumn === false) { // If no ';' can be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // Replace straight away.
        } else if (preg_match('/&(#[0-9]+|[A-Z|a-z|0-9]+);/', $string) === 0) { // If a standard escape cannot be found.
            $html = substr_replace($html, '&amp;', $positionAmp, 1); // This mean we need to escape the '&' sign.
            fixAmps($html, $positionAmp+5); // Recursive call from the new position.
        } else {
            fixAmps($html, $positionAmp+1); // Recursive call from the new position.
        }
    }
}

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

How to initialize a struct in accordance with C programming language standards

In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

How do I run a VBScript in 32-bit mode on a 64-bit machine?

WScript.exe exists in two versions, one in C:\Windows\System32\ and the other in C:\Windows\SysWOW64\ directories. They run respectively in 64 bits and 32 bits (against immediate logic but true).

You may add the following code at the beginning of your script so that it automatically starts again in 32 bits if it detects that it's called in 64 bits.

Note that it transmits the arguments if it calls itself to switch to 64 bits.

' C:\Windows\System32\WScript.exe = WScript.exe
Dim ScriptHost : ScriptHost = Mid(WScript.FullName, InStrRev(WScript.FullName, "\") + 1, Len(WScript.FullName))

Dim oWs : Set oWs = CreateObject("WScript.Shell")
Dim oProcEnv : Set oProcEnv = oWs.Environment("Process")

' Am I running 64-bit version of WScript.exe/Cscript.exe? So, call script again in x86 script host and then exit.
If InStr(LCase(WScript.FullName), LCase(oProcEnv("windir") & "\System32\")) And oProcEnv("PROCESSOR_ARCHITECTURE") = "AMD64" Then
    ' rebuild arguments
    If Not WScript.Arguments.Count = 0 Then
        Dim sArg, Arg
        sArg = ""
        For Each Arg In Wscript.Arguments
              sArg = sArg & " " & """" & Arg & """"
        Next
    End If

    Dim sCmd : sCmd = """" &  oProcEnv("windir") & "\SysWOW64\" & ScriptHost & """" & " """ & WScript.ScriptFullName & """" & sArg
    'WScript.Echo "Call " & sCmd
    oWs.Run sCmd
    WScript.Quit
End If

Python Pandas merge only certain columns

You can use .loc to select the specific columns with all rows and then pull that. An example is below:

pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')

In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc which allows you to specific the rows and columns you want in a numerical format. Using :, your selecting all rows, but [0:5] selects the first 5 columns. You could use .loc to specify by name, but if your dealing with long column names, then .iloc may be better.

Comparing Dates in Oracle SQL

from your query:

Select employee_id, count(*) From Employee 
Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95' 

i think its not to display the number of employees that are hired after June 20, 1994. if you want show number of employees, you can use:

Select count(*) From Employee 
Where to_char(employee_date_hired, 'YYYMMMDDD') > 19940620 

I think for best practice to compare dates you can use:

employee_date_hired > TO_DATE('20-06-1994', 'DD-MM-YYYY');
or
to_char(employee_date_hired, 'YYYMMMDDD') > 19940620;

How to initialize a nested struct?

You can define a struct and create its object in another struct like i have done below:

package main

import "fmt"

type Address struct {
    streetNumber int
    streetName   string
    zipCode      int
}

type Person struct {
    name    string
    age     int
    address Address
}

func main() {
    var p Person
    p.name = "Vipin"
    p.age = 30
    p.address = Address{
        streetName:   "Krishna Pura",
        streetNumber: 14,
        zipCode:      475110,
    }
    fmt.Println("Name: ", p.name)
    fmt.Println("Age: ", p.age)
    fmt.Println("StreetName: ", p.address.streetName)
    fmt.Println("StreeNumber: ", p.address.streetNumber)
}

Hope it helped you :)

What is the (best) way to manage permissions for Docker shared volumes?

If you using Docker Compose, start the container in previleged mode:

wordpress:
    image: wordpress:4.5.3
    restart: always
    ports:
      - 8084:80
    privileged: true

How to set zoom level in google map

What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:

20 : 1128.497220

19 : 2256.994440

18 : 4513.988880

17 : 9027.977761

16 : 18055.955520

15 : 36111.911040

14 : 72223.822090

13 : 144447.644200

12 : 288895.288400

11 : 577790.576700

10 : 1155581.153000

9 : 2311162.307000

8 : 4622324.614000

7 : 9244649.227000

6 : 18489298.450000

5 : 36978596.910000

4 : 73957193.820000

3 : 147914387.600000

2 : 295828775.300000

1 : 591657550.500000

Using Python, find anagrams for a list of words

This works fine:


def find_ana(l):
    a=[]
    for i in range(len(l)):
        for j in range(len(l)): 
            if (l[i]!=l[j]) and (sorted(l[i])==sorted(l[j])):
                a.append(l[i])
                a.append(l[j])

    return list(set(a))

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

What is the difference between DSA and RSA?

Referring, https://web.archive.org/web/20140212143556/http://courses.cs.tamu.edu:80/pooch/665_spring2008/Australian-sec-2006/less19.html

RSA
RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)

RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms. It creates a 320 bit signature, but with 512-1024 bit security again rests on difficulty of computing discrete logarithms has been quite widely accepted.

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.

DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k<q
compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures

DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

Explain the different tiers of 2 tier & 3 tier architecture?

Here is some help for 2Tier and 3Tier difference, please refer below.

ANSWER:
1. 2Tier is Client server architecture and 3Tier is Client, Server and Database architecture.
2. 3Tier has a Middle stage to communicate client to server, Where as in 2Tier client directly get communication to server.
3. 3Tier is like a MVC, But having difference in topologies
4. 3Tier is linear means in that request flow is Client>>>Middle Layer(SErver application) >>>Databse server and Response is reverse.
While in 2Tier it a Triangular View >>Controller>>Model
5. 3Tier is like Website while web browser is Client application(middle layer), and ASP/PHP language code is server application.

How to truncate a foreign key constrained table?

Tested on MYSQL Database

Solution 1:

SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table1;

Solution 2:

DELETE FROM table1;
ALTER TABLE table1 AUTO_INCREMENT = 1;
TRUNCATE table1;

This works for me. I hope, this will help you also. Thanks for asking this question.

Download file and automatically save it to folder

Well, your solution almost works. There are a few things to take into account to keep it simple:

  • Cancel the default navigation only for specific URLs you know a download will occur, or the user won't be able to navigate anywhere. This means you musn't change your website download URLs.

  • DownloadFileAsync doesn't know the name reported by the server in the Content-Disposition header so you have to specify one, or compute one from the original URL if that's possible. You cannot just specify the folder and expect the file name to be retrieved automatically.

  • You have to handle download server errors from the DownloadCompleted callback because the web browser control won't do it for you anymore.

Sample piece of code, that will download into the directory specified in textBox1, but with a random file name, and without any additional error handling:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
    /* change this to match your URL. For example, if the URL always is something like "getfile.php?file=xxx", try e.Url.ToString().Contains("getfile.php?") */
    if (e.Url.ToString().EndsWith(".zip")) {
        e.Cancel = true;
        string filePath = Path.Combine(textBox1.Text, Path.GetRandomFileName());
        var client = new WebClient();
        client.DownloadFileCompleted += client_DownloadFileCompleted;
        client.DownloadFileAsync(e.Url, filePath);
    }
}

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
    MessageBox.Show("File downloaded");
}

This solution should work but can be broken very easily. Try to consider some web service listing the available files for download and make a custom UI for it. It'll be simpler and you will control the whole process.

Reset ID autoincrement ? phpmyadmin

ALTER TABLE xxx AUTO_INCREMENT =1; or clear your table by TRUNCATE

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

Is there a no-duplicate List implementation out there?

You should seriously consider dhiller's answer:

  1. Instead of worrying about adding your objects to a duplicate-less List, add them to a Set (any implementation), which will by nature filter out the duplicates.
  2. When you need to call the method that requires a List, wrap it in a new ArrayList(set) (or a new LinkedList(set), whatever).

I think that the solution you posted with the NoDuplicatesList has some issues, mostly with the contains() method, plus your class does not handle checking for duplicates in the Collection passed to your addAll() method.

CSS Div Background Image Fixed Height 100% Width

But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

so it's better to use background:cover and set with media queries specific height's for popular resolutions.

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

Console.Write((int)response.StatusCode);

HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}

How to round the minute of a datetime object

This will get the 'floor' of a datetime object stored in tm rounded to the 10 minute mark before tm.

tm = tm - datetime.timedelta(minutes=tm.minute % 10,
                             seconds=tm.second,
                             microseconds=tm.microsecond)

If you want classic rounding to the nearest 10 minute mark, do this:

discard = datetime.timedelta(minutes=tm.minute % 10,
                             seconds=tm.second,
                             microseconds=tm.microsecond)
tm -= discard
if discard >= datetime.timedelta(minutes=5):
    tm += datetime.timedelta(minutes=10)

or this:

tm += datetime.timedelta(minutes=5)
tm -= datetime.timedelta(minutes=tm.minute % 10,
                         seconds=tm.second,
                         microseconds=tm.microsecond)

Is there a list of Pytz Timezones?

They appear to be populated by the tz database time zones found here.

enter image description here

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Another way without using Modal

Database: stocks Columns:id,name,company_name,exchange_name,status enter image description here

  $name ='aa'
  $stocks = DB::table('stocks')
            ->select('name', 'company_name', 'exchange_name')
            ->where(function($query) use ($name) {
                $query->where('name', 'like', '%' . $name . '%')
                ->orWhere('company_name', 'like', '%' . $name . '%');
            })
            ->Where('status', '=', 1)
            ->limit(20)
            ->get();

New to unit testing, how to write great tests?

It's worth noting that retro-fitting unit tests into existing code is far more difficult than driving the creation of that code with tests in the first place. That's one of the big questions in dealing with legacy applications... how to unit test? This has been asked many times before (so you may be closed as a dupe question), and people usually end up here:

Moving existing code to Test Driven Development

I second the accepted answer's book recommendation, but beyond that there's more information linked in the answers there.

What is the correct wget command syntax for HTTPS with username and password?

It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).

I followed the link suggested by @thomasbabuj and figured it out eventually.

You should try adding --auth-no-challenge and as @thomasbabuj suggested replace your password entry

I.e

wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip

How to add a delay for a 2 or 3 seconds

Use a timer with an interval set to 2–3 seconds.

You have three different options to choose from, depending on which type of application you're writing:

  1. System.Timers.Timer
  2. System.Windows.Forms.Timer
  3. System.Threading.Timer

Don't use Thread.Sleep if your application need to process any inputs on that thread at the same time (WinForms, WPF), as Sleep will completely lock up the thread and prevent it from processing other messages. Assuming a single-threaded application (as most are), your entire application will stop responding, rather than just delaying an operation as you probably intended. Note that it may be fine to use Sleep in pure console application as there are no "events" to handle or on separate thread (also Task.Delay is better option).

In addition to timers and Sleep you can use Task.Delay which is asynchronous version of Sleep that does not block thread from processing events (if used properly - don't turn it into infinite sleep with .Wait()).

 public async void ClickHandler(...)
 {
      // whatever you need to do before delay goes here         

      await Task.Delay(2000);

      // whatever you need to do after delay.
 }

The same await Task.Delay(2000) can be used in a Main method of a console application if you use C# 7.1 (Async main on MSDN blogs).

Note: delaying operation with Sleep has benefit of avoiding race conditions that comes from potentially starting multiple operations with timers/Delay. Unfortunately freezing UI-based application is not acceptable so you need to think about what will happen if you start multiple delays (i.e. if it is triggered by a button click) - consider disabling such button, or canceling the timer/task or making sure delayed operation can be done multiple times safely.

How to write to file in Ruby?

For those of us that learn by example...

Write text to a file like this:

IO.write('/tmp/msg.txt', 'hi')

BONUS INFO ...

Read it back like this

IO.read('/tmp/msg.txt')

Frequently, I want to read a file into my clipboard ***

Clipboard.copy IO.read('/tmp/msg.txt')

And other times, I want to write what's in my clipboard to a file ***

IO.write('/tmp/msg.txt', Clipboard.paste)

*** Assumes you have the clipboard gem installed

See: https://rubygems.org/gems/clipboard

Is it possible to style a select box?

Here's a little plug if you mostly want to

  • go crazy customizing the closed state of a select element
  • but at open state, you favor a better native experience to picking options (scroll wheel, arrow keys, tab focus, ajax modifications to options, proper zindex, etc)
  • dislike the messy ul, li generated markups

Then jquery.yaselect.js could be a better fit. Simply:

$('select').yaselect();

And the final markup is:

<div class="yaselect-wrap">
  <div class="yaselect-current"><!-- current selection --></div>
</div>
<select class="yaselect-select" size="5">
  <!-- your option tags -->
</select>

Check it out on github.com

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

Solving "adb server version doesn't match this client" error

What worked for me:

  1. adb kill-server
  2. Close all chrome://inspect/#devices windows/tabs
  3. adb start-server
  4. adb devices

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

"/tmp/mysql.sock" will be created automatically when you start the MySQL server. So remember to do that before starting the rails server.

What does %>% mean in R

matrix multiplication, see the following example:

> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
     [,1] [,2] [,3]
[1,]    1    5    1
[2,]    3    8    3
[3,]    4    9    3
> 
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
> 
> B
     [,1] [,2] [,3]
[1,]    2    8    3
[2,]    4    9    4
[3,]    5    2    5
> 
> 
> A %*% B
     [,1] [,2] [,3]
[1,]   27   55   28
[2,]   53  102   56
[3,]   59  119   63

> B %*% A
     [,1] [,2] [,3]
[1,]   38  101   35
[2,]   47  128   43
[3,]   31   86   26

Also see:

http://en.wikipedia.org/wiki/Matrix_multiplication

If this does not follow the size of matrix rule you will get the error:

> A <- matrix(c(1,2,3,4,5,6), 3,2)
    > A
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)

> B
         [,1] [,2] [,3]
    [1,]    3    4    4
    [2,]    1    4    4
    [3,]    3    4    3
    > A%*%B
    Error in A %*% B : non-conformable arguments

What's the CMake syntax to set and use variables?

When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.

The Syntax

Strings using set():

  • set(MyString "Some Text")
  • set(MyStringWithVar "Some other Text: ${MyString}")
  • set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")

Or with string():

  • string(APPEND MyStringWithContent " ${MyString}")

Lists using set():

  • set(MyList "a" "b" "c")
  • set(MyList ${MyList} "d")

Or better with list():

  • list(APPEND MyList "a" "b" "c")
  • list(APPEND MyList "d")

Lists of File Names:

  • set(MySourcesList "File.name" "File with Space.name")
  • list(APPEND MySourcesList "File.name" "File with Space.name")
  • add_excutable(MyExeTarget ${MySourcesList})

The Documentation

The Scope or "What value does my variable have?"

First there are the "Normal Variables" and things you need to know about their scope:

  • Normal variables are visible to the CMakeLists.txt they are set in and everything called from there (add_subdirectory(), include(), macro() and function()).
  • The add_subdirectory() and function() commands are special, because they open-up their own scope.
    • Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).
    • So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE)
    • You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE)
  • On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from.

Second there is the "Global Variables Cache". Things you need to know about the Cache:

  • If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry.
  • Cache values are stored in the CMakeCache.txt file in your binary output directory.
  • The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring. I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values.

    Please note that the INTERNAL cache variable type does imply FORCE

  • In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.

  • You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value, just cmake -D var=value or with cmake -C CMakeInitialCache.cmake.
  • You can unset entries in the Cache with unset(... CACHE).

The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables.

Variable Pitfalls and "How to debug variable changes?"

To avoid pitfalls you should know the following about variables:

  • Local variables do hide cached variables if both have the same name
  • The find_... commands - if successful - do write their results as cached variables "so that no call will search again"
  • Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important
    • set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c"
    • The recommendation is that you always use quotation marks with the one exception when you want to give a list as list
    • Generally prefer the list() command for handling lists
  • The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope.
  • A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used.
  • Environment variables may differ from where CMake generated the make environment and when the the make files are put to use.
    • A change in an environment variable does not re-trigger the generation process.
    • Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached.

Sometimes only debugging variables helps. The following may help you:

  • Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmake
  • Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails.
  • Use variable_watch() to see where your variables are read/written/removed.
  • Look into the directory properties CACHE_VARIABLES and VARIABLES
  • Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.

Special Syntax

  • Environment Variables
    • You can can read $ENV{...} and write set(ENV{...} ...) environment variables
  • Generator Expressions
    • Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)
    • Very handy e.g. in compiler/linker command lines and in multi-configuration environments
  • References
    • With ${${...}} you can give variable names in a variable and reference its content.
    • Often used when giving a variable name as function/macro parameter.
  • Constant Values (see if() command)
    • With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...})
    • True if the constant is 1, ON, YES, TRUE, Y, or a non-zero number.
    • False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
    • This syntax is often use for something like if(MSVC), but it can be confusing for someone who does not know this syntax shortcut.
  • Recursive substitutions
    • You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...)
    • But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1":
      • if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1")
      • if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1")
      • So the best solution here would be - see above - to directly check for if(MSVC)
    • The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054. I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted."
  • The option() command
    • Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies
    • But be aware, don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.

References

How do I change the default port (9000) that Play uses when I execute the "run" command?

Play 2.2.1 on Windows supports a PLAY_OPTS environment variable. Play's play.bat file contains this line:

java -Dsbt.ivy.home="%~dp0repository" -Dplay.home="%~dp0framework" -Dsbt.boot.properties="%fp%framework/sbt/play.boot.properties" %PLAY_OPTS% -jar "%~dp0framework\sbt\sbt-launch.jar" %*

so to run on port 9002, do

set PLAY_OPTS=-Dhttp.port=9002
play run

Create a copy of a table within the same database DB2

We can copy all columns from one table to another, existing table:

INSERT INTO table2 SELECT * FROM table1;

Or we can copy only the columns we want to into another, existing table:

INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;

or SELECT * INTO BACKUP_TABLE1 FROM TABLE1

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

You don't have permission to the Python folder.

sudo chown -R $USER /usr/local/lib/python2.7

Log exception with traceback

Here is a version that uses sys.excepthook

import traceback
import sys

logger = logging.getLogger()

def handle_excepthook(type, message, stack):
     logger.error(f'An unhandled exception occured: {message}. Traceback: {traceback.format_tb(stack)}')

sys.excepthook = handle_excepthook

Generating a PDF file from React Components

Rendering react as pdf is generally a pain, but there is a way around it using canvas.

The idea is to convert : HTML -> Canvas -> PNG (or JPEG) -> PDF

To achieve the above, you'll need :

  1. html2canvas &
  2. jsPDF

_x000D_
_x000D_
import React, {Component, PropTypes} from 'react';_x000D_
_x000D_
// download html2canvas and jsPDF and save the files in app/ext, or somewhere else_x000D_
// the built versions are directly consumable_x000D_
// import {html2canvas, jsPDF} from 'app/ext';_x000D_
_x000D_
_x000D_
export default class Export extends Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
  }_x000D_
_x000D_
  printDocument() {_x000D_
    const input = document.getElementById('divToPrint');_x000D_
    html2canvas(input)_x000D_
      .then((canvas) => {_x000D_
        const imgData = canvas.toDataURL('image/png');_x000D_
        const pdf = new jsPDF();_x000D_
        pdf.addImage(imgData, 'JPEG', 0, 0);_x000D_
        // pdf.output('dataurlnewwindow');_x000D_
        pdf.save("download.pdf");_x000D_
      })_x000D_
    ;_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (<div>_x000D_
      <div className="mb5">_x000D_
        <button onClick={this.printDocument}>Print</button>_x000D_
      </div>_x000D_
      <div id="divToPrint" className="mt4" {...css({_x000D_
        backgroundColor: '#f5f5f5',_x000D_
        width: '210mm',_x000D_
        minHeight: '297mm',_x000D_
        marginLeft: 'auto',_x000D_
        marginRight: 'auto'_x000D_
      })}>_x000D_
        <div>Note: Here the dimensions of div are same as A4</div> _x000D_
        <div>You Can add any component here</div>_x000D_
      </div>_x000D_
    </div>);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

The snippet will not work here because the required files are not imported.

An alternate approach is being used in this answer, where the middle steps are dropped and you can simply convert from HTML to PDF. There is an option to do this in the jsPDF documentation as well, but from personal observation, I feel that better accuracy is achieved when dom is converted into png first.

Update 0: September 14, 2018

The text on the pdfs created by this approach will not be selectable. If that's a requirement, you might find this article helpful.

Get random item from array

Use PHP Rand function

<?php
  $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";
?>

More Help

Resolve host name to an ip address

Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8

Regex doesn't work in String.matches()

[a-z] matches a single char between a and z. So, if your string was just "d", for example, then it would have matched and been printed out.

You need to change your regex to [a-z]+ to match one or more chars.

CSS text-overflow: ellipsis; not working?

I faced the same issue and it seems like none of the solution above works for Safari. For non-safari browser, this works just fine:

display: block; /* or in-line block according to your requirement */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

For Safari, this is the one that works for me. Note that the media query to check if the browser is Safari might change over time, so just tinker with the media query if it doesn't work for you. With line-clamp property, it would also be possible to have multiple lines in the web with ellipsis, see here.

// Media-query for Safari-only browser.
@media not all and (min-resolution: 0.001dpcm) {
  @media {
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    display: -webkit-box;
    white-space: normal;
  }
}

What does Java option -Xmx stand for?

C:\java -X

    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

How to get first element in a list of tuples?

I wondered why nobody suggested to use numpy, but now after checking i understand. It is maybe not the best for mixed type arrays.

This would be a solution in numpy:

>>> import numpy as np

>>> a = np.asarray([(1, u'abc'), (2, u'def')])
>>> a[:, 0].astype(int).tolist()
[1, 2]

Update row with data from another row in the same table

If you just need to insert a new row with a data from another row,

    insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;

Why is lock(this) {...} bad?

It is bad form to use this in lock statements because it is generally out of your control who else might be locking on that object.

In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness.

A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using this violates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock on this unless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal.

Finally, there is the common misconception that lock(this) actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is false. The object passed as a parameter to lock merely serves as a key. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed.

This is why it's bad to use strings as the keys in lock statements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, an Object instance will do nicely.

Run the following C# code as an example.

public class Person
{
    public int Age { get; set;  }
    public string Name { get; set; }

    public void LockThis()
    {
        lock (this)
        {
            System.Threading.Thread.Sleep(10000);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var nancy = new Person {Name = "Nancy Drew", Age = 15};
        var a = new Thread(nancy.LockThis);
        a.Start();
        var b = new Thread(Timewarp);
        b.Start(nancy);
        Thread.Sleep(10);
        var anotherNancy = new Person { Name = "Nancy Drew", Age = 50 };
        var c = new Thread(NameChange);
        c.Start(anotherNancy);
        a.Join();
        Console.ReadLine();
    }

    static void Timewarp(object subject)
    {
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // A lock does not make the object read-only.
        lock (person.Name)
        {
            while (person.Age <= 23)
            {
                // There will be a lock on 'person' due to the LockThis method running in another thread
                if (Monitor.TryEnter(person, 10) == false)
                {
                    Console.WriteLine("'this' person is locked!");
                }
                else Monitor.Exit(person);
                person.Age++;
                if(person.Age == 18)
                {
                    // Changing the 'person.Name' value doesn't change the lock...
                    person.Name = "Nancy Smith";
                }
                Console.WriteLine("{0} is {1} years old.", person.Name, person.Age);
            }
        }
    }

    static void NameChange(object subject)
    {
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // You should avoid locking on strings, since they are immutable.
        if (Monitor.TryEnter(person.Name, 30) == false)
        {
            Console.WriteLine("Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \"Nancy Drew\".");
        }
        else Monitor.Exit(person.Name);

        if (Monitor.TryEnter("Nancy Drew", 30) == false)
        {
            Console.WriteLine("Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!");
        }
        else Monitor.Exit("Nancy Drew");
        if (Monitor.TryEnter(person.Name, 10000))
        {
            string oldName = person.Name;
            person.Name = "Nancy Callahan";
            Console.WriteLine("Name changed from '{0}' to '{1}'.", oldName, person.Name);
        }
        else Monitor.Exit(person.Name);
    }
}

Console output

'this' person is locked!
Nancy Drew is 16 years old.
'this' person is locked!
Nancy Drew is 17 years old.
Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string "Nancy Drew".
'this' person is locked!
Nancy Smith is 18 years old.
'this' person is locked!
Nancy Smith is 19 years old.
'this' person is locked!
Nancy Smith is 20 years old.
Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!
'this' person is locked!
Nancy Smith is 21 years old.
'this' person is locked!
Nancy Smith is 22 years old.
'this' person is locked!
Nancy Smith is 23 years old.
'this' person is locked!
Nancy Smith is 24 years old.
Name changed from 'Nancy Drew' to 'Nancy Callahan'.

Android: Expand/collapse animation

I stumbled over the same problem today and I guess the real solution to this question is this

<LinearLayout android:id="@+id/container"
android:animateLayoutChanges="true"
...
 />

You will have to set this property for all topmost layouts, which are involved in the shift. If you now set the visibility of one layout to GONE, the other will take the space as the disappearing one is releasing it. There will be a default animation which is some kind of "fading out", but I think you can change this - but the last one I have not tested, for now.

Generating CSV file for Excel, how to have a newline inside a value

UTF files that contain a BOM will cause Excel to treat new lines literally even in that field is surrounded by quotes. (Tested Excel 2008 Mac)

The solution is to make any new lines a carriage return (CHR 13) rather than a line feed.

Sending email with PHP from an SMTP server

The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.

  1. mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
  2. mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
  3. Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.

No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

how to set default method argument values?

You can accomplish this via method overloading.

public int doSomething(int arg1, int arg2)
{
        return 0;
}

public int doSomething()
{
        return doSomething(defaultValue0, defaultValue1);
}

By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.

How do you read CSS rule values with JavaScript?

I created a version that searches all stylesheets and returns matches as a key/value object. You can also specify startsWith to match child styles.

getStylesBySelector('.pure-form-html', true);

returns:

{
    ".pure-form-html body": "padding: 0; margin: 0; font-size: 14px; font-family: tahoma;",
    ".pure-form-html h1": "margin: 0; font-size: 18px; font-family: tahoma;"
}

from:

.pure-form-html body {
    padding: 0;
    margin: 0;
    font-size: 14px;
    font-family: tahoma;
}

.pure-form-html h1 {
    margin: 0;
    font-size: 18px;
    font-family: tahoma;
}

The code:

/**
 * Get all CSS style blocks matching a CSS selector from stylesheets
 * @param {string} className - class name to match
 * @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)
 * @example getStylesBySelector('pure-form .pure-form-html ')
 * @returns {object} key/value object containing matching styles otherwise null
 */
function getStylesBySelector(className, startingWith) {

    if (!className || className === '') throw new Error('Please provide a css class name');

    var styleSheets = window.document.styleSheets;
    var result = {};

    // go through all stylesheets in the DOM
    for (var i = 0, l = styleSheets.length; i < l; i++) {

        var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];

        // go through all classes in each document
        for (var x = 0, ll = classes.length; x < ll; x++) {

            var selector = classes[x].selectorText || '';
            var content = classes[x].cssText || classes[x].style.cssText || '';

            // if the selector matches
            if ((startingWith && selector.indexOf(className) === 0) || selector === className) {

                // create an object entry with selector as key and value as content
                result[selector] = content.split(/(?:{|})/)[1].trim();
            }
        }
    }

    // only return object if we have values, otherwise null
    return Object.keys(result).length > 0 ? result : null;
}

I'm using this in production as part of the pure-form project. Hope it helps.

Convert IEnumerable to DataTable

I've written a library to handle this for me. It's called DataTableProxy and is available as a NuGet package. Code and documentation is on Github

Create controller for partial view in ASP.NET MVC

If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:

// Assuming the controller is named NewController
@{Html.RenderAction("ActionName", 
                     "New", 
                      new { routeValueOne = "SomeValue" });
}

jquery getting post action url

Try this ocde;;

var formAction = $("#signup").attr('action');

glm rotate usage in Opengl

I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)) you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z)) instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))

Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:

glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));

You can add glm::radians() if you want to keep using degrees. And add the includes:

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

Deserialize JSON with C#

Serialization:

// Convert an object to JSON string format
string jsonData = JsonConvert.SerializeObject(obj);

Response.Write(jsonData);

Deserialization::

To deserialize a dynamic object

  string json = @"{
      'Name': 'name',
      'Description': 'des'
    }";

var res = JsonConvert.DeserializeObject< dynamic>(json);

Response.Write(res.Name);

Android. Fragment getActivity() sometimes returns null

I know this is a old question but i think i must provide my answer to it because my problem was not solved by others.

first of all : i was dynamically adding fragments using fragmentTransactions. Second: my fragments were modified using AsyncTasks (DB queries on a server). Third: my fragment was not instantiated at activity start Fourth: i used a custom fragment instantiation "create or load it" in order to get the fragment variable. Fourth: activity was recreated because of orientation change

The problem was that i wanted to "remove" the fragment because of the query answer, but the fragment was incorrectly created just before. I don't know why, probably because of the "commit" be done later, the fragment was not added yet when it was time to remove it. Therefore getActivity() was returning null.

Solution : 1)I had to check that i was correctly trying to find the first instance of the fragment before creating a new one 2)I had to put serRetainInstance(true) on that fragment in order to keep it through orientation change (no backstack needed therefore no problem) 3)Instead of "recreating or getting old fragment" just before "remove it", I directly put the fragment at activity start. Instantiating it at activity start instead of "loading" (or instantiating) the fragment variable before removing it prevented getActivity problems.

How to fire AJAX request Periodically?

You can use setTimeout or setInterval.

The difference is - setTimeout triggers your function only once, and then you must set it again. setInterval keeps triggering expression again and again, unless you tell it to stop

Determine if variable is defined in Python

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.

Simple logical operators in Bash

if ([ $NUM1 == 1 ] || [ $NUM2 == 1 ]) && [ -z "$STR" ]
then
    echo STR is empty but should have a value.
fi

Easiest way to convert a List to a Set in Java

If you use Eclipse Collections:

MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();

The MutableSet interface extends java.util.Set whereas the MutableIntSet interface does not. You can also convert any Iterable to a Set using the Sets factory class.

Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));

There is more explanation of the mutable factories available in Eclipse Collections here.

If you want an ImmutableSet from a List, you can use the Sets factory as follows:

ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))

Note: I am a committer for Eclipse Collections

What is Scala's yield?

The keyword yield in Scala is simply syntactic sugar which can be easily replaced by a map, as Daniel Sobral already explained in detail.

On the other hand, yield is absolutely misleading if you are looking for generators (or continuations) similar to those in Python. See this SO thread for more information: What is the preferred way to implement 'yield' in Scala?

python: create list of tuples from lists

You're looking for the zip builtin function. From the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

Maven dependencies are failing with a 501 error

The reason for the observed error is explained in Central 501 HTTPS Required

Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.

It looks like latest versions of Maven (tried with 3.6.0, 3.6.1) are already using the HTTPS URL by default.

Here are the dates when the major repositories will switch:

Your Java builds might break starting January 13th (if you haven't yet switched repo access to HTTPS)

Update: Seems like from maven 3.2.3 maven central is accessed via HTTPS See https://stackoverflow.com/a/25411658/5820670

Maven Change log (http://maven.apache.org/docs/3.2.3/release-notes.html)

How do I set/unset a cookie with jQuery?

A simple example of set cookie in your browser:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

Simple just copy/paste and use this code for set your cookie.

How do you change library location in R?

You can edit Rprofile in the base library (in 'C:/Program Files/R.Files/library/base/R' by default) to include code to be run on startup. Append

########        User code        ########
.libPaths('C:/my/dir')

to Rprofile using any text editor (like Notepad) to cause R to add 'C:/my/dir' to the list of libraries it knows about.

(Notepad can't save to Program Files, so save your edited Rprofile somewhere else and then copy it in using Windows Explorer.)

undefined offset PHP error

If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:

function get_match($regex,$content)
{
    if (preg_match($regex,$content,$matches)) {
        return $matches[0];
    } else {
        return null;
    }
}

keycloak Invalid parameter: redirect_uri

Go to keycloak admin console > SpringBootKeycloak> Cients>login-app page. Here in valid-redirect uris section add http://localhost:8080/sso/login

This will help resolve indirect-uri problem

Resizing an Image without losing any quality

Unless you're doing vector graphics, there's no way to resize an image without potentially losing some image quality.

Error when trying vagrant up

vagrant init laravel/homestead

and then

vagrant up

Was what worked for me.

JQuery datepicker language

Include language file source in your head script of the HTML body.

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>

Example on JSFiddle

Is there any standard for JSON API response format?

Best Response for web apis that can easily understand by mobile developers.

This is for "Success" Response

{  
   "ReturnCode":"1",
   "ReturnMsg":"Successfull Transaction",
   "ReturnValue":"",
   "Data":{  
      "EmployeeName":"Admin",
      "EmployeeID":1
   }
}

This is for "Error" Response

{
    "ReturnCode": "4",
    "ReturnMsg": "Invalid Username and Password",
    "ReturnValue": "",
    "Data": {}
}

How does the JPA @SequenceGenerator annotation work

I have MySQL schema with autogen values. I use strategy=GenerationType.IDENTITY tag and seems to work fine in MySQL I guess it should work most db engines as well.

CREATE TABLE user (
    id bigint NOT NULL auto_increment,
    name varchar(64) NOT NULL default '',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

User.java:

// mark this JavaBean to be JPA scoped class
@Entity
@Table(name="user")
public class User {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;    // primary key (autogen surrogate)

    @Column(name="name")
    private String name;

    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name=name; }
}

How to wait for the 'end' of 'resize' event and only then perform an action?

Well, as far as the window manager is concerned, each resize event is its own message, with a distinct beginning and end, so technically, every time the window is resized, it is the end.

Having said that, maybe you want to set a delay to your continuation? Here's an example.

var t = -1;
function doResize()
{
    document.write('resize');
}
$(document).ready(function(){
    $(window).resize(function(){
        clearTimeout(t);
        t = setTimeout(doResize, 1000);
    });
});

How to prevent multiple definitions in C?

If you're using Visual Studio you could also do "#pragma once" at the top of the headerfile to achieve the same thing as the "#ifndef ..."-wrapping. Some other compilers probably support it as well .. .. However, don't do this :D Stick with the #ifndef-wrapping to achieve cross-compiler compatibility. I just wanted to let you know that you could also do #pragma once, since you'll probably meet this statement quite a bit when reading other peoples code.

Good luck with it

Why use multiple columns as primary keys (composite primary key)

Your second question

How many columns can be used together as a primary key in a given table?

is implementation specific: it's defined in the actual DBMS being used.[1],[2],[3] You have to inspect the technical specification of the database system you use. Some are very detailed, some are not. Searching the web about such limitations can be hard because the terminology varies. The term composite primary key should be mandatory ;)

If you cannot find explicit information, try creating a test database to ensure you can expect stable (and specific) handling of the limit violations (which are to be expected). Be careful to get the right information about this: sometimes the limits are accumulated, and you'll see different results with different database layouts.


Using boolean values in C

If you are using a C99 compiler it has built-in support for bool types:

#include <stdbool.h>
int main()
{
  bool b = false;
  b = true;
}

http://en.wikipedia.org/wiki/Boolean_data_type

Android Studio - Auto complete and other features not working

If nothing works (like happened with me ) go to your user profile in windows at %userprofile% . You will find folders there (hidden) named with the version of the android studio you are using and prefixed with a dot.

like .AndroidStudio3.1. Just delete that .

How to find the foreach index?

You can put a hack in your foreach, such as a field incremented on each run-through, which is exactly what the for loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).

A foreach will give you your index in the form of your $key value, so such a hack shouldn't be necessary.

e.g., in a foreach

$index = 0;
foreach($data as $key=>$val) {
    // Use $key as an index, or...

    // ... manage the index this way..
    echo "Index is $index\n";
    $index++;
}

How can I post data as form data instead of a request payload?

This isn't a direct answer, but rather a slightly different design direction:

Do not post the data as a form, but as a JSON object to be directly mapped to server-side object, or use REST style path variable

Now I know neither option might be suitable in your case since you're trying to pass a XSRF key. Mapping it into a path variable like this is a terrible design:

http://www.someexample.com/xsrf/{xsrfKey}

Because by nature you would want to pass xsrf key to other path too, /login, /book-appointment etc. and you don't want to mess your pretty URL

Interestingly adding it as an object field isn't appropriate either, because now on each of json object you pass to server you have to add the field

{
  appointmentId : 23,
  name : 'Joe Citizen',
  xsrf : '...'
}

You certainly don't want to add another field on your server-side class which does not have a direct semantic association with the domain object.

In my opinion the best way to pass your xsrf key is via a HTTP header. Many xsrf protection server-side web framework library support this. For example in Java Spring, you can pass it using X-CSRF-TOKEN header.

Angular's excellent capability of binding JS object to UI object means we can get rid of the practice of posting form all together, and post JSON instead. JSON can be easily de-serialized into server-side object and support complex data structures such as map, arrays, nested objects, etc.

How do you post array in a form payload? Maybe like this:

shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday

or this:

shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday

Both are poor design..

NodeJS - What does "socket hang up" actually mean?

In case you're using node-http-proxy, please be aware to this issue, which will result a socket hang-up error : https://github.com/nodejitsu/node-http-proxy/issues/180.

For resolution, also in this link, simply move declaring the API route (for proxying) within express routes before express.bodyParser().

How do I print part of a rendered HTML page in JavaScript?

<div id="invocieContainer">
    <div class="row">
        ...Your html Page content here....
    </div>
</div>

<script src="/Scripts/printThis.js"></script>
<script>
    $(document).on("click", "#btnPrint", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("#invocieContainer").printThis({
            debug: false, // show the iframe for debugging
            importCSS: true, // import page CSS
            importStyle: true, // import style tags
            printContainer: true, // grab outer container as well as the contents of the selector
            loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
            pageTitle: "", // add title to print page
            removeInline: false, // remove all inline styles from print elements
            printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
            header: null, // prefix to html
            formValues: true // preserve input/form values
        });

    });
</script>

For printThis.js souce code, copy and pase below URL in new tab https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js

How to compile LEX/YACC files on Windows?

the easiest method is to download and install cygwin and download gcc and flex packages during installation. Then to run a lex file for eg. abc.l

we write

flex abc.l
gcc lex.yy.c -o abc.exe
./abc.exe

Shell Script Syntax Error: Unexpected End of File

In my case, I found that placing a here document (like sqplus ... << EOF) statements indented also raise the same error as shown below:

./dbuser_case.ksh: line 25: syntax error: unexpected end of file

So after removing the indentation for this, then it went fine.

Hope it helps...

How do you list all triggers in a MySQL database?

The command for listing all triggers is:

show triggers;

or you can access the INFORMATION_SCHEMA table directly by:

select trigger_schema, trigger_name, action_statement
from information_schema.triggers

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

Why use Gradle instead of Ant or Maven?

Gradle nicely combines both Ant and Maven, taking the best from both frameworks. Flexibility from Ant and convention over configuration, dependency management and plugins from Maven.

So if you want to have a standard java build, like in maven, but test task has to do some custom step it could look like below.

build.gradle:

apply plugin:'java'
task test{
  doFirst{
    ant.copy(toDir:'build/test-classes'){fileset dir:'src/test/extra-resources'}
  }
  doLast{
    ...
  }
}

On top of that it uses groovy syntax which gives much more expression power then ant/maven's xml.

It is a superset of Ant - you can use all Ant tasks in gradle with nicer, groovy-like syntax, ie.

ant.copy(file:'a.txt', toDir:"xyz")

or

ant.with{
  delete "x.txt"
  mkdir "abc"
  copy file:"a.txt", toDir: "abc"
}

What does \d+ mean in regular expression terms?

\d is a digit (a character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.

This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.

Check substring exists in a string in C

Try to use pointers...

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

int main()
{

  char str[] = "String1 subString1 Strinstrnd subStr ing1subString";
  char sub[] = "subString";

  char *p1, *p2, *p3;
  int i=0,j=0,flag=0;

  p1 = str;
  p2 = sub;

  for(i = 0; i<strlen(str); i++)
  {
    if(*p1 == *p2)
      {
          p3 = p1;
          for(j = 0;j<strlen(sub);j++)
          {
            if(*p3 == *p2)
            {
              p3++;p2++;
            } 
            else
              break;
          }
          p2 = sub;
          if(j == strlen(sub))
          {
             flag = 1;
            printf("\nSubstring found at index : %d\n",i);
          }
      }
    p1++; 
  }
  if(flag==0)
  {
       printf("Substring NOT found");
  }
return (0);
}

How can I use a JavaScript variable as a PHP variable?

You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don

How to pass values between Fragments

This simple implementation helps to pass data between fragments in a simple way. Think you want to pass data from 'Frgment1' to 'Fragment2'

In Fragment1(Set data to send)

 Bundle bundle = new Bundle();
 bundle.putString("key","Jhon Doe"); // set your parameteres

 Fragment2 nextFragment = new Fragment2();
 nextFragment.setArguments(bundle);

 FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
 fragmentManager.beginTransaction().replace(R.id.content_drawer, nextFragment).commit();

In Fragment2 onCreateView method (Get parameteres)

String value = this.getArguments().getString("key");//get your parameters
Toast.makeText(getActivity(), value+" ", Toast.LENGTH_LONG).show();//show data in tost

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Also make sure you just don't have a pending transaction. :)

I was doing some tests around and began a transaction to be safe but never closed it. I wish the error would have been more explicit but oh well!

Console app arguments, how arguments are passed to Main method

The Main method is the Entry point of your application. If you checkout via ildasm then

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint

This is what helps in calling the method

The arguments are passed as say C:\AppName arg1 arg2 arg3

Connection timeout for SQL server

If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .

It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.

In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?

Also as it creates an Object and its always good to assign value in object rather than manipulating string.

Here is the code sample:

var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);

sscsb.ConnectTimeout = 30;

var conn = new SqlConnection(sscsb.ConnectionString);

Sorting arraylist in alphabetical order (case insensitive)

Custom Comparator should help

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
});

Or if you are using Java 8:

list.sort(String::compareToIgnoreCase);

Posting form to different MVC post action depending on the clicked submit button

You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:

In this way you don't need to do anything special on the server side.

Of course, you can use Url extensions methods in your Razor to specify the form action.

For browsers supporting HMTL5: simply define your submit buttons like this:

<input type='submit' value='...' formaction='@Url.Action(...)' />

For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):

$(document).on('click', '[type="submit"][data-form-action]', function (event) {
  var $this = $(this);
  var formAction = $this.attr('data-form-action');
  $this.closest('form').attr('action', formAction);
});

NOTE: This script will handle the click for any element in the page that has type=submit and data-form-action attributes. When this happens, it takes the value of data-form-action attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.

Then you simply have to add a data-form-action attribute with the desired action URL to your button, like this:

<input type='submit' data-form-action='@Url.Action(...)' value='...'/>

Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.

As you can see, this requires no custom routing, you can use the standard Url extension methods, and you have nothing special to do in modern browsers.

How to ignore parent css style

You could turn it off by overriding it like this:

height:auto !important;

Equivalent of Math.Min & Math.Max for Dates?

// Two different dates
var date1 = new Date(2013, 05, 13); 
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate); 

http://jsfiddle.net/5CR37/

jQuery: Scroll down page a set increment (in pixels) on click?

You can do that using animate like in the following link:

http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery

If you want to do it using scrollTo plugin, then take a look the following:

How to scroll the window using JQuery $.scrollTo() function

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

Using pip behind a proxy with CNTLM

At CentOS (actually I think all linux distros are similar) run

env|grep http_proxy

and

env|grep https_proxy

check what is the output of those commands (they should contain your proxy addresses).

If the outputs are empty or have incorrect values, modify them, for ex:

export http_proxy=http://10.1.1.1:8080
export https_proxy=http://10.1.1.1:8080

Now try to fetch and install some packages by using pip:

pip --proxy http://10.1.1.1:8080 install robotframework

and actually I have never met the case when it didn't work. For some systems you need to be a root (sudo is not enough).

How to convert empty spaces into null values, using SQL Server?

I solved a similar problem using NULLIF function:

UPDATE table 
SET col1 = NULLIF(col1, '')

From the T-SQL reference:

NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.

error: expected class-name before ‘{’ token

I got the same error with a different problem,

I used namespaces in my headers and forgot the closing bracket and got this cryptic error instead.

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

center image in div with overflow hidden

Most recent solution:

HTML

<div class="parent">
    <img src="image.jpg" height="600" width="600"/>
</div>

CSS

.parent {
    width: 200px;
    height: 200px;
    overflow: hidden;
    /* Magic */
    display: flex;
    align-items: center; /* vertical */
    justify-content: center; /* horizontal */
}

How to list all available Kafka brokers in a cluster?

Using Confluent's REST Proxy API v3:

curl -X GET -H "Accept: application/vnd.api+json" localhost:8082/v3/clusters

where localhost:8082 is Kafka Proxy address.

jquery animate background position

Using Firefox:
specifying two values: Doesn't work with any combination of syntax -- as several pointed out above. Using Firebug, I get "Error in parsing value for 'background-position'. Declaration dropped." until the animation ends.

'backgroundPosition': '17.5em' -- specifiying 1 value: works in FF and CHrome OPera, SF(Safari) and IE, with a caveat that the 2nd value or y position (vertical) gets set to "center". From Firebug, the element's style gets set to:
style="background-position: 17.5em center;"

Format Date time in AngularJS

Have you seen the Writing directives (short version) section of the documentation?

HTML

<div ng-controller="Ctrl2">
      Date format: <input ng-model="format"> <hr/>
      Current time is: <span my-current-time="format"></span>
</div> 

JS

function Ctrl2($scope) {
  $scope.format = 'M/d/yy h:mm:ss a';
}

Skip rows during csv import pandas

I don't have reputation to comment yet, but I want to add to alko answer for further reference.

From the docs:

skiprows: A collection of numbers for rows in the file to skip. Can also be an integer to skip the first n rows

What is the iPhone 4 user-agent?

Note: The user agent strings from Facebook's internal browser do indicate the actual physical device. Even the cellphone carrier (eg. AT&T)

Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 [FBAN/FBIOS;FBAV/149.0.0.39.64;FBBV/79173879;FBDV/iPhone7,2;FBMD/iPhone;FBSN/iOS;FBSV/10.3.3;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0

Mozilla/5.0 (iPhone; CPU iPhone OS 11_1 like Mac OS X) AppleWebKit/604.3.5 (KHTML, like Gecko) Mobile/15B93 [FBAN/FBIOS;FBAV/148.0.0.45.64;FBBV/78032376;FBDV/iPhone10,4;FBMD/iPhone;FBSN/iOS;FBSV/11.1;FBSS/2;FBCR/AT&T;FBID/phone;FBLC/en_US;FBOP/5;FBRV/0]

These won't be the case in Safari or Chrome from iOS - only within the browser inside the Facebook app.

(I'm getting iPhone9 too though - not quite sure what that is!)

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

jQuery Remove string from string

To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace function since it is not a mutator function:

myString = myString.replace('username1','');

iOS: how to perform a HTTP POST request?

You can use NSURLConnection as follows:

  1. Set your NSURLRequest: Use requestWithURL:(NSURL *)theURL to initialise the request.

    If you need to specify a POST request and/or HTTP headers, use NSMutableURLRequest with

    • (void)setHTTPMethod:(NSString *)method
    • (void)setHTTPBody:(NSData *)data
    • (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
  2. Send your request in 2 ways using NSURLConnection:

    • Synchronously: (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

      This returns a NSData variable that you can process.

      IMPORTANT: Remember to kick off the synchronous request in a separate thread to avoid blocking the UI.

    • Asynchronously: (void)start

Don't forget to set your NSURLConnection's delegate to handle the connection as follows:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.data setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
    [self.data appendData:d];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
                                 message:[error localizedDescription]
                                delegate:nil
                       cancelButtonTitle:NSLocalizedString(@"OK", @"") 
                       otherButtonTitles:nil] autorelease] show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];

    // Do anything you want with it 

    [responseText release];
}

// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSString *username = @"username";
    NSString *password = @"password";

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
                                                             password:password
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

Get list from pandas dataframe column or row?

Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist() on to turn them into a Python list. Alternatively you cast it with list(x).

import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")

Output:

DataFrame:
   one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

column types:
one    float64
two      int64
dtype: object

col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>

col_one_arr:
[ 1.  2.  3. nan]
type:<class 'numpy.ndarray'>

Move entire line up and down in Vim

Assuming the cursor is on the line you like to move.

Moving up and down: :m for move

:m +1 - moves down 1 line

:m -2 - move up 1 lines

(Note you can replace +1 with any numbers depending on how many lines you want to move it up or down, ie +2 would move it down 2 lines, -3 would move it up 2 lines)

To move to specific line

:set number - display number lines (easier to see where you are moving it to)

:m 3 - move the line after 3rd line (replace 3 to any line you'd like)

Moving multiple lines:

V (i.e. Shift-V) and move courser up and down to select multiple lines in VIM

once selected hit : and run the commands above, m +1 etc

How to use a wildcard in the classpath to add multiple jars?

This works on Windows:

java -cp "lib/*" %MAINCLASS%

where %MAINCLASS% of course is the class containing your main method.

Alternatively:

java -cp "lib/*" -jar %MAINJAR%

where %MAINJAR% is the jar file to launch via its internal manifest.

Using SQL LIKE and IN together

Use the longer version of IN which is a bunch of OR.

SELECT * FROM tablename 
WHERE column LIKE 'M510%'
OR column LIKE 'M615%'
OR column LIKE 'M515%'
OR column LIKE 'M612%';

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I had the same problem with SQL Server 2008 R2 and when I checked "SQL Server Configuration Manager" My SQL Server instance had Stopped. Right Clicking and Starting the Instance solved the issue.

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

In a unix shell, how to get yesterday's date into a variable?

Thanks for the help everyone, but since i'm on HP-UX (after all: the more you pay, the less features you get...) i've had to resort to perl:

perl -e '@T=localtime(time-86400);printf("%02d/%02d/%04d",$T[3],$T[4]+1,$T[5]+1900)' | read dt

How to disable margin-collapsing?

I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.

Using CSS :before and :after pseudo-elements with inline CSS?

as mentioned above: its not possible to call a css pseudo-class / -element inline. what i now did, is: give your element a unique identifier, f.ex. an id or a unique class. and write a fitting <style> element

<style>#id29:before { content: "*";}</style>
<article id="id29">
  <!-- something -->
</article>

fugly, but what inline css isnt..?

jQuery: Get height of hidden element in jQuery

Following Nick Craver's solution, setting the element's visibility allows it to get accurate dimensions. I've used this solution very very often. However, having to reset the styles manually, I've come to find this cumbersome, given that modifying the element's initial positioning/display in my css through development, I often forget to update the related javascript code. The following code doesn't reset the styles per say, but removes the inline styles added by javascript:

$("#myDiv")
.css({
    position:   'absolute',
    visibility: 'hidden',
    display:    'block'
});

optionHeight = $("#myDiv").height();
optionWidth = $("#myDiv").width();

$("#myDiv").attr('style', '');

The only assumption here is that there can't be other inline styles or else they will be removed aswell. The benefit here, however, is that the element's styles are returned to what they were in the css stylesheet. As a consequence, you can write this up as a function where an element is passed through, and a height or width is returned.

Another issue I've found of setting the styles inline via js is that when dealing with transitions through css3, you become forced to adapt your style rules' weights to be stronger than an inline style, which can be frustrating sometimes.

How to iterate over rows in a DataFrame in Pandas

You can write your own iterator that implements namedtuple

from collections import namedtuple

def myiter(d, cols=None):
    if cols is None:
        v = d.values.tolist()
        cols = d.columns.values.tolist()
    else:
        j = [d.columns.get_loc(c) for c in cols]
        v = d.values[:, j].tolist()

    n = namedtuple('MyTuple', cols)

    for line in iter(v):
        yield n(*line)

This is directly comparable to pd.DataFrame.itertuples. I'm aiming at performing the same task with more efficiency.


For the given dataframe with my function:

list(myiter(df))

[MyTuple(c1=10, c2=100), MyTuple(c1=11, c2=110), MyTuple(c1=12, c2=120)]

Or with pd.DataFrame.itertuples:

list(df.itertuples(index=False))

[Pandas(c1=10, c2=100), Pandas(c1=11, c2=110), Pandas(c1=12, c2=120)]

A comprehensive test
We test making all columns available and subsetting the columns.

def iterfullA(d):
    return list(myiter(d))

def iterfullB(d):
    return list(d.itertuples(index=False))

def itersubA(d):
    return list(myiter(d, ['col3', 'col4', 'col5', 'col6', 'col7']))

def itersubB(d):
    return list(d[['col3', 'col4', 'col5', 'col6', 'col7']].itertuples(index=False))

res = pd.DataFrame(
    index=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    columns='iterfullA iterfullB itersubA itersubB'.split(),
    dtype=float
)

for i in res.index:
    d = pd.DataFrame(np.random.randint(10, size=(i, 10))).add_prefix('col')
    for j in res.columns:
        stmt = '{}(d)'.format(j)
        setp = 'from __main__ import d, {}'.format(j)
        res.at[i, j] = timeit(stmt, setp, number=100)

res.groupby(res.columns.str[4:-1], axis=1).plot(loglog=True);

enter image description here

enter image description here

What is android:weightSum in android, and how does it work?

From developer documentation

This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

Addition to @Shubhayu answer

rest 3/5 can be used for other child layouts which really doesn't need any specific portion of containing layout.

this is potential use of android:weightSum property.

Convert a character digit to the corresponding integer in C

char chVal = '5';
char chIndex;

if ((chVal >= '0') && (chVal <= '9')) {

    chIndex = chVal - '0';
}
else 
if ((chVal >= 'a') && (chVal <= 'z')) {

    chIndex = chVal - 'a';
}
else 
if ((chVal >= 'A') && (chVal <= 'Z')) {

    chIndex = chVal - 'A';
}
else {
    chIndex = -1; // Error value !!!
}

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Adding

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

in manifest and using same as Martin:

path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); 
File file = new File(path, "/" + fname);

It worked.

Get month name from number

Some good answers already make use of calendar but the effect of setting the locale hasn't been mentioned yet.

Calendar set month names according to the current locale, for exemple in French:

import locale
import calendar

locale.setlocale(locale.LC_ALL, 'fr_FR')

assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'

If you plan on using setlocale in your code, make sure to read the tips and caveats and extension writer sections from the documentation. The example shown here is not representative of how it should be used. In particular, from these two sections:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program […]

Extension modules should never call setlocale() […]

How to get client IP address using jQuery


<html lang="en">
<head>
    <title>Jquery - get ip address</title>
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
</head>
<body>


<h1>Your Ip Address : <span class="ip"></span></h1>


<script type="text/javascript">
    $.getJSON("http://jsonip.com?callback=?", function (data) {
        $(".ip").text(data.ip);
    });
</script>


</body>
</html>

Array.size() vs Array.length

.size() is not a native JS function of Array (at least not in any browser that I know of).

.length should be used.


If

.size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.

or

There might be some plugin on your browser that is mucking with the Array prototype.

How to delete file from public folder in laravel 5.1

For Delete files from the public folders, we can use the File::delete function into the Laravel. For use File need to use File into the controller OR We can use \File. This consider the root of the file.

// Delete a single file
File::delete($filename);

For delete Multiple files

// Delete multiple files
File::delete($file1, $file2, $file3);

Delete an array of Files

// Delete an array of files
$files = array($file1, $file2);
File::delete($files);

JavaScript unit test tools for TDD

Chutzpah - A JavaScript Test Runner

I created an open source project called Chutzpah which is a test runner for JavaScript unit tests. Chutzpah enables you to run JavaScript unit tests from the command line and from inside of Visual Studio. It also supports running in the TeamCity continuous integration server.

How do I set Tomcat Manager Application User Name and Password for NetBeans?

Update the 'apache-tomcat-8.5.5\conf\tomcat-users.xml file. uncomment the roles and add/replace the following line.and restart server

tomcat-users.xml file

<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="standard,manager,admin,manager-gui,manager-script"/>

Comparing user-inputted characters in C

For a start, your answer variable should be of type char, not char*.

As for the if statement:

if (answer == ('Y' || 'y'))

This is first evaluating 'Y' || 'y' which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.

You could use the more correct:

if ((answer == 'Y') || (answer == 'y'))

but you really should be using:

if (toupper(answer) == 'Y')

since that's the more portable way to achieve the same end.


*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.

How can I find whitespace in a String?

Use Apache Commons StringUtils:

StringUtils.containsWhitespace(str)

How to Update Date and Time of Raspberry Pi With out Internet

You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.

Configure Win7 as authoritative time server. Configure RasPi time server lookup.

Can I use conditional statements with EJS templates (in JMVC)?

Just making code shorter you can use ES6 features. The same things can be written as

app.get("/recipes", (req, res) => {
    res.render("recipes.ejs", {
        recipes
    });
}); 

And the Templeate can be render as the same!

<%if (recipes.length > 0) { %>
// Do something with more than 1 recipe
<% } %>

Byte Array in Python

Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray type.

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>> 

SQL: How to to SUM two values from different tables

For your current structure, you could also try the following:

select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country

I think I prefer a union between the two tables, and a group by on the country name as mentioned above.

But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)