Programs & Examples On #Nsdecimalnumber

NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from –128 through 127.

How to initialize an array in one step using Ruby?

If you have an Array of strings, you can also initialize it like this:

array = %w{1 2 3}

just separate each element with any whitespace

How do I detect if software keyboard is visible on Android Device or not?

try this:

InputMethodManager imm = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    if (imm.isAcceptingText()) {
        writeToLog("Software Keyboard was shown");
    } else {
        writeToLog("Software Keyboard was not shown");
    }

What does git push -u mean?

"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull or git push without arguments. A little bit down, this article explains and demonstrates this concept.

Java Object Null Check for method

You can add a guard condition to the method to ensure books is not null and then check for null when iterating the array:

public static double calculateInventoryTotal(Book[] books)
{
    if(books == null){
        throw new IllegalArgumentException("Books cannot be null");
    }

    double total = 0;

    for (int i = 0; i < books.length; i++)
    {
        if(books[i] != null){
            total += books[i].getPrice();
        }
    }

    return total;
}

Is it possible to validate the size and type of input=file in html5

I could do this (demo):

<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
    <form >
        <input type="file" id="f" data-max-size="32154" />
        <input type="submit" />
    </form>
<script>
$(function(){
    $('form').submit(function(){
        var isOk = true;
        $('input[type=file][data-max-size]').each(function(){
            if(typeof this.files[0] !== 'undefined'){
                var maxSize = parseInt($(this).attr('max-size'),10),
                size = this.files[0].size;
                isOk = maxSize > size;
                return isOk;
            }
        });
        return isOk;
    });
});
</script>
</body>
</html>

Pass multiple arguments into std::thread

If you're getting this, you may have forgotten to put #include <thread> at the beginning of your file. OP's signature seems like it should work.

List vs tuple, when to use each?

But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?

For input parameters it's best to accept the most generic interface that does what you need. It is seldom just a tuple or list - more often it's sequence, sliceable or even iterable. Python's duck typing usually gets it for free, unless you explicitly check input types. Don't do that unless absolutely unavoidable.

For the data that you produce (output parameters) just return what's most convenient for you, e.g. return whatever datatype you keep or whatever your helper function returns.

One thing to keep in mind is to avoid returning a list (or any other mutable) that's part of your state, e.g.

class ThingsKeeper
    def __init__(self):
        self.__things = []

    def things(self):
        return self.__things  #outside objects can now modify your state

    def safer(self):
        return self.__things[:]  #it's copy-on-write, shouldn't hurt performance

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Create the certificate chain file with the intermediate and root ca.

cat intermediate/certs/intermediate.cert.pem certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem

chmod 444 intermediate/certs/ca-chain.cert.pem

Then verfify

openssl verify -CAfile intermediate/certs/ca-chain.cert.pem \
  intermediate/certs/www.example.com.cert.pem

www.example.com.cert.pem: OK Deploy the certific

Where is Ubuntu storing installed programs?

Just for an addition reference to the above answers. I can not use dpkg -L to find the correct path for cuda. See the results I got from dpkg -L

$ dpkg -L cuda
/.
/usr
/usr/share
/usr/share/doc
/usr/share/doc/cuda
/usr/share/doc/cuda/copyright
/usr/share/doc/cuda/changelog.Debian.gz

the correct path is /usr/local/cuda

$ ll /usr/local | grep cuda

lrwxrwxrwx  1 root root    8 Oct 20 18:45 cuda -> cuda-9.0/

drwxr-xr-x 15 root root 4096 Oct 20 18:44 cuda-9.0/

Btw, I did install cuda by the command of

dpkg -i xx_cuda_xxx.deb

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

I had the same problem in my code. I was concatenating a string to create a string. Below is the part of code.

int scannerId = 1;
std:strring testValue;
strInXml = std::string(std::string("<inArgs>" \
                        "<scannerID>" + scannerId) + std::string("</scannerID>" \
                        "<cmdArgs>" \
                        "<arg-string>" + testValue) + "</arg-string>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "</cmdArgs>"\
                        "</inArgs>");

Limit results in jQuery UI Autocomplete

I could solve this problem by adding the following content to my CSS file:

.ui-autocomplete {
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;
}

Serializing/deserializing with memory stream

Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize and add following two methods:

public class SerilizeDeserialize
{

    // Serialize collection of any type to a byte stream

    public static byte[] Serialize<T>(T obj)
    {
        using (MemoryStream memStream = new MemoryStream())
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            binSerializer.Serialize(memStream, obj);
            return memStream.ToArray();
        }
    }

    // DSerialize collection of any type to a byte stream

    public static T Deserialize<T>(byte[] serializedObj)
    {
        T obj = default(T);
        using (MemoryStream memStream = new MemoryStream(serializedObj))
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            obj = (T)binSerializer.Deserialize(memStream);
        }
        return obj;
    }

}

How To use these method in your Class:

ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);

ArrayList arrayListMemDes = new ArrayList();

arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);

Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
    Console.WriteLine(item);
}

How do I set vertical space between list items?

you can also use the line-height property on the ul

_x000D_
_x000D_
ul {
  line-height: 45px;
}
_x000D_
<ul>
<li>line one</li>
<li>line two</li>
<li>line three</li>
</ul>
_x000D_
_x000D_
_x000D_

Get Application Name/ Label via ADB Shell or Terminal

A shell script to accomplish this:

#!/bin/bash

# Remove whitespace
function remWS {
    if [ -z "${1}" ]; then
        cat | tr -d '[:space:]'
    else
        echo "${1}" | tr -d '[:space:]'
    fi
}

for pkg in $(adb shell pm list packages -3 | cut -d':' -f2); do
    apk_loc="$(adb shell pm path $(remWS $pkg) | cut -d':' -f2 | remWS)"
    apk_name="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 $'application-label:\'(.+)\'' | remWS)"
    apk_info="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 '\b(package: .+)')"

    echo "$apk_name v$(echo $apk_info | pcregrep -io1 -e $'\\bversionName=\'(.+?)\'')"
done

How can I make SQL case sensitive string comparison on MySQL?

Instead of using the = operator, you may want to use LIKE or LIKE BINARY

// this returns 1 (true)
select 'A' like 'a'

// this returns 0 (false)
select 'A' like binary 'a'


select * from user where username like binary 'a'

It will take 'a' and not 'A' in its condition

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Numeric defines the TOTAL number of digits, and then the number after the decimal.

A numeric(3,2) can only hold up to 9.99.

jwt check if token expired

This is the answer if someone want to know

if (Date.now() >= exp * 1000) {
  return false;
}

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

In iOS9 Apple finally introduced the possibility to register your app to handle certain http:// URLs: Universal Links.

A very rough explanation of how it works:

  • You declare interest in opening http:// URLs for certain domains (web urls) in your app.
  • On the server of the specified domains you have to indicate which URLs to open in which app that has declared interest in opening URLs from the server's domain.
  • The iOS URL loading service checks all attempts to open http:// URLs for a setup as explained above and opens the correct app automatically if installed; without going through Safari first...

This is the cleanest way to do deep linking on iOS, unfortunately it works only in iOS9 and newer...

Split string, convert ToList<int>() in one line

Better use int.TryParse to avoid exceptions;

var numbers = sNumbers
            .Split(',')
            .Where(x => int.TryParse(x, out _))
            .Select(int.Parse)
            .ToList();

Hide password with "•••••••" in a textField

in Swift 3.0 or Later

passwordTextField.isSecureTextEntry = true

How do I find the parent directory in C#?

string parent = System.IO.Directory.GetParent(str_directory).FullName;

See BOL

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

Summing elements in a list

You can use map function and pythons inbuilt sum() function. It simplifies the solution. And reduces the complexity.
a=map(int,raw_input().split())
sum(a)
Done!

Multiline text in JLabel

if you want your jLabel Text to resize automaticly for example in a stretchable gridbaglayout its enough just to put its text in html tags like so:

JLabel label = new JLabel("<html>First line and maybe second line</html>");

Best way to check if MySQL results returned in PHP?

Of all the options above I would use

if (mysql_num_rows($result)==0) { PERFORM ACTION }

checking against the result like below

if (!$result) { PERFORM ACTION }

This will be true if a mysql_error occurs so effectively if an error occurred you could then enter a duplicate user-name...

MVC - Set selected value of SelectList

Doug answered my question... But I'll explain what my problem was exactly, and how Doug helped me solve my problem which you could be encountering.

I call jquery $.post and am replacing my div with my partial view, like so.

function AddNewAddress (paramvalue) {
    $.post(url, { param: paramvalue}, function(d) {
        $('#myDiv').replaceWith(d);
    });
}

When doing so, for some reason when stepping into my model my selected value affiliated property was never set, only until I stepped into the view it came into scope.

So, What I had before

@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"})

however even though Model.CustomerAddresses[i].YearsAtAddressSelectList, was set... it didn't set the selected value.

So after....

 @Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, new SelectList(Model.CustomerAddresses[i].YearsAtAddressSelectList, "Value", "Text", Model.CustomerAddresses[i].YearsAtAddress), new { onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")" })

and it worked!

I decided not to use DropDownListFor as it has problem when using unobtrusive validation, which is why i reference the following if your curious in a class classed

HtmlExtensions.cs




[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes));

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes));

}


[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]

[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
{
    if (expression == null)
    {
        throw new ArgumentNullException("expression");
    }


    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);



    IDictionary<string, object> validationAttributes = htmlHelper
        .GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);



    if (htmlAttributes == null)
        htmlAttributes = validationAttributes;
    else
        htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value);



    return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes);

}

Paging with LINQ for objects

Using Skip and Take is definitely the way to go. If I were implementing this, I would probably write my own extension method to handle paging (to make the code more readable). The implementation can of course use Skip and Take:

static class PagingUtils {
  public static IEnumerable<T> Page<T>(this IEnumerable<T> en, int pageSize, int page) {
    return en.Skip(page * pageSize).Take(pageSize);
  }
  public static IQueryable<T> Page<T>(this IQueryable<T> en, int pageSize, int page) {
    return en.Skip(page * pageSize).Take(pageSize);
  }
}

The class defines two extension methods - one for IEnumerable and one for IQueryable, which means that you can use it with both LINQ to Objects and LINQ to SQL (when writing database query, the compiler will pick the IQueryable version).

Depending on your paging requirements, you could also add some additional behavior (for example to handle negative pageSize or page value). Here is an example how you would use this extension method in your query:

var q = (from p in products
         where p.Show == true
         select new { p.Name }).Page(10, pageIndex);

