Programs & Examples On #Mutability

Aren't Python strings immutable? Then why does a + " " + b work?

'mutable' means that we can change the content of the string, 'immutable' means that we can't add an extra string.

click for photo proof

How do I clone a generic List in Java?

I find using addAll works fine.

ArrayList<String> copy = new ArrayList<String>();
copy.addAll(original);

parentheses are used rather than the generics syntax

What is the difference between 127.0.0.1 and localhost

Well, by IP is faster.

Basically, when you call by server name, it is converted to original IP.

But it would be difficult to memorize an IP, for this reason the domain name was created.

Personally I use http://localhost instead of http://127.0.0.1 or http://username.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

Index inside map() function

You will be able to get the current iteration's index for the map method through its 2nd parameter.

Example:

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

Output:

The current iteration is: 0 <br>The current element is: h

The current iteration is: 1 <br>The current element is: e

The current iteration is: 2 <br>The current element is: l

The current iteration is: 3 <br>The current element is: l 

The current iteration is: 4 <br>The current element is: o

See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Parameters

callback - Function that produces an element of the new Array, taking three arguments:

1) currentValue
The current element being processed in the array.

2) index
The index of the current element being processed in the array.

3) array
The array map was called upon.

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

What is the .idea folder?

There is no problem in deleting this. It's not only the WebStorm IDE creating this file, but also PhpStorm and all other of JetBrains' IDEs.

It is safe to delete it but if your project is from GitLab or GitHub then you will see a warning.

Hibernate vs JPA vs JDO - pros and cons of each?

I am using JPA (OpenJPA implementation from Apache which is based on the KODO JDO codebase which is 5+ years old and extremely fast/reliable). IMHO anyone who tells you to bypass the specs is giving you bad advice. I put the time in and was definitely rewarded. With either JDO or JPA you can change vendors with minimal changes (JPA has orm mapping so we are talking less than a day to possibly change vendors). If you have 100+ tables like I do this is huge. Plus you get built0in caching with cluster-wise cache evictions and its all good. SQL/Jdbc is fine for high performance queries but transparent persistence is far superior for writing your algorithms and data input routines. I only have about 16 SQL queries in my whole system (50k+ lines of code).

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

> is not in the documentation.

< is for one-way binding.

@ binding is for passing strings. These strings support {{}} expressions for interpolated values.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope.

& binding is for passing a method into your directive's scope so that it can be called within your directive.

When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.

What does the "+" (plus sign) CSS selector mean?

It would match any element p that's immediately adjacent to an element 'p'. See: http://www.w3.org/TR/CSS2/selector.html

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){
                    alert('ok');
                }
});

Excel VBA - How to Redim a 2D array?

i solved this in a shorter fashion.

Dim marray() as variant, array2() as variant, YY ,ZZ as integer
YY=1
ZZ=1

Redim marray(1 to 1000, 1 to 10)
Do while ZZ<100 ' this is populating the first array
marray(ZZ,YY)= "something"
ZZ=ZZ+1
YY=YY+1 
Loop
'this part is where you store your array in another then resize and restore to original
array2= marray
Redim marray(1 to ZZ-1, 1 to YY)
marray = array2

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

In Win10 it might be helpful to download VirtualBox latest version.

It was the only thing that solved it for me. Hope it will save someone some time and trouble.

Regex not operator

No, there's no direct not operator. At least not the way you hope for.

You can use a zero-width negative lookahead, however:

\((?!2001)[0-9a-zA-z _\.\-:]*\)

The (?!...) part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).

There are actually 4 combinations of lookarounds with 2 axes:

  • lookbehind / lookahead : specifies if the characters before or after the point are considered
  • positive / negative : specifies if the characters must match or must not match.

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

How to make a countdown timer in Android?

Try this way:

private void startTimer() {
    startTimer = new CountDownTimer(30000, 1000) {

        public void onTick(long millisUntilFinished) {

            long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
 TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

            Log.e(TAG, "onTick: "+sec );
            tv_timer.setText(String.format("( %02d SEC )", sec));
            if(sec == 1)
            {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_timer.setText("( 00 SEC )");
                    }
                }, 1000);
            }


        }

        public void onFinish() {
            tv_timer.setText("Timer finish");
        }
    }.start();
}

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

How to create enum like type in TypeScript?

Update:

As noted by @iX3, Typescript 2.4 has support for enum strings.

See:Create an enum with string values in Typescript


Original answer:

For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;

Solution 1:

copied from: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/

There is a simple solution: Just cast the string literal to any before assigning:

export enum Language {
    English = <any>"English",
    German = <any>"German",
    French = <any>"French",
    Italian = <any>"Italian"
}

solution 2:

copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html

You can use a string literal as a type. For example:

let foo: 'Hello';

Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:

let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"

They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:

type CardinalDirection =
    "North"
    | "East"
    | "South"
    | "West";

function move(distance: number, direction: CardinalDirection) {
    // ...
}

move(1,"North"); // Okay
move(1,"Nurth"); // Error!

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Check your internet connection is stable or not. May be this will work with you

create a white rgba / CSS3

I believe

rgba( 0, 0, 0, 0.8 )

is equivalent in shade with #333.

Live demo: http://jsfiddle.net/8MVC5/1/

TypeScript: Interfaces vs Types

Other answers are great! Few other things which Type can do but Interface can't

You can use union in type

type Name = string | { FullName: string };

const myName = "Jon"; // works fine

const myFullName: Name = {
  FullName: "Jon Doe", //also works fine
};

Iterating over union properties in type

type Keys = "firstName" | "lastName";

type Name = {
  [key in Keys]: string;
};

const myName: Name = {
  firstName: "jon",
  lastName: "doe",
};

Intersection in type ( however, also supported in Interface with extends)

type Name = {
  firstName: string;
  lastName: string;
};

type Address = {
  city: string;
};

const person: Name & Address = {
  firstName: "jon",
  lastName: "doe",
  city: "scranton",
};

Also not that type was introduced later as compared to interface and according to the latest release of TS type can do *almost everything which interface can and much more!


*except Declaration merging (personal opinion: It's good that it's not supported in type as it may lead to inconsistency in code)

How to access array elements in a Django template?

when you render a request tou coctext some information: for exampel:

return render(request, 'path to template',{'username' :username , 'email'.email})

you can acces to it on template like this : for variabels :

{% if username %}{{ username }}{% endif %}

for array :

{% if username %}{{ username.1 }}{% endif %}
{% if username %}{{ username.2 }}{% endif %}

you can also name array objects in views.py and ten use it like:

{% if username %}{{ username.first }}{% endif %}

if there is other problem i wish to help you

How do I get the last inserted ID of a MySQL table in PHP?

It's ok to use mysql_insert_id(), but there is one specific note about using it, you must call it after executed INSERT query, means in the same script session. If you use it otherwise it wouldn't work correctly.

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Math operations from string

The best way would be to do:

print eval("2 + 2")

If you wanted to you could use a variable:

addition = eval("2 + 2") print addition

If you really wanted to, you could use a function:

def add(num1, num2): eval("num1 + num2")

Store output of subprocess.Popen call in a string

subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen

import subprocess

command = "ntpq -p"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)

#Launch the shell command:
output = process.communicate()

print output[0]

In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:

command = ["ntpq", "-p"]  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)

If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:

import subprocess

command = "ntpq -p"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

#Launch the shell command:
output, error = process.communicate()

How do I get multiple subplots in matplotlib?

  • You can also unpack the axes in the subplots call

  • And set whether you want to share the x and y axes between the subplots

Like this:

import matplotlib.pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()

enter image description here

Authentication failed because remote party has closed the transport stream

Adding the below code helped me overcome the issue.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

Difference between const reference and normal parameter

The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.

Because the reference is a const reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.

There are crucial differences. If the parameter is a const reference, but the object passed it was not in fact const then the value of the object may be changed during the function call itself.

E.g.

int a;

void DoWork(const int &n)
{
    a = n * 2;  // If n was a reference to a, n will have been doubled 

    f();  // Might change the value of whatever n refers to 
}

int main()
{
    DoWork(a);
}

Also if the object passed in was not actually const then the function could (even if it is ill advised) change its value with a cast.

e.g.

void DoWork(const int &n)
{
    const_cast<int&>(n) = 22;
}

This would cause undefined behaviour if the object passed in was actually const.

When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.

When the parameter is passed by value and extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.

Combining two expressions (Expression<Func<T, bool>>)

I suggest one more improvement to PredicateBuilder and ExpressionVisitor solutions. I called it UnifyParametersByName and you can find it in MIT library of mine: LinqExprHelper. It allows for combining arbitary lambda expressions. Usually the questions are asked about predicate expression, but this idea extends to projection expressions as well.

The following code employs a method ExprAdres which creates a complicated parametrized expression, using inline lambda. This complicated expression is coded only once, and then reused, thanks to the LinqExprHelper mini-library.

public IQueryable<UbezpExt> UbezpFull
{
    get
    {
        System.Linq.Expressions.Expression<
            Func<UBEZPIECZONY, UBEZP_ADRES, UBEZP_ADRES, UbezpExt>> expr =
            (u, parAdrM, parAdrZ) => new UbezpExt
            {
                Ub = u,
                AdrM = parAdrM,
                AdrZ = parAdrZ,
            };

        // From here an expression builder ExprAdres is called.
        var expr2 = expr
            .ReplacePar("parAdrM", ExprAdres("M").Body)
            .ReplacePar("parAdrZ", ExprAdres("Z").Body);
        return UBEZPIECZONY.Select((Expression<Func<UBEZPIECZONY, UbezpExt>>)expr2);
    }
}

And this is the subexpression building code:

public static Expression<Func<UBEZPIECZONY, UBEZP_ADRES>> ExprAdres(string sTyp)
{
    return u => u.UBEZP_ADRES.Where(a => a.TYP_ADRESU == sTyp)
        .OrderByDescending(a => a.DATAOD).FirstOrDefault();
}

What I tried to achieve was to perform parametrized queries without need to copy-paste and with ability to use inline lambdas, which are so pretty. Without all these helper-expression stuff, I would be forced to create whole query in one go.

How to update Xcode from command line

I am now running OS Big Sur. xcode-select --install, and sudo xcode-select --reset did not resolve my issue, neither did the recommended subsequent softwareupdate --install -a command. For good measure, I tried the recommended download from Apple Downloads, but the Command Line Tools downloads available there are not compatible with my OS.

I upvoted the fix that resolved for me, sudo xcode-select --switch /Library/Developer/CommandLineTools/ and added this post for environment context.

How do I enable/disable log levels in Android?

I took a simple route - creating a wrapper class that also makes use of variable parameter lists.

 public class Log{
        public static int LEVEL = android.util.Log.WARN;


    static public void d(String tag, String msgFormat, Object...args)
    {
        if (LEVEL<=android.util.Log.DEBUG)
        {
            android.util.Log.d(tag, String.format(msgFormat, args));
        }
    }

    static public void d(String tag, Throwable t, String msgFormat, Object...args)
    {
        if (LEVEL<=android.util.Log.DEBUG)
        {
            android.util.Log.d(tag, String.format(msgFormat, args), t);
        }
    }

    //...other level logging functions snipped

How to convert List to Json in Java

Look at the google gson library. It provides a rich api for dealing with this and is very straightforward to use.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

Try placing the desired java directory in PATH before not needed java directories in your PATH.

Make a nav bar stick

/* Add css in your style */


.sticky-header {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 100;
    border-top: 0;
    transition: 0.3s;
}


/* and use this javascript code: */

$(document).ready(function() {

  $(window).scroll(function () {
    if ($(window).scrollTop() > ) {
      $('.headercss').addClass('sticky-header');
    } else{
      $('.headercss').removeClass('sticky-header');
    }
  });
});

PHP-FPM doesn't write to error log

I gathered insights from a bunch of answers here and I present a comprehensive solution:

So, if you setup nginx with php5-fpm and log a message using error_log() you can see it in /var/log/nginx/error.log by default.

A problem can arise if you want to log a lot of data (say an array) using error_log(print_r($myArr, true));. If an array is large enough, it seems that nginx will truncate your log entry.

To get around this you can configure fpm (php.net fpm config) to manage logs. Here are the steps to do so.

  1. Open /etc/php5/fpm/pool.d/www.conf:

    $ sudo nano /etc/php5/fpm/pool.d/www.conf

  2. Uncomment the following two lines by removing ; at the beginning of the line: (error_log is defined here: php.net)

    ;php_admin_value[error_log] = /var/log/fpm-php.www.log ;php_admin_flag[log_errors] = on

  3. Create /var/log/fpm-php.www.log:

    $ sudo touch /var/log/fpm-php.www.log;

  4. Change ownership of /var/log/fpm-php.www.log so that php5-fpm can edit it:

    $ sudo chown vagrant /var/log/fpm-php.www.log

    Note: vagrant is the user that I need to give ownership to. You can see what user this should be for you by running $ ps aux | grep php.*www and looking at first column.

  5. Restart php5-fpm:

    $ sudo service php5-fpm restart

Now your logs will be in /var/log/fpm-php.www.log.

Google reCAPTCHA: How to get user response and validate in the server side?

The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.

But that does not keep your site safe from HTTP client request forgery.

Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and foll your site to make it think that this field was provided by the google widget. So you have to validate this token.

In human speech it would be like,

  • Your Server: Hey Google, there's a dude that tells me that he's not a robot. He says that you already verified that he's a human, and he told me to give you this token as a proof of that.
  • Google: Hmm... let me check this token... yes I remember this dude I gave him this token... yeah he's made of flesh and bone let him through.
  • Your Server: Hey Google, there's another dude that tells me that he's a human. He also gave me a token.
  • Google: Hmm... it's the same token you gave me last time... I'm pretty sure this guy is trying to fool you. Tell him to get off your site.

Validating the response is really easy. Just make a GET Request to

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

And replace the response_string with the value that you earlier got by the g-recaptcha-response field.

You will get a JSON Response with a success field.

More information here: https://developers.google.com/recaptcha/docs/verify

Edit: It's actually a POST, as per documentation here.

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

setTimeout in for-loop does not print consecutive values

the real solution is here, but you need to be familiar with PHP programing language. you must mix PHP and JAVASCRIPT orders in order to reach to your purpose.

pay attention to this :

<?php 
for($i=1;$i<=3;$i++){
echo "<script language='javascript' >
setTimeout(function(){alert('".$i."');},3000);  
</script>";
}
?> 

It exactly does what you want, but be careful about how to make ralation between PHP variables and JAVASCRIPT ones.

rails 3 validation on uniqueness on multiple attributes

In Rails 2, I would have written:

validates_uniqueness_of :zipcode, :scope => :recorded_at

In Rails 3:

validates :zipcode, :uniqueness => {:scope => :recorded_at}

For multiple attributes:

validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}

Output to the same line overwriting previous output?

I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'.

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',

This is shorter than other non-python 3 solutions, but also more difficult to maintain.

Send PHP variable to javascript function

A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:

data: 'username='+username+'&password='+password,

In the FILE2.php example, you would retrieve those values like this:

$uname = $_POST['username'];
$pword = $_POST['password'];

Then do your MySQL lookup and return the values thus:

echo 'You are logged in';

This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.

Here is another good example to review.

The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.

The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).

The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.

In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.

When is a language considered a scripting language?

Traditionally, when talking about the difference about scripting versus programming, scripts are interpreted and programs are compiled. A language can be executed in different ways - interpreted or compiled (to bytecode or machine code). This does not make a language one or another.

In some eyes, the way you use a language makes it a scripting language (for example, game developers who develop mainly in C++ will script the objects in Lua). Again, the lines are blurred - a language can be used for a programming by one person and the same language can be used for scripting language by another.

This is from the wikipedia article about scripting languages:

A scripting language, script language or extension language is a programming language that allows control of one or more software applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the end-user. Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code. Scripting languages are nearly always embedded in the applications they control.

You will notice the use of "usually", "often", "traditionally" and "nearly always" - these all tell you that there is no set of distinct attributes that make a specific language a "scripting language".

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

doGet and doPost in Servlets

If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted. On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.

Examples from my html:

<body>  
<form action="StartProcessUrl" method="post">
.....
.....

Examples from my java servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
         String surname = request.getParameter("txtSurname");
         String firstname = request.getParameter("txtForename");
         String rqNo = request.getParameter("txtRQ6");
         String nhsNo = request.getParameter("txtNHSNo");

         String attachment1 = request.getParameter("base64textarea1");
         String attachment2 = request.getParameter("base64textarea2");

.........
.........

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

fatal: 'origin' does not appear to be a git repository

$HOME/.gitconfig is your global config for git.
There are three levels of config files.

 cat $(git rev-parse --show-toplevel)/.git/config

(mentioned by bereal) is your local config, local to the repo you have cloned.

you can also type from within your repo:

git remote -v

And see if there is any remote named 'origin' listed in it.

If not, if that remote (which is created by default when cloning a repo) is missing, you can add it again:

git remote add origin url/to/your/fork

The OP mentions:

Doing git remote -v gives:

upstream git://git.moodle.org/moodle.git (fetch) 
upstream git://git.moodle.org/moodle.git (push)

So 'origin' is missing: the reference to your fork.
See "What is the difference between origin and upstream in github"

enter image description here

Javascript: How to check if a string is empty?

if (value == "") {
  // it is empty
}

SHA512 vs. Blowfish and Bcrypt

Blowfish is not a hashing algorithm. It's an encryption algorithm. What that means is that you can encrypt something using blowfish, and then later on you can decrypt it back to plain text.

SHA512 is a hashing algorithm. That means that (in theory) once you hash the input you can't get the original input back again.

They're 2 different things, designed to be used for different tasks. There is no 'correct' answer to "is blowfish better than SHA512?" You might as well ask "are apples better than kangaroos?"

If you want to read some more on the topic here's some links:

Optional Parameters in Go?

You can encapsulate this quite nicely in a func similar to what is below.

package main

import (
        "bufio"
        "fmt"
        "os"
)

func main() {
        fmt.Println(prompt())
}

func prompt(params ...string) string {
        prompt := ": "
        if len(params) > 0 {
                prompt = params[0]
        }
        reader := bufio.NewReader(os.Stdin)
        fmt.Print(prompt)
        text, _ := reader.ReadString('\n')
        return text
}

In this example, the prompt by default has a colon and a space in front of it . . .

: 

. . . however you can override that by supplying a parameter to the prompt function.

prompt("Input here -> ")

This will result in a prompt like below.

Input here ->

How do you implement a good profanity filter?

I concluded, in order to create a good profanity filter we need 3 main components, or at least it is what I am going to do. These they are:

  1. The filter: a background service that verify against a blacklist, dictionary or something like that.
  2. Not allow anonymous account
  3. Report abuse

A bonus, it will be to reward somehow those who contribute with accurate abuse reporters and punish the offender, e.g. suspend their accounts.

Can Windows' built-in ZIP compression be scripted?

Just for clarity: GZip is not an MS-only algorithm as suggested by Guy Starbuck in his comment from August. The GZipStream in System.IO.Compression uses the Deflate algorithm, just the same as the zlib library, and many other zip tools. That class is fully interoperable with unix utilities like gzip.

The GZipStream class is not scriptable from the commandline or VBScript, to produce ZIP files, so it alone would not be an answer the original poster's request.

The free DotNetZip library does read and produce zip files, and can be scripted from VBScript or Powershell. It also includes command-line tools to produce and read/extract zip files.

Here's some code for VBScript:

dim filename 
filename = "C:\temp\ZipFile-created-from-VBScript.zip"

WScript.echo("Instantiating a ZipFile object...")
dim zip 
set zip = CreateObject("Ionic.Zip.ZipFile")

WScript.echo("using AES256 encryption...")
zip.Encryption = 3

WScript.echo("setting the password...")
zip.Password = "Very.Secret.Password!"

WScript.echo("adding a selection of files...")
zip.AddSelectedFiles("*.js")
zip.AddSelectedFiles("*.vbs")

WScript.echo("setting the save name...")
zip.Name = filename

WScript.echo("Saving...")
zip.Save()

WScript.echo("Disposing...")
zip.Dispose()

WScript.echo("Done.")

Here's some code for Powershell:

[System.Reflection.Assembly]::LoadFrom("c:\\dinoch\\bin\\Ionic.Zip.dll");

$directoryToZip = "c:\\temp";
$zipfile =  new-object Ionic.Zip.ZipFile;
$e= $zipfile.AddEntry("Readme.txt", "This is a zipfile created from within powershell.")
$e= $zipfile.AddDirectory($directoryToZip, "home")
$zipfile.Save("ZipFiles.ps1.out.zip");

In a .bat or .cmd file, you can use the zipit.exe or unzip.exe tools. Eg:

zipit NewZip.zip  -s "This is string content for an entry"  Readme.txt  src 

Maximum and Minimum values for ints

The sys.maxint constant has been removed from Python 3.0 onward, instead use sys.maxsize.

Integers

  • PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.
  • PEP 238: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)
  • The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
  • The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally strips that character will chop off the last digit instead. (Use str() instead.)
  • Octal literals are no longer of the form 0720; use 0o720 instead.

Refer : https://docs.python.org/3/whatsnew/3.0.html#integers

Call child component method from parent class - Angular

I had an exact situation where the Parent-component had a Select element in a form and on submit, I needed to call the relevant Child-Component's method according to the selected value from the select element.

Parent.HTML:

<form (ngSubmit)='selX' [formGroup]="xSelForm">
    <select formControlName="xSelector">
      ...
    </select>
<button type="submit">Submit</button>
</form>
<child [selectedX]="selectedX"></child>

Parent.TS:

selX(){
  this.selectedX = this.xSelForm.value['xSelector'];
}

Child.TS:

export class ChildComponent implements OnChanges {
  @Input() public selectedX;

  //ngOnChanges will execute if there is a change in the value of selectedX which has been passed to child as an @Input.

  ngOnChanges(changes: { [propKey: string]: SimpleChange }) {
    this.childFunction();
  }
  childFunction(){ }
}

Hope this helps.

How do I Search/Find and Replace in a standard string?

Why not return a modified string?

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not changed: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

How to use select/option/NgFor on an array of objects in Angular2

I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `
      <h4>Select Object via 2-way binding</h4>

      <select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
      </select>

      <h4>You selected:</h4> {{selectedObject }}
  `,
  directives: [FORM_DIRECTIVES]
})
export class App {
  objArray:TestObject[];
  selectedObject:TestObject;
  constructor(){
    this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
    this.selectedObject = this.objArray[1];
  }
  updateSelectedValue(event:string): void{
    this.selectedObject = JSON.parse(event);
  }
}

Delete all lines beginning with a # from a file

I'm a little surprised nobody has suggested the most obvious solution:

grep -v '^#' filename

This solves the problem as stated.

But note that a common convention is for everything from a # to the end of a line to be treated as a comment:

sed 's/#.*$//' filename

though that treats, for example, a # character within a string literal as the beginning of a comment (which may or may not be relevant for your case) (and it leaves empty lines).

A line starting with arbitrary whitespace followed by # might also be treated as a comment:

grep -v '^ *#' filename

if whitespace is only spaces, or

grep -v '^[  ]#' filename

where the two spaces are actually a space followed by a literal tab character (type "control-v tab").

For all these commands, omit the filename argument to read from standard input (e.g., as part of a pipe).

User GETDATE() to put current date into SQL variable

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

Showing all session data at once?

echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";

Display yet formatting then you can view properly.

gnuplot : plotting data from multiple input files in a single graph

replot

This is another way to get multiple plots at once:

plot file1.data
replot file2.data

Load JSON text into class object in c#

To create a json class off a string, copy the string.

In Visual Sudio, click Edit > Paste special > Paste Json as classes.

kill a process in bash

It is not clear to me what you mean by "escape an executable which is running", but ctrl-z will put a process into the background and return control to the command line. You can then use the fg command to bring the program back into the foreground.

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

[nodemon] Internal watch failed: watch /home/Document/nmmExpressServer/bin ENOSPC
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `nodemon ./bin/www`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start script.

This is the error I got when running nodemon ./bin/www.

The solution was closing an Atom window that had a entire directory of folders open in the project window.

I don't know why, but I'm assuming Atom and nodemon use similar processes to watch files/folders.

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

getSupportFragmentManager() is not part of Fragment, so you cannot get it here that way. You can get it from parent Activity (so in onAttach() the earliest) using normal

activity.getSupportFragmentManager();

or you can try getChildFragmentManager(), which is in scope of Fragment, but requires API17+

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You don't need to down grade. You can run more than one version of Java on MacOS. You can set the version of your terminal with this command in MacOS.

# List Java versions installed
/usr/libexec/java_home -V

# Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)

# Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

# Java 1.7
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

# Java 1.6
export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)

You can set the default value in the .bashrc, .profile, or .zprofile

What is SuppressWarnings ("unchecked") in Java?

Simply: It's a warning by which the compiler indicates that it cannot ensure type safety.

JPA service method for example:

@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
    Query query = entitymanager.createQuery("SELECT u FROM User u");
    return (List<User>)query.getResultList();
}

If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList.

In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.

I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html

Local dependency in package.json

Actually, as of npm 2.0, there is support now local paths (see here).

How to suppress Pandas Future warning ?

Warnings are annoying. As mentioned in other answers, you can suppress them using:

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:

import warnings
warnings.filterwarnings("error")

But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:

import warnings
warnings.simplefilter(action='error', category=FutureWarning)

Printing a 2D array in C

...
for(int i=0;i<3;i++){ //Rows
for(int j=0;j<5;j++){ //Cols
 printf("%<...>\t",var);
}
printf("\n");
}
...

considering that <...> would be d,e,f,s,c... etc datatype... X)

Controlling Spacing Between Table Cells

Use the border-spacing property on the table element to set the spacing between cells.

Make sure border-collapse is set to separate (or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).

How do I print an IFrame from javascript in Safari/Chrome

Put a print function in the iframe and call it from the parent.

iframe:

function printMe() {
  window.print()
}

parent:

document.frame1.printMe()

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.

      <select defaultValue={'DEFAULT'} >
        <option value="DEFAULT" disabled>Choose a salutation ...</option>
        <option value="1">Mr</option>
        <option value="2">Mrs</option>
        <option value="3">Ms</option>
        <option value="4">Miss</option>
        <option value="5">Dr</option>
      </select>

Here the user is forced to pick an option!

EDIT

If this is a controlled component

In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.

 function TheSelectComponent(props){
     let currentValue = props.curentValue || "DEFAULT";
     return(
      <select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
        <option value="DEFAULT" disabled>Choose a salutation ...</option>
        <option value="1">Mr</option>
        <option value="2">Mrs</option>
        <option value="3">Ms</option>
        <option value="4">Miss</option>
        <option value="5">Dr</option>
      </select>
    )
}

How to upgrade scikit-learn package in anaconda

Anaconda comes with the conda package manager which is designed to handle these kinds of upgrades. Start by updating conda itself to get the most recent package lists:

conda update conda

And then install the version of scikit-learn you want

conda install scikit-learn=0.17

All necessary dependencies will be upgraded as well. If you have trouble with conda on Windows, there are some relevant FAQ here: http://docs.continuum.io/anaconda/faq

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

CSS

img{border:2px solid black;}

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

How to see indexes for a database or table in MySQL?

To check all disabled indexes on db

SELECT INDEX_SCHEMA, COLUMN_NAME, COMMENT 
FROM information_schema.statistics
WHERE table_schema = 'mydb'
AND COMMENT = 'disabled'

Giving graphs a subtitle in matplotlib

What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different fontsize arguments). Hope that helps!

How to get data by SqlDataReader.GetValue by column name

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

Change size of axes title and labels in ggplot2

If you are creating many graphs, you could be tired of typing for each graph the lines of code controlling for the size of the titles and texts. What I typically do is creating an object (of class "theme" "gg") that defines the desired theme characteristics. You can do that at the beginning of your code.

My_Theme = theme(
  axis.title.x = element_text(size = 16),
  axis.text.x = element_text(size = 14),
  axis.title.y = element_text(size = 16))

Next, all you will have to do is adding My_Theme to your graphs.

g + My_Theme
if you have another graph, g1, just write:
g1 + My_Theme 
and so on.

What's the best way to determine which version of Oracle client I'm running?

Issue #1: Multiple Oracle clients are installed.

A very common issue I see in my environment is that I see both workstations and (app) servers with multiple Oracle clients, sometimes as many as four, and possibly with different versions and architectures. If you are relying on the PATH and running a utility like SQLPLUS or TNSPING you'll have one of two unacceptable results:

  • either your PATH successfully resolves the executable and you get ONE version result
  • or, the PATH didn't resolve the executable, and you get no results.

Either way, you are blind to possibly multiple client installations.

Issue #2: Instant Client doesn't have TNSPING, and sometimes doesn't include SQL*Plus.

If a computer has the Oracle Instant Client (not the full client), then TNSPING is not included, and SQLPLUS is an optional-addon. So can't rely on those tools being there. Furthermore, the Instant Client is sometimes installed as an unzip-and-go solution, so there's no Oracle Inventory and nothing in HKLM.

Issue #3: Client was installed using "Custom", and ODBC, OLEDB, ODP.Net, and JDBC were not installed.

Obvious case, there will be no ODBC or JDBC readme's to scrape version info from.

Solution:

One thing that the Instant client and the full client have in common is a DLL file called oraclient10.dll, oraclient11.dll, generally: oraclient*.dll. So let's traverse the hard disk to find them and extract their version info. PowerShell is amazing at this and can do it in one line, reminds me of home sweet Unix. So you could do this programatically or even remotely.

Here's the one-liner (sorry about the right scroll, but that's the nature of one-liners, eh?). Supposing you're already in a PowerShell:

gci C:\,D:\ -recurse -filter 'oraclient*.dll' -ErrorAction SilentlyContinue | %{ $_.VersionInfo } | ft -Property FileVersion, FileName -AutoSize

