Programs & Examples On #Webforms routing

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

How to import Angular Material in project?

Install & Add Material to Angular Projects

There is an automatic/easy way of adding Material to Angular Projects. Use the Angular CLI's install schematic to set up your Angular Material project by running the following command:

ng add @angular/material

The ng add command will additionally perform the following configurations:

  • Add project dependencies to package.json
  • Add the Roboto font to your index.html
  • Add the Material Design icon font to your index.html
  • Add a few global CSS styles to:
    • Remove margins from body
    • Set height: 100% on html and body
    • Set Roboto as the default application font

You're done! Angular Material is now configured to be used in your application.

Read more about this here

How do I find the install time and date of Windows?

Try this powershell command:

Get-ChildItem -Path HKLM:\System\Setup\Source* | 
 ForEach-Object {Get-ItemProperty -Path Registry::$_} | 
     Select-Object ProductName, ReleaseID, CurrentBuild, @{n="Install Date"; e={([DateTime]'1/1/1970').AddSeconds($_.InstallDate)}} | 
         Sort-Object "Install Date"

Format date to MM/dd/yyyy in JavaScript

ISO compliant dateString

If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:

const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString);                 // {object Date}

from here you can extract the desired values by using Date Getters:

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Non-standard date string

If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);

// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s);  // {object Date}


D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

How do shift operators work in Java?

Right and Left shift work on same way here is How Right Shift works; The Right Shift: The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its general form:

value >> num

Here, num specifies the number of positions to right-shift the value in value. That is, the >> moves all of the bits in the specified value to the right the number of bit positions specified by num. The following code fragment shifts the value 32 to the right by two positions, resulting in a being set to 8:

int a = 32;
a = a >> 2; // a now contains 8

When a value has bits that are “shifted off,” those bits are lost. For example, the next code fragment shifts the value 35 to the right two positions, which causes the two low-order bits to be lost, resulting again in a being set to 8.

int a = 35;
a = a >> 2; // a still contains 8

Looking at the same operation in binary shows more clearly how this happens:

00100011 35 >> 2
00001000 8

Each time you shift a value to the right, it divides that value by two—and discards any remainder. You can take advantage of this for high-performance integer division by 2. Of course, you must be sure that you are not shifting any bits off the right end. When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with the previous contents of the top bit. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right. For example, –8 >> 1 is –4, which, in binary, is

11111000 –8 >>1
11111100 –4

It is interesting to note that if you shift –1 right, the result always remains –1, since sign extension keeps bringing in more ones in the high-order bits. Sometimes it is not desirable to sign-extend values when you are shifting them to the right. For example, the following program converts a byte value to its hexadecimal string representation. Notice that the shifted value is masked by ANDing it with 0x0f to discard any sign-extended bits so that the value can be used as an index into the array of hexadecimal characters.

// Masking sign extension.
class HexByte {
  static public void main(String args[]) {
    char hex[] = {
      '0', '1', '2', '3', '4', '5', '6', '7',
      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
  byte b = (byte) 0xf1;
 System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
}
}

Here is the output of this program:

b = 0xf1

Save child objects automatically using JPA Hibernate

I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?

Well, there are two things here.

First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)

Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChildren(children);

session.save(parent);

A common pattern is to use link management methods:

@Entity
public class Parent {
    @Id private Long id;

    @OneToMany(mappedBy="parent")
    private List<Child> children = new ArrayList<Child>();

    ...

    protected void setChildren(List<Child> children) {
        this.children = children;
    }

    public void addToChildren(Child child) {
        child.setParent(this);
        this.children.add(child);
    }
}

And the code becomes:

Parent parent = new Parent();
...
Child c1 = new Child();
...

parent.addToChildren(c1);

session.save(parent);
References

file_get_contents() Breaks Up UTF-8 Characters

Exemple :

$string = file_get_contents(".../File.txt");
$string = mb_convert_encoding($string, 'UTF-8', "ISO-8859-1");
echo $string;

SQL Server: Maximum character length of object names

Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.

And the verification can be easily made with the following script contained in the blog post before:

DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)

Java Multithreading concept and join() method

My Comments:

When I see the output, the output is mixed with One, Two, Three which are the thread names and they run simultaneously. I am not sure when you say thread is not running by main method.

Not sure if I understood your question or not. But I m putting my answer what I could understand, hope it can help you.

1) Then you created the object, it called the constructor, in construct it has start method which started the thread and executed the contents written inside run() method.

So as you created 3 objects (3 threads - one, two, three), all 3 threads started executing simultaneously.

2) Join and Synchronization They are 2 different things, Synchronization is when there are multiple threads sharing a common resource and one thread should use that resource at a time. E.g. Threads such as DepositThread, WithdrawThread etc. do share a common object as BankObject. So while DepositThread is running, the WithdrawThread will wait if they are synchronized. wait(), notify(), notifyAll() are used for inter-thread communication. Plz google to know more.

about Join(), it is when multiple threads are running, but you join. e.g. if there are two thread t1 and t2 and in multi-thread env they run, the output would be: t1-0 t2-0 t1-1 t2-1 t1-2 t2-2

and we use t1.join(), it would be: t1-0 t1-1 t1-2 t2-0 t2-1 t2-2

This is used in realtime when sometimes you don't mix up the thread in certain conditions and one depends another to be completed (not in shared resource), so you can call the join() method.

How to add an image to the "drawable" folder in Android Studio?

Adding images to the drawable folder is pretty simple. Just follow these steps:

  1. Download the required image and save it on desktop.
  2. Now, go to Android Studio and right click on drawable inside res.
  3. On right clicking you will see 'Show in Explorer' or 'Reveal in Finder'.
  4. Click on 'Show in Explorer' or 'Reveal in Finder' and then drag or simply copy your downloaded image into drawable folder.

Your image will be saved inside drawable and you can use it.

Converting String to Int with Swift

Because a string might contain non-numerical characters you should use a guard to protect the operation. Example:

guard let labelInt:Int = Int(labelString) else {
    return
}

useLabelInt()

Integrating Dropzone.js into existing HTML form with other fields

I had the exact same problem and found that Varan Sinayee's answer was the only one that actually solved the original question. That answer can be simplified though, so here's a simpler version.

The steps are:

  1. Create a normal form (don't forget the method and enctype args since this is not handled by dropzone anymore).

  2. Put a div inside with the class="dropzone" (that's how Dropzone attaches to it) and id="yourDropzoneName" (used to change the options).

  3. Set Dropzone's options, to set the url where the form and files will be posted, deactivate autoProcessQueue (so it only happens when user presses 'submit') and allow multiple uploads (if you need it).

  4. Set the init function to use Dropzone instead of the default behavior when the submit button is clicked.

  5. Still in the init function, use the "sendingmultiple" event handler to send the form data along wih the files.

Voilà ! You can now retrieve the data like you would with a normal form, in $_POST and $_FILES (in the example this would happen in upload.php)

HTML

<form action="upload.php" enctype="multipart/form-data" method="POST">
    <input type="text" id ="firstname" name ="firstname" />
    <input type="text" id ="lastname" name ="lastname" />
    <div class="dropzone" id="myDropzone"></div>
    <button type="submit" id="submit-all"> upload </button>
</form>

JS

Dropzone.options.myDropzone= {
    url: 'upload.php',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 5,
    maxFiles: 5,
    maxFilesize: 1,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sendingmultiple", function(data, xhr, formData) {
            formData.append("firstname", jQuery("#firstname").val());
            formData.append("lastname", jQuery("#lastname").val());
        });
    }
}

Using if elif fi in shell scripts

Use double brackets...

if [[ expression ]]

How to generate a random number in C++?

Whenever you do a basic web search for random number generation in the C++ programming language this question is usually the first to pop up! I want to throw my hat into the ring to hopefully better clarify the concept of pseudo-random number generation in C++ for future coders that will inevitably search this same question on the web!

The Basics

Pseudo-random number generation involves the process of utilizing a deterministic algorithm that produces a sequence of numbers whose properties approximately resemble random numbers. I say approximately resemble, because true randomness is a rather elusive mystery in mathematics and computer science. Hence, why the term pseudo-random is utilized to be more pedantically correct!

Before you can actually use a PRNG, i.e., pseudo-random number generator, you must provide the algorithm with an initial value often referred too as the seed. However, the seed must only be set once before using the algorithm itself!

/// Proper way!
seed( 1234 ) /// Seed set only once...
for( x in range( 0, 10) ):
  PRNG( seed ) /// Will work as expected

/// Wrong way!
for( x in rang( 0, 10 ) ):
  seed( 1234 ) /// Seed reset for ten iterations!
  PRNG( seed ) /// Output will be the same...

Thus, if you want a good sequence of numbers, then you must provide an ample seed to the PRNG!

The Old C Way

The backwards compatible standard library of C that C++ has, uses what is called a linear congruential generator found in the cstdlib header file! This PRNG functions through a discontinuous piecewise function that utilizes modular arithmetic, i.e., a quick algorithm that likes to use the modulo operator '%'. The following is common usage of this PRNG, with regards to the original question asked by @Predictability:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main( void )
{
  int low_dist  = 1;
  int high_dist = 6;
  std::srand( ( unsigned int )std::time( nullptr ) );
  for( int repetition = 0; repetition < 10; ++repetition )
    std::cout << low_dist + std::rand() % ( high_dist - low_dist ) << std::endl;
  return 0;
}

The common usage of C's PRNG houses a whole host of issues such as:

  1. The overall interface of std::rand() isn't very intuitive for the proper generation of pseudo-random numbers between a given range, e.g., producing numbers between [1, 6] the way @Predictability wanted.
  2. The common usage of std::rand() eliminates the possibility of a uniform distribution of pseudo-random numbers, because of the Pigeonhole Principle.
  3. The common way std::rand() gets seeded through std::srand( ( unsigned int )std::time( nullptr ) ) technically isn't correct, because time_t is considered to be a restricted type. Therefore, the conversion from time_t to unsigned int is not guaranteed!

For more detailed information about the overall issues of using C's PRNG, and how to possibly circumvent them, please refer to Using rand() (C/C++): Advice for the C standard library’s rand() function!

The Standard C++ Way

Since the ISO/IEC 14882:2011 standard was published, i.e., C++11, the random library has been apart of the C++ programming language for a while now. This library comes equipped with multiple PRNGs, and different distribution types such as: uniform distribution, normal distribution, binomial distribution, etc. The following source code example demonstrates a very basic usage of the random library, with regards to @Predictability's original question:

#include <iostream>
#include <cctype>
#include <random>

using u32    = uint_least32_t; 
using engine = std::mt19937;

int main( void )
{
  std::random_device os_seed;
  const u32 seed = os_seed();

  engine generator( seed );
  std::uniform_int_distribution< u32 > distribute( 1, 6 );

  for( int repetition = 0; repetition < 10; ++repetition )
    std::cout << distribute( generator ) << std::endl;
  return 0;
}

The 32-bit Mersenne Twister engine, with a uniform distribution of integer values was utilized in the above example. (The name of the engine in source code sounds weird, because its name comes from its period of 2^19937-1 ). The example also uses std::random_device to seed the engine, which obtains its value from the operating system (If you are using a Linux system, then std::random_device returns a value from /dev/urandom).

Take note, that you do not have to use std::random_device to seed any engine. You can use constants or even the chrono library! You also don't have to use the 32-bit version of the std::mt19937 engine, there are other options! For more information about the capabilities of the random library, please refer to cplusplus.com

All in all, C++ programmers should not use std::rand() anymore, not because its bad, but because the current standard provides better alternatives that are more straight forward and reliable. Hopefully, many of you find this helpful, especially those of you who recently web searched generating random numbers in c++!