Cannot implicitly convert type 'int?' to 'int'.

simple

(i == null) ? i.Value : 0;

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Get the last day of the month in SQL

For SQL server 2012 or above use EOMONTH to get the last date of month

SQL query to display end date of current month

DECLARE @currentDate DATE = GETDATE()
SELECT EOMONTH (@currentDate) AS CurrentMonthED

SQL query to display end date of Next month

DECLARE @currentDate DATE = GETDATE()
SELECT EOMONTH (@currentDate, 1 ) AS NextMonthED

Use a cell value in VBA function with a variable

VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.

Dim val1 As Integer, val2 As Integer, i As Integer

For i = 1 To 333

  Sheets("Feuil2").Activate
  ActiveSheet.Cells(i, 1).Select

    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value

Sheets("Classeur2.csv").Select
Cells(val1, val2).Select

ActiveCell.FormulaR1C1 = "1"

Next i

Javascript: Load an Image from url and display

Add a div with ID imgDiv and make your script

 document.getElementById('imgDiv').innerHTML='<img src=\'http://webpage.com/images/'+document.getElementById('imagename').value +'.png\'>'

I tried to stay as close to your original as tp not overwhelm you with jQuery and such

Reload content in modal (twitter bootstrap)

You can force Modal to refresh the popup by adding this line at the end of the hide method of the Modal plugin (If you are using bootstrap-transition.js v2.1.1, it should be at line 836)

this.$element.removeData()

Or with an event listener

$('#modal').on('hidden', function() {
    $(this).data('modal').$element.removeData();
})

How to change menu item text dynamically in Android

Declare your menu field.

private Menu menu;

Following is onCreateOptionsMenu() method

public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
    try {
        getMenuInflater().inflate(R.menu.menu_main,menu);
    } catch (Exception e) {
        e.printStackTrace();
        Log.i(TAG, "onCreateOptionsMenu: error: "+e.getMessage());
    }
    return super.onCreateOptionsMenu(menu);
}

Following will be your name setter activity. Either through a button click or through conditional code

public void setMenuName(){
menu.findItem(R.id.menuItemId).setTitle(/*Set your desired menu title here*/);
}

This worked for me.

How to start Spyder IDE on Windows

on windows,

  1. pip install --upgrade spyder

  2. in powershell, start python shell, by typing python

    from spyder.app import start
    start.main()
    

That't it.

How do I break a string across more than one line of code in JavaScript?

A good solution here for VSCode users, if a string breaking down into multiple lines causes the problem (I faced this when I had to test a long JWT token, and somehow using template literals didn't do the trick.)

How do I correctly detect orientation change using Phonegap on iOS?

While working with the orientationchange event, I needed a timeout to get the correct dimensions of the elements in the page, but matchMedia worked fine. My final code:

var matchMedia = window.msMatchMedia || window.MozMatchMedia || window.WebkitMatchMedia || window.matchMedia;

if (typeof(matchMedia) !== 'undefined') {
  // use matchMedia function to detect orientationchange
  window.matchMedia('(orientation: portrait)').addListener(function() {
    // your code ...
  });
} else {
  // use orientationchange event with timeout (fires to early)
  $(window).on('orientationchange', function() {
    window.setTimeout(function() {
      // your code ...
    }, 300)
  });
}

How do I add a border to an image in HTML?

Here is some HTML and CSS code that would solve your issue:

CSS

.ImageBorder
{
    border-width: 1px;
    border-color: Black;
}

HTML

<img src="MyImage.gif" class="ImageBorder" />

Android Studio and Gradle build error

OK seems like a caching issue of some sort. There was indeed an error in code with the R.id.some_id not being found but the editor was not picking it up displaying that there were no errors.

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

Your content must have a ListView whose id attribute is 'android.R.id.list'

One other thing that affected me: If you have multiple test devices, make sure you are making changes to the layout used by the device. In my case, I spent a while making changes to xmls in the "layout" directory until I discovered that my larger phone (which I switched to halfway through testing) was using xmls in the "layout-sw360dp" directory. Grrr!

How to create a css rule for all elements except one class?

The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.

Unable to connect PostgreSQL to remote database using pgAdmin

I didn't have to change my prostgresql.conf file but, i did have to do the following based on my psql via command line was connecting and pgAdmin not connecting on RDS with AWS.

I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.

This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all <myip>/32 md5

As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.

Can't connect to docker from docker-compose

I have resolved the issue using following steps

$ sudo service docker status
$ sudo service docker start
$ sudo docker-compose up

now docker-compose up is working

SimpleDateFormat and locale based format string

tl;dr

LocalDate.now().format(
    DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM )
                     .withLocale( new Locale( "no" , "NO" ) )
)

The troublesome classes of java.util.Date and SimpleDateFormat are now legacy, supplanted by the java.time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

DateTimeFormatter

Use DateTimeFormatter to generate strings representing only the date-portion or the time-portion.

The DateTimeFormatter class can automatically localize.

To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.

Example:

Locale l = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( l );
String output = ld.format( f );

Going the other direction, you can parse a localized string.

LocalDate ld = LocalDate.parse( input , f );

Note that the locale and time zone are completely orthogonal issues. You can have a Montréal moment presented in Japanese language or an Auckland New Zealand moment presented in Hindi language.

Another example: Change 6 junio 2012 (Spanish) to 2012-06-06 (standard ISO 8601 format). The java.time classes use ISO 8601 formats by default for parsing/generating strings.

String input = "6 junio 2012";
Locale l = new Locale ( "es" , "ES" );
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "d MMMM uuuu" , l );
LocalDate ld = LocalDate.parse ( input , f );
String output = ld.toString();  // 2012-06-06. 

Peruse formats

Here is some example code for perusing the results of multiple formats in multiple locales, automatically localized.

An EnumSet is an implementation of Set, highly optimized for both low memory usage and fast execution speed when collecting Enum objects. So, EnumSet.allOf( FormatStyle.class ) gives us a collection of all four of the FormatStyle enum objects to loop. For more info, see Oracle Tutorial on enum types.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 );

List < Locale > locales = new ArrayList <>( 3 );
locales.add( Locale.CANADA_FRENCH );
locales.add( new Locale( "no" , "NO" ) );
locales.add( Locale.US );

// Or use all locales (almost 800 of them, for about 120K text results).
// Locale[] locales = Locale.getAvailableLocales(); // All known locales. Almost 800 of them.

for ( Locale locale : locales )
{
    System.out.println( "------|  LOCALE: " + locale + " — " + locale.getDisplayName() + "  |----------------------------------" + System.lineSeparator() );

    for ( FormatStyle style : EnumSet.allOf( FormatStyle.class ) )
    {
        DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale );
        String output = ld.format( f );
        System.out.println( output );
    }
    System.out.println( "" );
}
System.out.println( "« fin »" + System.lineSeparator() );

Output.

------|  LOCALE: fr_CA — French (Canada)  |----------------------------------

mardi 23 janvier 2018
23 janvier 2018
23 janv. 2018
18-01-23

------|  LOCALE: no_NO — Norwegian (Norway)  |----------------------------------

tirsdag 23. januar 2018
23. januar 2018
23. jan. 2018
23.01.2018

------|  LOCALE: en_US — English (United States)  |----------------------------------

Tuesday, January 23, 2018
January 23, 2018
Jan 23, 2018
1/23/18

« fin »

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How do you count the elements of an array in java

If you wish to have an Array in which you will not be allocating all of the elements, you will have to do your own bookkeeping to ensure how many elements you have placed in it via some other variable. If you'd like to avoid doing this while also getting an "Array" that can grow capacities after its initial instantiation, you can create an ArrayList

ArrayList<Integer> theArray = new ArrayList<Integer>();
theArray.add(5); // places at index 0
theArray.size(); // returns length of 1
int answer = theArray.get(0); // index 0 = 5

Don't forget to import it at the top of the file:

import java.util.ArrayList;

Fatal error: Call to undefined function pg_connect()

  1. Add 'PHPIniDir "C:/php"' into the httpd.conf file.(provided you have your PHP saved in C:, or else give the location where PHP is saved.)
  2. Uncomment following 'extension=php_pgsql.dll' in php.ini file
  3. Uncomment ';extension_dir = "ext"' in php.ini directory

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

This could be your connectors for MySQL which need to be updated, as MySQL8 changed the encryption of passwords - so older connectors are encrypting them incorrectly.

The maven repo for the java connector can be found here.
If you use flyway plugin, you should also consider updating it, too!

Then you can simply update your maven pom with:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

Or for others who use Gradle, you can update build.gradle with:

 buildscript {
    ext {
        ...
    }
    repositories {
        ...
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath('mysql:mysql-connector-java:8.0.11')
    }
 }

All that you really need to do (build.gradle example)

generate model using user:references vs user_id:integer

For the former, convention over configuration. Rails default when you reference another table with

 belongs_to :something

is to look for something_id.

references, or belongs_to is actually newer way of writing the former with few quirks.

Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:

t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true

or (note the plural):

add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

TypeScript function overloading

What is function overloading in general?

Function overloading or method overloading is the ability to create multiple functions of the same name with different implementations (Wikipedia)


What is function overloading in JS?

This feature is not possible in JS - the last defined function is taken in case of multiple declarations:

function foo(a1, a2) { return `${a1}, ${a2}` }
function foo(a1) { return `${a1}` } // replaces above `foo` declaration
foo(42, "foo") // "42"

... and in TS?

Overloads are a compile-time construct with no impact on the JS runtime:

function foo(s: string): string // overload #1 of foo
function foo(s: string, n: number): number // overload #2 of foo
function foo(s: string, n?: number): string | number {/* ... */} // foo implementation

A duplicate implementation error is triggered, if you use above code (safer than JS). TS chooses the first fitting overload in top-down order, so overloads are sorted from most specific to most broad.


Method overloading in TS: a more complex example

Overloaded class method types can be used in a similar way to function overloading:

class LayerFactory {
    createFeatureLayer(a1: string, a2: number): string
    createFeatureLayer(a1: number, a2: boolean, a3: string): number
    createFeatureLayer(a1: string | number, a2: number | boolean, a3?: string)
        : number | string { /*... your implementation*/ }
}

const fact = new LayerFactory()
fact.createFeatureLayer("foo", 42) // string
fact.createFeatureLayer(3, true, "bar") // number

The vastly different overloads are possible, as the function implementation is compatible to all overload signatures - enforced by the compiler.

More infos:

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