And if you're not in PowerShell, i.e. you're simply in a CMD shell, then no problem, just call powershell " ... ", as follows:

powershell "gci C:\,D:\ -recurse -filter 'oraclient*.dll' -ErrorAction SilentlyContinue | %{ $_.VersionInfo } | ft -Property FileVersion, FileName -AutoSize"

Example Outputs

Here's some outputs from some of my systems. This bad citizen has 3 Oracle 11.2.0.3 clients. You can see that some of them are 32-bit and others are 64-bit:

FileVersion            FileName
-----------            --------
11.2.0.3.0 Production  C:\NoSync\app\oracle\product\11.2\client_1\bin\oraclient...
11.2.0.3.0 Production  C:\oracle\product\11.2.0\client_1\bin\oraclient11.dll
11.2.0.3.0 Production  C:\oracle64\product\11.2.0\client_1\bin\oraclient11.dll

Another system, this one has 10g client on the D:\

FileVersion           FileName
-----------           --------
10.2.0.4.0 Production D:\oracle\product\10.2\BIN\oraclient10.dll

Caveats/Issues

  • This obviously requires PowerShell, which is standard in Windows 7+ and Server 2008 R2+. If you have XP (which you shouldn't any more) you can easily install PowerShell.

  • I haven't tried this on 8i/9i or 12c. If you are running 8i/9i, then there's a good chance you are on an old OS as well and don't have PowerShell and Heaven help you. It should work with 12c, since I see there is such a file oraclient12.dll that gets installed. I just don't have a Windows 12c client to play with yet.

How do I read a resource file from a Java jar file?

Outside of your technique, why not use the standard Java JarFile class to get the references you want? From there most of your problems should go away.

Determine command line working directory when running node bin script

Alternatively, if you want to solely obtain the current directory of the current NodeJS script, you could try something simple like this. Note that this will not work in the Node CLI itself:

var fs = require('fs'),
    path = require('path');

var dirString = path.dirname(fs.realpathSync(__filename));

// output example: "/Users/jb/workspace/abtest"
console.log('directory to start walking...', dirString);

a href link for entire div in HTML/CSS

This can be done in many ways. a. Using nested inside a tag.

<a href="link1.html">
   <div> Something in the div </div>
 </a>

b. Using the Inline JavaScript Method

<div onclick="javascript:window.location.href='link1.html' "> 
  Some Text 
</div>

c. Using jQuery inside tag

HTML:

<div class="demo" > Some text here </div>

jQuery:

$(".demo").click( function() {
  window.location.href="link1.html";
 });

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

How using try catch for exception handling is best practice

I know this is an old question, but nobody here mentioned the MSDN article, and it was the document that actually cleared it up for me, MSDN has a very good document on this, you should catch exceptions when the following conditions are true:

  • You have a good understanding of why the exception might be thrown, and you can implement a specific recovery, such as prompting the user to enter a new file name when you catch a FileNotFoundException object.

  • You can create and throw a new, more specific exception.

int GetInt(int[] array, int index)
{
    try
    {
        return array[index];
    }
    catch(System.IndexOutOfRangeException e)
    {
        throw new System.ArgumentOutOfRangeException(
            "Parameter index is out of range.");
    }
}
  • You want to partially handle an exception before passing it on for additional handling. In the following example, a catch block is used to add an entry to an error log before re-throwing the exception.
    try
{
    // Try to access a resource.
}
catch (System.UnauthorizedAccessException e)
{
    // Call a custom error logging procedure.
    LogError(e);
    // Re-throw the error.
    throw;     
}

I'd suggest reading the entire "Exceptions and Exception Handling" section and also Best Practices for Exceptions.

Event listener for when element becomes visible?

There is at least one way, but it's not a very good one. You could just poll the element for changes like this:

var previous_style,
    poll = window.setInterval(function()
{
    var current_style = document.getElementById('target').style.display;
    if (previous_style != current_style) {
        alert('style changed');
        window.clearInterval(poll);
    } else {
        previous_style = current_style;
    }
}, 100);

The DOM standard also specifies mutation events, but I've never had the chance to use them, and I'm not sure how well they're supported. You'd use them like this:

target.addEventListener('DOMAttrModified', function()
{
    if (e.attrName == 'style') {
        alert('style changed');
    }
}, false);

This code is off the top of my head, so I'm not sure if it'd work.

The best and easiest solution would be to have a callback in the function displaying your target.

Search for executable files using find command

Tip of the hat to @gniourf_gniourf for clearing up a fundamental misconception.

This answer attempts to provide an overview of the existing answers and to discuss their subtleties and relative merits as well as to provide background information, especially with respect to portability.

Finding files that are executable can refer to two distinct use cases:

  • user-centric: find files that are executable by the current user.
  • file-centric: find files that have (one or more) executable permission bits set.

Note that in either scenario it may make sense to use find -L ... instead of just find ... in order to also find symlinks to executables.

Note that the simplest file-centric case - looking for executables with the executable permissions bit set for ALL three security principals (user, group, other) - will typically, but not necessarily yield the same results as the user-centric scenario - and it's important to understand the difference.

User-centric (-executable)

  • The accepted answer commendably recommends -executable, IF GNU find is available.

    • GNU find comes with most Linux distros
      • By contrast, BSD-based platforms, including macOS, come with BSD find, which is less powerful.
    • As the scenario demands, -executable matches only files the current user can execute (there are edge cases.[1]).
  • The BSD find alternative offered by the accepted answer (-perm +111) answers a different, file-centric question (as the answer itself states).

    • Using just -perm to answer the user-centric question is impossible, because what is needed is to relate the file's user and group identity to the current user's, whereas -perm can only test the file's permissions.
      Using only POSIX find features, the question cannot be answered without involving external utilities.
    • Thus, the best -perm can do (by itself) is an approximation of -executable. Perhaps a closer approximation than -perm +111 is -perm -111, so as to find files that have the executable bit set for ALL security principals (user, group, other) - this strikes me as the typical real-world scenario. As a bonus, it also happens to be POSIX-compliant (use find -L to include symlinks, see farther below for an explanation):

      find . -type f -perm -111  # or: find . -type f -perm -a=x
      
  • gniourf_gniourf's answer provides a true, portable equivalent of -executable, using -exec test -x {} \;, albeit at the expense of performance.

    • Combining -exec test -x {} \; with -perm +111 (i.e., files with at least one executable bit set) may help performance in that exec needn't be invoked for every file (the following uses the POSIX-compliant equivalent of BSD find -perm +111 / GNU find -perm /111; see farther below for an explanation):

      find . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \) -exec test -x {} \; -print
      

File-centric (-perm)

  • To answer file-centric questions, it is sufficient to use the POSIX-compliant -perm primary (known as a test in GNU find terminology).
    • -perm allows you to test for any file permissions, not just executability.
    • Permissions are specified as either octal or symbolic modes. Octal modes are octal numbers (e.g., 111), whereas symbolic modes are strings (e.g., a=x).
    • Symbolic modes identify the security principals as u (user), g (group) and o (other), or a to refer to all three. Permissions are expressed as x for executable, for instance, and assigned to principals using operators =, + and -; for a full discussion, including of octal modes, see the POSIX spec for the chmod utility.
    • In the context of find:
      • Prefixing a mode with - (e.g., -ug=x) means: match files that have all the permissions specified (but matching files may have additional permissions).
      • Having NO prefix (e.g. 755) means: match files that have this full, exact set of permissions.
      • Caveat: Both GNU find and BSD find implement an additional, nonstandard prefix with are-ANY-of-the-specified-permission-bits-set logic, but do so with incompatible syntax:
        • BSD find: +
        • GNU find: / [2]
      • Therefore, avoid these extensions, if your code must be portable.
  • The examples below demonstrate portable answers to various file-centric questions.

File-centric command examples

Note:

  • The following examples are POSIX-compliant, meaning they should work in any POSIX-compatible implementation, including GNU find and BSD find; specifically, this requires:
    • NOT using nonstandard mode prefixes + or /.
    • Using the POSIX forms of the logical-operator primaries:
      • ! for NOT (GNU find and BSD find also allow -not); note that \! is used in the examples so as to protect ! from shell history expansions
      • -a for AND (GNU find and BSD find also allow -and)
      • -o for OR (GNU find and BSD find also allow -or)
  • The examples use symbolic modes, because they're easier to read and remember.
    • With mode prefix -, the = and + operators can be used interchangeably (e.g., -u=x is equivalent to -u+x - unless you apply -x later, but there's no point in doing that).
    • Use , to join partial modes; AND logic is implied; e.g., -u=x,g=x means that both the user and the group executable bit must be set.
    • Modes cannot themselves express negative matching in the sense of "match only if this bit is NOT set"; you must use a separate -perm expression with the NOT primary, !.
  • Note that find's primaries (such as -print, or -perm; also known as actions and tests in GNU find) are implicitly joined with -a (logical AND), and that -o and possibly parentheses (escaped as \( and \) for the shell) are needed to implement OR logic.
  • find -L ... instead of just find ... is used in order to also match symlinks to executables
    • -L instructs find to evaluate the targets of symlinks instead of the symlinks themselves; therefore, without -L, -type f would ignore symlinks altogether.
# Match files that have ALL executable bits set - for ALL 3 security
# principals (u (user), g (group), o (others)) and are therefore executable
# by *anyone*.
# This is the typical case, and applies to executables in _system_ locations
# (e.g., /bin) and user-installed executables in _shared_ locations
# (e.g., /usr/local/bin), for instance. 
find -L . -type f -perm -a=x  # -a=x is the same as -ugo=x

# The POSIX-compliant equivalent of `-perm +111` from the accepted answer:
# Match files that have ANY executable bit set.
# Note the need to group the permission tests using parentheses.
find -L . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \)

# A somewhat contrived example to demonstrate the use of a multi-principial
# mode (comma-separated clauses) and negation:
# Match files that have _both_ the user and group executable bit set, while
# also _not_ having the other executable bit set.
find -L . -type f -perm -u=x,g=x  \! -perm -o=x

[1] Description of -executable from man find as of GNU find 4.4.2:

Matches files which are executable and directories which are searchable (in a file name resolution sense). This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed.

[2] GNU find versions older than 4.5.12 also allowed prefix +, but this was first deprecated and eventually removed, because combining + with symbolic modes yields likely yields unexpected results due to being interpreted as an exact permissions mask. If you (a) run on a version before 4.5.12 and (b) restrict yourself to octal modes only, you could get away with using + with both GNU find and BSD find, but it's not a good idea.

How to create Windows EventLog source from command line?

If someone is interested, it is also possible to create an event source manually by adding some registry values.

Save the following lines as a .reg file, then import it to registry by double clicking it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\YOUR_EVENT_SOURCE_NAME_GOES_HERE]
"EventMessageFile"="C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\EventLogMessages.dll"
"TypesSupported"=dword:00000007

This creates an event source named YOUR_EVENT_SOURCE_NAME_GOES_HERE.

Convert float to std::string in C++

If you're worried about performance, check out the Boost::lexical_cast library.

sort files by date in PHP

This would get all files in path/to/files with an .swf extension into an array and then sort that array by the file's mtime

$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
    return filemtime($b) - filemtime($a);
});

The above uses an Lambda function and requires PHP 5.3. Prior to 5.3, you would do

usort($files, create_function('$a,$b', 'return filemtime($b)-filemtime($a);'));

If you don't want to use an anonymous function, you can just as well define the callback as a regular function and pass the function name to usort instead.

With the resulting array, you would then iterate over the files like this:

foreach($files as $file){
    printf('<tr><td><input type="checkbox" name="box[]"></td>
            <td><a href="%1$s" target="_blank">%1$s</a></td>
            <td>%2$s</td></tr>', 
            $file, // or basename($file) for just the filename w\out path
            date('F d Y, H:i:s', filemtime($file)));
}

Note that because you already called filemtime when sorting the files, there is no additional cost when calling it again in the foreach loop due to the stat cache.

How to check if a Unix .tar.gz file is a valid file without uncompressing?

These are all very sub-optimal solutions. From the GZIP spec

ID2 (IDentification 2)
These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213), to identify the file as being in gzip format.

Has to be coded into whatever language you're using.

php execute a background process

You might want to try to append this to your command

>/dev/null 2>/dev/null &

eg.

shell_exec('service named reload >/dev/null 2>/dev/null &');

How to concatenate strings in twig

To mix strings, variables and translations I simply do the following:

    {% set add_link = '
    <a class="btn btn-xs btn-icon-only" 
       title="' ~ 'string.to_be_translated'|trans ~ '" 
       href="' ~ path('acme_myBundle_link',{'link':link.id})  ~ '">
    </a>
    ' %}

Despite everything being mixed up, it works like a charm.

Which ChromeDriver version is compatible with which Chrome Browser version?

This is a helpful website listing the mapping for the latest releases of Chrome -

https://www.uitests-chromedrivermapping.com

JavaFX Panel inside Panel auto resizing

After hours of searching and testing finally got it just after posting the question!

You can use the "AnchorPane.topAnchor, AnchorPane.bottomAnchor, AnchorPane.leftAnchor, AnchorPane.rightAnchor" fxml commands with the value "0.0" to fit/stretch/align the child elements inside a AnchorPane. So, these commands tell to child element to follow its parent while resizing.

My updated code Main.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane fx:id="anchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="app.MainController">
    <!--<StackPane fx:id="stackPane" ></StackPane>--> <!-- replace with the following -->
    <StackPane fx:id="stackPane" AnchorPane.topAnchor="0.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" ></StackPane>
</AnchorPane>

Here is the result:

enter image description here

For api documentation: http://docs.oracle.com/javafx/2/api/javafx/scene/layout/AnchorPane.html

Codeigniter $this->input->post() empty while $_POST is working correctly

Solved as follows:

Does the following exclude the redirection that is .htacess that will run the $ this-> input- > post ('name' ) on the controller, in my case it worked perfectly .

abs, José Camargo]

What does "yield break;" do in C#?

It specifies that an iterator has come to an end. You can think of yield break as a return statement which does not return a value.

For example, if you define a function as an iterator, the body of the function may look like this:

for (int i = 0; i < 5; i++)
{
    yield return i;
}

Console.Out.WriteLine("You will see me");

Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.

Or like this with yield break:

int i = 0;
while (true)
{
    if (i < 5)
    {
        yield return i;
    }
    else
    {
        // note that i++ will not be executed after this
        yield break;
    }
    i++;
}

Console.Out.WriteLine("Won't see me");

In this case the last statement is never executed because we left the function early.

Using strtok with a std::string

First off I would say use boost tokenizer.
Alternatively if your data is space separated then the string stream library is very useful.

But both the above have already been covered.
So as a third C-Like alternative I propose copying the std::string into a buffer for modification.

std::string   data("The data I want to tokenize");

// Create a buffer of the correct length:
std::vector<char>  buffer(data.size()+1);

// copy the string into the buffer
strcpy(&buffer[0],data.c_str());

// Tokenize
strtok(&buffer[0]," ");