How to create a sticky footer that plays well with Bootstrap 3

easily set

position:absolute;
bottom:0;
width:100%;

to your .footer

just do it

Raise warning in Python without interrupting program

You shouldn't raise the warning, you should be using warnings module. By raising it you're generating error, rather than warning.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

In Alamofire 4 it is important to add the body data before you add the file data!

let parameters = [String: String]()
[...]
self.manager.upload(
    multipartFormData: { multipartFormData in
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: .utf8)!, withName: key)
        }
        multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")
    },
    to: path,
    [...]
)

How to shrink/purge ibdata1 file in MySQL

That ibdata1 isn't shrinking is a particularly annoying feature of MySQL. The ibdata1 file can't actually be shrunk unless you delete all databases, remove the files and reload a dump.

But you can configure MySQL so that each table, including its indexes, is stored as a separate file. In that way ibdata1 will not grow as large. According to Bill Karwin's comment this is enabled by default as of version 5.6.6 of MySQL.

It was a while ago I did this. However, to setup your server to use separate files for each table you need to change my.cnf in order to enable this:

[mysqld]
innodb_file_per_table=1

https://dev.mysql.com/doc/refman/5.6/en/innodb-file-per-table-tablespaces.html

As you want to reclaim the space from ibdata1 you actually have to delete the file:

  1. Do a mysqldump of all databases, procedures, triggers etc except the mysql and performance_schema databases
  2. Drop all databases except the above 2 databases
  3. Stop mysql
  4. Delete ibdata1 and ib_log files
  5. Start mysql
  6. Restore from dump

When you start MySQL in step 5 the ibdata1 and ib_log files will be recreated.

Now you're fit to go. When you create a new database for analysis, the tables will be located in separate ibd* files, not in ibdata1. As you usually drop the database soon after, the ibd* files will be deleted.

http://dev.mysql.com/doc/refman/5.1/en/drop-database.html

You have probably seen this:
http://bugs.mysql.com/bug.php?id=1341

By using the command ALTER TABLE <tablename> ENGINE=innodb or OPTIMIZE TABLE <tablename> one can extract data and index pages from ibdata1 to separate files. However, ibdata1 will not shrink unless you do the steps above.

Regarding the information_schema, that is not necessary nor possible to drop. It is in fact just a bunch of read-only views, not tables. And there are no files associated with the them, not even a database directory. The informations_schema is using the memory db-engine and is dropped and regenerated upon stop/restart of mysqld. See https://dev.mysql.com/doc/refman/5.7/en/information-schema.html.

What are the differences among grep, awk & sed?

Short definition:

grep: search for specific terms in a file

#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"

$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"

Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

awk is mostly used for data extraction and reporting. sed is a stream editor
Each one of them has its own functionality and specialties.

Example
Sed

$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'

Awk

$ awk '{print $2}' file.txt
# this will print the second column of file.txt

Basic awk usage:
Compute sum/average/max/min/etc. what ever you may need.

$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average:    30

I recommend that you read this book: Sed & Awk: 2nd Ed.

It will help you become a proficient sed/awk user on any unix-like environment.

Convert Python program to C/C++ code?

Just came across this new tool in hacker news.

From their page - "Nuitka is a good replacement for the Python interpreter and compiles every construct that CPython 2.6, 2.7, 3.2 and 3.3 offer. It translates the Python into a C++ program that then uses "libpython" to execute in the same way as CPython does, in a very compatible way."

$('body').on('click', '.anything', function(){})

You should use $(document). It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction), where the second argument specifies which specific element to target. In this case every element inside the body.

$(document).on('click','body *',function(){
    //  $(this) = your current element that clicked.
    // additional code
});

Safely turning a JSON string into an object

Just for fun, here is a way using a function:

 jsonObject = (new Function('return ' + jsonFormatData))()

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Try this:

var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";

ctx.Database.ExecuteSqlCommand(
    sql,
    new SqlParameter("@FirstName", firstname),
    new SqlParameter("@Id", id));

How to return a string from a C++ function?

string str1, str2, str3;

cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;

From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;

how to mysqldump remote db from local machine

One can invoke mysqldump locally against a remote server.

Example that worked for me:

mysqldump -h hostname-of-the-server -u mysql_user -p database_name > file.sql

I followed the mysqldump documentation on connection options.

CSS text-overflow: ellipsis; not working?

I have been having this problem and I wanted a solution that could easily work with dynamic widths. The solution use css grid. This is how the code looks like:

// css 
.parent{
      display: grid; 
      grid-template-columns: auto 1fr;
}      
.dynamic-width-child{
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
}
.fixed-width-child{
      white-space: nowrap;
}

.

// html
<div class="parent">
  <div class="dynamic-width-child">
    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii asdfhlhlafh;lshd;flhsd;lhfaaaaaaaaaaaaaaaaaaaa
  </div>
  <div class="fixed-width-child">Why?-Zed</div>

Android Studio - Unable to find valid certification path to requested target

I faced similar error after upgrading to Android Studio 3.1.2 with gradle 4.4 & plugin 3.1.2, then tried almost all of the above solutions with generating the same error again & again.

Invalidate Caches / Restart finally have done me the favor: File>Invalidate Caches / Restart...>Invalidate and Restart

See :hover state in Chrome Developer Tools

There are several ways to see HOVER STATE styles in Chrome Developer Tools.

Method 01

enter image description here

Method 02

enter image description here

With Firefox Default Developer Toll

enter image description here

With Firebug

enter image description here

How can I implement custom Action Bar with custom buttons in Android?

enter image description here

This is pretty much as close as you'll get if you want to use the ActionBar APIs. I'm not sure you can place a colorstrip above the ActionBar without doing some weird Window hacking, it's not worth the trouble. As far as changing the MenuItems goes, you can make those tighter via a style. It would be something like this, but I haven't tested it.

<style name="MyTheme" parent="android:Theme.Holo.Light">
    <item name="actionButtonStyle">@style/MyActionButtonStyle</item>
</style>

<style name="MyActionButtonStyle" parent="Widget.ActionButton">
    <item name="android:minWidth">28dip</item>
</style>

Here's how to inflate and add the custom layout to your ActionBar.

    // Inflate your custom layout
    final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
            R.layout.action_bar,
            null);

    // Set up your ActionBar
    final ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(actionBarLayout);

    // You customization
    final int actionBarColor = getResources().getColor(R.color.action_bar);
    actionBar.setBackgroundDrawable(new ColorDrawable(actionBarColor));

    final Button actionBarTitle = (Button) findViewById(R.id.action_bar_title);
    actionBarTitle.setText("Index(2)");

    final Button actionBarSent = (Button) findViewById(R.id.action_bar_sent);
    actionBarSent.setText("Sent");

    final Button actionBarStaff = (Button) findViewById(R.id.action_bar_staff);
    actionBarStaff.setText("Staff");

    final Button actionBarLocations = (Button) findViewById(R.id.action_bar_locations);
    actionBarLocations.setText("HIPPA Locations");

Here's the custom layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:orientation="horizontal"
    android:paddingEnd="8dip" >

    <Button
        android:id="@+id/action_bar_title"
        style="@style/ActionBarButtonWhite" />

    <Button
        android:id="@+id/action_bar_sent"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_staff"
        style="@style/ActionBarButtonOffWhite" />

    <Button
        android:id="@+id/action_bar_locations"
        style="@style/ActionBarButtonOffWhite" />

</LinearLayout>

Here's the color strip layout: To use it, just use merge in whatever layout you inflate in setContentView.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/colorstrip"
    android:background="@android:color/holo_blue_dark" />

Here are the Button styles:

<style name="ActionBarButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background">@null</item>
    <item name="android:ellipsize">end</item>
    <item name="android:singleLine">true</item>
    <item name="android:textSize">@dimen/text_size_small</item>
</style>

<style name="ActionBarButtonWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/white</item>
</style>

<style name="ActionBarButtonOffWhite" parent="@style/ActionBarButton">
    <item name="android:textColor">@color/off_white</item>
</style>

Here are the colors and dimensions I used:

<color name="action_bar">#ff0d0d0d</color>
<color name="white">#ffffffff</color>
<color name="off_white">#99ffffff</color>

<!-- Text sizes -->
<dimen name="text_size_small">14.0sp</dimen>
<dimen name="text_size_medium">16.0sp</dimen>

<!-- ActionBar color strip -->
<dimen name="colorstrip">5dp</dimen>

If you want to customize it more than this, you may consider not using the ActionBar at all, but I wouldn't recommend that. You may also consider reading through the Android Design Guidelines to get a better idea on how to design your ActionBar.

If you choose to forgo the ActionBar and use your own layout instead, you should be sure to add action-able Toasts when users long press your "MenuItems". This can be easily achieved using this Gist.

Winforms TableLayoutPanel adding rows programmatically

It's a weird design, but the TableLayoutPanel.RowCount property doesn't reflect the count of the RowStyles collection, and similarly for the ColumnCount property and the ColumnStyles collection.

What I've found I needed in my code was to manually update RowCount/ColumnCount after making changes to RowStyles/ColumnStyles.

Here's an example of code I've used:

    /// <summary>
    /// Add a new row to our grid.
    /// </summary>
    /// The row should autosize to match whatever is placed within.
    /// <returns>Index of new row.</returns>
    public int AddAutoSizeRow()
    {
        Panel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
        Panel.RowCount = Panel.RowStyles.Count;
        mCurrentRow = Panel.RowCount - 1;
        return mCurrentRow;
    }

Other thoughts

  • I've never used DockStyle.Fill to make a control fill a cell in the Grid; I've done this by setting the Anchors property of the control.

  • If you're adding a lot of controls, make sure you call SuspendLayout and ResumeLayout around the process, else things will run slow as the entire form is relaid after each control is added.

Can I embed a custom font in an iPhone application?

yes you can use custom font in your application

step by step following there:

Add your custom font files into your project in supporting files

Add a key to your Info.plist file called UIAppFonts.

Make this key an array

For each font you have, enter the full name of your font file (including the extension) as items to the UIAppFonts array

Save Info.plist Now in your application you can simply call [UIFont fontWithName:@"your Custom font Name" size:20] to get the custom font to use with your UILabels after applying this if your not getting correct font then you double click on the custom font , and see carefully top side font name is comming and copy this font , paste, here [UIFont fontWithName:@" here past your Custom font Name" size:20]

i hope you will get correct answer

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

for version 11 download the Microsoft SQL Server 2012 Feature Pack https://www.microsoft.com/en-us/download/confirmation.aspx?id=43339

  • ENU\x64\SQLSysClrTypes.msi
  • ENU\x64\SharedManagementObjects.msi

for version 12 download the Microsoft SQL Server 2014 SP2 Feature Pack https://www.microsoft.com/en-us/download/details.aspx?id=42295

  • ENU\x64\SQLSysClrTypes.msi
  • ENU\x64\SharedManagementObjects.msi

How to completely hide the navigation bar in iPhone / HTML5

The problem with all of the answers given so far is that on the something borrowed site, the Mac bar remains totally hidden when scrolling up, and the provided answers don't accomplish that.

If you just use scrollTo and then the user later scrolls up, the nav bar is revealed again, so it seems you have to put the whole site inside of a div and force scrolling to happen inside of that div rather than on the body which keeps the nav bar hidden during scrolling in any direction.

You can, however, still reveal the nav bar by touching near the top of the screen on apple devices.

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

finding first day of the month in python

This could be an alternative to Gustavo Eduardo Belduma's answer:

import datetime 
first_day_of_the_month = datetime.date.today().replace(day=1)

Webpack "OTS parsing error" loading fonts