Trigger to fire only if a condition is met in SQL Server

Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.

When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)

Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.

Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.

AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)

Creating email templates with Django

Use EmailMultiAlternatives and render_to_string to make use of two alternative templates (one in plain text and one in html):

from django.core.mail import EmailMultiAlternatives
from django.template import Context
from django.template.loader import render_to_string

c = Context({'username': username})    
text_content = render_to_string('mail/email.txt', c)
html_content = render_to_string('mail/email.html', c)

email = EmailMultiAlternatives('Subject', text_content)
email.attach_alternative(html_content, "text/html")
email.to = ['[email protected]']
email.send()

How to check the value given is a positive or negative integer?

I use in this case and it works :)

var pos = 0; 
var sign = 0;
var zero = 0;
var neg = 0;
for( var i in arr ) {
    sign = arr[i] > 0 ? 1 : arr[i] == 0 ? 0 : -1;
    if (sign === 0) {
        zero++; 
    } else if (sign === 1 ) {
        pos++;
    } else {
        neg++;
    }
}

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

So many answers.... all bad!

Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...

But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords.

anything with less than 8 characters OR anything with no numbers OR anything with no uppercase OR anything with no special characters

So:

^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$

If anything matches that, then it's an invalid password.

How to redirect verbose garbage collection output to a file?

Java 9 & Unified JVM Logging

JEP 158 introduces a common logging system for all components of the JVM which will change (and IMO simplify) how logging works with GC. JEP 158 added a new command-line option to control logging from all components of the JVM:

-Xlog

For example, the following option:

-Xlog:gc

will log messages tagged with gc tag using info level to stdout. Or this one:

-Xlog:gc=debug:file=gc.txt:none

would log messages tagged with gc tag using debug level to a file called gc.txt with no decorations. For more detailed discussion, you can checkout the examples in the JEP page.

Java : Convert formatted xml file to one line string

Using this answer which provides the code to use Dom4j to do pretty-printing, change the line that sets the output format from: createPrettyPrint() to: createCompactFormat()

public String unPrettyPrint(final String xml){  

    if (StringUtils.isBlank(xml)) {
        throw new RuntimeException("xml was null or blank in unPrettyPrint()");
    }

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createCompactFormat();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    }
    catch (Exception e) {
        throw new RuntimeException("Error un-pretty printing xml:\n" + xml, e);
    }
    return sw.toString();
}

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Yet another way to do this:

(Get-Date).AddDays(-1).Date.AddHours(22)

Exporting the values in List to excel

Fast way - ArrayToExcel (github)

byte[] excel = myList.ToExcel();
File.WriteAllBytes("result.xlsx", excel);

Finding the 'type' of an input element

To check input type

<!DOCTYPE html>
<html>
<body>

    <input type=number id="txtinp">
    <button onclick=checktype()>Try it</button>

    <script>
        function checktype() 
        {
            alert(document.getElementById("txtinp").type);
        }
    </script>

</body>
</html> 

Can I add extension methods to an existing static class?

I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.

How to list all files in a directory and its subdirectories in hadoop hdfs

If you are using hadoop 2.* API there are more elegant solutions:

    Configuration conf = getConf();
    Job job = Job.getInstance(conf);
    FileSystem fs = FileSystem.get(conf);

    //the second boolean parameter here sets the recursion to true
    RemoteIterator<LocatedFileStatus> fileStatusListIterator = fs.listFiles(
            new Path("path/to/lib"), true);
    while(fileStatusListIterator.hasNext()){
        LocatedFileStatus fileStatus = fileStatusListIterator.next();
        //do stuff with the file like ...
        job.addFileToClassPath(fileStatus.getPath());
    }

Round a divided number in Bash

If the decimal separator is comma (eg : LC_NUMERIC=fr_FR.UTF-8, see here):

$ printf "%.0f" $(echo "scale=2;3/2" | bc) 
bash: printf: 1.50: nombre non valable
0

Substitution is needed for ghostdog74 solution :

$ printf "%.0f" $(echo "scale=2;3/2" | bc | sed 's/[.]/,/')
2

or

$ printf "%.0f" $(echo "scale=2;3/2" | bc | tr '.' ',')
2

Can an Android Toast be longer than Toast.LENGTH_LONG?

Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:


     new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();


How can I manually generate a .pyc file from a .py file

You can compile individual files(s) from the command line with:

python -m compileall <file_1>.py <file_n>.py

Setting session variable using javascript

You could better use the localStorage of the web browser.

You can find a reference here

Multiple WHERE Clauses with LINQ extension methods

Surely:

if (useAdditionalClauses) 
{ 
  results = 
    results.Where(o => o.OrderStatus == OrderStatus.Open && 
    o.CustomerID == customerID)  
} 

Or just another .Where() call like this one (although I don't know why you would want to, unless it's split by another boolean control variable):

if (useAdditionalClauses) 
{ 
  results = results.Where(o => o.OrderStatus == OrderStatus.Open).
    Where(o => o.CustomerID == customerID);
} 