How to generate the JPA entity Metamodel?

Let's assume our application uses the following Post, PostComment, PostDetails, and Tag entities, which form a one-to-many, one-to-one, and many-to-many table relationships:

JPA Criteria Metamodel

How to generate the JPA Criteria Metamodel

The hibernate-jpamodelgen tool provided by Hibernate ORM can be used to scan the project entities and generate the JPA Criteria Metamodel. All you need to do is add the following annotationProcessorPath to the maven-compiler-plugin in the Maven pom.xml configuration file:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven-compiler-plugin.version}</version>
    <configuration>
        <annotationProcessorPaths>
            <annotationProcessorPath>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-jpamodelgen</artifactId>
                <version>${hibernate.version}</version>
            </annotationProcessorPath>
        </annotationProcessorPaths>
    </configuration>
</plugin>

Now, when the project is compiled, you can see that in the target folder, the following Java classes are generated:

> tree target/generated-sources/
target/generated-sources/
+-- annotations
    +-- com
        +-- vladmihalcea
            +-- book
                +-- hpjp
                    +-- hibernate
                        +-- forum
                        ¦   +-- PostComment_.java
                        ¦   +-- PostDetails_.java
                        ¦   +-- Post_.java
                        ¦   +-- Tag_.java

Tag entity Metamodel

If the Tag entity is mapped as follows:

@Entity
@Table(name = "tag")
public class Tag {

    @Id
    private Long id;

    private String name;

    //Getters and setters omitted for brevity
}

The Tag_ Metamodel class is generated like this:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Tag.class)
public abstract class Tag_ {

    public static volatile SingularAttribute<Tag, String> name;
    public static volatile SingularAttribute<Tag, Long> id;

    public static final String NAME = "name";
    public static final String ID = "id";
}

The SingularAttribute is used for the basic id and name Tag JPA entity attributes.

Post entity Metamodel

The Post entity is mapped like this:

@Entity
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        fetch = FetchType.LAZY
    )
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private PostDetails details;

    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(name = "post_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private List<Tag> tags = new ArrayList<>();
    
    //Getters and setters omitted for brevity
}

The Post entity has two basic attributes, id and title, a one-to-many comments collection, a one-to-one details association, and a many-to-many tags collection.

The Post_ Metamodel class is generated as follows:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Post.class)
public abstract class Post_ {

    public static volatile ListAttribute<Post, PostComment> comments;
    public static volatile SingularAttribute<Post, PostDetails> details;
    public static volatile SingularAttribute<Post, Long> id;
    public static volatile SingularAttribute<Post, String> title;
    public static volatile ListAttribute<Post, Tag> tags;

    public static final String COMMENTS = "comments";
    public static final String DETAILS = "details";
    public static final String ID = "id";
    public static final String TITLE = "title";
    public static final String TAGS = "tags";
}

The basic id and title attributes, as well as the one-to-one details association, are represented by a SingularAttribute while the comments and tags collections are represented by the JPA ListAttribute.

PostDetails entity Metamodel

The PostDetails entity is mapped like this:

@Entity
@Table(name = "post_details")
public class PostDetails {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

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

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private Post post;
    
    //Getters and setters omitted for brevity
}

All entity attributes are going to be represented by the JPA SingularAttribute in the associated PostDetails_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostDetails.class)
public abstract class PostDetails_ {

    public static volatile SingularAttribute<PostDetails, Post> post;
    public static volatile SingularAttribute<PostDetails, String> createdBy;
    public static volatile SingularAttribute<PostDetails, Long> id;
    public static volatile SingularAttribute<PostDetails, Date> createdOn;

    public static final String POST = "post";
    public static final String CREATED_BY = "createdBy";
    public static final String ID = "id";
    public static final String CREATED_ON = "createdOn";
}

PostComment entity Metamodel

The PostComment is mapped as follows:

@Entity
@Table(name = "post_comment")
public class PostComment {

    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    private String review;
    
    //Getters and setters omitted for brevity
}

And, all entity attributes are represented by the JPA SingularAttribute in the associated PostComments_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostComment.class)
public abstract class PostComment_ {

    public static volatile SingularAttribute<PostComment, Post> post;
    public static volatile SingularAttribute<PostComment, String> review;
    public static volatile SingularAttribute<PostComment, Long> id;

    public static final String POST = "post";
    public static final String REVIEW = "review";
    public static final String ID = "id";
}

Using the JPA Criteria Metamodel

Without the JPA Metamodel, a Criteria API query that needs to fetch the PostComment entities filtered by their associated Post title would look like this:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join("post");

query.where(
    builder.equal(
        post.get("title"),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Notice that we used the post String literal when creating the Join instance, and we used the title String literal when referencing the Post title.

The JPA Metamodel allows us to avoid hard-coding entity attributes, as illustrated by the following example:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.where(
    builder.equal(
        post.get(Post_.title),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Or, let's say we want to fetch a DTO projection while filtering the Post title and the PostDetails createdOn attributes.

We can use the Metamodel when creating the join attributes, as well as when building the DTO projection column aliases or when referencing the entity attributes we need to filter:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);

Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.multiselect(
    postComment.get(PostComment_.id).alias(PostComment_.ID),
    postComment.get(PostComment_.review).alias(PostComment_.REVIEW),
    post.get(Post_.title).alias(Post_.TITLE)
);

query.where(
    builder.and(
        builder.like(
            post.get(Post_.title),
            "%Java Persistence%"
        ),
        builder.equal(
            post.get(Post_.details).get(PostDetails_.CREATED_BY),
            "Vlad Mihalcea"
        )
    )
);

List<PostCommentSummary> comments = entityManager
    .createQuery(query)
    .unwrap(Query.class)
    .setResultTransformer(Transformers.aliasToBean(PostCommentSummary.class))
    .getResultList();

Cool, right?

PHP Error: Function name must be a string

If you wanna ascertain if cookie is set...use

if (isset($_COOKIE['cookie']))

tsc throws `TS2307: Cannot find module` for a local file

I was in trouble to import an Enum in typescript

error TS2307: Cannot find module...

What I did to make it work was migrate the enum to another file and make this change:

export enum MyEnum{
    VALUE = "MY_VALUE"
}

to

export enum MyEnum{
    VALUE = 1
}

For loop in multidimensional javascript array

var cubes = [["string", "string"], ["string", "string"]];

for(var i = 0; i < cubes.length; i++) {
    for(var j = 0; j < cubes[i].length; j++) {
        console.log(cubes[i][j]);
    }
}

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

Deleting elements from std::set while iterating

C++20 will have "uniform container erasure", and you'll be able to write:

std::erase_if(numbers, [](int n){ return n % 2 == 0 });

And that will work for vector, set, deque, etc. See cppReference for more info.

How to generate and validate a software license key?

There are many ways to generate license keys, but very few of those ways are truly secure. And it's a pity, because for companies, license keys have almost the same value as real cash.

Ideally, you would want your license keys to have the following properties:

  1. Only your company should be able to generate license keys for your products, even if someone completely reverse engineers your products (which WILL happen, I speak from experience). Obfuscating the algorithm or hiding an encryption key within your software is really out of the question if you are serious about controlling licensing. If your product is successful, someone will make a key generator in a matter of days from release.

  2. A license key should be useable on only one computer (or at least you should be able to control this very tightly)

  3. A license key should be short and easy to type or dictate over the phone. You don't want every customer calling the technical support because they don't understand if the key contains a "l" or a "1". Your support department would thank you for this, and you will have lower costs in this area.

So how do you solve these challenges ?

  1. The answer is simple but technically challenging: digital signatures using public key cryptography. Your license keys should be in fact signed "documents", containing some useful data, signed with your company's private key. The signatures should be part of the license key. The product should validate the license keys with the corresponding public key. This way, even if someone has full access to your product's logic, they cannot generate license keys because they don't have the private key. A license key would look like this: BASE32(CONCAT(DATA, PRIVATE_KEY_ENCRYPTED(HASH(DATA)))) The biggest challenge here is that the classical public key algorithms have large signature sizes. RSA512 has an 1024-bit signature. You don't want your license keys to have hundreds of characters. One of the most powerful approaches is to use elliptic curve cryptography (with careful implementations to avoid the existing patents). ECC keys are like 6 times shorter than RSA keys, for the same strength. You can further reduce the signature sizes using algorithms like the Schnorr digital signature algorithm (patent expired in 2008 - good :) )

  2. This is achievable by product activation (Windows is a good example). Basically, for a customer with a valid license key, you need to generate some "activation data" which is a signed message embedding the computer's hardware id as the signed data. This is usually done over the internet, but only ONCE: the product sends the license key and the computer hardware id to an activation server, and the activation server sends back the signed message (which can also be made short and easy to dictate over the phone). From that moment on, the product does not check the license key at startup, but the activation data, which needs the computer to be the same in order to validate (otherwise, the DATA would be different and the digital signature would not validate). Note that the activation data checking do not require verification over the Internet: it is sufficient to verify the digital signature of the activation data with the public key already embedded in the product.

  3. Well, just eliminate redundant characters like "1", "l", "0", "o" from your keys. Split the license key string into groups of characters.

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

flutter corner radius with transparent background

If you want to round corners with transparent background, the best approach is using ClipRRect.

return ClipRRect(
  borderRadius: BorderRadius.circular(40.0),
  child: Container(
    height: 800.0,
    width: double.infinity,
    color: Colors.blue,
    child: Center(
      child: new Text("Hi modal sheet"),
    ),
  ),
);

nodejs mongodb object id to string

The result returned by find is an array.

Try this instead:

console.log(user[0]["_id"]);

Steps to send a https request to a rest service in Node js

Using the request module solved the issue.

// Include the request library for Node.js   
var request = require('request');
//  Basic Authentication credentials   
var username = "vinod"; 
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(   
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }  
},
 function (error, response, body) {
 console.log(body); }  );         

MVC DateTime binding with incorrect date format

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
    if (string.IsNullOrEmpty(str)) return null;
    var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
    return date;
}

ApiNotActivatedMapError for simple html page using google-places-api

Assuming you already have a application created under google developer console, Follow the below steps

  1. Go to the following link https://console.cloud.google.com/apis/dashboard? you will be getting the below page enter image description here
  2. Click on ENABLE APIS AND SERVICES you will be directed to following page enter image description here
  3. Select the desired option - in this case "Maps JavaScript API"
  4. Click ENABLE button as below, enter image description here

Note: Please use a server to load the html file

What is the height of iPhone's onscreen keyboard?

The keyboard height depends on the model, the QuickType bar, user settings... The best approach is calculate dinamically:

Swift 3.0

    var heightKeyboard : CGFloat?

    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    }

    func keyboardShown(notification: NSNotification) {
           if let infoKey  = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
               let rawFrame = (infoKey as AnyObject).cgRectValue {
               let keyboardFrame = view.convert(rawFrame, from: nil)
               self.heightKeyboard = keyboardFrame.size.height
               // Now is stored in your heightKeyboard variable
           }
    }

What is a correct MIME type for .docx, .pptx, etc.?

Here is the (almost) complete file extensions's MIME in a JSON format. Just do example: MIME["ppt"], MIME["docx"], etc