I just had the same issue with Font Awesome. Turned out this was caused by a problem with FTP. The file was uploaded as text (ASCII) instead of binary, which corrupted the file. I simply changed my FTP software to binary, re-uploaded the font files, and then it all worked.

https://css-tricks.com/forums/topic/custom-fonts-returns-failed-to-decode-downloaded-font/ this helped me in the end I had the same issue with FTP transferring files as text

Reading RFID with Android phones

I recently worked on a project to read the RFID tags. The project used the Devices from manufacturers like Zebra (we were using RFD8500 ) & TSL.

More devices are from Motorola & other vendors as well!

We have to use the native SDK api's provided by the manufacturer, how it works is by pairing the device by the Bluetooth of the phones and so the data transfer between both devices take place! The programming is based on subscribe pattern where the scan should be read by the device trigger(hardware trigger) or soft trigger (from the application).

The Tag read gives us the tagId & the RSSI which is the distance factor from the RFID tags!

This is the sample app:

We get all the device paired to our Android/iOS phones :

get device list

connect

connected

Scan

Convert string to date in bash

We can use date -d option

1) Change format to "%Y-%m-%d" format i.e 20121212 to 2012-12-12

date -d '20121212' +'%Y-%m-%d'

2)Get next or last day from a given date=20121212. Like get a date 7 days in past with specific format

date -d '20121212 -7 days' +'%Y-%m-%d'

3) If we are getting date in some variable say dat

dat2=$(date -d "$dat -1 days" +'%Y%m%d')

How to remove provisioning profiles from Xcode

open your terminal then use this command

cd /Users/youruser/Library/MobileDevice/Provisioning\ Profiles/

check first inside your folder by use this command

ls

then if all files not use, delete by use this command

rm *

How to center a <p> element inside a <div> container?

You only need to add text-align: center to your <div>

In your case also remove both styles that you added to your <p>.

Check out the demo here: http://jsfiddle.net/76uGE/3/

Good Luck

How to add icon inside EditText view in Android ?

You can set drawableLeft in the XML as suggested by marcos, but you might also want to set it programmatically - for example in response to an event. To do this use the method setCompoundDrawablesWithIntrincisBounds(int, int, int, int):

EditText editText = findViewById(R.id.myEditText);

// Set drawables for left, top, right, and bottom - send 0 for nothing
editTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.myDrawable, 0, 0, 0);

window.open target _self v window.location.href?

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

Powershell equivalent of bash ampersand (&) for forking/running background processes

You can do something like this.

$a = start-process -NoNewWindow powershell {timeout 10; 'done'} -PassThru

And if you want to wait for it:

$a | wait-process

Bonus osx or linux version:

$a = start-process pwsh '-c',{start-sleep 5; 'done'} -PassThru 

Example pinger script I have. The args are passed as an array:

$1 = start -n powershell pinger,comp001 -pa

Java - Writing strings to a CSV file

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvFile {

    public static void main(String[]args){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new File("NewData.csv"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        StringBuilder builder = new StringBuilder();
        String columnNamesList = "Id,Name";
        // No need give the headers Like: id, Name on builder.append
        builder.append(columnNamesList +"\n");
        builder.append("1"+",");
        builder.append("Chola");
        builder.append('\n');
        pw.write(builder.toString());
        pw.close();
        System.out.println("done!");
    }
}

Could not open ServletContext resource

I think currently the application-context.xml file is into src/main/resources AND the social.properties file is into src/main/java... so when you package (mvn package) or when you run tomcat (mvn tomcat:run) your social.properties disappeared (I know you said when you checked into the .war the files are here... but your exception says the opposite).

The solution is simply to put all your configuration files (application-context.xml and social.properties) into src/main/resources to follow the maven standard structure.

How do I position a div relative to the mouse pointer using jQuery?

var mouseX;
var mouseY;
$(document).mousemove( function(e) {
   mouseX = e.pageX; 
   mouseY = e.pageY;
});  
$(".classForHoverEffect").mouseover(function(){
  $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});

the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,

$(".classForHoverEffect").mouseout(function(){
  $('#DivToShow').fadeOut('slow');
});

If you DIV is already positioned, you can simply use

$('.classForHoverEffect').hover(function(){
  $('#DivToShow').fadeIn('slow');
});

Also, keep in mind, your DIV style needs to be set to display:none; in order for it to fadeIn or show.

How to use ADB in Android Studio to view an SQLite DB

What it mentions as you type adb?

step1. >adb shell
step2. >cd data/data
step3. >ls -l|grep "your app package here"
step4. >cd "your app package here"
step5. >sqlite3 xx.db

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

Iterate through a C array

You can store the size somewhere, or you can have a struct with a special value set that you use as a sentinel, the same way that '\0' indicates the end of a string.

Getting value of HTML text input

See my jsFiddle here: http://jsfiddle.net/fuDBL/

Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.

$('input[name="email"]').change(function(){
  $('#regLink').attr('href')+$('input[name="email"]').val();
});

How do you perform a left outer join using linq extension methods

Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:

var qry = Foos.GroupJoin(
      Bars.OrderByDescending(b => b.Id),
      foo => foo.Foo_Id,
      bar => bar.Foo_Id,
      (f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });

Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).

How to get full REST request body using Jersey?

Try this using this single code:

import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/serviceX")
public class MyClassRESTService {

    @POST
    @Path("/doSomething")   
    public void someMethod(String x) {

        System.out.println(x);
                // String x contains the body, you can process
                // it, parse it using JAXB and so on ...

    }
}

The url for try rest services ends .... /serviceX/doSomething

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Thought I'd give a full answer combining some of the possible intricacies required for completeness.

  1. Check if you have 32-bit or 64-bit IIS installed:
    • Go to IIS Manager ? Application Pools, choose the appropriate app pool then Advanced Settings.
    • Check the setting "Enable 32-bit Applications". If that's true, that means the worker process is forced to run in 32-bit. If the setting is false, then the app pool is running in 64-bit mode.
    • You can also open up Task Manager and check w3wp.exe. If it's showing as w3wp*32.exe then it's 32-bit.
  2. Download the appropriate version here: https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads.
  3. Install it.
  4. Close and reopen IIS Manager to ensure the URL Rewrite module appears.

Check if string contains only letters in javascript

Try this

var Regex='/^[^a-zA-Z]*$/';

 if(Regex.test(word))
 {
 //...
 }

I think it will be working for you.

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

Another option is to add a new OnClickListener as parameter in setOnClickListener() and overriding the onClick()-method:

mycards_button = ((Button)this.findViewById(R.id.Button_MyCards)); 
exit_button = ((Button)this.findViewById(R.id.Button_Exit));

// Add onClickListener to mycards_button
mycards_button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        // Start new activity
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
    }
});

// Add onClickListener to exit_button
exit_button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        // Display alertDialog
        MyAlertDialog();
    }
});

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

function amiLoadedInIFrame() {
    try {
         // Introduce a new propery in window.top
         window.top.dummyAttribute = true;
         // If window.dummyAttribute is there.. then window and window.top are same intances
         return !window.dummyAttribute;
    } catch(e) {
         // Exception will be raised when the top is in different domain
         return true;
    }
}

How to avoid using Select in Excel VBA

How to avoid copy-paste?

Let's face it: this one appears a lot when recording macros:

Range("X1").Select
Selection.Copy
Range("Y9).Select
Selection.Paste

While the only thing the person wants is:

Range("Y9").Value = Range("X1").Value

Therefore, instead of using copy-paste in VBA macros, I'd advise the following simple approach:

Destination_Range.Value = Source_Range.Value

Replace image src location using CSS

You could do this but it is hacky

.application-title {
   background:url("/path/to/image.png");
   /* set these dims according to your image size */
   width:500px;
   height:500px;
}

.application-title img {
   display:none;
}

Here is a working example:

http://jsfiddle.net/5tbxkzzc/

Doctrine and LIKE query

you can also do it like that :

$ver = $em->getRepository('GedDocumentBundle:version')->search($val);

$tail = sizeof($ver);

git switch branch without discarding local changes

You could use --merge/-m git checkout option: git checkout -m <another-branch>

-m --merge

When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.

Source: https://git-scm.com/docs/git-checkout

"java.lang.OutOfMemoryError: PermGen space" in Maven build

This very annoying error so what I did: Under Windows:

Edit system environment variables - > Edit Variables -> New

then fill

MAVEN_OPTS
-Xms512m -Xmx2048m -XX:MaxPermSize=512m

enter image description here

Then restart the console and run the maven build again. No more Maven space/perm size problems.

Map vs Object in JavaScript

Additionally to being iterable in a well-defined order, and the ability to use arbitrary values as keys (except -0), maps can be useful because of the following reasons:

  • The spec enforces map operations to be sublinear on average.

    Any non-stupid implementation of object will use a hash table or similar, so property lookups will probably be constant on average. Then objects could be even faster than maps. But that is not required by the spec.

  • Objects can have nasty unexpected behaviors.

    For example, let's say you didn't set any foo property to a newly created object obj, so you expect obj.foo to return undefined. But foo could be built-in property inherited from Object.prototype. Or you attempt to create obj.foo by using an assignment, but some setter in Object.prototype runs instead of storing your value.

    Maps prevent these kind of things. Well, unless some script messes up with Map.prototype. And Object.create(null) would work too, but then you lose the simple object initializer syntax.

Getting Image from URL (Java)

Directly calling a URL to get an image may concern with major security issues. You need to ensure that you have sufficient rights to access that resource. However You can use ByteOutputStream to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

Same error, different situation. I'm posting this here because someone might be in same situation as mine.

I was using context API like below.

export const withDB = Component => props => {
    <DBContext.Consumer>
        {db => <Component {...props} db={db} />}
    </DBContext.Consumer>
}

So basically the error message is giving you the answer.

Nothing was returned from render. This usually means a return statement is missing

withDB should return a html block. But it wasn't returning anything. Revising my code to below solved my issue.

export const withDB = Component => props => {
  return (
    <DBContext.Consumer>
        {db => <Component {...props} db={db} />}
    </DBContext.Consumer>
  )
}

Count all occurrences of a string in lots of files with grep

Here is a faster-than-grep AWK alternative way of doing this, which handles multiple matches of <url> per line, within a collection of XML files in a directory:

awk '/<url>/{m=gsub("<url>","");total+=m}END{print total}' some_directory/*.xml

This works well in cases where some XML files don't have line breaks.

How do you change library location in R?

I've used this successfully inside R script:

library("reshape2",lib.loc="/path/to/R-packages/")

useful if for whatever reason libraries are in more than one place.

How to remove files and directories quickly via terminal (bash shell)

rm -rf *

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Java, Check if integer is multiple of a number

Use modulo

whenever a number x is a multiple of some number y, then always x % y equal to 0, which can be used as a check. So use

if (j % 4 == 0) 

GIT clone repo across local file system in windows

Either enter absolute paths or relative paths.

For example the first one below uses absolute paths :

(this is from inside the folder which contains the repository and the backup as subfolders. also remember that the backup folder is not modified if it already contains anything. and if it is not present, a new folder will be created )

~/git$ git clone --no-hardlinks ~/git/git_test1/   ~/git/bkp_repos/

The following uses relative paths :

~/git$ git clone --no-hardlinks git_test1/   bkp_repos2/

PHP - SSL certificate error: unable to get local issuer certificate

for guzzle you can try this :

$client = new Client(env('API_HOST'));
$client->setSslVerification(false);

tested on guzzle/guzzle 3.*

How do I use CMake?

Yes, cmake and make are different programs. cmake is (on Linux) a Makefile generator (and Makefile-s are the files driving the make utility). There are other Makefile generators (in particular configure and autoconf etc...). And you can find other build automation programs (e.g. ninja).

How to change JDK version for an Eclipse project

In the preferences section under Java -> Installed JREs click the Add button and navigate to the 1.5 JDK home folder. Then check that one in the list and it will become the default for all projects:

enter image description here

How can I get the root domain URI in ASP.NET?

To get the entire request URL string:

HttpContext.Current.Request.Url

To get the www.foo.com portion of the request:

HttpContext.Current.Request.Url.Host

Note that you are, to some degree, at the mercy of factors outside your ASP.NET application. If IIS is configured to accept multiple or any host header for your application, then any of those domains which resolved to your application via DNS may show up as the Request Url, depending on which one the user entered.

Stopping a thread after a certain amount of time

If you want to use a class:

from datetime import datetime,timedelta

class MyThread(): 

    def __init__(self, name, timeLimit):        
        self.name = name
        self.timeLimit = timeLimit
    def run(self): 
        # get the start time
        startTime = datetime.now()
    
        while True:
           # stop if the time limit is reached :
           if((datetime.now()-startTime)>self.timeLimit):
               break
           print('A')

mt = MyThread('aThread',timedelta(microseconds=20000))
mt.run()

iterrows pandas get next rows value

I would use shift() function as follows:

df['value_1'] = df.value.shift(-1)
[print(x) for x in df.T.unstack().dropna(how = 'any').values];

which produces

AA
BB
BB
CC
CC

This is how the code above works:

Step 1) Use shift function

df['value_1'] = df.value.shift(-1)
print(df)

produces

value value_1
0    AA      BB
1    BB      CC
2    CC     NaN

step 2) Transpose:

df = df.T
print(df)

produces:

          0   1    2
value    AA  BB   CC
value_1  BB  CC  NaN

Step 3) Unstack:

df = df.unstack()
print(df)

produces:

0  value       AA
   value_1     BB
1  value       BB
   value_1     CC
2  value       CC
   value_1    NaN
dtype: object

Step 4) Drop NaN values

df = df.dropna(how = 'any')
print(df)

produces:

0  value      AA
   value_1    BB
1  value      BB
   value_1    CC
2  value      CC
dtype: object

Step 5) Return a Numpy representation of the DataFrame, and print value by value:

df = df.values
[print(x) for x in df];

produces:

AA
BB
BB
CC
CC

Sorting object property by values

Couln't find answer above that would both work and be SMALL, and would support nested objects (not arrays), so I wrote my own one :) Works both with strings and ints.

  function sortObjectProperties(obj, sortValue){
      var keysSorted = Object.keys(obj).sort(function(a,b){return obj[a][sortValue]-obj[b][sortValue]});
      var objSorted = {};
      for(var i = 0; i < keysSorted.length; i++){
          objSorted[keysSorted[i]] = obj[keysSorted[i]];
      }
      return objSorted;
    }

Usage:

    /* sample object with unsorder properties, that we want to sort by 
    their "customValue" property */

    var objUnsorted = {
       prop1 : {
          customValue : 'ZZ'
       },
       prop2 : {
          customValue : 'AA'
       }
    }

    // call the function, passing object and property with it should be sorted out
    var objSorted = sortObjectProperties(objUnsorted, 'customValue');

    // now console.log(objSorted) will return:
    { 
       prop2 : {
          customValue : 'AA'
       },
       prop1 : {
          customValue : 'ZZ'
       } 
    }

Amazon S3 direct file upload from client browser - private key disclosure

Adding more info to the accepted answer, you can refer to my blog to see a running version of the code, using AWS Signature version 4.

Will summarize here:

As soon as the user selects a file to be uploaded, do the followings: 1. Make a call to the web server to initiate a service to generate required params

  1. In this service, make a call to AWS IAM service to get temporary cred

  2. Once you have the cred, create a bucket policy (base 64 encoded string). Then sign the bucket policy with the temporary secret access key to generate final signature

  3. send the necessary parameters back to the UI

  4. Once this is received, create a html form object, set the required params and POST it.

For detailed info, please refer https://wordpress1763.wordpress.com/2016/10/03/browser-based-upload-aws-signature-version-4/

Textarea that can do syntax highlighting on the fly?

You can Highlight text in a <textarea>, using a <div> carefully placed behind it.

check out Highlight Text Inside a Textarea.

How to query first 10 rows and next time query other 10 rows from table

for first 10 rows...

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 0,10

for next 10 rows

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 10,10

Input mask for numeric and decimal

Use tow function to solve it ,Very simple and useful:

HTML:

<input class="int-number" type="text" />
<input class="decimal-number" type="text" />

JQuery:

//Integer Number
$(document).on("input", ".int-number", function (e) {
  this.value = this.value.replace(/[^0-9]/g, '');
});

//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});

How do I set the rounded corner radius of a color drawable using xml?

Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

<stroke
    android:width="5dp"
    android:color="#1271BB" />

<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" /></shape>

Convert Java Array to Iterable

First of all, I can only agree that Arrays.asList(T...) is clearly the best solution for Wrapper types or arrays with non-primtive datatypes. This method calls a constructor of a simple private static AbstractList implementation in the Arrays class which basically saves the given array reference as field and simulates a list by overriding the needed methods.

If you can choose between a primtive type or a Wrapper type for your array, I would use the Wrapper type for such situations but of course, it's not always useful or required. There would be only two possibilities you can do:

1) You can create a class with a static method for each primitive datatype array (boolean, byte, short, int, long, char, float, double returning an Iterable<WrapperType>. These methods would use anonymous classes of Iterator (besides Iterable) which are allowed to contain the reference of the comprising method's argument (for example an int[]) as field in order to implement the methods.

-> This approach is performant and saves you memory (except for the memory of the newly created methods, even though, using Arrays.asList() would take memory in the same way)

2) Since arrays don't have methods (as to be read on the side you linked) they can't provide an Iterator instance either. If you really are too lazy to write new classes, you must use an instance of an already existing class that implements Iterable because there is no other way around than instantiating Iterable or a subtype.
The ONLY way to create an existing Collection derivative implementing Iterable is to use a loop (except you use anonymous classes as described above) or you instantiate an Iterable implementing class whose constructor allows a primtive type array (because Object[] doesn't allow arrays with primitive type elements) but as far as I know, the Java API doesn't feature a class like that.

The reason for the loop can be explained easily:
for each Collection you need Objects and primtive datatypes aren't objects. Objects are much bigger than primitive types so that they require additional data which must be generated for each element of the primitive type array. That means if two ways of three (using Arrays.asList(T...) or using an existing Collection) require an aggregate of objects, you need to create for each primitive value of your int[] array the wrapper object. The third way would use the array as is and use it in an anonymous class as I think it's preferable due to fast performance.

There is also a third strategy using an Object as argument for the method where you want to use the array or Iterable and it would require type checks to figure out which type the argument has, however I wouldn't recommend it at all as you usually need to consider that the Object hasn't always the required type and that you need seperate code for certain cases.

In conclusion, it's the fault of Java's problematic Generic Type system which doesn't allow to use primitive types as generic type which would save a lot of code by using simply Arrays.asList(T...). So you need to program for each primitive type array, you need, such a method (which basically makes no difference to the memory used by a C++ program which would create for each used type argument a seperate method.

How to connect to remote Redis server?

redis-cli -h XXX.XXX.XXX.XXX -p YYYY

xxx.xxx.xxx.xxx is the IP address and yyyy is the port

EXAMPLE from my dev environment

redis-cli -h 10.144.62.3 -p 30000

REDIS CLI COMMANDS

Host, port, password and database By default redis-cli connects to the server at 127.0.0.1 port 6379. As you can guess, you can easily change this using command line options. To specify a different host name or an IP address, use -h. In order to set a different port, use -p.

redis-cli -h redis15.localnet.org -p 6390 ping

Python Inverse of a Matrix

Numpy will be suitable for most people, but you can also do matrices in Sympy

Try running these commands at http://live.sympy.org/

M = Matrix([[1, 3], [-2, 3]])
M
M**-1

For fun, try M**(1/2)

Print commit message of a given commit in git

I started to use

git show-branch --no-name <hash>

It seems to be faster than

git show -s --format=%s <hash>

Both give the same result

I actually wrote a small tool to see the status of all my repos. You can find it on github.

enter image description here

What's your favorite "programmer" cartoon?

I think the IT consultant's image is the best:

Reasons why people who work with computers have a lot of spare time

(linking because the picture's pretty big)

Convert string to date in Swift

Swift 3.0 - 4.2

import Foundation

extension String {

    func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{

        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from: self)

        return date

    }
}

extension Date {

    func toString(withFormat format: String = "EEEE ? d MMMM yyyy") -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.calendar = Calendar(identifier: .persian)
        dateFormatter.dateFormat = format
        let str = dateFormatter.string(from: self)

        return str
    }
}

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

If you are using liquibase to update your SQL Server, you are likely trying to insert a record key into an autoIncrement field. By removing the column from the insert, your script should run.

<changeSet id="CREATE_GROUP_TABLE" >
    <createTable tableName="GROUP_D">
        <column name="GROUP_ID" type="INTEGER" autoIncrement="true">
            <constraints primaryKey="true"/>
        </column>
    </createTable>
</changeSet>

<changeSet id="INSERT_UNKNOWN_GROUP" >
    <insert tableName="GROUP_D">    

        <column name="GROUP_ID" valueNumeric="-1"/>
 ...
    </insert>
</changeSet>

How to compile the finished C# project and then run outside Visual Studio?

Compile the Release version as .exe file, then just copy onto a machine with a suitable version of .NET Framework installed and run it there. The .exe file is located in the bin\Release subfolder of the project folder.

What do all of Scala's symbolic operators mean?

<= is just like you would "read" it: 'less than or equals'. So it's a mathematical operator, in the list of < (is less than?), > (is greater than?), == (equals?), != (is not equal?), <= (is less than or equal?), and >= (is greater than or equal?).

This must not be confused with => which is kind of a double right-hand arrow, used to separate the argument list from the body of a function and to separate the testing condition in pattern matching (a case block) from the body executed when a match occurs. You can see example of this in my previous two answers. First, the function use:

coll.map(tup => tup._2.reverse)

which is already abbreviated as the types are omitted. The follow function would be

// function arguments         function body
(tup: Tuple2[Int, String]) => tup._2.reverse

and the pattern matching use:

def extract2(l: List[Int]) = l match {
   // if l matches Nil    return "empty"
   case Nil            => "empty"
   // etc.
   case ::(head, Nil)  => "exactly one element (" + head + ")"
   // etc.
   case ::(head, tail) => "more than one element"
}

Unknown Column In Where Clause

For me the root of the problem was a number which I copied to use in a WHERE clause. The number had "invisible" symbol, at least for MySQL Workbench. I placed the number in the Chrome console it was clearly visible.

Regular Expression to get a string between parentheses in Javascript

Try string manipulation:

var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
    console.log(newTxt[i].split(')')[0]);
}

or regex (which is somewhat slow compare to the above)

var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
    var str = matches[i];
    console.log(str.substring(1, str.length - 1));
}

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Your second delegate is not a rewrite of the first in anonymous delegate (rather than lambda) format. Look at your conditions.

First:

x.ID == packageId || x.Parent.ID == packageId || x.Parent.Parent.ID == packageId

Second:

(x.ID == packageId) || (x.Parent != null && x.Parent.ID == packageId) || 
(x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)

The call to the lambda would throw an exception for any x where the ID doesn't match and either the parent is null or doesn't match and the grandparent is null. Copy the null checks into the lambda and it should work correctly.

Edit after Comment to Question