Or another reassignment to results: `results = results.Where(blah).

Moment js date time comparison

I believe you are looking for the query functions, isBefore, isSame, and isAfter.

But it's a bit difficult to tell exactly what you're attempting. Perhaps you are just looking to get the difference between the input time and the current time? If so, consider the difference function, diff. For example:

moment().diff(date_time, 'minutes')

A few other things:

  • There's an error in the first line:

      var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
    

    That's not going to work. I think you meant:

      var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
    

    Of course, you might as well:

      var date_time = '2013-03-24T10:15:20:12Z';
    
  • You're using: .tz('UTC') incorrectly. .tz belongs to moment-timezone. You don't need to use that unless you're working with other time zones, like America/Los_Angeles.

    If you want to parse a value as UTC, then use:

      moment.utc(theStringToParse)
    

    Or, if you want to parse a local value and convert it to UTC, then use:

      moment(theStringToParse).utc()
    

    Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.

  • You seem to be getting the "now" instance by moment(new Date()). You can instead just use moment().

Updated

Based on your edit, I think you can just do this:

var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');

Or, if you would like to ensure that your fields are validated to be in the correct format:

var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD  HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

Best way to move files between S3 buckets?

For me the following command just worked:

aws s3 mv s3://bucket/data s3://bucket/old_data --recursive

JS: iterating over result of getElementsByClassName using Array.forEach

As already said, getElementsByClassName returns a HTMLCollection, which is defined as

[Exposed=Window]
interface HTMLCollection {
  readonly attribute unsigned long length;
  getter Element? item(unsigned long index);
  getter Element? namedItem(DOMString name);
};

Previously, some browsers returned a NodeList instead.

[Exposed=Window]
interface NodeList {
  getter Node? item(unsigned long index);
  readonly attribute unsigned long length;
  iterable<Node>;
};

The difference is important, because DOM4 now defines NodeLists as iterable.

According to Web IDL draft,

Objects implementing an interface that is declared to be iterable support being iterated over to obtain a sequence of values.

Note: In the ECMAScript language binding, an interface that is iterable will have “entries”, “forEach”, “keys”, “values” and @@iterator properties on its interface prototype object.

That means that, if you want to use forEach, you can use a DOM method which returns a NodeList, like querySelectorAll.

document.querySelectorAll(".myclass").forEach(function(element, index, array) {
  // do stuff
});

Note this is not widely supported yet. Also see forEach method of Node.childNodes?

How to disable Home and other system buttons in Android?

Frankly it is not possible to disable the home button at least on new api levels , that is from 4.0 onwards. It is also not advisable to do that. You can however, block the back button by overriding the

public void onBackPressed() {
    // do not call super onBackPressed.
}

in order to override the home button, you could use a timer for example, and after every time check if the main screen is your screen or not, or your package is on top or not, (i am sure you will get links to it), and display your activity using the flag single_top.

That way , even if the home button is pressed you will be able to bring your app to the top.

Also make sure that the app has a way to exit, because such kind of apps can really be annoying and should never be developed.

Happy coding.

P.S: It is not possible to intercept the home event, when the home button is pressed.

You can use on attach to window methods and also keyguard methods, but not for api levels from 4.0 onwards.

How do I parse a string with a decimal point to a double?

System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CurrentCulture;

string _pos = dblstr.Replace(".",
    ci.NumberFormat.NumberDecimalSeparator).Replace(",",
        ci.NumberFormat.NumberDecimalSeparator);

double _dbl = double.Parse(_pos);

How can I compile LaTeX in UTF8?

\usepackage[utf8]{inputenc} will not work for a bibliographic entry such as this:

@ARTICLE{Hardy2007,
author = {Ibn Taymiyyah, A?mad ibn ?Abd al{-}Halim},
title = {Naq? al{-}man?iq},
shorttitle = {Naq? al-man?iq},
editor = {?amzah, A?mad},
publisher = {Maktabat a{l-}Sunnah},
address = {Cairo},
year = {1970},
sortname = {IbnTaymiyyaNaqdalmantiq},
keywords = { Logic, Medieval}} 

For this entry use \usepackage[utf8x]{inputenc}

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

Uncaught ReferenceError: jQuery is not defined

you need to put it after wp_head(); Because that loads your jQuery and you need to load jQuery first and then your js

css3 transition animation on load?

I think I have found a sort of work around for the OP question - instead of a transition beginning 'on.load' of the page - I found that using an animation for an opacity fade in had the same effect, (I was looking for the same thing as OP).

So I wanted to have the body text fade in from white(same as site background) to black text colour on page load - and I've only been coding since Monday so I was looking for an 'on.load' style thing code, but don't know JS yet - so here is my code that worked well for me.

#main p {
  animation: fadein 2s;
}
@keyframes fadein {
  from { opacity: 0}
  to   { opacity: 1}
}

And for whatever reason, this doesn't work for .class only #id's(at least not on mine)

Hope this helps - as I know this site helps me a lot!

Error in strings.xml file in Android

https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Escaping apostrophes and quotes

If you have an apostrophe or a quote in your string, you must either escape it or enclose the whole string in the other type of enclosing quotes. For example, here are some stings that do and don't work:

<string name="good_example">"This'll work"</string>
<string name="good_example_2">This\'ll also work</string>
<string name="bad_example">This doesn't work</string>
<string name="bad_example_2">XML encodings don&apos;t work</string>

How to refresh a Page using react-route Link

To refresh page you don't need react-router, simple js:

window.location.reload();

To re-render view in React component, you can just fire update with props/state.

What's the difference between KeyDown and KeyPress in .NET?

KeyPress is a higher level of abstraction than KeyDown (and KeyUp). KeyDown and KeyUp are hardware related: the actual action of a key on the keyboard. KeyPress is more "I received a character from the keyboard".

Angular 2 execute script after template render

I've used this method (reported here )

export class AppComponent {

  constructor() {
    if(document.getElementById("testScript"))
      document.getElementById("testScript").remove();
    var testScript = document.createElement("script");
    testScript.setAttribute("id", "testScript");
    testScript.setAttribute("src", "assets/js/test.js");
    document.body.appendChild(testScript);
  }
}

it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.

How update the _id of one MongoDB Document?

You can also create a new document from MongoDB compass or using command and set the specific _id value that you want.

How to get random value out of an array?

On-liner:

echo $array[array_rand($array,1)]

$("#form1").validate is not a function

If you had a link I could look to see what the issue is but here are a couple questions and things to check:

  • Is the ID for your form named "form" in the HTML?
  • Check to see if messages are required, maybe there is some imbalance in parameters
  • You should also add the 'type="text/javascript"' attributes where you are getting jQuery from Google

Also, if you're going to use the Google CDN for getting jQuery you may as well use Microsoft's CDN for getting your validation file. Any of these URLs will work:

Django DB Settings 'Improperly Configured' Error

For people using IntelliJ, with these settings I was able to query from the shell (on windows).

enter image description here

In php, is 0 treated as empty?

I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements, 0 (or the string '0' which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.

using empty() first and then strlen() is your best best if you need this as well, as:

if(!empty($var) && strlen($var)){
    echo '"$var" is present and has a non-falsey value!';
}

What is the method for converting radians to degrees?

a complete circle in radians is 2*pi. A complete circle in degrees is 360. To go from degrees to radians, it's (d/360) * 2*pi, or d*pi/180.

sscanf in Python

You could install pandas and use pandas.read_fwf for fixed width format files. Example using /proc/net/arp:

In [230]: df = pandas.read_fwf("/proc/net/arp")

In [231]: print(df)
       IP address HW type Flags         HW address Mask Device
0   141.38.28.115     0x1   0x2  84:2b:2b:ad:e1:f4    *   eth0
1   141.38.28.203     0x1   0x2  c4:34:6b:5b:e4:7d    *   eth0
2   141.38.28.140     0x1   0x2  00:19:99:ce:00:19    *   eth0
3   141.38.28.202     0x1   0x2  90:1b:0e:14:a1:e3    *   eth0
4    141.38.28.17     0x1   0x2  90:1b:0e:1a:4b:41    *   eth0
5    141.38.28.60     0x1   0x2  00:19:99:cc:aa:58    *   eth0
6   141.38.28.233     0x1   0x2  90:1b:0e:8d:7a:c9    *   eth0
7    141.38.28.55     0x1   0x2  00:19:99:cc:ab:00    *   eth0
8   141.38.28.224     0x1   0x2  90:1b:0e:8d:7a:e2    *   eth0
9   141.38.28.148     0x1   0x0  4c:52:62:a8:08:2c    *   eth0
10  141.38.28.179     0x1   0x2  90:1b:0e:1a:4b:50    *   eth0

In [232]: df["HW address"]
Out[232]:
0     84:2b:2b:ad:e1:f4
1     c4:34:6b:5b:e4:7d
2     00:19:99:ce:00:19
3     90:1b:0e:14:a1:e3
4     90:1b:0e:1a:4b:41
5     00:19:99:cc:aa:58
6     90:1b:0e:8d:7a:c9
7     00:19:99:cc:ab:00
8     90:1b:0e:8d:7a:e2
9     4c:52:62:a8:08:2c
10    90:1b:0e:1a:4b:50

In [233]: df["HW address"][5]
Out[233]: '00:19:99:cc:aa:58'

By default it tries to figure out the format automagically, but there are options you can give for more explicit instructions (see documentation). There are also other IO routines in pandas that are powerful for other file formats.

How do I find out which computer is the domain controller in Windows programmatically?

In C#/.NET 3.5 you could write a little program to do:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    string controller = context.ConnectedServer;
    Console.WriteLine( "Domain Controller:" + controller );
} 

This will list all the users in the current domain:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal searchPrincipal = new UserPrincipal(context))
    {
       using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
       {
           foreach (UserPrincipal principal in searcher.FindAll())
           {
               Console.WriteLine( principal.SamAccountName);
           }
       }
    }
}

How to print a query string with parameter values when using Hibernate

for development with Wildfly ( standalone.xml), add those loggers:

<logger category="org.hibernate.SQL">
   <level name="DEBUG"/>
</logger>
<logger category="org.hibernate.type.descriptor.sql">
   <level name="TRACE"/>
</logger>

Java 8 Lambda Stream forEach with multiple statements

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    System.out.println(item);
    System.out.println(item.toLowerCase());
  }
});

How do I calculate r-squared using Python and Numpy?

You can execute this code directly, this will find you the polynomial, and will find you the R-value you can put a comment down below if you need more explanation.

from scipy.stats import linregress
import numpy as np

x = np.array([1,2,3,4,5,6])
y = np.array([2,3,5,6,7,8])

p3 = np.polyfit(x,y,3) # 3rd degree polynomial, you can change it to any degree you want
xp = np.linspace(1,6,6)  # 6 means the length of the line
poly_arr = np.polyval(p3,xp)

poly_list = [round(num, 3) for num in list(poly_arr)]
slope, intercept, r_value, p_value, std_err = linregress(x, poly_list)
print(r_value**2)

How do I add a linker or compile flag in a CMake file?

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

There are several ways to add them:

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

    add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
    
  2. Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    
  3. Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    

Right now I use method 2.

How to do a FULL OUTER JOIN in MySQL?

I fix the response, and works include all rows (based on response of Pavle Lekic)

    (
    SELECT a.* FROM tablea a
    LEFT JOIN tableb b ON a.`key` = b.key
    WHERE b.`key` is null
    )
    UNION ALL
    (
    SELECT a.* FROM tablea a
    LEFT JOIN tableb b ON a.`key` = b.key
    where  a.`key` = b.`key`
    )
    UNION ALL
    (
    SELECT b.* FROM tablea a
    right JOIN tableb b ON b.`key` = a.key
    WHERE a.`key` is null
    );

Remote origin already exists on 'git push' to a new repository

I got the same issue, and here is how I fixed it after doing some research:

  1. Download GitHub for Windows or use something similar, which includes a shell
  2. Open the Git Shell from task menu. This will open a power shell including Git commands.
  3. In the shell, switch to your old repository, e.g. cd C:\path\to\old\repository
  4. Show status of the old repository

  5. Now remove the remote repository from local repository by using

    git remote rm origin
    
  6. Check again with step 4. It should show origin only, instead of the fetch and push path.

  7. Now that your old remote repository is disconnected, you can add the new remote repository. Use the following to connect to your new repository.

Note: In case you are using Bitbucket, you would create a project on Bitbucket first. After creation, Bitbucket will display all required Git commands to push your repository to remote, which look similar to the next code snippet. However, this works for other repositories, too.

cd /path/to/my/repo # If haven't done yet
git remote add mynewrepo https://[email protected]/team-or-user-name/myproject.git
git push -u mynewrepo master # To push changes for the first time

That's it.

How to upload files on server folder using jsp

Below code is working on my live server as well as in my own Lapy.

Note:

Please Create data folder in WebContent and put in any single image or any file(jsp or html file).

Add jar files

commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar

upload.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>

UploadServlet.java

package com.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }

            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(
                    request, response);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }

}

web.xml

  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>

done.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>

Listing files in a specific "folder" of a AWS S3 bucket

As other have already said, everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.

If you don't need objects which end with a '/' you can safely delete them e.g. via REST api or AWS Java SDK (I assume you have write access). You will not lose "nested files" (there no files, so you will not lose objects whose names are prefixed with the key you delete)

AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion("region").build();
amazonS3.deleteObject(new DeleteObjectRequest("my-bucket", "users/<user-id>/contacts/<contact-id>/"));

Please note that I'm using ProfileCredentialsProvider so that my requests are not anonymous. Otherwise, you will not be able to delete an object. I have my AWS keep key stored in ~/.aws/credentials file.

Django - taking values from POST request

If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables

Matplotlib figure facecolor (background color)

I had to use the transparent keyword to get the color I chose with my initial

fig=figure(facecolor='black')

like this:

savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)

Swift - Remove " character from string

If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:

someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])

Laravel Unknown Column 'updated_at'

Nice answer by Alex and Sameer, but maybe just additional info on why is necessary to put

public $timestamps = false;

Timestamps are nicely explained on official Laravel page:

By default, Eloquent expects created_at and updated_at columns to exist on your >tables. If you do not wish to have these columns automatically managed by >Eloquent, set the $timestamps property on your model to false.

how to add button click event in android studio

//as I understand it, the "this" denotes the current view(focus) in the android program

No, "this" will only work if your MainActivity referenced by this implements the View.OnClickListener, which is the parameter type for the setOnClickListener() method. It means that you should implement View.OnClickListener in MainActivity.

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

your google-services.json package name must match your build.gradle applicationId (applicationId "your package name")

How can I capture the result of var_dump to a string?

function return_var_dump(){
    // It works like var_dump, but it returns a string instead of printing it.
    $args = func_get_args(); // For <5.3.0 support ...
    ob_start();
    call_user_func_array('var_dump', $args);
    return ob_get_clean();
}

Bash script prints "Command Not Found" on empty lines

You may want to update you .bashrc and .bash_profile files with aliases to recognize the command you are entering.

.bashrc and .bash_profile files are hidden files probably located on your C: drive where you save your program files.

Gulp command not found after install

I realize that this is an old thread, but for Future-Me, and posterity, I figured I should add my two-cents around the "running npm as sudo" discussion. Disclaimer: I do not use Windows. These steps have only been proven on non-windows machines, both virtual and physical.

You can avoid the need to use sudo by changing the permission to npm's default directory.


How to: change permissions in order to run npm without sudo

Step 1: Find out where npm's default directory is.

  • To do this, open your terminal and run:
    npm config get prefix

Step 2: Proceed, based on the output of that command:

  • Scenario One: npm's default directory is /usr/local
    For most users, your output will show that npm's default directory is /usr/local, in which case you can skip to step 4 to update the permissions for the directory.
  • Scenario Two: npm's default directory is /usr or /Users/YOURUSERNAME/node_modules or /Something/Else/FishyLooking
    If you find that npm's default directory is not /usr/local, but is instead something you can't explain or looks fishy, you should go to step 3 to change the default directory for npm, or you risk messing up your permissions on a much larger scale.

Step 3: Change npm's default directory:

  • There are a couple of ways to go about this, including creating a directory specifically for global installations and then adding that directory to your $PATH, but since /usr/local is probably already in your path, I think it's simpler to just change npm's default directory to that. Like so: npm config set prefix /usr/local
    • For more info on the other approaches I mentioned, see the npm docs here.

Step 4: Update the permissions on npm's default directory:

  • Once you've verified that npm's default directory is in a sensible location, you can update the permissions on it using the command:
    sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

Now you should be able to run npm <whatever> without sudo. Note: You may need to restart your terminal in order for these changes to take effect.

When to use Task.Delay, when to use Thread.Sleep?

if the current thread is killed and you use Thread.Sleep and it is executing then you might get a ThreadAbortException. With Task.Delay you can always provide a cancellation token and gracefully kill it. Thats one reason I would choose Task.Delay. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspx

I also agree efficiency is not paramount in this case.

What rules does software version numbering follow?

The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:

  • Major version numbers change whenever there is some significant change being introduced. For example, a large or potentially backward-incompatible change to a software package.
  • Minor version numbers change when a new, minor feature is introduced or when a set of smaller features is rolled out.
  • Patch numbers change when a new build of the software is released to customers. This is normally for small bug-fixes or the like.

Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.

There are many variants to versioning. It all boils down to personal preference.

For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.

How to send a model in jQuery $.ajax() post request to MVC controller method

I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();

This post may be helpful. Post with jquery and ajax

Have a look at the doc here.. Ajax serialize

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

For those working with Criteria, I found that

criteria.setFetchMode("lazily_fetched_member", FetchMode.EAGER);

did everything I needed had done.

Initial fetch mode for collections is set to FetchMode.LAZY to provide performance, but when I need the data, I just add that line and enjoy the fully populated objects.

Converting dict to OrderedDict

If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:

from collections import OrderedDict

order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)

WiX tricks and tips

Editing Dialogs

One good ability to edit dialogs is using SharpDevelop in a version 4.0.1.7090 (or higher). With help of this tool a standalone dialog (wxs files from WiX sources like e.g. InstallDirDlg.wxs) can be opened, previewed and edited in Design view.

What is difference between functional and imperative programming languages?

Most modern languages are in varying degree both imperative and functional but to better understand functional programming, it will be best to take an example of pure functional language like Haskell in contrast of imperative code in not so functional language like java/C#. I believe it is always easy to explain by example, so below is one.

Functional programming: calculate factorial of n i.e n! i.e n x (n-1) x (n-2) x ...x 2 X 1

-- | Haskell comment goes like
-- | below 2 lines is code to calculate factorial and 3rd is it's execution  

factorial 0 = 1
factorial n = n * factorial (n - 1)
factorial 3

-- | for brevity let's call factorial as f; And x => y shows order execution left to right
-- | above executes as := f(3) as 3 x f(2) => f(2) as 2 x f(1) => f(1) as 1 x f(0) => f(0) as 1  
-- | 3 x (2 x (1 x (1)) = 6

Notice that Haskel allows function overloading to the level of argument value. Now below is example of imperative code in increasing degree of imperativeness:

//somewhat functional way
function factorial(n) {
  if(n < 1) {
     return 1;
  }
  return n * factorial(n-1);   
}
factorial(3);

//somewhat more imperative way
function imperativeFactor(n) {
  int f = 1;
  for(int i = 1; i <= n; i++) {
     f = f * i;
  }
  return f;
}

This read can be a good reference to understand that how imperative code focus more on how part, state of machine (i in for loop), order of execution, flow control.

The later example can be seen as java/C# lang code roughly and first part as limitation of the language itself in contrast of Haskell to overload the function by value (zero) and hence can be said it is not purist functional language, on the other hand you can say it support functional prog. to some extent.

Disclosure: none of the above code is tested/executed but hopefully should be good enough to convey the concept; also I would appreciate comments for any such correction :)

jQuery Validate Plugin - How to create a simple custom rule?

You can create a simple rule by doing something like this:

jQuery.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");

And then applying this like so:

$('validatorElement').validate({
    rules : {
        amount : { greaterThanZero : true }
    }
});

Just change the contents of the 'addMethod' to validate your checkboxes.

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

How to add certificate chain to keystore?

I solved the problem by cat'ing all the pems together:

cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD

(keytool didn't know what to do with a PKCS7 formatted key)

I got all the pems from letsencrypt

How to create NSIndexPath for TableView

Obligatory answer in Swift : NSIndexPath(forRow:row, inSection: section)

You will notice that NSIndexPath.indexPathForRow(row, inSection: section) is not available in swift and you must use the first method to construct the indexPath.

How may I reference the script tag that loaded the currently-executing script?

If you can assume the file name of the script, you can find it. I've only really tested the following function in Firefox so far.

  function findMe(tag, attr, file) {
    var tags = document.getElementsByTagName(tag);
    var r = new RegExp(file + '$');
    for (var i = 0;i < tags.length;i++) {
      if (r.exec(tags[i][attr])) {
        return tags[i][attr];
      }
    }
  };
  var element = findMe('script', 'src', 'scripts.js');

How to comment multiple lines with space or indent

  • You can customize every short cut operation according to your habbit.

Just go to Tools > Options > Environment > Keyboard > Find the action you want to set key board short-cut and change according to keyboard habbit.

Converting HTML string into DOM elements?

You can use a DOMParser, like so:

_x000D_
_x000D_
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";_x000D_
var doc = new DOMParser().parseFromString(xmlString, "text/xml");_x000D_
console.log(doc.firstChild.innerHTML); // => <a href="#">Link..._x000D_
console.log(doc.firstChild.firstChild.innerHTML); // => Link
_x000D_
_x000D_
_x000D_

What to do with "Unexpected indent" in python?

One issue which doesn't seem to have been mentioned is that this error can crop up due to a problem with the code that has nothing to do with indentation.

For example, take the following script:

def add_one(x):
    try:
        return x + 1
add_one(5)

This returns an IndentationError: unexpected unindent when the problem is of course a missing except: statement.

My point: check the code above where the unexpected (un)indent is reported!

JUnit test for System.out.println()

Instead of redirecting System.out, I would refactor the class that uses System.out.println() by passing a PrintStream as a collaborator and then using System.out in production and a Test Spy in the test. That is, use Dependency Injection to eliminate the direct use of the standard output stream.

In Production

ConsoleWriter writer = new ConsoleWriter(System.out));

In the Test

ByteArrayOutputStream outSpy = new ByteArrayOutputStream();
ConsoleWriter writer = new ConsoleWriter(new PrintStream(outSpy));
writer.printSomething();
assertThat(outSpy.toString(), is("expected output"));

Discussion

This way the class under test becomes testable by a simple refactoring, without having the need for indirect redirection of the standard output or obscure interception with a system rule.

How do I reference tables in Excel using VBA?

A "table" in Excel is indeed known as a ListObject.

The "proper" way to reference a table is by getting its ListObject from its Worksheet i.e. SheetObject.ListObjects(ListObjectName).

If you want to reference a table without using the sheet, you can use a hack Application.Range(ListObjectName).ListObject.

NOTE: This hack relies on the fact that Excel always creates a named range for the table's DataBodyRange with the same name as the table. However this range name can be changed...though it's not something you'd want to do since the name will reset if you edit the table name! Also you could get a named range with no associated ListObject.

Given Excel's not-very-helpful 1004 error message when you get the name wrong, you may want to create a wrapper...

Public Function GetListObject(ByVal ListObjectName As String, Optional ParentWorksheet As Worksheet = Nothing) As Excel.ListObject
On Error Resume Next

    If (Not ParentWorksheet Is Nothing) Then
        Set GetListObject = ParentWorksheet.ListObjects(ListObjectName)
    Else
        Set GetListObject = Application.Range(ListObjectName).ListObject
    End If

On Error GoTo 0 'Or your error handler

    If (Not GetListObject Is Nothing) Then
        'Success
    ElseIf (Not ParentWorksheet Is Nothing) Then
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found on sheet '" & ParentWorksheet.Name & "'!")
    Else
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found!")
    End If

End Function

Also some good ListObject info here.

JAXB: how to marshall map into <key>value</key>

I'm still working on a better solution but using MOXy JAXB, I've been able to handle the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <mapProperty>
      <map>
         <key>value</key>
         <key2>value2</key2>
      </map>
   </mapProperty>
</root>

You need to use an @XmlJavaTypeAdapter on your Map property:

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Map<String, String> mapProperty;

    public Root() {
        mapProperty = new HashMap<String, String>();
    }

    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, String> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, String> map) {
        this.mapProperty = map;
    }

}

The implementation of the XmlAdapter is as follows:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MapAdapter extends XmlAdapter<AdaptedMap, Map<String, String>> {

    @Override
    public AdaptedMap marshal(Map<String, String> map) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Element rootElement = document.createElement("map");
        document.appendChild(rootElement);

        for(Entry<String,String> entry : map.entrySet()) {
            Element mapElement = document.createElement(entry.getKey());
            mapElement.setTextContent(entry.getValue());
            rootElement.appendChild(mapElement);
        }

        AdaptedMap adaptedMap = new AdaptedMap();
        adaptedMap.setValue(document);
        return adaptedMap;
    }

    @Override
    public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Element rootElement = (Element) adaptedMap.getValue();
        NodeList childNodes = rootElement.getChildNodes();
        for(int x=0,size=childNodes.getLength(); x<size; x++) {
            Node childNode = childNodes.item(x);
            if(childNode.getNodeType() == Node.ELEMENT_NODE) {
                map.put(childNode.getLocalName(), childNode.getTextContent());
            }
        }
        return map;
    }

}

The AdpatedMap class is where all the magic happens, we will use a DOM to represent the content. We will trick JAXB intro dealing with a DOM through the combination of @XmlAnyElement and a property of type Object:

import javax.xml.bind.annotation.XmlAnyElement;

public class AdaptedMap {

    private Object value;

    @XmlAnyElement
    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

This solution requires the MOXy JAXB implementation. You can configure the JAXB runtime to use the MOXy implementation by adding a file named jaxb.properties in with your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

The following demo code can be used to verify the code:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(new File("src/forum74/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }
}

Toggle visibility property of div

There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.

Example:

function toggleVideo() {
     var e = document.getElementById('video-over');

     if(e.style.visibility == 'visible') {
          e.style.visibility = 'hidden';
     } else if(e.style.visibility == 'hidden') {
          e.style.visibility = 'visible';
     }
}

Element count of an array in C++

_countof(my_array) in MSVC

I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

Elements of an array in C++ are objects, not pointers, so you cannot have derived type object as an element.

And like mentioned above, sizeof(my_array) (like _countof() as well) will work just in the scope of array definition.

Can two Java methods have same name with different return types?

According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {
    public static void main(String... args) {
        Main.<Integer>print();
        Main.<Short>print();
        Main.<Byte>print();
        Main.<Void>print();
    }

    public static <T extends Integer> int print() {
        System.out.println("here - Integer");
        return 0;
    }
    public static <T extends Short> short print() {
        System.out.println("here - Short");
        return 0;
    }
    public static <T extends Byte> byte print() {
        System.out.println("here - Byte");
        return 0;
    }
    public static <T extends Void> void print() {
        System.out.println("here - Void");
    }
}

Prints

here - Integer
here - Short
here - Byte
here - Void

For more details, read my article here

How do I change the value of a global variable inside of a function

<script>
var x = 2; //X is global and value is 2.

function myFunction()
{
 x = 7; //x is local variable and value is 7.

}

myFunction();

alert(x); //x is gobal variable and the value is 7
</script>

Generate random string/characters in JavaScript

Another nice way to randomize a string from the characters A-Za-z0-9:

function randomString(length) {
    if ( length <= 0 ) return "";
    var getChunk = function(){
        var i, //index iterator
            rand = Math.random()*10e16, //execute random once
            bin = rand.toString(2).substr(2,10), //random binary sequence
            lcase = (rand.toString(36)+"0000000000").substr(0,10), //lower case random string
            ucase = lcase.toUpperCase(), //upper case random string
            a = [lcase,ucase], //position them in an array in index 0 and 1
            str = ""; //the chunk string
        b = rand.toString(2).substr(2,10);
        for ( i=0; i<10; i++ )
            str += a[bin[i]][i]; //gets the next character, depends on the bit in the same position as the character - that way it will decide what case to put next
        return str;
    },
    str = ""; //the result string
    while ( str.length < length  )
        str += getChunk();
    str = str.substr(0,length);
    return str;
}

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

How to mount the android img file under linux?

I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img files all the time.

Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount

"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...

So, how to get the file from the inside of userdata.img?" To load .img files you have to select loop and load the .img Select loop

Next you select mount Select mount

Furius ISO mount handles all the other options loading the .img file to your /home/dir.

Named parameters in JDBC

JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.

NamedParameterJDBCTemplate supports named parameters, you can use them like that:

 NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

 MapSqlParameterSource paramSource = new MapSqlParameterSource();
 paramSource.addValue("name", name);
 paramSource.addValue("city", city);
 jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);

Get current URL/URI without some of $_GET variables

Most of the answers are wrong.

The Question is to get url without some query param .

Here is the function that works. It does more things actually. You can remove the param that you don't want and you can add or modify an existing one.

/**
 * Function merges the query string values with the given array and returns the new URL
 * @param string $route
 * @param array $mergeQueryVars
 * @param array $removeQueryVars
 * @return string
 */
public static function getUpdatedUrl($route = '', $mergeQueryVars = [], $removeQueryVars = [])
{
    $currentParams = $request = Yii::$app->request->getQueryParams();

    foreach($mergeQueryVars as $key=> $value)
    {
        $currentParams[$key] = $value;
    }

    foreach($removeQueryVars as $queryVar)
    {
        unset($currentParams[$queryVar]);
    }

    $currentParams[0] = $route == '' ? Yii::$app->controller->getRoute() : $route;

    return Yii::$app->urlManager->createUrl($currentParams);

}

usage:

ClassName:: getUpdatedUrl('',[],['remove_this1','remove_this2'])

This will remove query params 'remove_this1' and 'remove_this2' from URL and return you the new URL

How do I pause my shell script for a second before continuing?

And what about:

read -p "Press enter to continue"

How to add soap header in java

i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.

Grep characters before and after match?

You can use regexp grep for finding + second grep for highlight

echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string

23_string_and

enter image description here

What is the easiest way to get current GMT time in Unix timestamp format?

Python 3 seconds with microsecond decimal resolution:

from datetime import datetime
print(datetime.now().timestamp())

Python 3 integer seconds:

print(int(datetime.now().timestamp()))

WARNING on datetime.utcnow().timestamp()!

datetime.utcnow() is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects

For something like 1am UTC:

from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())

or

print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())

if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!

What is the most efficient way to concatenate N arrays?

Shorten with ES6.

new Set([].concat(...Array));

This does concat and unique the multiple arrays;

Demo on codepen

How to safely call an async method in C# without await

The answer by Peter Ritchie was what I wanted, and Stephen Cleary's article about returning early in ASP.NET was very helpful.

As a more general problem however (not specific to an ASP.NET context) the following Console application demonstrates the usage and behavior of Peter's answer using Task.ContinueWith(...)

static void Main(string[] args)
{
  try
  {
    // output "hello world" as method returns early
    Console.WriteLine(GetStringData());
  }
  catch
  {
    // Exception is NOT caught here
  }
  Console.ReadLine();
}

public static string GetStringData()
{
  MyAsyncMethod().ContinueWith(OnMyAsyncMethodFailed, TaskContinuationOptions.OnlyOnFaulted);
  return "hello world";
}

public static async Task MyAsyncMethod()
{
  await Task.Run(() => { throw new Exception("thrown on background thread"); });
}

public static void OnMyAsyncMethodFailed(Task task)
{
  Exception ex = task.Exception;
  // Deal with exceptions here however you want
}

GetStringData() returns early without awaiting MyAsyncMethod() and exceptions thrown in MyAsyncMethod() are dealt with in OnMyAsyncMethodFailed(Task task) and not in the try/catch around GetStringData()

Getting a union of two arrays in JavaScript

_x000D_
_x000D_
function unique(arrayName)_x000D_
{_x000D_
  var newArray=new Array();_x000D_
  label: for(var i=0; i<arrayName.length;i++ )_x000D_
  {  _x000D_
    for(var j=0; j<newArray.length;j++ )_x000D_
    {_x000D_
      if(newArray[j]==arrayName[i]) _x000D_
        continue label;_x000D_
    }_x000D_
    newArray[newArray.length] = arrayName[i];_x000D_
  }_x000D_
  return newArray;_x000D_
}_x000D_
_x000D_
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);_x000D_
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);_x000D_
var union = unique(arr1.concat(arr2));_x000D_
console.log(union);
_x000D_
_x000D_
_x000D_

How to declare an array of objects in C#

With LINQ, you can transform the array of uninitialized elements into the new collection of created objects with one line of code.

var houses = new GameObject[200].Select(h => new GameObject()).ToArray();

Actually, you can use any other source for this, even generated sequence of integers:

var houses = Enumerable.Repeat(0, 200).Select(h => new GameObject()).ToArray();

However, the first case seems to me more readable, although the type of original sequence is not important.

How To fix white screen on app Start up?

White background is caused because of the Android starts while the app loads on memory, and it can be avoided if you just add this 2 line of code under SplashTheme.

<item name="android:windowDisablePreview">true</item>
<item name="android:windowIsTranslucent">true</item>

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.

See http://pypi.python.org/pypi/pep8

How do you test to see if a double is equal to NaN?

You might want to consider also checking if a value is finite via Double.isFinite(value). Since Java 8 there is a new method in Double class where you can check at once if a value is not NaN and infinity.

/**
 * Returns {@code true} if the argument is a finite floating-point
 * value; returns {@code false} otherwise (for NaN and infinity
 * arguments).
 *
 * @param d the {@code double} value to be tested
 * @return {@code true} if the argument is a finite
 * floating-point value, {@code false} otherwise.
 * @since 1.8
 */
public static boolean isFinite(double d)

Calling dynamic function with dynamic number of parameters

Now I'm using this:

Dialoglar.Confirm = function (_title, _question, callback_OK) {
    var confirmArguments = arguments;
    bootbox.dialog({
        title: "<b>" + _title + "</b>",
        message: _question,
        buttons: {
            success: {
                label: "OK",
                className: "btn-success",
                callback: function () {
                    if (typeof(callback_OK) == "function") {                            callback_OK.apply(this,Array.prototype.slice.call(confirmArguments, 3));
                    }
                }
            },
            danger: {
                label: "Cancel",
                className: "btn-danger",
                callback: function () {
                    $(this).hide();
                }
            }
        }
    });
};

How to add a custom right-click menu to a webpage?

A simple way you could do it is use onContextMenu to return a JavaScript function:

<input type="button" value="Example" onContextMenu="return RightClickFunction();">

<script>
 function RightClickFunction() {
  // Enter your code here;
  return false;
 }
</script>

And by entering return false; you will cancel out the context menu.

if you still want to display the context menu you can just remove the return false; line.

SQL: How to perform string does not equal

Another way of getting the results

SELECT * from table WHERE SUBSTRING(tester, 1, 8)  <> 'username' or tester is null

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

Can't concatenate 2 arrays in PHP

Try saying

$array[] = array('Item 2'); 

Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.

How to replace substrings in windows batch file

SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%

EDIT

Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.

Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:

@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
  SET "line=%%L"
  SETLOCAL ENABLEDELAYEDEXPANSION
  ECHO !line:bath=hello!
  ENDLOCAL
)
ENDLOCAL

You can add a redirection to a file:

  ECHO !line:bath=hello!>>file2.txt

Or you can apply the redirection to the batch file. It must be a different file.

EDIT 2

Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !, ^ et al. (Thanks, jeb!)

Eloquent Collection: Counting and Detect Empty

You can do

$result = Model::where(...)->count(); 

to count the results.

You can also use

if ($result->isEmpty()){}

to check whether or not the result is empty.

Create a new Ruby on Rails application using MySQL instead of SQLite

In Rails 3, you could do

$rails new projectname --database=mysql

How to write both h1 and h2 in the same line?

Put the h1 and h2 in a container with an id of container then:

#container {
    display: flex;
    justify-content: space-beteen;
}

How to perform a real time search and filter on a HTML table

you can use native javascript like this

_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
  var input, filter, table, tr, td, i;_x000D_
  input = document.getElementById("myInput");_x000D_
  filter = input.value.toUpperCase();_x000D_
  table = document.getElementById("myTable");_x000D_
  tr = table.getElementsByTagName("tr");_x000D_
  for (i = 0; i < tr.length; i++) {_x000D_
    td = tr[i].getElementsByTagName("td")[0];_x000D_
    if (td) {_x000D_
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {_x000D_
        tr[i].style.display = "";_x000D_
      } else {_x000D_
        tr[i].style.display = "none";_x000D_
      }_x000D_
    }       _x000D_
  }_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

To draw an Underline below the TextView in Android

If your TextView has fixed width, alternative solution can be to create a View which will look like an underline and position it right below your TextView.

<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent">

        <TextView
            android:id="@+id/myTextView"
            android:layout_width="20dp"
            android:layout_height="wrap_content"/>

        <View
            android:layout_width="20dp"
            android:layout_height="1dp"
            android:layout_below="@+id/myTextView"
            android:background="#CCCCCC"/>
</RelativeLayout>

Git Bash: Could not open a connection to your authentication agent

I checked all the solutions on this post and the post that @kenorb referenced above, and I did not find any solution that worked for me.

I am using Git 1.9.5 Preview on Windows 7 with the following configuration: - Run Git from the Windows Command Prompt - Checkout Windows-style, commit Unix-style line endings

I used the 'Git Bash' console for everything... And all was well until I tried to install the SSH keys. GitHub's documentation says to do the following (don't run these commands until you finish reading the post):

Ensure ssh-agent is enabled:

If you are using Git Bash, turn on ssh-agent:
# start the ssh-agent in the background
ssh-agent -s
# Agent pid 59566
If you are using another terminal prompt, such as msysgit, turn on ssh-agent:
# start the ssh-agent in the background
eval $(ssh-agent -s)
# Agent pid 59566

Now of course I missed the fact that you were supposed to do one or the other. So, I ran these commands multiple times because the later ssh-add command was failing, so I returned to this step, and continued to retry over and over.

This results in 1 Windows 'ssh-agent' process being created every single time you run these commands (notice the new PID every time you enter those commands?)

So, Ctrl+Alt+Del and hit End Process to stop each 'ssh-agent.exe' process.

Now that all the messed up stuff from the failed attempts is cleaned up, I will tell you how to get it working...

In 'Git Bash':

Start the 'ssh-agent.exe' process

eval $(ssh-agent -s)

And install the SSH keys

ssh-add "C:\Users\MyName\.ssh\id_rsa"

* Adjust the path above with your username, and make sure that the location of the* /.ssh directory is in the correct place. I think you choose this location during the Git installation? Maybe not...

The part I was doing wrong before I figured this out was I was not using quotes around the 'ssh-add' location. The above is how it needs to be entered on Windows.

How to disable 'X-Frame-Options' response header in Spring Security?

If using XML configuration you can use

<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:security="http://www.springframework.org/schema/security"> 
<security:http>
    <security:headers>
         <security:frame-options disabled="true"></security:frame-options>
    </security:headers>
</security:http>
</beans>

cannot redeclare block scoped variable (typescript)

The best explanation I could get is from Tamas Piro's post.

TLDR; TypeScript uses the DOM typings for the global execution environment. In your case there is a 'co' property on the global window object.

To solve this:

  1. Rename the variable, or
  2. Use TypeScript modules, and add an empty export{}:
export {};

or

  1. Configure your compiler options by not adding DOM typings:

Edit tsconfig.json in the TypeScript project directory.

{
    "compilerOptions": {
        "lib": ["es6"]
      }
}

Uncaught TypeError: Cannot read property 'top' of undefined

If this error appears whenever you click on the <a> tag. Try the code below.

CORRECT :

<a href="javascript:void(0)">

This malfunction occurs because your href is set to # inside of your <a> tag. Basically, your app is trying to find href which does not exist. The right way to set empty href is shown above.

WRONG :

<a href="#">

How do I get the information from a meta tag with JavaScript?

My variant of the function:

const getMetaValue = (name) => {
  const element = document.querySelector(`meta[name="${name}"]`)
  return element?.getAttribute('content')
}

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

How to access property of anonymous type in C#?

The accepted answer correctly describes how the list should be declared and is highly recommended for most scenarios.

But I came across a different scenario, which also covers the question asked. What if you have to use an existing object list, like ViewData["htmlAttributes"] in MVC? How can you access its properties (they are usually created via new { @style="width: 100px", ... })?

For this slightly different scenario I want to share with you what I found out. In the solutions below, I am assuming the following declaration for nodes:

List<object> nodes = new List<object>();

nodes.Add(
new
{
    Checked = false,
    depth = 1,
    id = "div_1" 
});

1. Solution with dynamic

In C# 4.0 and higher versions, you can simply cast to dynamic and write:

if (nodes.Any(n => ((dynamic)n).Checked == false))
    Console.WriteLine("found a  not checked  element!");

Note: This is using late binding, which means it will recognize only at runtime if the object doesn't have a Checked property and throws a RuntimeBinderException in this case - so if you try to use a non-existing Checked2 property you would get the following message at runtime: "'<>f__AnonymousType0<bool,int,string>' does not contain a definition for 'Checked2'".

2. Solution with reflection

The solution with reflection works both with old and new C# compiler versions. For old C# versions please regard the hint at the end of this answer.

Background

As a starting point, I found a good answer here. The idea is to convert the anonymous data type into a dictionary by using reflection. The dictionary makes it easy to access the properties, since their names are stored as keys (you can access them like myDict["myProperty"]).

Inspired by the code in the link above, I created an extension class providing GetProp, UnanonymizeProperties and UnanonymizeListItems as extension methods, which simplify access to anonymous properties. With this class you can simply do the query as follows:

if (nodes.UnanonymizeListItems().Any(n => (bool)n["Checked"] == false))
{
    Console.WriteLine("found a  not checked  element!");
}

or you can use the expression nodes.UnanonymizeListItems(x => (bool)x["Checked"] == false).Any() as if condition, which filters implicitly and then checks if there are any elements returned.

To get the first object containing "Checked" property and return its property "depth", you can use:

var depth = nodes.UnanonymizeListItems()
             ?.FirstOrDefault(n => n.Contains("Checked")).GetProp("depth");

or shorter: nodes.UnanonymizeListItems()?.FirstOrDefault(n => n.Contains("Checked"))?["depth"];

Note: If you have a list of objects which don't necessarily contain all properties (for example, some do not contain the "Checked" property), and you still want to build up a query based on "Checked" values, you can do this:

if (nodes.UnanonymizeListItems(x => { var y = ((bool?)x.GetProp("Checked", true)); 
                                      return y.HasValue && y.Value == false;}).Any())
{
    Console.WriteLine("found a  not checked   element!");
}

This prevents, that a KeyNotFoundException occurs if the "Checked" property does not exist.


The class below contains the following extension methods:

  • UnanonymizeProperties: Is used to de-anonymize the properties contained in an object. This method uses reflection. It converts the object into a dictionary containing the properties and its values.
  • UnanonymizeListItems: Is used to convert a list of objects into a list of dictionaries containing the properties. It may optionally contain a lambda expression to filter beforehand.
  • GetProp: Is used to return a single value matching the given property name. Allows to treat not-existing properties as null values (true) rather than as KeyNotFoundException (false)

For the examples above, all that is required is that you add the extension class below:

public static class AnonymousTypeExtensions
{
    // makes properties of object accessible 
    public static IDictionary UnanonymizeProperties(this object obj)
    {
        Type type = obj?.GetType();
        var properties = type?.GetProperties()
               ?.Select(n => n.Name)
               ?.ToDictionary(k => k, k => type.GetProperty(k).GetValue(obj, null));
        return properties;
    }
    
    // converts object list into list of properties that meet the filterCriteria
    public static List<IDictionary> UnanonymizeListItems(this List<object> objectList, 
                    Func<IDictionary<string, object>, bool> filterCriteria=default)
    {
        var accessibleList = new List<IDictionary>();
        foreach (object obj in objectList)
        {
            var props = obj.UnanonymizeProperties();
            if (filterCriteria == default
               || filterCriteria((IDictionary<string, object>)props) == true)
            { accessibleList.Add(props); }
        }
        return accessibleList;
    }

    // returns specific property, i.e. obj.GetProp(propertyName)
    // requires prior usage of AccessListItems and selection of one element, because
    // object needs to be a IDictionary<string, object>
    public static object GetProp(this object obj, string propertyName, 
                                 bool treatNotFoundAsNull = false)
    {
        try 
        {
            return ((System.Collections.Generic.IDictionary<string, object>)obj)
                   ?[propertyName];
        }
        catch (KeyNotFoundException)
        {
            if (treatNotFoundAsNull) return default(object); else throw;
        }
    }
}

Hint: The code above is using the null-conditional operators, available since C# version 6.0 - if you're working with older C# compilers (e.g. C# 3.0), simply replace ?. by . and ?[ by [ everywhere (and do the null-handling traditionally by using if statements or catch NullReferenceExceptions), e.g.

var depth = nodes.UnanonymizeListItems()
            .FirstOrDefault(n => n.Contains("Checked"))["depth"];

As you can see, the null-handling without the null-conditional operators would be cumbersome here, because everywhere you removed them you have to add a null check - or use catch statements where it is not so easy to find the root cause of the exception resulting in much more - and hard to read - code.

If you're not forced to use an older C# compiler, keep it as is, because using null-conditionals makes null handling much easier.

Note: Like the other solution with dynamic, this solution is also using late binding, but in this case you're not getting an exception - it will simply not find the element if you're referring to a non-existing property, as long as you keep the null-conditional operators.

What might be useful for some applications is that the property is referred to via a string in solution 2, hence it can be parameterized.

How to stop console from closing on exit?

Yes, in VS2010 they changed this behavior somewhy.
Open your project and navigate to the following menu: Project -> YourProjectName Properties -> Configuration Properties -> Linker -> System. There in the field SubSystem use the drop-down to select Console (/SUBSYSTEM:CONSOLE) and apply the change.
"Start without debugging" should do the right thing now.

Or, if you write in C++ or in C, put

system("pause");

at the end of your program, then you'll get "Press any key to continue..." even when running in debug mode.

How to find length of digits in an integer?

Format in scientific notation and pluck off the exponent:

int("{:.5e}".format(1000000).split("e")[1]) + 1

I don't know about speed, but it's simple.

Please note the number of significant digits after the decimal (the "5" in the ".5e" can be an issue if it rounds up the decimal part of the scientific notation to another digit. I set it arbitrarily large, but could reflect the length of the largest number you know about.

Isn't the size of character in Java 2 bytes?

In ASCII text file each character is just one byte

How to enter newline character in Oracle?

Chr(Number) should work for you.

select 'Hello' || chr(10) ||' world' from dual

Remember different platforms expect different new line characters:

  • CHR(10) => LF, line feed (unix)
  • CHR(13) => CR, carriage return (windows, together with LF)

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

If you are not using the assembly directly in code then Visual Studio whilst trying to be helpful detects that it is not used and doesn't include it in the output. I'm not sure why you are seeing different behaviour between Visual Studio and MSBuild. You could try setting the build output to diagnostic for both and compare the results see where it diverges.

As for your elmah.dll reference if you are not referencing it directly in code you could add it as an item to your project and set the Build Action to Content and the Copy to Output Directory to Always.

How to print an exception in Python 3?

I've use this :

except (socket.timeout, KeyboardInterrupt) as e:
    logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
    break

Let me know if it does not work for you !!

How can I show an element that has display: none in a CSS rule?

Because setting the div's display style property to "" doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.

You need to set it to something that has a value:

document.getElementById('mybox').style.display = "block";

What you're doing would work if you were replacing an inline style on the div, like this:

<div id="myBox" style="display: none;"></div>

document.getElementById('mybox').style.display = "";

Finalize vs Dispose

The main difference between Dispose and Finalize is that:

Dispose is usually called by your code. The resources are freed instantly when you call it. People forget to call the method, so using() {} statement is invented. When your program finishes the execution of the code inside the {}, it will call Dispose method automatically.

Finalize is not called by your code. It is mean to be called by the Garbage Collector (GC). That means the resource might be freed anytime in future whenever GC decides to do so. When GC does its work, it will go through many Finalize methods. If you have heavy logic in this, it will make the process slow. It may cause performance issues for your program. So be careful about what you put in there.

I personally would write most of the destruction logic in Dispose. Hopefully, this clears up the confusion.

Javascript - validation, numbers only

// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:

$(document).ready(function () {
       $(".nosonly").keydown(function (event) {
           // Allow only backspace and delete
           if (event.keyCode == 46 || event.keyCode == 8) {
               // let it happen, don't do anything
           }
           else {
               // Ensure that it is a number and stop the keypress
               if (event.keyCode < 48 || event.keyCode > 57) {
              alert("Only Numbers Allowed"),event.preventDefault();
               }
           }
       });
   });

How to determine if a point is in a 2D triangle?

bool point2Dtriangle(double e,double f, double a,double b,double c, double g,double h,double i, double v, double w){
    /* inputs: e=point.x, f=point.y
               a=triangle.Ax, b=triangle.Bx, c=triangle.Cx 
               g=triangle.Ay, h=triangle.By, i=triangle.Cy */
    v = 1 - (f * (b - c) + h * (c - e) + i * (e - b)) / (g * (b - c) + h * (c - a) + i * (a - b));
    w = (f * (a - b) + g * (b - e) + h * (e - a)) / (g * (b - c) + h * (c - a) + i * (a - b));
    if (*v > -0.0 && *v < 1.0000001 && *w > -0.0 && *w < *v) return true;//is inside
    else return false;//is outside
    return 0;
} 

almost perfect Cartesian coordinates converted from barycentric are exported within *v (x) and *w (y) doubles. Both export doubles should have a * char before in every case, likely: *v and *w Code can be used for the other triangle of a quadrangle too. Hereby signed wrote only triangle abc from the clockwise abcd quad.

A---B
|..\\.o|  
|....\\.| 
D---C 

the o point is inside ABC triangle for testing with with second triangle call this function CDA direction, and results should be correct after *v=1-*v; and *w=1-*w; for the quadrangle

css rotate a pseudo :after or :before content:""

.process-list:after{
    content: "\2191";
    position: absolute;
    top:50%;
    right:-8px;
    background-color: #ea1f41;
    width:35px;
    height: 35px;
    border:2px solid #ffffff;
    border-radius: 5px;
    color: #ffffff;
    z-index: 10000;
    -webkit-transform: rotate(50deg) translateY(-50%);
    -moz-transform: rotate(50deg) translateY(-50%);
    -ms-transform: rotate(50deg) translateY(-50%);
    -o-transform: rotate(50deg) translateY(-50%);
    transform: rotate(50deg) translateY(-50%);
}

you can check this code . i hope you will easily understand.

convert '1' to '0001' in JavaScript

String.prototype.padZero= function(len, c){
    var s= this, c= c || '0';
    while(s.length< len) s= c+ s;
    return s;
}

dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.

Search and replace part of string in database

update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')

and you do it in a single pass.

What is a MIME type?

I couldn't possibly explain it better than wikipedia does: http://en.wikipedia.org/wiki/MIME_type

In addition to e-mail applications, Web browsers also support various MIME types. This enables the browser to display or output files that are not in HTML format.

IOW, it helps the browser (or content consumer, because it may not just be a browser) determine what content they are about to consume; this means a browser may be able to make a decision on the correct plugin to use to display content, or a media player may be able to load up the correct codec or plugin.

Printing Even and Odd using two Threads in Java

   private Object lock = new Object();
   private volatile boolean isOdd = false;


    public void generateEvenNumbers(int number) throws InterruptedException {

        synchronized (lock) {
            while (isOdd == false) 
            {
                lock.wait();
            }
            System.out.println(number);
            isOdd = false;
            lock.notifyAll();
        }
    }

    public void generateOddNumbers(int number) throws InterruptedException {

        synchronized (lock) {
            while (isOdd == true) {
                lock.wait();
            }
            System.out.println(number);
            isOdd = true;
            lock.notifyAll();
        }
    }

Node.js: get path from the request

simply call req.url. that should do the work. you'll get something like /something?bla=foo

Server unable to read htaccess file, denying access to be safe

Just my solution. I had extracted a file, had some minor changes, and got the error above. Deleted everything, uploaded and extracted again, and normal business.

How to find out what type of a Mat object is with Mat::type() in OpenCV

For debugging purposes in case you want to look up a raw Mat::type in a debugger:

+--------+----+----+----+----+------+------+------+------+
|        | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) |
+--------+----+----+----+----+------+------+------+------+
| CV_8U  |  0 |  8 | 16 | 24 |   32 |   40 |   48 |   56 |
| CV_8S  |  1 |  9 | 17 | 25 |   33 |   41 |   49 |   57 |
| CV_16U |  2 | 10 | 18 | 26 |   34 |   42 |   50 |   58 |
| CV_16S |  3 | 11 | 19 | 27 |   35 |   43 |   51 |   59 |
| CV_32S |  4 | 12 | 20 | 28 |   36 |   44 |   52 |   60 |
| CV_32F |  5 | 13 | 21 | 29 |   37 |   45 |   53 |   61 |
| CV_64F |  6 | 14 | 22 | 30 |   38 |   46 |   54 |   62 |
+--------+----+----+----+----+------+------+------+------+

So for example, if type = 30 then OpenCV data type is CV_64FC4. If type = 50 then the OpenCV data type is CV_16UC(7).

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Try without command mvn in the command line. Example:

From:

mvn clean install jetty:run

To:

clean install jetty:run

Vue v-on:click does not work on component

If you want to listen to a native event on the root element of a component, you have to use the .native modifier for v-on, like following:

<template>
  <div id="app">
    <test v-on:click.native="testFunction"></test>
  </div>
</template>

or in shorthand, as suggested in comment, you can as well do:

<template>
  <div id="app">
    <test @click.native="testFunction"></test>
  </div>
</template>

How to turn off Wifi via ADB?

Simple way to switch wifi on non-rooted devices is to use simple app:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        try {
            wfm.setWifiEnabled(Boolean.parseBoolean(getIntent().getStringExtra("wifi")));
        } catch (Exception e) {
        }
        System.exit(0);
    }
}

AndroidManifest.xml:

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

ADB commands:

$ adb shell am start -n org.mytools.config/.MainActivity -e wifi true
$ adb shell am start -n org.mytools.config/.MainActivity -e wifi false

Oracle SQL update based on subquery between two tables

Without examples of the dataset of staging this is a shot in the dark, but have you tried something like this?

update PRODUCTION p,
       staging s
set p.name = s.name  
    p.count = s.count
where p.id = s.id

This would work assuming the id column matches on both tables.

AngularJS Folder Structure

I'm on my third angularjs app and the folder structure has improved every time so far. I keep mine simple right now.

index.html (or .php)
/resources
  /css
  /fonts
  /images
  /js
    /controllers
    /directives
    /filters
    /services
  /partials (views)

I find that good for single apps. I haven't really had a project yet where I'd need multiple.

Valid characters of a hostname?

If you're registering a domain and the termination (ex .com) it is not IDN, as Aaron Hathaway said: Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a through z (in a case-insensitive manner), the digits 0 through 9, and the hyphen -. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

Later, Spain with it's .es, .com.es, .org.es, .nom,es, .gob.es and .edu.es introduced IDN tlds, if your tld is one of .es or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.

If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.

Keep in mind some programs could not work well, especially old, outdated and unpopular ones.

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

state machines tutorials

Unfortunately, most of the articles on state machines are written for C++ or other languages that have direct support for polymorphism as it's nice to model the states in an FSM implementation as classes that derive from an abstract state class.

However, it's pretty easy to implement state machines in C using either switch statements to dispatch events to states (for simple FSMs, they pretty much code right up) or using tables to map events to state transitions.

There are a couple of simple, but decent articles on a basic framework for state machines in C here:

Edit: Site "under maintenance", web archive links:

switch statement-based state machines often use a set of macros to 'hide' the mechanics of the switch statement (or use a set of if/then/else statements instead of a switch) and make what amounts to a "FSM language" for describing the state machine in C source. I personally prefer the table-based approach, but these certainly have merit, are widely used, and can be effective especially for simpler FSMs.

One such framework is outlined by Steve Rabin in "Game Programming Gems" Chapter 3.0 (Designing a General Robust AI Engine).

A similar set of macros is discussed here:

If you're also interested in C++ state machine implementations there's a lot more that can be found. I'll post pointers if you're interested.

Instance member cannot be used on type

Sometimes Xcode when overrides methods adds class func instead of just func. Then in static method you can't see instance properties. It is very easy to overlook it. That was my case.

enter image description here

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will not "grayout" the textbox and will still submit the value on a postback.

Common Header / Footer with static HTML

The only way to include another file with just static HTML is an iframe. I wouldn't consider it a very good solution for headers and footers. If your server doesn't support PHP or SSI for some bizarre reason, you could use PHP and preprocess it locally before upload. I would consider that a better solution than iframes.