{"x3d": "application/vnd.hzn-3d-crossword", "3gp": "video/3gpp", "3g2": "video/3gpp2", "mseq": "application/vnd.mseq", "pwn": "application/vnd.3m.post-it-notes", "plb": "application/vnd.3gpp.pic-bw-large", "psb": "application/vnd.3gpp.pic-bw-small", "pvb": "application/vnd.3gpp.pic-bw-var", "tcap": "application/vnd.3gpp2.tcap", "7z": "application/x-7z-compressed", "abw": "application/x-abiword", "ace": "application/x-ace-compressed", "acc": "application/vnd.americandynamics.acc", "acu": "application/vnd.acucobol", "atc": "application/vnd.acucorp", "adp": "audio/adpcm", "aab": "application/x-authorware-bin", "aam": "application/x-authorware-map", "aas": "application/x-authorware-seg", "air": "application/vnd.adobe.air-application-installer-package+zip", "swf": "application/x-shockwave-flash", "fxp": "application/vnd.adobe.fxp", "pdf": "application/pdf", "ppd": "application/vnd.cups-ppd", "dir": "application/x-director", "xdp": "application/vnd.adobe.xdp+xml", "xfdf": "application/vnd.adobe.xfdf", "aac": "audio/x-aac", "ahead": "application/vnd.ahead.space", "azf": "application/vnd.airzip.filesecure.azf", "azs": "application/vnd.airzip.filesecure.azs", "azw": "application/vnd.amazon.ebook", "ami": "application/vnd.amiga.ami", "N/A": "application/andrew-inset", "apk": "application/vnd.android.package-archive", "cii": "application/vnd.anser-web-certificate-issue-initiation", "fti": "application/vnd.anser-web-funds-transfer-initiation", "atx": "application/vnd.antix.game-component", "dmg": "application/x-apple-diskimage", "mpkg": "application/vnd.apple.installer+xml", "aw": "application/applixware", "mp3": "audio/mpeg", "les": "application/vnd.hhe.lesson-player", "swi": "application/vnd.aristanetworks.swi", "s": "text/x-asm", "atomcat": "application/atomcat+xml", "atomsvc": "application/atomsvc+xml", "atom, .xml": "application/atom+xml", "ac": "application/pkix-attr-cert", "aif": "audio/x-aiff", "avi": "video/x-msvideo", "aep": "application/vnd.audiograph", "dxf": "image/vnd.dxf", "dwf": "model/vnd.dwf", "par": "text/plain-bas", "bcpio": "application/x-bcpio", "bin": "application/octet-stream", "bmp": "image/bmp", "torrent": "application/x-bittorrent", "cod": "application/vnd.rim.cod", "mpm": "application/vnd.blueice.multipass", "bmi": "application/vnd.bmi", "sh": "application/x-sh", "btif": "image/prs.btif", "rep": "application/vnd.businessobjects", "bz": "application/x-bzip", "bz2": "application/x-bzip2", "csh": "application/x-csh", "c": "text/x-c", "cdxml": "application/vnd.chemdraw+xml", "css": "text/css", "cdx": "chemical/x-cdx", "cml": "chemical/x-cml", "csml": "chemical/x-csml", "cdbcmsg": "application/vnd.contact.cmsg", "cla": "application/vnd.claymore", "c4g": "application/vnd.clonk.c4group", "sub": "image/vnd.dvb.subtitle", "cdmia": "application/cdmi-capability", "cdmic": "application/cdmi-container", "cdmid": "application/cdmi-domain", "cdmio": "application/cdmi-object", "cdmiq": "application/cdmi-queue", "c11amc": "application/vnd.cluetrust.cartomobile-config", "c11amz": "application/vnd.cluetrust.cartomobile-config-pkg", "ras": "image/x-cmu-raster", "dae": "model/vnd.collada+xml", "csv": "text/csv", "cpt": "application/mac-compactpro", "wmlc": "application/vnd.wap.wmlc", "cgm": "image/cgm", "ice": "x-conference/x-cooltalk", "cmx": "image/x-cmx", "xar": "application/vnd.xara", "cmc": "application/vnd.cosmocaller", "cpio": "application/x-cpio", "clkx": "application/vnd.crick.clicker", "clkk": "application/vnd.crick.clicker.keyboard", "clkp": "application/vnd.crick.clicker.palette", "clkt": "application/vnd.crick.clicker.template", "clkw": "application/vnd.crick.clicker.wordbank", "wbs": "application/vnd.criticaltools.wbs+xml", "cryptonote": "application/vnd.rig.cryptonote", "cif": "chemical/x-cif", "cmdf": "chemical/x-cmdf", "cu": "application/cu-seeme", "cww": "application/prs.cww", "curl": "text/vnd.curl", "dcurl": "text/vnd.curl.dcurl", "mcurl": "text/vnd.curl.mcurl", "scurl": "text/vnd.curl.scurl", "car": "application/vnd.curl.car", "pcurl": "application/vnd.curl.pcurl", "cmp": "application/vnd.yellowriver-custom-menu", "dssc": "application/dssc+der", "xdssc": "application/dssc+xml", "deb": "application/x-debian-package", "uva": "audio/vnd.dece.audio", "uvi": "image/vnd.dece.graphic", "uvh": "video/vnd.dece.hd", "uvm": "video/vnd.dece.mobile", "uvu": "video/vnd.uvvu.mp4", "uvp": "video/vnd.dece.pd", "uvs": "video/vnd.dece.sd", "uvv": "video/vnd.dece.video", "dvi": "application/x-dvi", "seed": "application/vnd.fdsn.seed", "dtb": "application/x-dtbook+xml", "res": "application/x-dtbresource+xml", "ait": "application/vnd.dvb.ait", "svc": "application/vnd.dvb.service", "eol": "audio/vnd.digital-winds", "djvu": "image/vnd.djvu", "dtd": "application/xml-dtd", "mlp": "application/vnd.dolby.mlp", "wad": "application/x-doom", "dpg": "application/vnd.dpgraph", "dra": "audio/vnd.dra", "dfac": "application/vnd.dreamfactory", "dts": "audio/vnd.dts", "dtshd": "audio/vnd.dts.hd", "dwg": "image/vnd.dwg", "geo": "application/vnd.dynageo", "es": "application/ecmascript", "mag": "application/vnd.ecowin.chart", "mmr": "image/vnd.fujixerox.edmics-mmr", "rlc": "image/vnd.fujixerox.edmics-rlc", "exi": "application/exi", "mgz": "application/vnd.proteus.magazine", "epub": "application/epub+zip", "eml": "message/rfc822", "nml": "application/vnd.enliven", "xpr": "application/vnd.is-xpr", "xif": "image/vnd.xiff", "xfdl": "application/vnd.xfdl", "emma": "application/emma+xml", "ez2": "application/vnd.ezpix-album", "ez3": "application/vnd.ezpix-package", "fst": "image/vnd.fst", "fvt": "video/vnd.fvt", "fbs": "image/vnd.fastbidsheet", "fe_launch": "application/vnd.denovo.fcselayout-link", "f4v": "video/x-f4v", "flv": "video/x-flv", "fpx": "image/vnd.fpx", "npx": "image/vnd.net-fpx", "flx": "text/vnd.fmi.flexstor", "fli": "video/x-fli", "ftc": "application/vnd.fluxtime.clip", "fdf": "application/vnd.fdf", "f": "text/x-fortran", "mif": "application/vnd.mif", "fm": "application/vnd.framemaker", "fh": "image/x-freehand", "fsc": "application/vnd.fsc.weblaunch", "fnc": "application/vnd.frogans.fnc", "ltf": "application/vnd.frogans.ltf", "ddd": "application/vnd.fujixerox.ddd", "xdw": "application/vnd.fujixerox.docuworks", "xbd": "application/vnd.fujixerox.docuworks.binder", "oas": "application/vnd.fujitsu.oasys", "oa2": "application/vnd.fujitsu.oasys2", "oa3": "application/vnd.fujitsu.oasys3", "fg5": "application/vnd.fujitsu.oasysgp", "bh2": "application/vnd.fujitsu.oasysprs", "spl": "application/x-futuresplash", "fzs": "application/vnd.fuzzysheet", "g3": "image/g3fax", "gmx": "application/vnd.gmx", "gtw": "model/vnd.gtw", "txd": "application/vnd.genomatix.tuxedo", "ggb": "application/vnd.geogebra.file", "ggt": "application/vnd.geogebra.tool", "gdl": "model/vnd.gdl", "gex": "application/vnd.geometry-explorer", "gxt": "application/vnd.geonext", "g2w": "application/vnd.geoplan", "g3w": "application/vnd.geospace", "gsf": "application/x-font-ghostscript", "bdf": "application/x-font-bdf", "gtar": "application/x-gtar", "texinfo": "application/x-texinfo", "gnumeric": "application/x-gnumeric", "kml": "application/vnd.google-earth.kml+xml", "kmz": "application/vnd.google-earth.kmz", "gqf": "application/vnd.grafeq", "gif": "image/gif", "gv": "text/vnd.graphviz", "gac": "application/vnd.groove-account", "ghf": "application/vnd.groove-help", "gim": "application/vnd.groove-identity-message", "grv": "application/vnd.groove-injector", "gtm": "application/vnd.groove-tool-message", "tpl": "application/vnd.groove-tool-template", "vcg": "application/vnd.groove-vcard", "h261": "video/h261", "h263": "video/h263", "h264": "video/h264", "hpid": "application/vnd.hp-hpid", "hps": "application/vnd.hp-hps", "hdf": "application/x-hdf", "rip": "audio/vnd.rip", "hbci": "application/vnd.hbci", "jlt": "application/vnd.hp-jlyt", "pcl": "application/vnd.hp-pcl", "hpgl": "application/vnd.hp-hpgl", "hvs": "application/vnd.yamaha.hv-script", "hvd": "application/vnd.yamaha.hv-dic", "hvp": "application/vnd.yamaha.hv-voice", "sfd-hdstx": "application/vnd.hydrostatix.sof-data", "stk": "application/hyperstudio", "hal": "application/vnd.hal+xml", "html": "text/html", "irm": "application/vnd.ibm.rights-management", "sc": "application/vnd.ibm.secure-container", "ics": "text/calendar", "icc": "application/vnd.iccprofile", "ico": "image/x-icon", "igl": "application/vnd.igloader", "ief": "image/ief", "ivp": "application/vnd.immervision-ivp", "ivu": "application/vnd.immervision-ivu", "rif": "application/reginfo+xml", "3dml": "text/vnd.in3d.3dml", "spot": "text/vnd.in3d.spot", "igs": "model/iges", "i2g": "application/vnd.intergeo", "cdy": "application/vnd.cinderella", "xpw": "application/vnd.intercon.formnet", "fcs": "application/vnd.isac.fcs", "ipfix": "application/ipfix", "cer": "application/pkix-cert", "pki": "application/pkixcmp", "crl": "application/pkix-crl", "pkipath": "application/pkix-pkipath", "igm": "application/vnd.insors.igm", "rcprofile": "application/vnd.ipunplugged.rcprofile", "irp": "application/vnd.irepository.package+xml", "jad": "text/vnd.sun.j2me.app-descriptor", "jar": "application/java-archive", "class": "application/java-vm", "jnlp": "application/x-java-jnlp-file", "ser": "application/java-serialized-object", "java": "text/x-java-source,java", "js": "application/javascript", "json": "application/json", "joda": "application/vnd.joost.joda-archive", "jpm": "video/jpm", "jpeg, .jpg": "image/x-citrix-jpeg", "pjpeg": "image/pjpeg", "jpgv": "video/jpeg", "ktz": "application/vnd.kahootz", "mmd": "application/vnd.chipnuts.karaoke-mmd", "karbon": "application/vnd.kde.karbon", "chrt": "application/vnd.kde.kchart", "kfo": "application/vnd.kde.kformula", "flw": "application/vnd.kde.kivio", "kon": "application/vnd.kde.kontour", "kpr": "application/vnd.kde.kpresenter", "ksp": "application/vnd.kde.kspread", "kwd": "application/vnd.kde.kword", "htke": "application/vnd.kenameaapp", "kia": "application/vnd.kidspiration", "kne": "application/vnd.kinar", "sse": "application/vnd.kodak-descriptor", "lasxml": "application/vnd.las.las+xml", "latex": "application/x-latex", "lbd": "application/vnd.llamagraphics.life-balance.desktop", "lbe": "application/vnd.llamagraphics.life-balance.exchange+xml", "jam": "application/vnd.jam", "123": "application/vnd.lotus-1-2-3", "apr": "application/vnd.lotus-approach", "pre": "application/vnd.lotus-freelance", "nsf": "application/vnd.lotus-notes", "org": "application/vnd.lotus-organizer", "scm": "application/vnd.lotus-screencam", "lwp": "application/vnd.lotus-wordpro", "lvp": "audio/vnd.lucent.voice", "m3u": "audio/x-mpegurl", "m4v": "video/x-m4v", "hqx": "application/mac-binhex40", "portpkg": "application/vnd.macports.portpkg", "mgp": "application/vnd.osgeo.mapguide.package", "mrc": "application/marc", "mrcx": "application/marcxml+xml", "mxf": "application/mxf", "nbp": "application/vnd.wolfram.player", "ma": "application/mathematica", "mathml": "application/mathml+xml", "mbox": "application/mbox", "mc1": "application/vnd.medcalcdata", "mscml": "application/mediaservercontrol+xml", "cdkey": "application/vnd.mediastation.cdkey", "mwf": "application/vnd.mfer", "mfm": "application/vnd.mfmp", "msh": "model/mesh", "mads": "application/mads+xml", "mets": "application/mets+xml", "mods": "application/mods+xml", "meta4": "application/metalink4+xml", "mcd": "application/vnd.mcd", "flo": "application/vnd.micrografx.flo", "igx": "application/vnd.micrografx.igx", "es3": "application/vnd.eszigno3+xml", "mdb": "application/x-msaccess", "asf": "video/x-ms-asf", "exe": "application/x-msdownload", "cil": "application/vnd.ms-artgalry", "cab": "application/vnd.ms-cab-compressed", "ims": "application/vnd.ms-ims", "application": "application/x-ms-application", "clp": "application/x-msclip", "mdi": "image/vnd.ms-modi", "eot": "application/vnd.ms-fontobject", "xls": "application/vnd.ms-excel", "xlam": "application/vnd.ms-excel.addin.macroenabled.12", "xlsb": "application/vnd.ms-excel.sheet.binary.macroenabled.12", "xltm": "application/vnd.ms-excel.template.macroenabled.12", "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12", "chm": "application/vnd.ms-htmlhelp", "crd": "application/x-mscardfile", "lrm": "application/vnd.ms-lrm", "mvb": "application/x-msmediaview", "mny": "application/x-msmoney", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", "ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", "potx": "application/vnd.openxmlformats-officedocument.presentationml.template", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "obd": "application/x-msbinder", "thmx": "application/vnd.ms-officetheme", "onetoc": "application/onenote", "pya": "audio/vnd.ms-playready.media.pya", "pyv": "video/vnd.ms-playready.media.pyv", "ppt": "application/vnd.ms-powerpoint", "ppam": "application/vnd.ms-powerpoint.addin.macroenabled.12", "sldm": "application/vnd.ms-powerpoint.slide.macroenabled.12", "pptm": "application/vnd.ms-powerpoint.presentation.macroenabled.12", "ppsm": "application/vnd.ms-powerpoint.slideshow.macroenabled.12", "potm": "application/vnd.ms-powerpoint.template.macroenabled.12", "mpp": "application/vnd.ms-project", "pub": "application/x-mspublisher", "scd": "application/x-msschedule", "xap": "application/x-silverlight-app", "stl": "application/vnd.ms-pki.stl", "cat": "application/vnd.ms-pki.seccat", "vsd": "application/vnd.visio", "vsdx": "application/vnd.visio2013", "wm": "video/x-ms-wm", "wma": "audio/x-ms-wma", "wax": "audio/x-ms-wax", "wmx": "video/x-ms-wmx", "wmd": "application/x-ms-wmd", "wpl": "application/vnd.ms-wpl", "wmz": "application/x-ms-wmz", "wmv": "video/x-ms-wmv", "wvx": "video/x-ms-wvx", "wmf": "application/x-msmetafile", "trm": "application/x-msterminal", "doc": "application/msword", "docm": "application/vnd.ms-word.document.macroenabled.12", "dotm": "application/vnd.ms-word.template.macroenabled.12", "wri": "application/x-mswrite", "wps": "application/vnd.ms-works", "xbap": "application/x-ms-xbap", "xps": "application/vnd.ms-xpsdocument", "mid": "audio/midi", "mpy": "application/vnd.ibm.minipay", "afp": "application/vnd.ibm.modcap", "rms": "application/vnd.jcp.javame.midlet-rms", "tmo": "application/vnd.tmobile-livetv", "prc": "application/x-mobipocket-ebook", "mbk": "application/vnd.mobius.mbk", "dis": "application/vnd.mobius.dis", "plc": "application/vnd.mobius.plc", "mqy": "application/vnd.mobius.mqy", "msl": "application/vnd.mobius.msl", "txf": "application/vnd.mobius.txf", "daf": "application/vnd.mobius.daf", "fly": "text/vnd.fly", "mpc": "application/vnd.mophun.certificate", "mpn": "application/vnd.mophun.application", "mj2": "video/mj2", "mpga": "audio/mpeg", "mxu": "video/vnd.mpegurl", "mpeg": "video/mpeg", "m21": "application/mp21", "mp4a": "audio/mp4", "mp4": "application/mp4", "m3u8": "application/vnd.apple.mpegurl", "mus": "application/vnd.musician", "msty": "application/vnd.muvee.style", "mxml": "application/xv+xml", "ngdat": "application/vnd.nokia.n-gage.data", "n-gage": "application/vnd.nokia.n-gage.symbian.install", "ncx": "application/x-dtbncx+xml", "nc": "application/x-netcdf", "nlu": "application/vnd.neurolanguage.nlu", "dna": "application/vnd.dna", "nnd": "application/vnd.noblenet-directory", "nns": "application/vnd.noblenet-sealer", "nnw": "application/vnd.noblenet-web", "rpst": "application/vnd.nokia.radio-preset", "rpss": "application/vnd.nokia.radio-presets", "n3": "text/n3", "edm": "application/vnd.novadigm.edm", "edx": "application/vnd.novadigm.edx", "ext": "application/vnd.novadigm.ext", "gph": "application/vnd.flographit", "ecelp4800": "audio/vnd.nuera.ecelp4800", "ecelp7470": "audio/vnd.nuera.ecelp7470", "ecelp9600": "audio/vnd.nuera.ecelp9600", "oda": "application/oda", "ogx": "application/ogg", "oga": "audio/ogg", "ogv": "video/ogg", "dd2": "application/vnd.oma.dd2+xml", "oth": "application/vnd.oasis.opendocument.text-web", "opf": "application/oebps-package+xml", "qbo": "application/vnd.intu.qbo", "oxt": "application/vnd.openofficeorg.extension", "osf": "application/vnd.yamaha.openscoreformat", "weba": "audio/webm", "webm": "video/webm", "odc": "application/vnd.oasis.opendocument.chart", "otc": "application/vnd.oasis.opendocument.chart-template", "odb": "application/vnd.oasis.opendocument.database", "odf": "application/vnd.oasis.opendocument.formula", "odft": "application/vnd.oasis.opendocument.formula-template", "odg": "application/vnd.oasis.opendocument.graphics", "otg": "application/vnd.oasis.opendocument.graphics-template", "odi": "application/vnd.oasis.opendocument.image", "oti": "application/vnd.oasis.opendocument.image-template", "odp": "application/vnd.oasis.opendocument.presentation", "otp": "application/vnd.oasis.opendocument.presentation-template", "ods": "application/vnd.oasis.opendocument.spreadsheet", "ots": "application/vnd.oasis.opendocument.spreadsheet-template", "odt": "application/vnd.oasis.opendocument.text", "odm": "application/vnd.oasis.opendocument.text-master", "ott": "application/vnd.oasis.opendocument.text-template", "ktx": "image/ktx", "sxc": "application/vnd.sun.xml.calc", "stc": "application/vnd.sun.xml.calc.template", "sxd": "application/vnd.sun.xml.draw", "std": "application/vnd.sun.xml.draw.template", "sxi": "application/vnd.sun.xml.impress", "sti": "application/vnd.sun.xml.impress.template", "sxm": "application/vnd.sun.xml.math", "sxw": "application/vnd.sun.xml.writer", "sxg": "application/vnd.sun.xml.writer.global", "stw": "application/vnd.sun.xml.writer.template", "otf": "application/x-font-otf", "osfpvg": "application/vnd.yamaha.openscoreformat.osfpvg+xml", "dp": "application/vnd.osgi.dp", "pdb": "application/vnd.palm", "p": "text/x-pascal", "paw": "application/vnd.pawaafile", "pclxl": "application/vnd.hp-pclxl", "efif": "application/vnd.picsel", "pcx": "image/x-pcx", "psd": "image/vnd.adobe.photoshop", "prf": "application/pics-rules", "pic": "image/x-pict", "chat": "application/x-chat", "p10": "application/pkcs10", "p12": "application/x-pkcs12", "p7m": "application/pkcs7-mime", "p7s": "application/pkcs7-signature", "p7r": "application/x-pkcs7-certreqresp", "p7b": "application/x-pkcs7-certificates", "p8": "application/pkcs8", "plf": "application/vnd.pocketlearn", "pnm": "image/x-portable-anymap", "pbm": "image/x-portable-bitmap", "pcf": "application/x-font-pcf", "pfr": "application/font-tdpfr", "pgn": "application/x-chess-pgn", "pgm": "image/x-portable-graymap", "png": "image/x-png", "ppm": "image/x-portable-pixmap", "pskcxml": "application/pskc+xml", "pml": "application/vnd.ctc-posml", "ai": "application/postscript", "pfa": "application/x-font-type1", "pbd": "application/vnd.powerbuilder6", "pgp": "application/pgp-signature", "box": "application/vnd.previewsystems.box", "ptid": "application/vnd.pvi.ptid1", "pls": "application/pls+xml", "str": "application/vnd.pg.format", "ei6": "application/vnd.pg.osasli", "dsc": "text/prs.lines.tag", "psf": "application/x-font-linux-psf", "qps": "application/vnd.publishare-delta-tree", "wg": "application/vnd.pmi.widget", "qxd": "application/vnd.quark.quarkxpress", "esf": "application/vnd.epson.esf", "msf": "application/vnd.epson.msf", "ssf": "application/vnd.epson.ssf", "qam": "application/vnd.epson.quickanime", "qfx": "application/vnd.intu.qfx", "qt": "video/quicktime", "rar": "application/x-rar-compressed", "ram": "audio/x-pn-realaudio", "rmp": "audio/x-pn-realaudio-plugin", "rsd": "application/rsd+xml", "rm": "application/vnd.rn-realmedia", "bed": "application/vnd.realvnc.bed", "mxl": "application/vnd.recordare.musicxml", "musicxml": "application/vnd.recordare.musicxml+xml", "rnc": "application/relax-ng-compact-syntax", "rdz": "application/vnd.data-vision.rdz", "rdf": "application/rdf+xml", "rp9": "application/vnd.cloanto.rp9", "jisp": "application/vnd.jisp", "rtf": "application/rtf", "rtx": "text/richtext", "link66": "application/vnd.route66.link66+xml", "rss, .xml": "application/rss+xml", "shf": "application/shf+xml", "st": "application/vnd.sailingtracker.track", "svg": "image/svg+xml", "sus": "application/vnd.sus-calendar", "sru": "application/sru+xml", "setpay": "application/set-payment-initiation", "setreg": "application/set-registration-initiation", "sema": "application/vnd.sema", "semd": "application/vnd.semd", "semf": "application/vnd.semf", "see": "application/vnd.seemail", "snf": "application/x-font-snf", "spq": "application/scvp-vp-request", "spp": "application/scvp-vp-response", "scq": "application/scvp-cv-request", "scs": "application/scvp-cv-response", "sdp": "application/sdp", "etx": "text/x-setext", "movie": "video/x-sgi-movie", "ifm": "application/vnd.shana.informed.formdata", "itp": "application/vnd.shana.informed.formtemplate", "iif": "application/vnd.shana.informed.interchange", "ipk": "application/vnd.shana.informed.package", "tfi": "application/thraud+xml", "shar": "application/x-shar", "rgb": "image/x-rgb", "slt": "application/vnd.epson.salt", "aso": "application/vnd.accpac.simply.aso", "imp": "application/vnd.accpac.simply.imp", "twd": "application/vnd.simtech-mindmapper", "csp": "application/vnd.commonspace", "saf": "application/vnd.yamaha.smaf-audio", "mmf": "application/vnd.smaf", "spf": "application/vnd.yamaha.smaf-phrase", "teacher": "application/vnd.smart.teacher", "svd": "application/vnd.svd", "rq": "application/sparql-query", "srx": "application/sparql-results+xml", "gram": "application/srgs", "grxml": "application/srgs+xml", "ssml": "application/ssml+xml", "skp": "application/vnd.koan", "sgml": "text/sgml", "sdc": "application/vnd.stardivision.calc", "sda": "application/vnd.stardivision.draw", "sdd": "application/vnd.stardivision.impress", "smf": "application/vnd.stardivision.math", "sdw": "application/vnd.stardivision.writer", "sgl": "application/vnd.stardivision.writer-global", "sm": "application/vnd.stepmania.stepchart", "sit": "application/x-stuffit", "sitx": "application/x-stuffitx", "sdkm": "application/vnd.solent.sdkm+xml", "xo": "application/vnd.olpc-sugar", "au": "audio/basic", "wqd": "application/vnd.wqd", "sis": "application/vnd.symbian.install", "smi": "application/smil+xml", "xsm": "application/vnd.syncml+xml", "bdm": "application/vnd.syncml.dm+wbxml", "xdm": "application/vnd.syncml.dm+xml", "sv4cpio": "application/x-sv4cpio", "sv4crc": "application/x-sv4crc", "sbml": "application/sbml+xml", "tsv": "text/tab-separated-values", "tiff": "image/tiff", "tao": "application/vnd.tao.intent-module-archive", "tar": "application/x-tar", "tcl": "application/x-tcl", "tex": "application/x-tex", "tfm": "application/x-tex-tfm", "tei": "application/tei+xml", "txt": "text/plain", "dxp": "application/vnd.spotfire.dxp", "sfs": "application/vnd.spotfire.sfs", "tsd": "application/timestamped-data", "tpt": "application/vnd.trid.tpt", "mxs": "application/vnd.triscape.mxs", "t": "text/troff", "tra": "application/vnd.trueapp", "ttf": "application/x-font-ttf", "ttl": "text/turtle", "umj": "application/vnd.umajin", "uoml": "application/vnd.uoml+xml", "unityweb": "application/vnd.unity", "ufd": "application/vnd.ufdl", "uri": "text/uri-list", "utz": "application/vnd.uiq.theme", "ustar": "application/x-ustar", "uu": "text/x-uuencode", "vcs": "text/x-vcalendar", "vcf": "text/x-vcard", "vcd": "application/x-cdlink", "vsf": "application/vnd.vsf", "wrl": "model/vrml", "vcx": "application/vnd.vcx", "mts": "model/vnd.mts", "vtu": "model/vnd.vtu", "vis": "application/vnd.visionary", "viv": "video/vnd.vivo", "ccxml": "application/ccxml+xml,", "vxml": "application/voicexml+xml", "src": "application/x-wais-source", "wbxml": "application/vnd.wap.wbxml", "wbmp": "image/vnd.wap.wbmp", "wav": "audio/x-wav", "davmount": "application/davmount+xml", "woff": "application/x-font-woff", "wspolicy": "application/wspolicy+xml", "webp": "image/webp", "wtb": "application/vnd.webturbo", "wgt": "application/widget", "hlp": "application/winhlp", "wml": "text/vnd.wap.wml", "wmls": "text/vnd.wap.wmlscript", "wmlsc": "application/vnd.wap.wmlscriptc", "wpd": "application/vnd.wordperfect", "stf": "application/vnd.wt.stf", "wsdl": "application/wsdl+xml", "xbm": "image/x-xbitmap", "xpm": "image/x-xpixmap", "xwd": "image/x-xwindowdump", "der": "application/x-x509-ca-cert", "fig": "application/x-xfig", "xhtml": "application/xhtml+xml", "xml": "application/xml", "xdf": "application/xcap-diff+xml", "xenc": "application/xenc+xml", "xer": "application/patch-ops-error+xml", "rl": "application/resource-lists+xml", "rs": "application/rls-services+xml", "rld": "application/resource-lists-diff+xml", "xslt": "application/xslt+xml", "xop": "application/xop+xml", "xpi": "application/x-xpinstall", "xspf": "application/xspf+xml", "xul": "application/vnd.mozilla.xul+xml", "xyz": "chemical/x-xyz", "yaml": "text/yaml", "yang": "application/yang", "yin": "application/yin+xml", "zir": "application/vnd.zul", "zip": "application/zip", "zmm": "application/vnd.handheld-entertainment+xml", "zaz": "application/vnd.zzazz.deck+xml"}

Insert, on duplicate update in PostgreSQL?

Edit: This does not work as expected. Unlike the accepted answer, this produces unique key violations when two processes repeatedly call upsert_foo concurrently.

Eureka! I figured out a way to do it in one query: use UPDATE ... RETURNING to test if any rows were affected:

CREATE TABLE foo (k INT PRIMARY KEY, v TEXT);

CREATE FUNCTION update_foo(k INT, v TEXT)
RETURNS SETOF INT AS $$
    UPDATE foo SET v = $2 WHERE k = $1 RETURNING $1
$$ LANGUAGE sql;

CREATE FUNCTION upsert_foo(k INT, v TEXT)
RETURNS VOID AS $$
    INSERT INTO foo
        SELECT $1, $2
        WHERE NOT EXISTS (SELECT update_foo($1, $2))
$$ LANGUAGE sql;

The UPDATE has to be done in a separate procedure because, unfortunately, this is a syntax error:

... WHERE NOT EXISTS (UPDATE ...)

Now it works as desired:

SELECT upsert_foo(1, 'hi');
SELECT upsert_foo(1, 'bye');
SELECT upsert_foo(3, 'hi');
SELECT upsert_foo(3, 'bye');

Could not find module "@angular-devkit/build-angular"

Unfortunately, none of the provided solutions worked perfectly for me, but grepit's answer inspired me to do the following steps. I uninstalled node.js via my OS (Windows 10) and installed it again. Then installed Angular CLI. Then created a new project, and copied my old project's src file into this new one and the error's gone.

Here are the instructions:

  1. Uninstall node.js via your OS and install it again
  2. npm install -g @angular/cli
  3. Rename your project to YOUR_PROJECT_NAME.old
  4. ng new YOUR_PROJECT_NAME
  5. Run this hello world project (ng serve) to make sure that you won't get the error.
  6. xcopy YOUR_PROJECT_NAME.old\src\*.* YOUR_PROJECT_NAME\src /s
    This is Windows version of copy, change it based on your own OS.

CSS to hide INPUT BUTTON value text

Applying font-size: 0.1px; to the button works for me in Firefox, Internet Explorer 6, Internet Explorer 7, and Safari. None of the other solutions I've found worked across all of the browsers.

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

Get the last non-empty cell in a column in Google Sheets

If the column expanded only by contiguously added dates as in my case - I used just MAX function to get last date.

The final formula will be:

=DAYS360(A2; MAX(A2:A)) 

Rename multiple files by replacing a particular pattern in the filenames using a shell script

An example to help you get off the ground.

for f in *.jpg; do mv "$f" "$(echo "$f" | sed s/IMG/VACATION/)"; done

In this example, I am assuming that all your image files contain the string IMG and you want to replace IMG with VACATION.

The shell automatically evaluates *.jpg to all the matching files.

The second argument of mv (the new name of the file) is the output of the sed command that replaces IMG with VACATION.

If your filenames include whitespace pay careful attention to the "$f" notation. You need the double-quotes to preserve the whitespace.

ValidateRequest="false" doesn't work in Asp.Net 4

I know this is an old question, but if you encounter this problem in MVC 3 then you can decorate your ActionMethod with [ValidateInput(false)] and just switch off request validation for a single ActionMethod, which is handy. And you don't need to make any changes to the web.config file, so you can still use the .NET 4 request validation everywhere else.

e.g.

[ValidateInput(false)]
public ActionMethod Edit(int id, string value)
{
    // Do your own checking of value since it could contain XSS stuff!
    return View();
}

Replace all occurrences of a String using StringBuilder?

The class org.apache.commons.lang3.text.StrBuilder in Apache Commons Lang allows replacements:

public StrBuilder replaceAll(String searchStr, String replaceStr)

* This does not receive a regular expression but a simple string.

Getting the exception value in Python

If you don't know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you'll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

Use <meta charset="utf-8" /> for web browsers when using HTML5.

Use <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> when using HTML4 or XHTML, or for outdated dom parsers, like DOMDocument in php 5.3

Create a branch in Git from another branch

Do simultaneous work on the dev branch. What happens is that in your scenario the feature branch moves forward from the tip of the dev branch, but the dev branch does not change. It's easier to draw as a straight line, because it can be thought of as forward motion. You made it to point A on dev, and from there you simply continued on a parallel path. The two branches have not really diverged.

Now, if you make a commit on dev, before merging, you will again begin at the same commit, A, but now features will go to C and dev to B. This will show the split you are trying to visualize, as the branches have now diverged.

*-----*Dev-------*Feature

Versus

       /----*DevB
*-----*DevA
       \----*FeatureC

Missing Microsoft RDLC Report Designer in Visual Studio

Below Different tools for Editing Rdlc report:

  1. ReportBuilder 3.0 : Microsoft Editor for Rdlc report.
  2. Microsoft® SQL Server® 2008 Express with Advanced Services: Another tool is to use Sql Server Business intelligence for reporting that can be installed with Sql Server Express with Advanced Sevices.
  3. fyiReporting: It is opensource tool presented for editing Rdlc reports .

zsh compinit: insecure directories

Once you understand the cause, solution is trivial and unequivocal.

  • Cause: the directories output by compaudit have write permission by either group or others (world-writable); or those files are owned by somebody else other than root or yourself.

  • Example: In my case, compaudit gave me that:

% compaudit 
There are insecure directories:
/usr/local/share/zsh/site-functions
/usr/local/share/zsh

And if we list the permission of those files/directories we have (in this case)

% ls -lh /usr/local/share 
total 0
drwxr-xr-x  12 chbrandt  admin   384B Aug 14 10:45 aclocal
drwxr-xr-x   8 chbrandt  admin   256B Aug 14 10:45 doc
drwxr-xr-x   3 chbrandt  admin    96B Jul 24 21:00 fish
lrwxr-xr-x   1 chbrandt  admin    36B Aug 14 10:45 gettext -> ../Cellar/gettext/0.21/share/gettext
lrwxr-xr-x   1 chbrandt  admin    41B Aug 14 10:45 gettext-0.21 -> ../Cellar/gettext/0.21/share/gettext-0.21
lrwxr-xr-x   1 chbrandt  admin    37B Aug 14 10:45 gtk-doc -> ../Cellar/libidn2/2.3.0/share/gtk-doc
drwxr-xr-x   9 chbrandt  admin   288B Aug 14 10:45 info
drwxr-xr-x  58 chbrandt  admin   1.8K Aug 14 10:45 locale
lrwxr-xr-x   1 chbrandt  admin    41B Jul 27 17:12 luajit-2.0.5 -> ../Cellar/luajit/2.0.5/share/luajit-2.0.5
drwxr-xr-x   5 chbrandt  admin   160B Jul 27 17:12 man
lrwxr-xr-x   1 chbrandt  admin    33B Aug 14 10:45 nvim -> ../Cellar/neovim/0.4.4/share/nvim
drwxrwxr-x   3 chbrandt  admin    96B Jul 24 20:57 zsh
%
% ls -lh /usr/local/share/zsh 
total 0
drwxrwxr-x  4 chbrandt  admin   128B Jul 24 21:00 site-functions
%
% ls -lh /usr/local/share/zsh/site-functions 
total 0
lrwxr-xr-x  1 chbrandt  admin    39B Jul 24 21:00 _brew -> ../../../Homebrew/completions/zsh/_brew
lrwxr-xr-x  1 chbrandt  admin    44B Jul 24 21:00 _brew_cask -> ../../../Homebrew/completions/zsh/_brew_cask

Now we easily spot the issue, don't we? Notice how zsh/ and zsh/site-functions directories differ from the others... That 'w' allowing the admin group to modify them is not appreciated by zsh.

  • Solution: Turn off that group-writable permission!
% chmod g-w /usr/local/share/zsh 
% chmod g-w /usr/local/share/zsh/site-functions 

That's it! You're good to go. Open a new terminal and you should not see the "zsh compinit: insecure directories" message anymore ;)