If your original object is not a List<T>, then we have no way of knowing what the return type of FindAll() is, and whether or not this implements the IQueryable interface. If it does, then that likely explains the discrepancy. Because lambdas can be converted at compile time into an Expression<Func<T>> but anonymous delegates cannot, then you may be using the implementation of IQueryable when using the lambda version but LINQ-to-Objects when using the anonymous delegate version.

This would also explain why your lambda is not causing a NullReferenceException. If you were to pass that lambda expression to something that implements IEnumerable<T> but not IQueryable<T>, runtime evaluation of the lambda (which is no different from other methods, anonymous or not) would throw a NullReferenceException the first time it encountered an object where ID was not equal to the target and the parent or grandparent was null.

Added 3/16/2011 8:29AM EDT

Consider the following simple example:

IQueryable<MyObject> source = ...; // some object that implements IQueryable<MyObject>

var anonymousMethod =  source.Where(delegate(MyObject o) { return o.Name == "Adam"; });    
var expressionLambda = source.Where(o => o.Name == "Adam");

These two methods produce entirely different results.

The first query is the simple version. The anonymous method results in a delegate that's then passed to the IEnumerable<MyObject>.Where extension method, where the entire contents of source will be checked (manually in memory using ordinary compiled code) against your delegate. In other words, if you're familiar with iterator blocks in C#, it's something like doing this:

public IEnumerable<MyObject> MyWhere(IEnumerable<MyObject> dataSource, Func<MyObject, bool> predicate)
{
    foreach(MyObject item in dataSource)
    {
        if(predicate(item)) yield return item;
    }
}

The salient point here is that you're actually performing your filtering in memory on the client side. For example, if your source were some SQL ORM, there would be no WHERE clause in the query; the entire result set would be brought back to the client and filtered there.

The second query, which uses a lambda expression, is converted to an Expression<Func<MyObject, bool>> and uses the IQueryable<MyObject>.Where() extension method. This results in an object that is also typed as IQueryable<MyObject>. All of this works by then passing the expression to the underlying provider. This is why you aren't getting a NullReferenceException. It's entirely up to the query provider how to translate the expression (which, rather than being an actual compiled function that it can just call, is a representation of the logic of the expression using objects) into something it can use.

An easy way to see the distinction (or, at least, that there is) a distinction, would be to put a call to AsEnumerable() before your call to Where in the lambda version. This will force your code to use LINQ-to-Objects (meaning it operates on IEnumerable<T> like the anonymous delegate version, not IQueryable<T> like the lambda version currently does), and you'll get the exceptions as expected.

TL;DR Version

The long and the short of it is that your lambda expression is being translated into some kind of query against your data source, whereas the anonymous method version is evaluating the entire data source in memory. Whatever is doing the translating of your lambda into a query is not representing the logic that you're expecting, which is why it isn't producing the results you're expecting.

How do I download a binary file over HTTP?

Here is my Ruby http to file using open(name, *rest, &block).

require "open-uri"
require "fileutils"

def download(url, path)
  case io = open(url)
  when StringIO then File.open(path, 'w') { |f| f.write(io.read) }
  when Tempfile then io.close; FileUtils.mv(io.path, path)
  end
end

The main advantage here it is concise and simple, because open does much of the heavy lifting. And it does not read the whole response in memory.

The open method will stream responses > 1kb to a Tempfile. We can exploit this knowledge to implement this lean download to file method. See the OpenURI::Buffer implementation here.

Please be careful with user provided input! open(name, *rest, &block) is unsafe if name is coming from user input!

How do I make a simple makefile for gcc on Linux?

Depending on the number of headers and your development habits, you may want to investigate gccmakedep. This program examines your current directory and adds to the end of the makefile the header dependencies for each .c/cpp file. This is overkill when you have 2 headers and one program file. However, if you have 5+ little test programs and you are editing one of 10 headers, you can then trust make to rebuild exactly those programs which were changed by your modifications.

Difference between <span> and <div> with text-align:center;?

It might be, because your span element sets is side as width as its content. if you have a div with 500px width and text-align center, and you enter a span tag it should be aligned in the center. So your problem might be a CSS one. Install Firebug at Firefox and check the style attributes your span or div object has.

subsetting a Python DataFrame

Regarding some points mentioned in previous answers, and to improve readability:

No need for data.loc or query, but I do think it is a bit long.

The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.

I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.

q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time

df.loc[q_product & q_start & q_end, c('Time,Product')]

# c is just a convenience
c = lambda v: v.split(',') 

"Cross origin requests are only supported for HTTP." error when loading a local file

Use http:// or https:// to create url

error: localhost:8080

solution: http://localhost:8080

AlertDialog styling - how to change style (color) of title, message, etc

Here's my Code to theme the alert dialog box:

<style name="alertDialog" parent="Theme.AppCompat.Dialog.Alert">
    <item name="android:background">@color/light_button_text_color</item>
    <item name="android:textColor">@android:color/black</item>
    <item name="android:textColorPrimary">@android:color/black</item>
    <item name="android:textColorSecondary">@android:color/black</item>
    <item name="android:titleTextColor" tools:targetApi="m">@android:color/black</item>
</style>

Place this code in styles.xml. In your java apply this theme as:

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.alertDialog);

Output of the code

How to change the background colour's opacity in CSS

Use RGB values combined with opacity to get the transparency that you wish.

For instance,

<div style=" background: rgb(255, 0, 0) ; opacity: 0.2;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.4;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.6;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.8;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 1;">&nbsp;</div>

Similarly, with actual values without opacity, will give the below.

<div style=" background: rgb(243, 191, 189) ; ">&nbsp;</div>
<div style=" background: rgb(246, 143, 142) ; ">&nbsp;</div>
<div style=" background: rgb(249, 95 , 94)  ; ">&nbsp;</div>
<div style=" background: rgb(252, 47, 47)   ; ">&nbsp;</div>
<div style=" background: rgb(255, 0, 0)     ; ">&nbsp;</div>

You can have a look at this WORKING EXAMPLE.

Now, if we specifically target your issue, here is the WORKING DEMO SPECIFIC TO YOUR ISSUE.

The HTML

<div class="social">
    <img src="http://www.google.co.in/images/srpr/logo4w.png" border="0" />
</div>

The CSS:

social img{
    opacity:0.5;
}
.social img:hover {
    opacity:1;
    background-color:black;
    cursor:pointer;
    background: rgb(255, 0, 0) ; opacity: 0.5;
}

Hope this helps Now.

How can I pad a String in Java?

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).

Best way to do Version Control for MS Excel

I'm not aware of a tool that does this well but I've seen a variety of homegrown solutions. The common thread of these is to minimise the binary data under version control and maximise textual data to leverage the power of conventional scc systems. To do this:

  • Treat the workbook like any other application. Seperate logic, config and data.
  • Separate code from the workbook.
  • Build the UI programmatically.
  • Write a build script to reconstruct the workbook.

How do I get column names to print in this C# program?

Print datatable rows with column

Here is solution 

DataTable datatableinfo= new DataTable();

// Fill data table 

//datatableinfo=fill by function or get data from database

//Print data table with rows and column


for (int j = 0; j < datatableinfo.Rows.Count; j++)
{
    for (int i = 0; i < datatableinfo.Columns.Count; i++)    
        {    
            Console.Write(datatableinfo.Columns[i].ColumnName + " ");    
            Console.WriteLine(datatableinfo.Rows[j].ItemArray[i]+" "); 
        }
}


Ouput :
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value

Can an interface extend multiple interfaces in Java?

I think your confusion lies with multiple inheritance, in which it is bad practise to do so and in Java this is also not possible. However, implementing multiple interfaces is allowed in Java and it is also safe.

indexOf and lastIndexOf in PHP?

This is the best way to do it, very simple.

$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');

echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;

bash assign default value

The default value parameter expansion is often useful in build scripts like the example one below. If the user just calls the script as-is, perl will not be built in. The user has to explicitly set WITH_PERL to a value other than "no" to have it built in.

$ cat defvar.sh
#!/bin/bash

WITH_PERL=${WITH_PERL:-no}

if [[ "$WITH_PERL" != no ]]; then
    echo "building with perl"
    # ./configure --enable=perl
else
    echo "not building with perl"
    # ./configure
fi

Build without Perl

$ ./defvar.sh
not building with perl

Build with Perl

$ WITH_PERL=yes ./defvar.sh
building with perl

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

How do you copy and paste into Git Bash

MacBook pro doesnt have an ins key. Use FN + ENTER to paste

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

Generating a drop down list of timezones with PHP

I would like to leave here this idea:

/*----------TIME ZONE LIST---------*/
function TZList($data_type = false){
    $_all_timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
    $TIMEZONE_LIST = array();
    foreach($_all_timezone_identifiers as $k => $v){
        $_tzone_group = explode("/", $_all_timezone_identifiers[$k])[0];

        $_tzone_new = new DateTimeZone($_all_timezone_identifiers[$k]);
        $_tzone_new_date = new DateTime("now", $_tzone_new);

        $tzone_arr = array(
                            'timezone' => $_all_timezone_identifiers[$k],
                            'timediff' => $_tzone_new_date->format('P'),
                            'timezone_offset' => $_tzone_new_date->format('Z')/60, //minutes
                            'text' => "(GMT" .$_tzone_new_date->format('P') .") " .$_all_timezone_identifiers[$k]
                            );

        //BY CONTINENT
        if($data_type === true) $TIMEZONE_LIST[$_tzone_group][] = $tzone_arr; else $TIMEZONE_LIST[] = $tzone_arr;
    }

    //BY TIMEZONE: "America/New_York"
    if(is_string($data_type)){
        $key = array_search($data_type, array_column($TIMEZONE_LIST, 'timezone'));
        $TIMEZONE_LIST = $key !== false ? $TIMEZONE_LIST[$key] : null;
    }

    return $TIMEZONE_LIST;
}
/*--------------------------------*/

Thank you.

What is the best way to call a script from another script?

You should not be doing this. Instead, do:

test1.py:

 def print_test():
      print "I am a test"
      print "see! I do nothing productive."

service.py

#near the top
from test1 import print_test
#lots of stuff here
print_test()

TCPDF Save file to folder?

this stores the generated pdf file in your custom folder of your project

$filename= "{$membership->id}.pdf"; 
$filelocation = "D:\\wamp\\www\\project\\custom";//windows
$filelocation = "/var/www/project/custom"; //Linux

$fileNL = $filelocation."\\".$filename;//Windows
$fileNL = $filelocation."/".$filename; //Linux

$this->pdf->Output($fileNL, 'F');

Remove element of a regular array

Here's how I did it...

    public static ElementDefinitionImpl[] RemoveElementDefAt(
        ElementDefinition[] oldList,
        int removeIndex
    )
    {
        ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];

        int offset = 0;
        for ( int index = 0; index < oldList.Length; index++ )
        {
            ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
            if ( index == removeIndex )
            {
                //  This is the one we want to remove, so we won't copy it.  But 
                //  every subsequent elementDef will by shifted down by one.
                offset = -1;
            }
            else
            {
                newElementDefList[ index + offset ] = elementDef;
            }
        }
        return newElementDefList;
    }

How does true/false work in PHP?

Zero is false, nonzero is true.

In php you can test more explicitly using the === operator.

if (0==false) 
    echo "works"; // will echo works

if (0===false) 
    echo "works"; // will not echo anything

How to read the Stock CPU Usage data

From High Performance Android Apps book (page 157):

  • what we see is equivalent of adb shell dumpsys cpuinfo command
  • Numbers are showing CPU load over 1 minute, 5 minutes and 15 minutes (from the left)
  • Colors are showing time spent by CPU in user space (green), kernel (red) and IO interrupt (blue)

AttributeError: 'list' object has no attribute 'encode'

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

Nesting queries in SQL

The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