Check if url contains string with JQuery

if(window.location.href.indexOf("?added-to-cart=555") >= 0)

It's window.location.href, not window.location.

This compilation unit is not on the build path of a Java project

For those who still have problems after attempting the suggestions above: I solved the issue by updating the maven project.

how does Request.QueryString work?

The HttpRequest class represents the request made to the server and has various properties associated with it, such as QueryString.

The ASP.NET run-time parses a request to the server and populates this information for you.

Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.

Note: not all properties will be populated, for instance if your request has no query string, then the QueryString will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:

if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
    // Query string value is there so now use it
    int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}

Convert Text to Uppercase while typing in Text box

I use to do this thing (Code Behind) ASP.NET using VB.NET:

1) Turn AutoPostBack = True in properties of said Textbox

2) Code for Textbox (Event : TextChanged) Me.TextBox1.Text = Me.TextBox1.Text.ToUpper

3) Observation After entering the string variables in TextBox1, when user leaves TextBox1, AutoPostBack fires the code when Text was changed during "TextChanged" event.

Is it possible to display my iPhone on my computer monitor?

This is a tool that will help you, i installed it myself

Here is the link

How to Apply Corner Radius to LinearLayout

try this, for Programmatically to set a background with radius to LinearLayout or any View.

 private Drawable getDrawableWithRadius() {

    GradientDrawable gradientDrawable   =   new GradientDrawable();
    gradientDrawable.setCornerRadii(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
    gradientDrawable.setColor(Color.RED);
    return gradientDrawable;
}

LinearLayout layout = new LinearLayout(this);
layout.setBackground(getDrawableWithRadius());

After submitting a POST form open a new window showing the result

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

Get properties and values from unknown object

void Test(){
    var obj = new{a="aaa", b="bbb"};

    var val_a = obj.GetValObjDy("a"); //="aaa"
    var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{            
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

Attach parameter to button.addTarget action in Swift

If you want to send additional parameters to the buttonClicked method, for example an indexPath or urlString, you can subclass the UIButton:

class SubclassedUIButton: UIButton {
    var indexPath: Int?
    var urlString: String?
}

Make sure to change the button's class in the identity inspector to subclassedUIButton. You can access the parameters inside the buttonClicked method using sender.indexPath or sender.urlString.

Note: If your button is inside a cell you can set the value of these additional parameters in the cellForRowAtIndexPath method (where the button is created).

How to prune local tracking branches that do not exist on remote anymore

This works for me using git 2.21.0 - it deletes local tracking branches which are merged into HEAD where I have previously --set-upstream on push (I use push.default=upstream because it works best with multiple remotes) and that upstream branch has since been deleted by a fetch --prune (or implicitly if fetch.prune=true in git config):

git branch -vv --merged | grep ': gone]' | awk '{print $1}' | xargs git branch -d

The use of --merged and -d make this a very 'safe' delete. A more aggressive version could drop the --merged and use -D

Converting String to Double in Android

I had the same issue, but I have just figured out that :

  • parsing the EditText value in the Oncreate method caused the app to crash because when the app starts, there are no values to parse or maybe the placeholders which are letter.

My code:

package com.example.herodav.volumeapp;

import android.renderscript.Double2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    EditText height, length, depth;
    TextView volume;
    double h,l,d,vol;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        height = (EditText)findViewById(R.id.h);
        length = (EditText)findViewById(R.id.l);
        depth = (EditText)findViewById(R.id.d);
        volume = (TextView)findViewById(R.id.v);

        Button btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculateVolume();
                volume.setText("Volume = " + String.valueOf(vol));
            }
        });
    }

    public void calculateVolume(){
        h = Double.parseDouble(height.getText().toString());
        l = Double.parseDouble(length.getText().toString());
        d = Double.parseDouble(depth.getText().toString());
        vol = h*l*d;
    }
}