Sorting an Array of int using BubbleSort

Here we go

static String arrayToString(int[] array) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < array.length; i++) {
      stringBuilder.append(array[i]).append(",");
    }
    return stringBuilder.deleteCharAt(stringBuilder.length()-1).toString();
  }

  public static void main(String... args){
    int[] unsorted = {9,2,1,4,0};
    System.out.println("Sorting an array of Length "+unsorted.length);
    enhancedBubbleSort(unsorted);
    //dumbBubbleSort(unsorted);
    //bubbleSort(unsorted);
    //enhancedBubbleSort(unsorted);
    //enhancedBubbleSortBetterStructured(unsorted);
    System.out.println("Sorted Array: "+arrayToString(unsorted));

  }

  // this is the dumbest BubbleSort
  static int[] dumbBubbleSort(int[] array){
    for (int i = 0; i<array.length-1 ; i++) {
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          // Just swap
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
      System.out.println("After "+(i+1)+" pass: "+arrayToString(array));
    }
    return array;
  }

  //this "-i" in array.length - 1-i brings some improvement.
  // Then for making our bestcase scenario better ( o(n) , we will introduce isswapped flag) that's enhanced bubble sort

  static int[] bubbleSort(int[] array){
    for (int i = 0; i<array.length-1 ; i++) {
      for (int j = 0; j < array.length - 1-i; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
      System.out.println("After "+(i+1)+" pass: "+arrayToString(array));
    }
    return array;
  }

  static int[] enhancedBubbleSort(int[] array){
    int i=0;
    while (true) {
      boolean swapped = false;
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped =true;
        }
      }
      i++;
      System.out.println("After "+(i)+" pass: "+arrayToString(array));
      if(!swapped){
        // Last iteration (of outer loop) didnot result in any swaps. so stopping here
        break;
      }
    }
    return array;
  }

  static int[] enhancedBubbleSortBetterStructured(int[] array){
    int i=0;
    boolean swapped = true;
    while (swapped) {
      swapped = false;
      for (int j = 0; j < array.length - 1; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped = true;
        }
      }
      i++;
      System.out.println("After "+(i)+" pass: "+arrayToString(array));
    }
    return array;
  }

HTML list-style-type dash

Instead of using lu li, used dl (definition list) and dd. <dd> can be defined using standard css style such as {color:blue;font-size:1em;} and use as marker whatever symbol you place after the html tag. It works like ul li, but allows you to use any symbol, you just have to indent it to get the indented list effect you normally get with ul li.

CSS:
dd{text-indent:-10px;}

HTML
<dl>
<dd>- One</dd>
<dd>- Two</dd>
<dd>- Three</dd></dl>

Gives you much cleaner code! That way, you could use any type of character as marker! Indent is of about -10px and it works perfect!

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

How can I move a tag on a git branch to a different commit?

I'll leave here just another form of this command that suited my needs.
There was a tag v0.0.1.2 that I wanted to move.

$ git tag -f v0.0.1.2 63eff6a

Updated tag 'v0.0.1.2' (was 8078562)

And then:

$ git push --tags --force

How to multiply duration by integer?

It's nice that Go has a Duration type -- having explicitly defined units can prevent real-world problems.

And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.

/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
    return time.Duration(factor) * d        // method 1 -- multiply in 'Duration'
 // return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}

The official documentation demonstrates using method #1:

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).

By the way, the int64 representation of Duration in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration, like int64, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292, and that's exactly how it is implemented:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

So, because we know that the underlying representation of Duration is an int64, performing the cast between int64 and Duration is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.

If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.

Switch statement multiple cases in JavaScript

Here's different approach avoiding the switch statement altogether:

var cases = {
  afshin: function() { alert('hey'); },
  _default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;

cases[ varName ] ? cases[ varName ]() : cases._default();

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

How can I keep Bootstrap popovers alive while being hovered?

I found the mouseleave will not fire when weird things happen, like the window focus changes suddenly, then the user comes back to the browser. In cases like that, mouseleave will never fire until the cursor goes over and leaves the element again.

This solution I came up with relies on mouseenter on the window object, so it disappears when the mouse is moved anywhere else on the page.

This was designed to work with having multiple elements on the page that will trigger it (like in a table).

var allMenus = $(".menus");
allMenus.popover({
    html: true,
    trigger: "manual",
    placement: "bottom",
    content: $("#menuContent")[0].outerHTML
}).on("mouseenter", (e) => {
    allMenus.not(e.target).popover("hide");
    $(e.target).popover("show");
    e.stopPropagation();
}).on("shown.bs.popover", () => {
    $(window).on("mouseenter.hidepopover", (e) => {
        if ($(e.target).parents(".popover").length === 0) {
            allMenus.popover("hide");
            $(window).off("mouseenter.hidepopover");
        }
    });
});

Calling a javascript function in another js file

use "var" while creating function, then you can access that from another file. make sure both files are well connected to your project and can access each other.

file_1.js

var firstLetterUppercase = function(str) {
   str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
      return letter.toUpperCase();
   });
   return str;
}

accessing this function/variable form file_2.js file

firstLetterUppercase("gobinda");

output => Gobinda

hope this will help somebody, happy coding !!!

capture div into image using html2canvas

window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.

_x000D_
_x000D_
$("#btn_screenshot").click(function(){_x000D_
     element_to_png("container", "testhtmltocanvasimg");_x000D_
});_x000D_
_x000D_
_x000D_
function element_to_png(srcElementID, targetIMGid){_x000D_
    console.log("element_to_png called for element id " + srcElementID);_x000D_
    html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
        var myImage = canvas.toDataURL("image/png");_x000D_
        $("#"+targetIMGid).attr("src", myImage);_x000D_
  console.log("html2canvas completed.  png rendered to " + targetIMGid);_x000D_
    });_x000D_
}
_x000D_
<div id="testhtmltocanvasdiv" class="mt-3">_x000D_
   <img src="" id="testhtmltocanvasimg">_x000D_
</div>
_x000D_
_x000D_
_x000D_

I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!

How do I set the path to a DLL file in Visual Studio?

Go through project properties -> Reference Paths

Then add folder with DLL's

SelectedValue vs SelectedItem.Value of DropDownList

One important distinction between the two (which is visible in the Reflected code) is that SelectedValue will return an empty string if a nothing is selected, whereas SelectedItem.Value will throw a NullReference exception.

isset in jQuery?

function isset(element) {
    return element.length > 0;
}

http://jsfiddle.net/8KYxe/1/


Or, as a jQuery extension:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}

Get local IP address

Other way to get IP using linq expression:

public static List<string> GetAllLocalIPv4(NetworkInterfaceType type)
{
    return NetworkInterface.GetAllNetworkInterfaces()
                   .Where(x => x.NetworkInterfaceType == type && x.OperationalStatus == OperationalStatus.Up)
                   .SelectMany(x => x.GetIPProperties().UnicastAddresses)
                   .Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
                   .Select(x => x.Address.ToString())
                   .ToList();
}

What's the correct way to communicate between controllers in AngularJS?

You can do it by using angular events that is $emit and $broadcast. As per our knowledge this is the best, efficient and effective way.

First we call a function from one controller.

var myApp = angular.module('sample', []);
myApp.controller('firstCtrl', function($scope) {
    $scope.sum = function() {
        $scope.$emit('sumTwoNumber', [1, 2]);
    };
});
myApp.controller('secondCtrl', function($scope) {
    $scope.$on('sumTwoNumber', function(e, data) {
        var sum = 0;
        for (var a = 0; a < data.length; a++) {
            sum = sum + data[a];
        }
        console.log('event working', sum);

    });
});

You can also use $rootScope in place of $scope. Use your controller accordingly.

Targeting .NET Framework 4.5 via Visual Studio 2010

There are pretty limited scenarios that I can think of where this would be useful, but let's assume you can't get funds to purchase VS2012 or something to that effect. If that's the case and you have Windows 7+ and VS 2010 you may be able to use the following hack I put together which seems to work (but I haven't fully deployed an application using this method yet).

  1. Backup your project file!!!

  2. Download and install the Windows 8 SDK which includes the .NET 4.5 SDK.

  3. Open your project in VS2010.

  4. Create a text file in your project named Compile_4_5_CSharp.targets with the following contents. (Or just download it here - Make sure to remove the ".txt" extension from the file name):

    <Project DefaultTargets="Build"
     xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    
        <!-- Change the target framework to 4.5 if using the ".NET 4.5" configuration -->
        <PropertyGroup Condition=" '$(Platform)' == '.NET 4.5' ">
            <DefineConstants Condition="'$(DefineConstants)'==''">
                TARGETTING_FX_4_5
            </DefineConstants>
            <DefineConstants Condition="'$(DefineConstants)'!='' and '$(DefineConstants)'!='TARGETTING_FX_4_5'">
                $(DefineConstants);TARGETTING_FX_4_5
            </DefineConstants>
            <PlatformTarget Condition="'$(PlatformTarget)'!=''"/>
            <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
        </PropertyGroup>
    
        <!-- Import the standard C# targets -->
        <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
    
        <!-- Add .NET 4.5 as an available platform -->
        <PropertyGroup>
           <AvailablePlatforms>$(AvailablePlatforms),.NET 4.5</AvailablePlatforms>
        </PropertyGroup>
    </Project>
    
  5. Unload your project (right click -> unload).

  6. Edit the project file (right click -> Edit *.csproj).

  7. Make the following changes in the project file:

    a. Replace the default Microsoft.CSharp.targets with the target file created in step 4

    <!-- Old Import Entry -->
    <!-- <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -->
    
    <!-- New Import Entry -->
    <Import Project="Compile_4_5_CSharp.targets" />
    

    b. Change the default platform to .NET 4.5

    <!-- Old default platform entry -->
    <!-- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> -->
    
    <!-- New default platform entry -->
    <Platform Condition=" '$(Platform)' == '' ">.NET 4.5</Platform>
    

    c. Add AnyCPU platform to allow targeting other frameworks as specified in the project properties. This should be added just before the first <ItemGroup> tag in the file

    <PropertyGroup Condition="'$(Platform)' == 'AnyCPU'">
        <PlatformTarget>AnyCPU</PlatformTarget>
    </PropertyGroup>
    
    .
    .
    .
    <ItemGroup>
    .
    .
    .
    
  8. Save your changes and close the *.csproj file.

  9. Reload your project (right click -> Reload Project).

  10. In the configuration manager (Build -> Configuration Manager) make sure the ".NET 4.5" platform is selected for your project.

  11. Still in the configuration manager, create a new solution platform for ".NET 4.5" (you can base it off "Any CPU") and make sure ".NET 4.5" is selected for the solution.

  12. Build your project and check for errors.

  13. Assuming the build completed you can verify that you are indeed targeting 4.5 by adding a reference to a 4.5 specific class to your source code:

    using System;
    using System.Text;
    
    namespace testing
    {
        using net45check = System.Reflection.ReflectionContext;
    }
    
  14. When you compile using the ".NET 4.5" platform the build should succeed. When you compile under the "Any CPU" platform you should get a compiler error:

    Error 6: The type or namespace name 'ReflectionContext' does not exist in
    the namespace 'System.Reflection' (are you missing an assembly reference?)
    

What's the difference between map() and flatMap() methods in Java 8?

flatMap() also takes advantage of partial lazy evaluation of streams. It will read the fist stream and only when required, will go to the next stream. The behaviour is explained in detail here: Is flatMap guaranteed to be lazy?

how to cancel/abort ajax request in axios

Axios does not support canceling requests at the moment. Please see this issue for details.

UPDATE: Cancellation support was added in axios v0.15.

EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.

Example:

const cancelTokenSource = axios.CancelToken.source();