I

CSS @font-face not working in ie

Change as per below

@font-face {
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); /* IE */
    src: local("Futura"), url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); /* non-IE */  
}

body nav {
     font-family: "Futura";
    font-size:1.2em;
    height: 40px;
}

SQL Server: how to select records with specific date from datetime column

For Perfect DateTime Match in SQL Server

SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC

TypeScript and React - children type?

I'm using the following

type Props = { children: React.ReactNode };

const MyComponent: React.FC<Props> = ({children}) => {
  return (
    <div>
      { children }
    </div>
  );

export default MyComponent;

Add a custom attribute to a Laravel / Eloquent model on load?

Let say you have 2 columns named first_name and last_name in your users table and you want to retrieve full name. you can achieve with the following code :

class User extends Eloquent {


    public function getFullNameAttribute()
    {
        return $this->first_name.' '.$this->last_name;
    }
}

now you can get full name as:

$user = User::find(1);
$user->full_name;

Bootstrap 4 - Responsive cards in card-columns

If you are using Sass:

$card-column-sizes: (
    xs: 2,
    sm: 3,
    md: 4,
    lg: 5,
);

@each $breakpoint-size, $column-count in $card-column-sizes {
    @include media-breakpoint-up($breakpoint-size) {
      .card-columns {
        column-count: $column-count;
        column-gap: 1.25rem;

        .card {
          display: inline-block;
          width: 100%; // Don't let them exceed the column width
        }
      }
    }
}

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

How can I turn a DataTable to a CSV?

I wrapped this up into an extension class, which allows you to call:

myDataTable.WriteToCsvFile("C:\\MyDataTable.csv");

on any DataTable.

public static class DataTableExtensions 
{
    public static void WriteToCsvFile(this DataTable dataTable, string filePath) 
    {
        StringBuilder fileContent = new StringBuilder();

        foreach (var col in dataTable.Columns) 
        {
            fileContent.Append(col.ToString() + ",");
        }

        fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);

        foreach (DataRow dr in dataTable.Rows) 
        {
            foreach (var column in dr.ItemArray) 
            {
                fileContent.Append("\"" + column.ToString() + "\",");
            }

            fileContent.Replace(",", System.Environment.NewLine, fileContent.Length - 1, 1);
        }

        System.IO.File.WriteAllText(filePath, fileContent.ToString());
    }
}

How To Set A JS object property name from a variable

var jsonVariable = {};
for(var i=1; i < 3; i++) {
  jsonVariable[i + 'name'] = 'name' + i;        
}

Converting string to tuple without splitting characters

Have a look at the Python tutorial on tuples:

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

If you put just a pair of parentheses around your string object, they will only turn that expression into an parenthesized expression (emphasis added):

A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.

An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).

Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.

That is (assuming Python 2.7),

a = 'Quattro TT'
print tuple(a)        # <-- you create a tuple from a sequence 
                      #     (which is a string)
print tuple([a])      # <-- you create a tuple from a sequence 
                      #     (which is a list containing a string)
print tuple(list(a))  # <-- you create a tuple from a sequence 
                      #     (which you create from a string)
print (a,)            # <-- you create a tuple containing the string
print (a)             # <-- it's just the string wrapped in parentheses

The output is as expected:

('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
Quattro TT

To add some notes on the print statement. When you try to create a single-element tuple as part of a print statement in Python 2.7 (as in print (a,)) you need to use the parenthesized form, because the trailing comma of print a, would else be considered part of the print statement and thus cause the newline to be suppressed from the output and not a tuple being created:

A '\n' character is written at the end, unless the print statement ends with a comma.

In Python 3.x most of the above usages in the examples would actually raise SyntaxError, because in Python 3 print turns into a function (you need to add an extra pair of parentheses). But especially this may cause confusion:

print (a,)            # <-- this prints a tuple containing `a` in Python 2.x
                      #     but only `a` in Python 3.x

Setting selected values for ng-options bound select elements

Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2

_x000D_
_x000D_
<select ng-model="objBillingAddress.StateId"  >_x000D_
   <option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
                                                </select>
_x000D_
_x000D_
_x000D_

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Word-wrap in an HTML table

The following works for me in Internet Explorer. Note the addition of the table-layout:fixed CSS attribute

_x000D_
_x000D_
td {_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<table style="table-layout: fixed; width: 100%">_x000D_
  <tr>_x000D_
    <td style="word-wrap: break-word">_x000D_
      LongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongWord_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

Jquery Open in new Tab (_blank)

Replace this line:

$(this).target = "_blank";

With:

$( this ).attr( 'target', '_blank' );

That will set its HREF to _blank.

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

Is there a difference between "throw" and "throw ex"?

Yes, there is a difference;

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.

    static void Main(string[] args)
    {
        try
        {
            Method2();
        }
        catch (Exception ex)
        {
            Console.Write(ex.StackTrace.ToString());
            Console.ReadKey();
        }
    }
    
    private static void Method2()
    {
        try
        {
            Method1();
        }
        catch (Exception ex)
        {
            //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
            throw ex;
        }
    }
    
    private static void Method1()
    {
        try
        {
            throw new Exception("Inside Method1");
        }
        catch (Exception)
        {
            throw;
        }
    }
    

Why does PEP-8 specify a maximum line length of 79 characters?

Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.

Resetting remote to a certain commit

If your branch is not development or production, the easiest way to achieve this is resetting to a certain commit locally and create a new branch from there. You can use:

git checkout 000000

(where 000000 is the commit id where you want to go) in your problematic branch and then simply create a new branch:

git remote add [name_of_your_remote]

Then you can create a new PR and all will work fine!

PHP function ssh2_connect is not working

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road

HTML code for INR

Please try this -

INR (₹) sign HTML Code - &#x20B9;

When do I use path params vs. query params in a RESTful API?

Once I designed an API which main resource was people. Usually users would request filtered people so, to prevent users to call something like /people?settlement=urban every time, I implemented /people/urban which later enabled me to easily add /people/rural. Also this allows to access the full /people list if it would be of any use later on. In short, my reasoning was to add a path to common subsets

From here:

Aliases for common queries

To make the API experience more pleasant for the average consumer, consider packaging up sets of conditions into easily accessible RESTful paths. For example, the recently closed tickets query above could be packaged up as GET /tickets/recently_closed

Simple Vim commands you wish you'd known earlier

I wish I'd known basic visual block mode stuff earlier. Even if you don't use Vim for anything else, it can be a big time saver to open up a file in Vim just for some block operations. I'm quite sure I wasted a ton of time doing this kind of thing manually.

Examples I've found particularly useful, when, say, refactoring lists of symbolic constant names consistently:

Enter Visual Block mode (Ctrl + Q for me on Windows instead of Ctrl + V)

Move the cursor to highlight the desired block.

Then, I whatever text and press Esc to have the text inserted in front of the block on every line.

Use A instead of I to have the text inserted after the block on every line.

Also - simply toggling the case of a visual selection with ~ can be a big time saver.

And simply deleting columns, too, with d of course.

How do I change JPanel inside a JFrame on the fly?

Problem: My component does not appear after I have added it to the container.

You need to invoke revalidate and repaint after adding a component before it will show up in your container.

Source: http://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is a POSIX standard but not standard C.

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had approximately the same problem with Laravel 5.5 on ubuntu, finally i've found a solution here to switch between the versions of php used by apache :

  1. sudo a2dismod php5
  2. sudo a2enmod php7.1
  3. sudo service apache2 restart

and it works

How to pip or easy_install tkinter on Windows

Inside cmd, run command pip install tk and Tkinter should install.

how do you increase the height of an html textbox

Don't the height and font-size CSS properties work for you ?

How do I flush the cin buffer?

#include <stdio_ext.h>

and then use function

__fpurge(stdin)

How to start an application using android ADB tools?

Step 1: First get all the package name of the apps installed in your Device, by using:

adb shell pm list packages

Step 2: You will get all the package names, copy the one you want to start using adb.

Step 3: Add your desired package name in the below command.

adb shell monkey -p 'your package name' -v 500

For Example:
adb shell monkey -p com.estrongs.android.pop -v 500 to start the Es explorer.

How do I print the type or class of a variable in Swift?

I've tried some of the other answers here but milage seems to very on what the underling object is.

However I did found a way you can get the Object-C class name for an object by doing the following:

now?.superclass as AnyObject! //replace now with the object you are trying to get the class name for

Here is and example of how you would use it:

let now = NSDate()
println("what is this = \(now?.superclass as AnyObject!)")

In this case it will print NSDate in the console.

Android selector & text color

I got by doing several tests until one worked, so: res/color/button_dark_text.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#000000" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#000000" /> <!-- focused -->
     <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

res/layout/view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
    <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="EXIT"
       android:textColor="@color/button_dark_text" />
</LinearLayout>

What does 'URI has an authority component' mean?

I found out that the URL of the application conflicted with a module in the Sun GlassFish. So, in the file sun-web.xml I renamed the <context-root>/servlets-samples</context-root>.

It is now working.

Java String.split() Regex

You could also do something like:

String str = "a + b - c * d / e < f > g >= h <= i == j";
String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");

It handles white spaces and words of variable length and produces the array:

[a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]

RegExp in TypeScript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

Controller not a function, got undefined, while defining controllers globally

If you're using routes (high probability) and your config has a reference to a controller in a module that's not declared as dependency then initialisation might fail too.

E.g assuming you've configured ngRoute for your app, like

angular.module('yourModule',['ngRoute'])
.config(function($routeProvider, $httpProvider) { ... });

Be careful in the block that declares the routes,

.when('/resourcePath', { 
templateUrl: 'resource.html',
controller: 'secondModuleController' //lives in secondModule
});

Declare secondModule as a dependency after 'ngRoute' should resolve the issue. I know I had this problem.

Force Java timezone as GMT/UTC

Execute this line in MySQL to reset your timezone:

SET @@global.time_zone = '+00:00';

Unable to allocate array with shape and data type

change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:

data['label'] = data['label'].astype(np.uint8)

Display Image On Text Link Hover CSS Only

It can be done using CSS alone. It works perfect on my machine in Firefox, Chrome and Opera browser under Ubuntu 12.04.

CSS :

.hover_img a { position:relative; }
.hover_img a span { position:absolute; display:none; z-index:99; }
.hover_img a:hover span { display:block; }

HTML :

<div class="hover_img">
     <a href="#">Show Image<span><img src="images/01.png" alt="image" height="100" /></span></a>
</div>

How to use subList()

I've implemented and tested this one; it should cover most bases:

public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
    int size = list.size();
    if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
        return Collections.emptyList();
    }

    fromIndex = Math.max(0, fromIndex);
    toIndex = Math.min(size, toIndex);

    return list.subList(fromIndex, toIndex);
}

How to update only one field using Entity Framework?

I was looking for same and finally I found the solution

using (CString conn = new CString())
{
    USER user = conn.USERs.Find(CMN.CurrentUser.ID);
    user.PASSWORD = txtPass.Text;
    conn.SaveChanges();
}

believe me it work for me like a charm.

Bootstrap: align input with button

I tried all the above codes and none of them fixed my issues. Here is what worked for me. I used input-group-addon.

<div class = "input-group">
  <span class = "input-group-addon">Go</span>
  <input type = "text" class = "form-control" placeholder="you are the man!">
</div>

How to measure time taken between lines of code in python?

If you want to measure CPU time, can use time.process_time() for Python 3.3 and above:

import time
start = time.process_time()
# your code here    
print(time.process_time() - start)

First call turns the timer on, and second call tells you how many seconds have elapsed.

There is also a function time.clock(), but it is deprecated since Python 3.3 and will be removed in Python 3.8.

There are better profiling tools like timeit and profile, however time.process_time() will measure the CPU time and this is what you're are asking about.

If you want to measure wall clock time instead, use time.time().

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Refresh Page C# ASP.NET

Use:

Response.Redirect(Request.RawUrl, true);

How to display both icon and title of action inside ActionBar?

Using app:showAsAction="always|withText". I am using Android 4.1.1, but it should applicable anyway. Mine look like below

<item
        android:id="@+id/action_sent_current_data"
        android:icon="@drawable/ic_upload_cloud"
        android:orderInCategory="100"
        android:title="@string/action_sent_current_data"
        app:showAsAction="always|withText"/>

How do I add the Java API documentation to Eclipse?

if you are using maven:

mvn eclipse:eclipse -DdownloadSources=true  -DdownloadJavadocs=true

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

Setting the height of a SELECT in IE

i wanted to set the height of the select box to be smaller than the default. i used

select {
   position: relative;
   height: 10px !important;
   display: inline-block;
}

this works on ie7 and ie8. you might only need the height property, i just added the position and display to override properties inherited from higher up the dom.

How to make a class JSON serializable

I came up with my own solution. Use this method, pass any document (dict,list, ObjectId etc) to serialize.

def getSerializable(doc):
    # check if it's a list
    if isinstance(doc, list):
        for i, val in enumerate(doc):
            doc[i] = getSerializable(doc[i])
        return doc

    # check if it's a dict
    if isinstance(doc, dict):
        for key in doc.keys():
            doc[key] = getSerializable(doc[key])
        return doc

    # Process ObjectId
    if isinstance(doc, ObjectId):
        doc = str(doc)
        return doc

    # Use any other custom serializting stuff here...

    # For the rest of stuff
    return doc

JQuery - $ is not defined

When using jQuery in asp.net, if you are using a master page and you are loading the jquery source file there, make sure you have the header contentplaceholder after all the jquery script references.

I had a problem where any pages that used that master page would return '$ is not defined' simply because the incorrect order was making the client side code run before the jquery object was created. So make sure you have:

<head runat="server">
    <script type="text/javascript" src="Scripts/jquery-VERSION#.js"></script>
    <asp:ContentPlaceHolder id="Header" runat="server"></asp:ContentPlaceHolder>
</head>

That way the code will run in order and you will be able to run jQuery code on the child pages.

git - pulling from specific branch

Laravel documentation example:

git pull https://github.com/laravel/docs.git 5.8

based on the command format:

git pull origin <branch>

Image Greyscale with CSS & re-color on mouse-over?

There are numerous methods of accomplishing this, which I'll detail with a few examples below.

Pure CSS (using only one colored image)

img.grayscale {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 3.5+ */
  filter: gray; /* IE6-9 */
  -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
}

img.grayscale:hover {
  filter: none;
  -webkit-filter: grayscale(0%);
}

_x000D_
_x000D_
img.grayscale {_x000D_
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");_x000D_
  /* Firefox 3.5+, IE10 */_x000D_
  filter: gray;_x000D_
  /* IE6-9 */_x000D_
  -webkit-filter: grayscale(100%);_x000D_
  /* Chrome 19+ & Safari 6+ */_x000D_
  -webkit-transition: all .6s ease;_x000D_
  /* Fade to color for Chrome and Safari */_x000D_
  -webkit-backface-visibility: hidden;_x000D_
  /* Fix for transition flickering */_x000D_
}_x000D_
_x000D_
img.grayscale:hover {_x000D_
  filter: none;_x000D_
  -webkit-filter: grayscale(0%);_x000D_
}_x000D_
_x000D_
svg {_x000D_
  background: url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);_x000D_
}_x000D_
_x000D_
svg image {_x000D_
  transition: all .6s ease;_x000D_
}_x000D_
_x000D_
svg image:hover {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<p>Firefox, Chrome, Safari, IE6-9</p>_x000D_
<img class="grayscale" src="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" width="400">_x000D_
<p>IE10 with inline SVG</p>_x000D_
<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 400 377" width="400" height="377">_x000D_
  <defs>_x000D_
     <filter id="filtersPicture">_x000D_
       <feComposite result="inputTo_38" in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />_x000D_
       <feColorMatrix id="filter_38" type="saturate" values="0" data-filterid="38" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image filter="url(&quot;#filtersPicture&quot;)" x="0" y="0" width="400" height="377" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s1600/a2cf7051-5952-4b39-aca3-4481976cb242.jpg" />_x000D_
   </svg>
_x000D_
_x000D_
_x000D_

You can find an article related to this technique here.

Pure CSS (using a grayscale and colored images)

This approach requires two copies of an image: one in grayscale and the other in full color. Using the CSS :hover psuedoselector, you can update the background of your element to toggle between the two:

#yourimage { 
    background: url(../grayscale-image.png);
}
#yourImage:hover { 
    background: url(../color-image.png};
}

_x000D_
_x000D_
#google {_x000D_
  background: url('http://www.google.com/logos/keystroke10-hp.png');_x000D_
  height: 95px;_x000D_
  width: 275px;_x000D_
  display: block;_x000D_
  /* Optional for a gradual animation effect */_x000D_
  transition: 0.5s;_x000D_
}_x000D_
_x000D_
#google:hover {_x000D_
  background: url('https://graphics217b.files.wordpress.com/2011/02/logo1w.png');_x000D_
}
_x000D_
<a id='google' href='http://www.google.com'></a>
_x000D_
_x000D_
_x000D_

This could also be accomplished by using a Javascript-based hover effect such as jQuery's hover() function in the same manner.

Consider a Third-Party Library

The desaturate library is a common library that allows you to easily switch between a grayscale version and full-colored version of a given element or image.

Java Process with Input/Output Stream

Firstly, I would recommend replacing the line

Process process = Runtime.getRuntime ().exec ("/bin/bash");

with the lines

ProcessBuilder builder = new ProcessBuilder("/bin/bash");
builder.redirectErrorStream(true);
Process process = builder.start();

ProcessBuilder is new in Java 5 and makes running external processes easier. In my opinion, its most significant improvement over Runtime.getRuntime().exec() is that it allows you to redirect the standard error of the child process into its standard output. This means you only have one InputStream to read from. Before this, you needed to have two separate Threads, one reading from stdout and one reading from stderr, to avoid the standard error buffer filling while the standard output buffer was empty (causing the child process to hang), or vice versa.

Next, the loops (of which you have two)

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

only exit when the reader, which reads from the process's standard output, returns end-of-file. This only happens when the bash process exits. It will not return end-of-file if there happens at present to be no more output from the process. Instead, it will wait for the next line of output from the process and not return until it has this next line.

Since you're sending two lines of input to the process before reaching this loop, the first of these two loops will hang if the process hasn't exited after these two lines of input. It will sit there waiting for another line to be read, but there will never be another line for it to read.

I compiled your source code (I'm on Windows at the moment, so I replaced /bin/bash with cmd.exe, but the principles should be the same), and I found that:

  • after typing in two lines, the output from the first two commands appears, but then the program hangs,
  • if I type in, say, echo test, and then exit, the program makes it out of the first loop since the cmd.exe process has exited. The program then asks for another line of input (which gets ignored), skips straight over the second loop since the child process has already exited, and then exits itself.
  • if I type in exit and then echo test, I get an IOException complaining about a pipe being closed. This is to be expected - the first line of input caused the process to exit, and there's nowhere to send the second line.

I have seen a trick that does something similar to what you seem to want, in a program I used to work on. This program kept around a number of shells, ran commands in them and read the output from these commands. The trick used was to always write out a 'magic' line that marks the end of the shell command's output, and use that to determine when the output from the command sent to the shell had finished.

I took your code and I replaced everything after the line that assigns to writer with the following loop:

while (scan.hasNext()) {
    String input = scan.nextLine();
    if (input.trim().equals("exit")) {
        // Putting 'exit' amongst the echo --EOF--s below doesn't work.
        writer.write("exit\n");
    } else {
        writer.write("((" + input + ") && echo --EOF--) || echo --EOF--\n");
    }
    writer.flush();

    line = reader.readLine();
    while (line != null && ! line.trim().equals("--EOF--")) {
        System.out.println ("Stdout: " + line);
        line = reader.readLine();
    }
    if (line == null) {
        break;
    }
}

After doing this, I could reliably run a few commands and have the output from each come back to me individually.

The two echo --EOF-- commands in the line sent to the shell are there to ensure that output from the command is terminated with --EOF-- even in the result of an error from the command.

Of course, this approach has its limitations. These limitations include:

  • if I enter a command that waits for user input (e.g. another shell), the program appears to hang,
  • it assumes that each process run by the shell ends its output with a newline,
  • it gets a bit confused if the command being run by the shell happens to write out a line --EOF--.
  • bash reports a syntax error and exits if you enter some text with an unmatched ).

These points might not matter to you if whatever it is you're thinking of running as a scheduled task is going to be restricted to a command or a small set of commands which will never behave in such pathological ways.

EDIT: improve exit handling and other minor changes following running this on Linux.

Using multiple delimiters in awk

Good news! awk field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|...":

awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file

Returns:

tc0001  tomcat7.1  demo.example.com
tc0001  tomcat7.2  quest.example.com
tc0001  tomcat7.5  www.example.com

Here:

  • -F"/|=" sets the input field separator to either / or =. Then, it sets the output field separator to a tab.

  • -vOFS='\t' is using the -v flag for setting a variable. OFS is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F.

  • {print $3, $5, $NF} prints the 3rd, 5th and last fields based on the input field separator.


See another example:

$ cat file
hello#how_are_you
i#am_very#well_thank#you

This file has two fields separators, # and _. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!

$ awk -F"#|_" '{print $2}' file
how
am

Where the files are numbered as follows:

hello#how_are_you           i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^           ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
  1    2   3   4            1  2   3    4    5    6

Cannot find pkg-config error

For Ubuntu/Debian OS,

apt-get install -y pkg-config

For Redhat/Yum OS,

yum install -y pkgconfig

For Archlinux OS,

pacman -S pkgconf

How do I add comments to package.json for npm install?

I have a funny hack idea.

Create an npm package name suitably as a comment divider for dependencies and devDependencies block in file package.json, for example x----x----x

{
    "name": "app-name",
    "dependencies": {
        "x----x----x": "this is the first line of a comment",
        "babel-cli": "6.x.x",
        "babel-core": "6.x.x",
        "x----x----x": "this is the second line of a comment",
        "knex": "^0.11.1",
        "mocha": "1.20.1",
        "x----x----x": "*"
    }
}

NOTE: You must add the last comment divider line with a valid version, like * in the block.

Read the package name of an Android APK

I also tried the de-compilation thing, it works but recently I found the easiest way:

  1. Download and install Appium from Appium website

  2. Open Appium->Android setting, choose the target apk file. And then you get everything you want, the package info, activity info.

Oracle: how to INSERT if a row doesn't exist

You should use Merge: For example:

MERGE INTO employees e
    USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
    ON (e.id = h.emp_id)
  WHEN MATCHED THEN
    UPDATE SET e.address = h.address
  WHEN NOT MATCHED THEN
    INSERT (id, address)
    VALUES (h.emp_id, h.address);

or

MERGE INTO employees e
    USING hr_records h
    ON (e.id = h.emp_id)
  WHEN MATCHED THEN
    UPDATE SET e.address = h.address
  WHEN NOT MATCHED THEN
    INSERT (id, address)
    VALUES (h.emp_id, h.address);

https://oracle-base.com/articles/9i/merge-statement