axios.get('/user/12345', {
  cancelToken: cancelTokenSource.token
});

// Cancel request
cancelTokenSource.cancel();

Extract a substring according to a pattern

Here are a few ways:

1) sub

sub(".*:", "", string)
## [1] "E001" "E002" "E003"

2) strsplit

sapply(strsplit(string, ":"), "[", 2)
## [1] "E001" "E002" "E003"

3) read.table

read.table(text = string, sep = ":", as.is = TRUE)$V2
## [1] "E001" "E002" "E003"

4) substring

This assumes second portion always starts at 4th character (which is the case in the example in the question):

substring(string, 4)
## [1] "E001" "E002" "E003"

4a) substring/regex

If the colon were not always in a known position we could modify (4) by searching for it:

substring(string, regexpr(":", string) + 1)

5) strapplyc

strapplyc returns the parenthesized portion:

library(gsubfn)
strapplyc(string, ":(.*)", simplify = TRUE)
## [1] "E001" "E002" "E003"

6) read.dcf

This one only works if the substrings prior to the colon are unique (which they are in the example in the question). Also it requires that the separator be colon (which it is in the question). If a different separator were used then we could use sub to replace it with a colon first. For example, if the separator were _ then string <- sub("_", ":", string)

c(read.dcf(textConnection(string)))
## [1] "E001" "E002" "E003"

7) separate

7a) Using tidyr::separate we create a data frame with two columns, one for the part before the colon and one for after, and then extract the latter.

library(dplyr)
library(tidyr)
library(purrr)

DF <- data.frame(string)
DF %>% 
  separate(string, into = c("pre", "post")) %>% 
  pull("post")
## [1] "E001" "E002" "E003"

7b) Alternately separate can be used to just create the post column and then unlist and unname the resulting data frame:

library(dplyr)
library(tidyr)

DF %>% 
  separate(string, into = c(NA, "post")) %>% 
  unlist %>%
  unname
## [1] "E001" "E002" "E003"

8) trimws We can use trimws to trim word characters off the left and then use it again to trim the colon.

trimws(trimws(string, "left", "\\w"), "left", ":")
## [1] "E001" "E002" "E003"

Note

The input string is assumed to be:

string <- c("G1:E001", "G2:E002", "G3:E003")

OSError: [WinError 193] %1 is not a valid Win32 application

The error is pretty clear. The file hello.py is not an executable file. You need to specify the executable:

subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])

You'll need python.exe to be visible on the search path, or you could pass the full path to the executable file that is running the calling script:

import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])

How to read file binary in C#?

Generally, I don't really see a possible way to do this. I've exhausted all of the options that the earlier comments gave you, and they don't seem to work. You could try this:

        `private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "This PC\\Documents";
        openFileDialog1.Filter = "All Files (*.*)|*.*";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Title = "Open a file with code";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string exeCode = string.Empty;
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName))) //Sets a new integer to the BinaryReader
            {
                br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                exeCode = Encoding.UTF8.GetString(br.ReadBytes(1000000000)); //Reads as many bytes as it can from the beginning of the .exe file
            }
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName)))
                br.Close(); //Closes the BinaryReader. Without it, opening the file with any other command will result the error "This file is being used by another process".

            richTextBox1.Text = exeCode;
        }
    }`
  • That's the code for the "Open..." button, but here's the code for the "Save..." button:

    ` private void button2_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog();

        save.Filter = "All Files (*.*)|*.*";
        save.Title = "Save Your Changes";
        save.InitialDirectory = "This PC\\Documents";
        save.FilterIndex = 1;
    
        if (save.ShowDialog() == DialogResult.OK)
        {
    
            using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(save.FileName))) //Sets a new integer to the BinaryReader
            {
                bw.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                bw.Write(richTextBox1.Text);
            }
        }
    }`
    
    • That's the save button. This works fine, but only shows the '!This cannot be run in DOS-Mode!' - Otherwise, if you can fix this, I don't know what to do.

    • My Site

CreateProcess: No such file or directory

I just had this problem.

In my case, the problem was due to problems when downloading the packages for GCC. The mingw-get program thought it finished the download, but it didn't.

I wanted to upgrade GCC, so I used mingw-get to get the newer version. For some reason, mingw-get thought the download for a particular file was finished, but it wasn't. When it went to extract the file, I guess it issued an error (which I didn't even bother to look -- I just ran "mingw-get update && mingw-get install mingw32-gcc" and left it there).

To solve, I removed gcc by doing "mingw-get remove mingw32-gcc" and also removed the package file (the one mingw-get didn't fully download), which was in the mingw cache folder ("C:\MinGW\var\cache\mingw-get\packages" in my system), then ran the install command again. It download and installed the missing parts of GCC (it had not fully downloaded the package gcc-core).

That solved my problem.

Interestingly enough, mingw-get was smart enough to continue the download of gcc-core even after me having deleted the package file in the cache folder, and also removed the package mingw32-gcc.

I think the more fundamental problem was that since gcc-core files were not installed, cc1 wasn't there. And gcc uses cc1. I guess that, when gcc tried to start cc1, it used CreateProcess somewhere passing the path of cc1, which was not the path of an existing file. Thus the error message.

How to import Google Web Font in CSS file?

We can easily do that in css3. We have to simply use @import statement. The following video easily describes the way how to do that. so go ahead and watch it out.

https://www.youtube.com/watch?v=wlPr6EF6GAo

Inserting an image with PHP and FPDF

Please note that you should not use any png when you are testing this , first work with jpg .

$myImage = "images/logos/mylogo.jpg";  // this is where you get your Image

$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);

Animate a custom Dialog

First, you have to create two animation resources in res/anim dir

slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromYDelta="100%"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toXDelta="0">
</translate>
</set>

slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate 
    android:duration="@android:integer/config_mediumAnimTime" 
    android:fromYDelta="0%p" 
    android:interpolator="@android:anim/accelerate_interpolator" 
    android:toYDelta="100%p">
</translate>
</set>

then you have to create a style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>

and add this line to your class

dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id

Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html

How do I enable C++11 in gcc?

I think you could do it using a specs file.

Under MinGW you could run
gcc -dumpspecs > specs

Where it says

*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT}

You change it to

*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT} -std=c++11

And then place it in
/mingw/lib/gcc/mingw32/<version>/specs

I'm sure you could do the same without a MinGW build. Not sure where to place the specs file though.

The folder is probably either /gcc/lib/ or /gcc/.

Show and hide a View with a slide up/down animation

One of the simple ways:

containerView.setLayoutTransition(LayoutTransition())
containerView.layoutTransition.enableTransitionType(LayoutTransition.CHANGING)

How to disable JavaScript in Chrome Developer Tools?

On Mac OS X:

  • Preferences
  • Show advanced settings
  • Press the "content settings" button
  • Scroll to the "JavaScript" section
  • Check the checkbox in front of "Do not allow any site to run JavaScript"

The Chrome Quick JavaScript Switcher extension is a lot easier though :-)

Updating a java map entry

If key is present table.put(key, val) will just overwrite the value else it'll create a new entry. Poof! and you are done. :)

you can get the value from a map by using key is table.get(key); That's about it

What is correct media query for IPad Pro?

Too late but may this save you from headache! All of these is because we have to detect the target browser is a mobile!

Is this a mobile then combine it with min/max-(width/height)'s

So Just this seems works:

@media (hover: none) {
    /* ... */
}

If the primary input mechanism system of the device cannot hover over elements with ease or they can but not easily (for example a long touch is performed to emulate the hover) or there is no primary input mechanism at all, we use none! There are many cases that you can read from bellow links.

Described as well Also for browser Support See this from MDN

String isNullOrEmpty in Java?

public static boolean isNull(String str) {
        return str == null ? true : false;
    }

    public static boolean isNullOrBlank(String param) {
        if (isNull(param) || param.trim().length() == 0) {
            return true;
        }
        return false;
    }

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

Can we overload the main method in Java?

Yes According to my point of view, we are able to overload the main method but method overloading that's it. For Example

class main_overload {
    public static void main(int a) {
        System.out.println(a);
    }
    public static void main(String args[]) {
        System.out.println("That's My Main Function");
        main(100);
    }
}

In This Double Back slash Step, I am just calling the main method....

"The system cannot find the file specified"

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. text

Generally issues like this are related to any of the following need to be looked at:

  • firewall settings from the web server to the database server
  • connection string errors
  • enable the appropriate protocol pipes/ tcp-ip

Try connecting to sql server with sql management server on the system that sql server is installed on and work from there. Pay attention to information in the errorlogs.

How to update the constant height constraint of a UIView programmatically?

To update a layout constraint you only need to update the constant property and call layoutIfNeeded after.

myConstraint.constant = newValue
myView.layoutIfNeeded()

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

Window vs Page vs UserControl for WPF navigation?

  • Window is like Windows.Forms.Form, so just a new window
  • Page is, according to online documentation:

    Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.

    So you basically use this if going you visualize some HTML content

  • UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows

Where is localhost folder located in Mac or Mac OS X?

The default Apache root folder (localhost/) is /Library/WebServer/Documents

Also, make sure you have the PHP5 module loaded in /etc/apache2/httpd.conf

LoadModule php5_module libexec/apache2/libphp5.so

Node.js fs.readdir recursive directory search

A. Have a look at the file module. It has a function called walk:

file.walk(start, callback)

Navigates a file tree, calling callback for each directory, passing in (null, dirPath, dirs, files).

This may be for you! And yes, it is async. However, I think you would have to aggregate the full path's yourself, if you needed them.

B. An alternative, and even one of my favourites: use the unix find for that. Why do something again, that has already been programmed? Maybe not exactly what you need, but still worth checking out:

var execFile = require('child_process').execFile;
execFile('find', [ 'somepath/' ], function(err, stdout, stderr) {
  var file_list = stdout.split('\n');
  /* now you've got a list with full path file names */
});

Find has a nice build-in caching mechanism that makes subsequent searches very fast, as long as only few folder have changed.

Make scrollbars only visible when a Div is hovered over?

This will work:

#div{
     max-height:300px;
     overflow:hidden;
}
#div:hover{
     overflow-y:scroll;
}

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

Pass Array Parameter in SqlCommand

Here is a minor variant of Brian's answer that someone else may find useful. Takes a List of keys and drops it into the parameter list.

//keyList is a List<string>
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
string sql = "SELECT fieldList FROM dbo.tableName WHERE keyField in (";
int i = 1;
foreach (string key in keyList) {
    sql = sql + "@key" + i + ",";
    command.Parameters.AddWithValue("@key" + i, key);
    i++;
}
sql = sql.TrimEnd(',') + ")";

Sending Email in Android using JavaMail API without using the default/built-in app

GmailBackground is small library to send an email in background without user interaction :

Usage:

    BackgroundMail.newBuilder(this)
            .withUsername("[email protected]")
            .withPassword("password12345")
            .withMailto("[email protected]")
            .withType(BackgroundMail.TYPE_PLAIN)
            .withSubject("this is the subject")
            .withBody("this is the body")
            .withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
                @Override
                public void onSuccess() {
                    //do some magic
                }
            })
            .withOnFailCallback(new BackgroundMail.OnFailCallback() {
                @Override
                public void onFail() {
                    //do some magic
                }
            })
            .send();

Configuration:

repositories {
    // ...
    maven { url "https://jitpack.io" }
 }
 dependencies {
            compile 'com.github.yesidlazaro:GmailBackground:1.2.0'
    }

Permissions:

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

Also for attachments, you need to set READ_EXTERNAL_STORAGE permission:

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

Source

(I've tested it myself)

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

Using Vim's tabs like buffers

If you want buffers to work like tabs, check out the tabline plugin.

That uses a single window, and adds a line on the top to simulate the tabs (just showing the list of buffers). This came out a long time ago when tabs were only supported in GVim but not in the command line vim. Since it is only operating with buffers, everything integrates well with the rest of vim.

How do I check for a network connection?

You can check for a network connection in .NET 2.0 using GetIsNetworkAvailable():

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

To monitor changes in IP address or changes in network availability use the events from the NetworkChange class:

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged

What is a clean, Pythonic way to have multiple constructors in Python?

I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.

class Gouda(Cheese):
    def __init__(self):
        super(Gouda).__init__(num_holes=10)


class Parmesan(Cheese):
    def __init__(self):
        super(Parmesan).__init__(num_holes=15) 

How do I "select Android SDK" in Android Studio?

There are multiple hit & trial solutions for this error. One of them will surely work for you. Below are the solutions:

1.

Tools -> Android -> Sync Project with Gradle Files (Android Studio 3.0.1)

2.

Go to build.gradle and click sync now

3.

Click this icon to sync gradle enter image description here

or edit any of your module gradle and then sync

4.

File -> Settings -> Android SDK -> Android SDK Location Edit -> Android SDK

5.

Open build.gradle file, just add a space or press enter. Then sync project.

6.

File -> Invalidate Caches / Restart

mongod command not recognized when trying to connect to a mongodb server

First, make sure you have the environment variable set up. 1. Right click on my computer 2. properties 3. advanced system settings 4. environment variables 5. edit the PATH variable. and add ;"C:\mongoDb\bin\" to the PATH variable.

Path in the quotes may differ depending on your installation directory. Do not forget the last '\' as it was the main problem in my case.

Can't access object property, even though it shows up in a console log

I had similar problem (when developing for SugarCRM), where I start with:

var leadBean = app.data.createBean('Leads', {id: this.model.attributes.parent_id});

// This should load object with attributes 
leadBean.fetch();

// Here were my attributes filled in with proper values including name
console.log(leadBean);

// Printed "undefined"
console.log(leadBean.attributes.name);

Problem was in fetch(), its async call so I had to rewrite my code into:

var leadBean = app.data.createBean('Leads', {id: this.model.attributes.parent_id});

// This should load object with attributes 
leadBean.fetch({
    success: function (lead) {
        // Printed my value correctly
        console.log(lead.attributes.name);
    }
});

Finish all previous activities

When user click on the logout button then write the following code:

Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

And also when after login if you call new activity do not use finish();

How to handle back button in activity

This is a simple way of doing something.

    @Override
        public void onBackPressed() {
            // do what you want to do when the "back" button is pressed.
            startActivity(new Intent(Activity.this, MainActivity.class));
            finish();
        }

I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.

OpenCV & Python - Image too big to display

Although I was expecting an automatic solution (fitting to the screen automatically), resizing solves the problem as well.

import cv2
cv2.namedWindow("output", cv2.WINDOW_NORMAL)        # Create window with freedom of dimensions
im = cv2.imread("earth.jpg")                        # Read image
imS = cv2.resize(im, (960, 540))                    # Resize image
cv2.imshow("output", imS)                            # Show image
cv2.waitKey(0)                                      # Display the image infinitely until any keypress

Unable to copy a file from obj\Debug to bin\Debug

I struggeled with this since years. I finally downloaded LockHunter to find out who locked the file. In my case it was MBAM. Once I added my project's directory to MBAMs exclusion list, I didn't have this problem anymore.

How to check if MySQL returns null/empty?

You can use is_null() function.

http://php.net/manual/en/function.is-null.php : in the comments :

mdufour at gmail dot com 20-Aug-2008 04:31 Testing for a NULL field/column returned by a mySQL query.

Say you want to check if field/column “foo” from a given row of the table “bar” when > returned by a mySQL query is null. You just use the “is_null()” function:

[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
     if (is_null($qValues["foo"]))
         echo "No foo data!";
     else
         echo "Foo data=".$qValues["foo"];
[…]

'router-outlet' is not a known element

There are two ways. 1. if you want to implement app.module.ts file then:

_x000D_
_x000D_
import { Routes, RouterModule } from '@angular/router';_x000D_
_x000D_
const appRoutes: Routes = [_x000D_
  { path: '', component: HomeComponent },_x000D_
  { path: 'user', component: UserComponent },_x000D_
  { path: 'server', component: ServerComponent }_x000D_
];_x000D_
_x000D_
@NgModule({_x000D_
  imports: [_x000D_
    RouterModule.forRoot(appRoutes)_x000D_
  ]_x000D_
})_x000D_
export class AppModule { }
_x000D_
_x000D_
_x000D_

  1. if you want to implement app-routing.module.ts (Separated Routing Module) file then:

_x000D_
_x000D_
//app-routing.module.ts_x000D_
import { NgModule } from '@angular/core';_x000D_
import { Routes, RouterModule } from '@angular/router';_x000D_
_x000D_
const appRoutes: Routes = [_x000D_
  { path: '', component: HomeComponent },_x000D_
  { path: 'users', component: UsersComponent },_x000D_
  { path: 'servers', component: ServersComponent }_x000D_
];_x000D_
_x000D_
@NgModule({_x000D_
  imports: [_x000D_
    RouterModule.forRoot(appRoutes)_x000D_
  ],_x000D_
  exports: [RouterModule]_x000D_
})_x000D_
export class AppRoutingModule { }_x000D_
_x000D_
//................................................................_x000D_
_x000D_
//app.module.ts_x000D_
import { AppRoutingModule } from './app-routing.module';_x000D_
_x000D_
@NgModule({_x000D_
  imports: [_x000D_
    AppRoutingModule_x000D_
  ]_x000D_
})_x000D_
export class AppModule { }
_x000D_
_x000D_
_x000D_

How do I create a list of random numbers without duplicates?

You can use Numpy library for quick answer as shown below -

Given code snippet lists down 6 unique numbers between the range of 0 to 5. You can adjust the parameters for your comfort.

import numpy as np
import random
a = np.linspace( 0, 5, 6 )
random.shuffle(a)
print(a)

Output

[ 2.  1.  5.  3.  4.  0.]

It doesn't put any constraints as we see in random.sample as referred here.

Hope this helps a bit.

Bootstrap control with multiple "data-toggle"

This is the best solution that I just implemented:

HTML

<a data-toggle="tooltip" rel="tooltip" data-placement="top" title="My Tooltip text!">Hover over me</a>

JAVASCRIPT that you anyway need to include regardless of what method you use.

$('[rel="tooltip"]').tooltip(); 

How to convert a plain object into an ES6 Map?

ES6

convert object to map:

const objToMap = (o) => new Map(Object.entries(o));

convert map to object:

const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )

Note: the mapToObj function assumes map keys are strings (will fail otherwise)

Does a `+` in a URL scheme/host/path represent a space?

Thou shalt always encode URLs.

Here is how Ruby encodes your URL:

irb(main):008:0> CGI.escape "a.com/a+b"
=> "a.com%2Fa%2Bb"

TypeError: 'module' object is not callable

I guess you have overridden the builtin function/variable or something else "module" by setting the global variable "module". just print the module see whats in it.

Determining the current foreground application from a background task or service

I combined two solutions in one method and it works for me for API 24 and for API 21. Others I didn't test.

The code in Kotlin:

private fun isAppInForeground(context: Context): Boolean {
    val appProcessInfo = ActivityManager.RunningAppProcessInfo()
    ActivityManager.getMyMemoryState(appProcessInfo)
    if (appProcessInfo.importance == IMPORTANCE_FOREGROUND ||
            appProcessInfo.importance == IMPORTANCE_VISIBLE) {
        return true
    } else if (appProcessInfo.importance == IMPORTANCE_TOP_SLEEPING ||
            appProcessInfo.importance == IMPORTANCE_BACKGROUND) {
        return false
    }

    val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val foregroundTaskInfo = am.getRunningTasks(1)[0]
    val foregroundTaskPackageName = foregroundTaskInfo.topActivity.packageName
    return foregroundTaskPackageName.toLowerCase() == context.packageName.toLowerCase()
}

and in Manifest

<!-- Check whether app in background or foreground -->
<uses-permission android:name="android.permission.GET_TASKS" />

How to call a method in MainActivity from another class?

You can make this method static.

public static void startChronometer(){
        mChronometer.start();
        showElapsedTime();
    } 

you can call this function in other class as below:

MainActivity.startChronometer();

OR

You can make an object of the main class in second class like,

MainActivity mActivity = new MainActivity();
mActivity.startChronometer();

Simple way to query connected USB devices info in Python?

For linux, I wrote a script called find_port.py which you can find here: https://github.com/dhylands/usb-ser-mon/blob/master/usb_ser_mon/find_port.py

It uses pyudev to enumerate all tty devices, and can match on various attributes.

Use the --list option to show all of the know USB serial ports and their attributes. You can filter by VID, PID, serial number, or vendor name. Use --help to see the filtering options.

find_port.py prints the /dev/ttyXXX name rather than the /dev/usb/... name.

$date + 1 year?

strtotime() is returning bool(false), because it can't parse the string '+one year' (it doesn't understand "one"). false is then being implicitly cast to the integer timestamp 0. It's a good idea to verify strtotime()'s output isn't bool(false) before you go shoving it in other functions.

From the docs:

Return Values

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

Ruby: How to convert a string to boolean

In rails, I've previously done something like this:

class ApplicationController < ActionController::Base
  # ...

  private def bool_from(value)
    !!ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
  end
  helper_method :bool_from

  # ...
end

Which is nice if you're trying to match your boolean strings comparisons in the same manner as rails would for your database.

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

Gradle store on local file system

I just stumbled onto this while searching for this answer. If you are using intellij, you can navigate to the file location, but opening the external lib folder in the project explorer, right clicking on the jar, and select Open Library Settings. enter image description here

How to list all tags along with the full message in git?

I prefer doing this on the command line, but if you don't mind a web interface and you use GitHub, you can visit https://github.com/user/repo/tags and click on the "..." next to each tag to display its annotation.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

How do I sort arrays using vbscript?

If you are going to output the lines anyway, you could run the output through the sort command. Not elegant, but it does not require much work:

cscript.exe //nologo YOUR-SCRIPT | Sort

Note //nologo omits the logo lines (Microsoft (R) Windows Script Host Version... blah blah blah) from appearing in the middle of your sorted output. (I guess MS does not know what stderr is for.)

See http://ss64.com/nt/sort.html for details on sort.

/+n is the most useful option if your sort key does not start in the first column.

Compares are always case-insensitive, which is lame.

what is the use of "response.setContentType("text/html")" in servlet

It means what type of response you want to send to client, some content types like :

 res.setContentType("image/gif");
 res.setContentType("application/pdf");
 res.setContentType("application/zip");

How can I dynamically switch web service addresses in .NET without a recompile?

When you generate a web reference and click on the web reference in the Solution Explorer. In the properties pane you should see something like this:

Web Reference Properties

Changing the value to dynamic will put an entry in your app.config.

Here is the CodePlex article that has more information.

Adding iOS UITableView HeaderView (not section header)

In Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    // We set the table view header.
    let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
    cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
    self.tableView.tableHeaderView = cellTableViewHeader

    // We set the table view footer, just know that it will also remove extra cells from tableview.
    let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
    cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
    self.tableView.tableFooterView = cellTableViewFooter
}

Encrypt and Decrypt in Java

If you use a static key, encrypt and decrypt always give the same result;

public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");

How do I create an executable in Visual Studio 2013 w/ C++?

  1. Click BUILD > Configuration Manager...
  2. Under Project contexts > Configuration, select "Release"
  3. BUILD > Build Solution or Rebuild Solution