Programs & Examples On #Diem

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I had this issue because i denied keychain access and in order to solve it you need to open keychain, Then click on the lock on top right of the screen to lock it again, after that you can archive and it will work

moment.js 24h format

_x000D_
_x000D_
//Format 24H use HH:mm_x000D_
let currentDate = moment().format('YYYY-MM-DD HH:mm')_x000D_
console.log(currentDate)_x000D_
_x000D_
//example of current time with defined Time zone +1_x000D_
let currentDateTm = moment().utcOffset('+0100').format('YYYY-MM-DD HH:mm')_x000D_
console.log(currentDateTm)
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

onclick or inline script isn't working in extension

Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).

You are going to have to do something similar to this:

Assign an ID to the link (<a onClick=hellYeah("xxx")> becomes <a id="link">), and use addEventListener to bind the event. Put the following in your popup.js file:

document.addEventListener('DOMContentLoaded', function() {
    var link = document.getElementById('link');
    // onClick's logic below:
    link.addEventListener('click', function() {
        hellYeah('xxx');
    });
});

popup.js should be loaded as a separate script file:

<script src="popup.js"></script>

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

In my case I haven't set the setContentView(R.layout.main);

If you create a new class do not foget to set this in on onCreate(Bundle savedInstanceState) method.

I have done this stupid mistake several times.

How to use onResume()?

The best way to understand would be to have all the LifeCycle methods overridden in your activity and placing a breakpoint(if checking in emulator) or a Log in each one of them. You'll get to know which one gets called when.

Just as an spoiler, onCreate() gets called first, then if you paused the activity by either going to home screen or by launching another activity, onPause() gets called. If the OS destroys the activity in the meantime, onDestroy() gets called. If you resume the app and the app already got destroyed, onCreate() will get called, or else onResume() will get called.

Edit: I forgot about onStop(), it gets called before onDestroy().

Do the exercise I mentioned and you'll be having a better understanding.

VBA - Range.Row.Count

That is nice question :)

When you have situation with 1 cell (A1), it is important to identify if second declared cell is not empty (sh.Range("A1").End(xlDown)). If it is true it means your range got out of control :) Look at code below:

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Arkusz1")

Dim k As Long

If IsEmpty(sh.Range("A1").End(xlDown)) = True Then
    k = 1

Else
    k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count

End If

How to compare arrays in C#?

There is no static Equals method in the Array class, so what you are using is actually Object.Equals, which determines if the two object references point to the same object.

If you want to check if the arrays contains the same items in the same order, you can use the SequenceEquals extension method:

childe1.SequenceEqual(grandFatherNode)

Edit:

To use SequenceEquals with multidimensional arrays, you can use an extension to enumerate them. Here is an extension to enumerate a two dimensional array:

public static IEnumerable<T> Flatten<T>(this T[,] items) {
  for (int i = 0; i < items.GetLength(0); i++)
    for (int j = 0; j < items.GetLength(1); j++)
      yield return items[i, j];
}

Usage:

childe1.Flatten().SequenceEqual(grandFatherNode.Flatten())

If your array has more dimensions than two, you would need an extension that supports that number of dimensions. If the number of dimensions varies, you would need a bit more complex code to loop a variable number of dimensions.

You would of course first make sure that the number of dimensions and the size of the dimensions of the arrays match, before comparing the contents of the arrays.

Edit 2:

Turns out that you can use the OfType<T> method to flatten an array, as RobertS pointed out. Naturally that only works if all the items can actually be cast to the same type, but that is usually the case if you can compare them anyway. Example:

childe1.OfType<Person>().SequenceEqual(grandFatherNode.OfType<Person>())

How do I check form validity with angularjs?

You can also use myform.$invalid

E.g.

if($scope.myform.$invalid){return;}

String representation of an Enum

If I'm understanding you correctly, you can simply use .ToString() to retrieve the name of the enum from the value (Assuming it's already cast as the Enum); If you had the naked int (lets say from a database or something) you can first cast it to the enum. Both methods below will get you the enum name.

AuthenticationMethod myCurrentSetting = AuthenticationMethod.FORMS;
Console.WriteLine(myCurrentSetting); // Prints: FORMS
string name = Enum.GetNames(typeof(AuthenticationMethod))[(int)myCurrentSetting-1];
Console.WriteLine(name); // Prints: FORMS

Keep in mind though, the second technique assumes you are using ints and your index is 1 based (not 0 based). The function GetNames also is quite heavy by comparison, you are generating a whole array each time it's called. As you can see in the first technique, .ToString() is actually called implicitly. Both of these are already mentioned in the answers of course, I'm just trying to clarify the differences between them.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

You can set the path variable for easily by command prompt.

  1. Open run and write cmd

  2. In the command window write the following: set path=%path%;C:\python36

  3. press enter.
  4. to check write python and enter. You will see the python version as shown in the picture.

enter image description here

java.lang.IllegalStateException: The specified child already has a parent

When you override OnCreateView in your RouteSearchFragment class, do you have the

if(view != null) {
    return view; 
}

code segment?

If so, removing the return statement should solve your problem.

You can keep the code and return the view if you don't want to regenerate view data, and onDestroyView() method you remove this view from its parent like so:

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
        }
    }

Finding all positions of substring in a larger string in C#

Why don't you use the built in RegEx class:

public static IEnumerable<int> GetAllIndexes(this string source, string matchString)
{
   matchString = Regex.Escape(matchString);
   foreach (Match match in Regex.Matches(source, matchString))
   {
      yield return match.Index;
   }
}

If you do need to reuse the expression then compile it and cache it somewhere. Change the matchString param to a Regex matchExpression in another overload for the reuse case.

! [rejected] master -> master (fetch first)

Follow the steps given below as I also had the same problem:

$ git pull origin master --allow-unrelated-histories 

(To see if local branch can be easily merged with remote one)

$ git push -u origin master 

(Now push entire content of local git repository to your online repository)

How to determine tables size in Oracle

If you don't have DBA rights then you can use user_segments table:

select bytes/1024/1024 MB from user_segments where segment_name='Table_name'

orderBy multiple fields in Angular

If you wants to sort on mulitple fields inside controller use this

$filter('orderBy')($scope.property_list, ['firstProp', 'secondProp']);

See also https://docs.angularjs.org/api/ng/filter/orderBy

How can I use random numbers in groovy?

Generate pseudo random numbers between 1 and an [UPPER_LIMIT]

You can use the following to generate a number between 1 and an upper limit.

Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1

Here is a specific example:

Example - Generate pseudo random numbers in the range 1 to 600:

Math.abs(new Random().nextInt() % 600) + 1

This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.


Generate pseudo random numbers between a [LOWER_LIMIT] and an [UPPER_LIMIT]

If you want to use a lower bound that is not equal to 1 then you can use the following formula.

Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]

Here is a specific example:

Example - Generate pseudo random numbers in the range of 40 to 99:

Math.abs( new Random().nextInt() % (99 - 40) ) + 40

This will generate a random number within a range of 40 and 99.

How to access first element of JSON object array?

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.

So either correct your source to:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };

and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

This may happen when the npm/lib folder got emptied for some reason (could also happen due to permission issues in the last usage).

A reinstallation of the node could solve the issue (as stated on other answers here), but I would suggest using a wonderful tool called nvm (Node Version Manager), which is able to manage multiple version of node and npm - this is mostly useful on dev machines with more than one projects require different versions of node.

When you install nvm, this message will go away and you will have the latest version of node and npm to use.

In order to see the list of currently installed node versions in your nvm, just run:

nvm list

In order to install and use a new node version, run:

nvm install <node_version>

For example to install latest version of node 10.x, run:

nvm install 10

In order to switch to currently installed version, run:

nvm use <node_version>

In order to switch to system's original node version, just run:

nvm use system

Hope this helps.

Good luck!

Angular 2 Scroll to bottom (Chat style)

const element = document.getElementById('box');
element.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' });

Delete all files of specific type (extension) recursively down a directory using a batch file

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.

How to Remove the last char of String in C#?

If you are using string datatype, below code works:

string str = str.Remove(str.Length - 1);

But when you have StringBuilder, you have to specify second parameter length as well.

SB

That is,

string newStr = sb.Remove(sb.Length - 1, 1).ToString();

To avoid below error:

SB2

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    rv.setExposeModelAttributes(false);
    return rv;
}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>
</bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

How to extract filename.tar.gz file

It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.

How can I backup a remote SQL Server database to a local drive?

You cannot create a backup from a remote server to a local disk - there is just no way to do this. And there are no third-party tools to do this either, as far as I know.

All you can do is create a backup on the remote server machine, and have someone zip it up and send it to you.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

It´s a issue of rounding the result, the solution for me is the following.

divider.divide(dividend,RoundingMode.HALF_UP);

How to find integer array size in java

There is no method call size() with array. you can use array.length

How to remove responsive features in Twitter Bootstrap 3?

This is explained in the official Bootstrap 3 release docs:

Steps to disable responsive views

To disable responsive features, follow these steps. See it in action in the modified template below.

  1. Remove (or just don't add) the viewport <meta> mentioned in the CSS docs
  2. Remove the max-width on the .container for all grid tiers with max-width: none !important; and set a regular width like width: 970px;. Be sure that this comes after the default Bootstrap CSS. You can optionally avoid the !important with media queries or some selector-fu.
  3. If using navbars, undo all the navbar collapsing and expanding behavior (this is too much to show here, so peep the example).
  4. For grid layouts, make use of .col-xs-* classes in addition to or in place of the medium/large ones. Don't worry, the extra-small device grid scales up to all resolutions, so you're set there.

You'll still need Respond.js for IE8 (since our media queries are still there and need to be picked up). This just disables the "mobile site" of Bootstrap.

See also the example on GetBootstrap.com/examples/non-responsive/

How can I open multiple files using "with open" in Python?

Since Python 3.3, you can use the class ExitStack from the contextlib module to safely
open an arbitrary number of files.

It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.

In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

If you are interested in the details, here is a generic example in order to explain how ExitStack operates:

from contextlib import ExitStack

class X:
    num = 1

    def __init__(self):
        self.num = X.num
        X.num += 1

    def __repr__(self):
        cls = type(self)
        return '{cls.__name__}{self.num}'.format(cls=cls, self=self)

    def __enter__(self):
        print('enter {!r}'.format(self))
        return self.num

    def __exit__(self, exc_type, exc_value, traceback):
        print('exit {!r}'.format(self))
        return True

xs = [X() for _ in range(3)]

with ExitStack() as stack:
    print(len(stack._exit_callbacks)) # number of callbacks called on exit
    nums = [stack.enter_context(x) for x in xs]
    print(len(stack._exit_callbacks))

print(len(stack._exit_callbacks))
print(nums)

Output:

0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]

How to distinguish between left and right mouse click with jQuery

$(document).ready(function () {
    var resizing = false;
    var frame = $("#frame");
    var origHeightFrame = frame.height();
    var origwidthFrame = frame.width();
    var origPosYGrip = $("#frame-grip").offset().top;
    var origPosXGrip = $("#frame-grip").offset().left;
    var gripHeight = $("#frame-grip").height();
    var gripWidth = $("#frame-grip").width();

    $("#frame-grip").mouseup(function (e) {
        resizing = false;
    });

    $("#frame-grip").mousedown(function (e) {
        resizing = true;
    });
    document.onmousemove = getMousepoints;
    var mousex = 0, mousey = 0, scrollTop = 0, scrollLeft = 0;
    function getMousepoints() {
        if (resizing) {
            var MouseBtnClick = event.which;
            if (MouseBtnClick == 1) {
                scrollTop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
                scrollLeft = document.documentElement ? document.documentElement.scrollLeft : document.body.scrollLeft;
                mousex = event.clientX + scrollLeft;
                mousey = event.clientY + scrollTop;

                frame.height(mousey);
                frame.width(mousex);
            }
            else {
                resizing = false;
            }
        }
        return true;

    }


});

How to Convert Int to Unsigned Byte and Back

The Integer.toString(size) call converts into the char representation of your integer, i.e. the char '5'. The ASCII representation of that character is the value 65.

You need to parse the string back to an integer value first, e.g. by using Integer.parseInt, to get back the original int value.

As a bottom line, for a signed/unsigned conversion, it is best to leave String out of the picture and use bit manipulation as @JB suggests.

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

jQuery scrollTop not working in Chrome but working in Firefox

A better way to solve this problem is to use a function like this:

function scrollToTop(callback, q) {

    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, function() {
            console.log('html scroll');
            callback(q)
        });
        return;
    }

    if ($('body').scrollTop()) {
        $('body').animate({ scrollTop: 0 }, function() {
            console.log('body scroll');
            callback(q)
        });
        return;
    }

    callback(q);
}

This will work across all browsers and prevents FireFox from scrolling up twice (which is what happens if you use the accepted answer - $("html,body").animate({ scrollTop: 0 }, "slow");).

What is Java Servlet?

Servlet is a java class to respond a HTTP request and produce a HTTP response...... when we make a page with the use of HTML then it would be a static page so to make it dynamic we use SERVLET {in simple words one can understand} To make use of servlet is overcomed by JSP it uses the code and HTML tag both in itself..

Replace part of a string in Python?

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

append option to select menu?

$(document).ready(function(){

    $('#mySelect').append("<option>BMW</option>")

})

Android Studio Gradle Configuration with name 'default' not found

I recently encountered this error when I refereneced a project that was initiliazed via a git submodule.

I ended up finding out that the root build.gradle file of the submodule (a java project) did not have the java plugin applied at the root level.

It only had

apply plugin: 'idea'

I added the java plugin:

apply plugin: 'idea'
apply plugin: 'java'

Once I applied the java plugin the 'default not found' message disappeared and the build succeeded.

Difference between <input type='submit' /> and <button type='submit'>text</button>

With <button>, you can use img tags, etc. where text is

<button type='submit'> text -- can be img etc.  </button>

with <input> type, you are limited to text

How can I convert string date to NSDate?

Below are some string to date format converting options can be usedin swift iOS.

  1. Thursday, Dec 27, 2018 format= EEEE, MMM d, yyyy
  2. 12/27/2018 format= MM/dd/yyyy
  3. 12-27-2018 09:59 format= MM-dd-yyyy HH:mm
  4. Dec 27, 9:59 AM format= MMM d, h:mm a
  5. December 2018 format= MMMM yyyy
  6. Dec 27, 2018 format= MMM d, yyyy
  7. Thu, 27 Dec 2018 09:59:19 +0000 format= E, d MMM yyyy HH:mm:ss Z
  8. 2018-12-27T09:59:19+0000 format= yyyy-MM-dd'T'HH:mm:ssZ
  9. 27.12.18 format= dd.MM.yy
  10. 09:59:19.815 format= HH:mm:ss.SSS

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

Sum columns with null values in oracle

select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0)) as total_hours
from hours_t
group by type, craft
order by type, craft

console.log not working in Angular2 Component (Typescript)

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.

Django DoesNotExist

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code

Calling an API from SQL Server stored procedure

Please see a link for more details.

Declare @Object as Int;
Declare @ResponseText as Varchar(8000);

Code Snippet
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT', --Your Web Service Url (invoked)
                 'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Select @ResponseText

Exec sp_OADestroy @Object

How do I run a Python script from C#?

The reason it isn't working is because you have UseShellExecute = false.

If you don't use the shell, you will have to supply the complete path to the python executable as FileName, and build the Arguments string to supply both your script and the file you want to read.

Also note, that you can't RedirectStandardOutput unless UseShellExecute = false.

I'm not quite sure how the argument string should be formatted for python, but you will need something like this:

private void run_cmd(string cmd, string args)
{
     ProcessStartInfo start = new ProcessStartInfo();
     start.FileName = "my/full/path/to/python.exe";
     start.Arguments = string.Format("{0} {1}", cmd, args);
     start.UseShellExecute = false;
     start.RedirectStandardOutput = true;
     using(Process process = Process.Start(start))
     {
         using(StreamReader reader = process.StandardOutput)
         {
             string result = reader.ReadToEnd();
             Console.Write(result);
         }
     }
}

How to set underline text on textview?

Use this

tvHide.setPaintFlags(tvHide.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

Easy way to concatenate two byte arrays

For two or multiple arrays, this simple and clean utility method can be used:

/**
 * Append the given byte arrays to one big array
 *
 * @param arrays The arrays to append
 * @return The complete array containing the appended data
 */
public static final byte[] append(final byte[]... arrays) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (arrays != null) {
        for (final byte[] array : arrays) {
            if (array != null) {
                out.write(array, 0, array.length);
            }
        }
    }
    return out.toByteArray();
}

Expansion of variables inside single quotes in a command in Bash

just use printf

instead of

repo forall -c '....$variable'

use printf to replace the variable token with the expanded variable.

For example:

template='.... %s'

repo forall -c $(printf "${template}" "${variable}")

Where to put a textfile I want to use in eclipse?

Depending on your Java class package name, you're probably 4 or 5 levels down the directory structure.

If your Java class package is, for example, com.stackoverflow.project, then your class is located at src/com/stackoverflow/project.

You can either move up the directory structure with multiple ../, or you can move the text file to the same package as your class. It would be easier to move the text file.

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Uploading Files in ASP.net without using the FileUpload server control

As others has answer, the Request.Files is an HttpFileCollection that contains all the files that were posted, you only need to ask that object for the file like this:

Request.Files["myFile"]

But what happen when there are more than one input mark-up with the same attribute name:

Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />

On the server side the previous code Request.Files["myFile"] only return one HttpPostedFile object instead of the two files. I have seen on .net 4.5 an extension method called GetMultiple but for prevoious versions it doesn't exists, for that matter i propose the extension method as:

public static IEnumerable<HttpPostedFile> GetMultiple(this HttpFileCollection pCollection, string pName)
{
        for (int i = 0; i < pCollection.Count; i++)
        {
            if (pCollection.GetKey(i).Equals(pName))
            {
                yield return pCollection.Get(i);
            }
        }
}

This extension method will return all the HttpPostedFile objects that have the name "myFiles" in the HttpFileCollection if any exists.

How to obtain the start time and end time of a day?

 //this will work for user in time zone MST with 7 off set or UTC with saving time 

 //I have tried all the above and they fail the only solution is to use some math
 //the trick is to rely on $newdate is time()     //strtotime is corrupt it tries to read to many minds
 //convert to time to use with javascript*1000
 
 $dnol = strtotime('today')*1000;
 $dn = ($newdate*1000)-86400000;
 $dz=$dn/86400000;      //divide into days
 $dz=floor($dz);     //filter off excess time
 $dzt=$dz*86400000;     // put back into days UTC
 $jsDate=$dzt*1+(7*3600000);     // 7 is the off set you can store the 7 in database
 $dzt=$dzt-3600000;      //adjusment for summerTime UTC additional table for these dates will drive you crazy
 //solution get users [time off sets] with browser, up date to data base for user with ajax when they ain't lookin



 <?php
 $t=time();
 echo($t . "<br>");
 echo(date("Y-m-d",$t));
 echo '<BR>'.$dnol;
 echo '<BR>'.$dzt.'<BR>';
 echo(date("Y-m-d",$dzt/1000));      //convert back for php /1000
 echo '<BR>';
 echo(date('Y-m-d h:i:s',$dzt/1000));

 ?>

Multiline TextView in Android?

I do not like the solution that forces the number of lines in the text view. I rather suggest you solve it via the solution proposed here. As I see the OP is also struggling with making text view look like proper in table and shrinkColumns is the correct directive to pass in to achieve what is wanted.

How to insert spaces/tabs in text using HTML/CSS

I like to use this:

In your CSS:

.tab { 
       display:inline-block; 
       margin-left: 40px; 
}

In your HTML:

<p>Some Text <span class="tab">Tabbed Text</span></p>

How to join entries in a set into one string?

The join is called on the string:

print ", ".join(set_3)

invalid target release: 1.7

Other than setting JAVA_HOME environment variable, you got to make sure you are using the correct JDK in your Maven run configuration. Go to Run -> Run Configuration, select your Maven Build configuration, go to JRE tab and set the correct Runtime JRE.

Maven run configuration

XPath with multiple conditions

Use:

/category[@name='Sport' and author/text()[1]='James Small']

or use:

/category[@name='Sport' and author[starts-with(.,'James Small')]]

It is a good rule to try to avoid using the // pseudo-operator whenever possible, because its evaluation can typically be very slow.

Also:

./somename

is equivalent to:

somename

so it is recommended to use the latter.

How to use opencv in using Gradle?

I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android

You can include it on your project only adding two lines into build.gradle file thanks to jitpack.io service.

Using jquery to get element's position relative to viewport

I found that the answer by cballou was no longer working in Firefox as of Jan. 2014. Specifically, if (self.pageYOffset) didn't trigger if the client had scrolled right, but not down - because 0 is a falsey number. This went undetected for a while because Firefox supported document.body.scrollLeft/Top, but this is no longer working for me (on Firefox 26.0).

Here's my modified solution:

var getPageScroll = function(document_el, window_el) {
  var xScroll = 0, yScroll = 0;
  if (window_el.pageYOffset !== undefined) {
    yScroll = window_el.pageYOffset;
    xScroll = window_el.pageXOffset;
  } else if (document_el.documentElement !== undefined && document_el.documentElement.scrollTop) {
    yScroll = document_el.documentElement.scrollTop;
    xScroll = document_el.documentElement.scrollLeft;
  } else if (document_el.body !== undefined) {// all other Explorers
    yScroll = document_el.body.scrollTop;
    xScroll = document_el.body.scrollLeft;
  }
  return [xScroll,yScroll];
};

Tested and working in FF26, Chrome 31, IE11. Almost certainly works on older versions of all of them.

Arraylist swap elements

You can use Collections.swap(List<?> list, int i, int j);

How to list physical disks?

Might want to include the old A: and B: drives as you never know who might be using them! I got tired of USB drives bumping my two SDHC drives that are just for Readyboost. I had been assigning them to High letters Z: Y: with a utility that will assign drive letters to devices as you wish. I wondered.... Can I make a Readyboost drive letter A: ? YES! Can I put my second SDHC drive letter as B: ? YES!

I've used Floppy Drives back in the day, never thought that A: or B: would come in handy for Readyboost.

My point is, don't assume A: & B: will not be used by anyone for anything You might even find the old SUBST command being used!

Incorrect integer value: '' for column 'id' at row 1

To let MySql generate sequence numbers for an AUTO_INCREMENT field you have three options:

  1. specify list a column list and omit your auto_incremented column from it as njk suggested. That would be the best approach. See comments.
  2. explicitly assign NULL
  3. explicitly assign 0

3.6.9. Using AUTO_INCREMENT:

...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

These three statements will produce the same result:

$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

So, it turns out that X11 wasn't actually installed on the centOS. There didn't seem to be any indication anywhere of it not being installed. I did the following command and now firefox opens:

yum groupinstall 'X Window System' 

Hope this answer will help others that are confused :)

error: command 'gcc' failed with exit status 1 on CentOS

Is gcc installed?

sudo yum install gcc

Reading content from URL with Node.js

try using the on error event of the client to find the issue.

var http = require('http');

var options = {
    host: 'google.com',
    path: '/'
}
var request = http.request(options, function (res) {
    var data = '';
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on('end', function () {
        console.log(data);

    });
});
request.on('error', function (e) {
    console.log(e.message);
});
request.end();

Tooltip on image

You can use the standard HTML title attribute of image for this:

<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>

What is the proper way to test if a parameter is empty in a batch file?

To sum things up:

set str=%~1
if not defined str ( echo Empty string )

This code will output "Empty string" if %1 is either "" or " or empty. Added it to the accepted answer that's currently incorrect.

Add table row in jQuery

    // Create a row and append to table
    var row = $('<tr />', {})
        .appendTo("#table_id");

    // Add columns to the row. <td> properties can be given in the JSON
    $('<td />', {
        'text': 'column1'
    }).appendTo(row);

    $('<td />', {
        'text': 'column2',
        'style': 'min-width:100px;'
    }).appendTo(row);

Move SQL Server 2008 database files to a new folder location

This is a complete procedure to transfer database and logins from an istance to a new one, scripting logins and relocating datafile and log files on the destination. Everything using metascripts.

http://zaboilab.com/sql-server-toolbox/massive-database-migration-between-sql-server-instances-the-complete-procedure

Sorry for the off-site procedure but scripts are very long. You have to:
- Script logins with original SID and HASHED password
- Create script to backup database using metascripts
- Create script to restore database passing relocate parameters using again metascripts
- Run the generated scripts on source and destination instance.
See details and download scripts following the link above.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

Windows 7

Try this,

run cmd as Admin.

Unistall all iis.

start /w pkgmgr.exe /uu:IIS-WebServerRole;WAS-WindowsActivationService

Reinstall iis and normaly it's work

Alain

In c# what does 'where T : class' mean?

It is a generic type constraint. In this case it means that the generic type T has to be a reference type (class, interface, delegate, or array type).

Double free or corruption after queue::push

You are getting double free or corruption because first destructor is for object q in this case the memory allocated by new will be free.Next time when detructor will be called for object t at that time the memory is already free (done for q) hence when in destructor delete[] myArray; will execute it will throw double free or corruption. The reason is that both object sharing the same memory so define \copy, assignment, and equal operator as mentioned in above answer.

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

How to parse SOAP XML?

This is also quite nice if you subsequently need to resolve any objects into arrays: $array = json_decode(json_encode($responseXmlObject), true);

Convert column classes in data.table

I provide a more general and safer way to do this stuff,

".." <- function (x) 
{
  stopifnot(inherits(x, "character"))
  stopifnot(length(x) == 1)
  get(x, parent.frame(4))
}


set_colclass <- function(x, class){
  stopifnot(all(class %in% c("integer", "numeric", "double","factor","character")))
  for(i in intersect(names(class), names(x))){
    f <- get(paste0("as.", class[i]))
    x[, (..("i")):=..("f")(get(..("i")))]
  }
  invisible(x)
}

The function .. makes sure we get a variable out of the scope of data.table; set_colclass will set the classes of your cols. You can use it like this:

dt <- data.table(i=1:3,f=3:1)
set_colclass(dt, c(i="character"))
class(dt$i)

How to switch between hide and view password

if (inputPassword.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
 //password is visible
                inputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
else if(inputPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
 //password is hidden
                inputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }

Why doesn't TFS get latest get the latest?

just want to add TFS MSBuild does not support special characters on folders i.e. "@"

i had experienced in the past where one of our project folders named as External@Project1

we created a TFS Build definition to run a custom msbuild file then the workspace folder is not getting any contents at the External@Project1 folder during workspace get latest. It seems that tfs get is failing but does not show any error.

after some trial and error and renaming the folder to _Project1. voila we got files on the the folder (_Project1).

1 = false and 0 = true?

It is common for comparison functions to return 0 on "equals", so that they can also return a negative number for "less than" and a positive number for "greater than". strcmp() and memcmp() work like this.

It is, however, idiomatic for zero to be false and nonzero to be true, because this is how the C flow control and logical boolean operators work. So it might be that the return values chosen for this function are fine, but it is the function's name that is in error (it should really just be called compare() or similar).

How do I remove an array item in TypeScript?

Same way as you would in JavaScript.

delete myArray[key];

Note that this sets the element to undefined.

Better to use the Array.prototype.splice function:

const index = myArray.indexOf(key, 0);
if (index > -1) {
   myArray.splice(index, 1);
}

How merge two objects array in angularjs?

Simple

var a=[{a:4}], b=[{b:5}]

angular.merge(a,b) // [{a:4, b:5}]

Tested on angular 1.4.1

Java - Check Not Null/Empty else assign default value

Use org.apache.commons.lang3.StringUtils

String emptyString = new String();    
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);

String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);

Both of the above options will print:

default

default

How to get a .csv file into R?

You need read.csv("C:/somedirectory/some/file.csv") and in general it doesn't hurt to actually look at the help page including its example section at the bottom.

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

Coloring Buttons in Android with Material Design and AppCompat

For those using an ImageButton here is how you do it:

In style.xml:

<style name="BlueImageButton" parent="Base.Widget.AppCompat.ImageButton">
    <item name="colorButtonNormal">@color/primary</item>
    <item name="android:tint">@color/white</item>
</style>

in v21/style.xml:

<style name="BlueImageButton" parent="Widget.AppCompat.ImageButton">
    <item name="android:colorButtonNormal">@color/primary</item>
    <item name="android:tint">@color/white</item>
</style>

Then in your layout file:

<android.support.v7.widget.AppCompatImageButton
    android:id="@+id/my_button"
    android:theme="@style/BlueImageButton"
    android:layout_width="42dp"
    android:layout_height="42dp"
    android:layout_gravity="center_vertical"
    android:src="@drawable/ic_check_black_24dp"
    />

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

Missing Authentication Token while accessing API Gateway?

I had the same problem which I solved the following way:

GET Method test

https://54wtstq8d2.execute-api.ap-southeast-2.amazonaws.com/dev/echo/hello
Authorization tab -> 
•   select type(AWS signature)
•   Add AccessKey and SecretKey

How to iterate over a std::map full of strings in C++

Note that the result of dereferencing an std::map::iterator is an std::pair. The values of first and second are not functions, they are variables.

Change:

iter->first()

to

iter->first

Ditto with iter->second.

DROP IF EXISTS VS DROP?

You forgot the table in your syntax:

drop table [table_name]

which drops a table.

Using

drop table if exists [table_name]

checks if the table exists before dropping it.
If it exists, it gets dropped.
If not, no error will be thrown and no action be taken.

How can I format a list to print each element on a separate line in python?

You can just use a simple loop: -

>>> mylist = ['10', '12', '14']
>>> for elem in mylist:
        print elem 

10
12
14

Setting Django up to use MySQL

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

You also need to create the /path/to/my.cnf file with similar settings from above

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.


If you are just testing your application on your local machine, you can use

python manage.py runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle's MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',

Note that you will first need to install mysql on your OS.

brew install mysql (MacOS)

Also, the mysql client package has changed for python 3 (MySQL-Client works only for python 2)

pip3 install mysqlclient

MySQL SELECT LIKE or REGEXP to match multiple words in one record

You can just replace each space with %

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%2100%'

(HTML) Download a PDF file instead of opening them in browser when clicked

The solution that worked best for me was the one written up by Nick on his blog

The basic idea of his solution is to use the Apache servers header mod and edit the .htaccess to include a FileMatch directive that the forces all *.pdf files to act as a stream instead of an attachment. While this doesn't actually involve editing HTML (as per the original question) it doesn't require any programming per se.

The first reason I preferred Nick's approach is because it allowed me to set it on a per folder basis so PDF's in one folder could still be opened in the browser while allowing others (the ones we would like users to edit and then re-upload) to be forced as downloads.

I would also like to add that there is an option with PDF's to post/submit fillable forms via an API to your servers, but that takes awhile to implement.

The second reason was because time is a consideration. Writing a PHP file handler to force the content disposition in the header() will also take less time than an API, but still longer than Nick's approach.

If you know how to turn on an Apache mod and edit the .htaccss you can get this in about 10 minutes. It requires Linux hosting (not Windows). This may not be appropriate approach for all uses as it requires high level server access to configure. As such, if you have said access it's probably because you already know how to do those two things. If not, check Nick's blog for more instructions.

Convert String to double in Java

To convert a string back into a double, try the following

String s = "10.1";
Double d = Double.parseDouble(s);

The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

I agree with some of the others' answers. The <head> and <header> tags have two unique and very unrelated functions. The <header> tag, if I'm not mistaken, was introduced in HTML5 and was created for increased accessibility, namely for screen readers. It's generally used to indicate the heading of your document and, in order to work appropriately and effectively, should be placed inside the <body> tag. The <head> tag, since it's origin, is used for SEO in that it constructs all of the necessary meta data and such. A valid HTML structure for your page with both tags included would be like something like this:

<!DOCTYPE html/>
<html lang="es">
    <head>
        <!--crazy meta stuff here-->
    </head>
    <body>
        <header>
            <!--Optional nav tag-->
            <nav>
            </nav>
        </header>
        <!--Body content-->
    </body>
</html>

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

I've just had same issue, this is what worked for me :

Note the message 'Server must be published with no modules present to make changes' on server dialog. So after removing the projects, re-publish your server, the option to set the server location should become re-enabled.

enter image description here

How to change default Anaconda python environment

Under Linux there is an easier way to set the default environment by modifying ~/.bashrc or ~/.bash_profile At the end you'll find something like

# added by Anaconda 2.1.0 installer
export PATH="~/anaconda/bin:$PATH"

Replace it with

# set python3 as default
export PATH="~/anaconda/envs/python3/bin:$PATH"

and thats all there is to it.

Trigger css hover with JS

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.


Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.

Exit single-user mode

I tried this is working

ALTER DATABASE dbName SET MULTI_USER WITH ROLLBACK IMMEDIATE

How do I test a website using XAMPP?

Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/www"
    ServerName example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs"
    ServerName htdocs.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

Circular (or cyclic) imports in Python

I got an example here that struck me!

foo.py

import bar

class gX(object):
    g = 10

bar.py

from foo import gX

o = gX()

main.py

import foo
import bar

print "all done"

At the command line: $ python main.py

Traceback (most recent call last):
  File "m.py", line 1, in <module>
    import foo
  File "/home/xolve/foo.py", line 1, in <module>
    import bar
  File "/home/xolve/bar.py", line 1, in <module>
    from foo import gX
ImportError: cannot import name gX

What do .c and .h file extensions mean to C?

They're not really library files. They're just source files. Like Stefano said, the .c file is the C source file which actually uses/defines the actual source of what it merely outlined in the .h file, the header file. The header file usually outlines all of the function prototypes and structures that will be used in the actual source file. Think of it like a reference/appendix. This is evident upon looking at the header file, as you will see :) So then when you want to use something that was written in these source files, you #include the header file, which contains the information that the compiler will need to know.

Gson: How to exclude specific fields from Serialization without annotations

So, you want to exclude firstName and country.name. Here is what your ExclusionStrategy should look like

    public class TestExclStrat implements ExclusionStrategy {

        public boolean shouldSkipClass(Class<?> arg0) {
            return false;
        }

        public boolean shouldSkipField(FieldAttributes f) {

            return (f.getDeclaringClass() == Student.class && f.getName().equals("firstName"))||
            (f.getDeclaringClass() == Country.class && f.getName().equals("name"));
        }

    }

If you see closely it returns true for Student.firstName and Country.name, which is what you want to exclude.

You need to apply this ExclusionStrategy like this,

    Gson gson = new GsonBuilder()
        .setExclusionStrategies(new TestExclStrat())
        //.serializeNulls() <-- uncomment to serialize NULL fields as well
        .create();
    Student src = new Student();
    String json = gson.toJson(src);
    System.out.println(json);

This returns:

{ "middleName": "J.", "initials": "P.F", "lastName": "Fry", "country": { "id": 91}}

I assume the country object is initialized with id = 91L in student class.


You may get fancy. For example, you do not want to serialize any field that contains "name" string in its name. Do this:

public boolean shouldSkipField(FieldAttributes f) {
    return f.getName().toLowerCase().contains("name"); 
}

This will return:

{ "initials": "P.F", "country": { "id": 91 }}

EDIT: Added more info as requested.

This ExclusionStrategy will do the thing, but you need to pass "Fully Qualified Field Name". See below:

    public class TestExclStrat implements ExclusionStrategy {

        private Class<?> c;
        private String fieldName;
        public TestExclStrat(String fqfn) throws SecurityException, NoSuchFieldException, ClassNotFoundException
        {
            this.c = Class.forName(fqfn.substring(0, fqfn.lastIndexOf(".")));
            this.fieldName = fqfn.substring(fqfn.lastIndexOf(".")+1);
        }
        public boolean shouldSkipClass(Class<?> arg0) {
            return false;
        }

        public boolean shouldSkipField(FieldAttributes f) {

            return (f.getDeclaringClass() == c && f.getName().equals(fieldName));
        }

    }

Here is how we can use it generically.

    Gson gson = new GsonBuilder()
        .setExclusionStrategies(new TestExclStrat("in.naishe.test.Country.name"))
        //.serializeNulls()
        .create();
    Student src = new Student();
    String json = gson.toJson(src);
    System.out.println(json); 

It returns:

{ "firstName": "Philip" , "middleName": "J.", "initials": "P.F", "lastName": "Fry", "country": { "id": 91 }}

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

I agree with the accepted answer. But for me, the issue was not that, instead I had to modify my Servlet-Class name from:-

<servlet-class>org.glassfish.jersey.servlet.ServletContainer.class</servlet-class> 

To:

<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

So, removing .class worked fine in my case. Hope it will help somebody!

Excel VBA - select a dynamic cell range

sub selectVar ()
    dim x,y as integer
    let srange = "A" & x & ":" & "m" & y
    range(srange).select
end sub

I think this is the simplest way.

Tkinter: How to use threads to preventing main event loop from "freezing"

When you join the new thread in the main thread, it will wait until the thread finishes, so the GUI will block even though you are using multithreading.

If you want to place the logic portion in a different class, you can subclass Thread directly, and then start a new object of this class when you press the button. The constructor of this subclass of Thread can receive a Queue object and then you will be able to communicate it with the GUI part. So my suggestion is:

  1. Create a Queue object in the main thread
  2. Create a new thread with access to that queue
  3. Check periodically the queue in the main thread

Then you have to solve the problem of what happens if the user clicks two times the same button (it will spawn a new thread with each click), but you can fix it by disabling the start button and enabling it again after you call self.prog_bar.stop().

import Queue

class GUI:
    # ...

    def tb_click(self):
        self.progress()
        self.prog_bar.start()
        self.queue = Queue.Queue()
        ThreadedTask(self.queue).start()
        self.master.after(100, self.process_queue)

    def process_queue(self):
        try:
            msg = self.queue.get(0)
            # Show result of the task if needed
            self.prog_bar.stop()
        except Queue.Empty:
            self.master.after(100, self.process_queue)

class ThreadedTask(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        time.sleep(5)  # Simulate long running process
        self.queue.put("Task finished")

Insert content into iFrame

This should do what you want:

$("#iframe").ready(function() {
    var body = $("#iframe").contents().find("body");
    body.append('Test');
});

Check this JSFiddle for working demo.

Edit: You can of course do it one line style:

$("#iframe").contents().find("body").append('Test');

How to automatically generate a stacktrace when my program crashes

I found that @tgamblin solution is not complete. It cannot handle with stackoverflow. I think because by default signal handler is called with the same stack and SIGSEGV is thrown twice. To protect you need register an independent stack for the signal handler.

You can check this with code below. By default the handler fails. With defined macro STACK_OVERFLOW it's all right.

#include <iostream>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <cassert>

using namespace std;

//#define STACK_OVERFLOW

#ifdef STACK_OVERFLOW
static char stack_body[64*1024];
static stack_t sigseg_stack;
#endif

static struct sigaction sigseg_handler;

void handler(int sig) {
  cerr << "sig seg fault handler" << endl;
  const int asize = 10;
  void *array[asize];
  size_t size;

  // get void*'s for all entries on the stack
  size = backtrace(array, asize);

  // print out all the frames to stderr
  cerr << "stack trace: " << endl;
  backtrace_symbols_fd(array, size, STDERR_FILENO);
  cerr << "resend SIGSEGV to get core dump" << endl;
  signal(sig, SIG_DFL);
  kill(getpid(), sig);
}

void foo() {
  foo();
}

int main(int argc, char **argv) {
#ifdef STACK_OVERFLOW
  sigseg_stack.ss_sp = stack_body;
  sigseg_stack.ss_flags = SS_ONSTACK;
  sigseg_stack.ss_size = sizeof(stack_body);
  assert(!sigaltstack(&sigseg_stack, nullptr));
  sigseg_handler.sa_flags = SA_ONSTACK;
#else
  sigseg_handler.sa_flags = SA_RESTART;  
#endif
  sigseg_handler.sa_handler = &handler;
  assert(!sigaction(SIGSEGV, &sigseg_handler, nullptr));
  cout << "sig action set" << endl;
  foo();
  return 0;
} 

CSS:Defining Styles for input elements inside a div

You can define style rules which only apply to specific elements inside your div with id divContainer like this:

#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */

How to validate date with format "mm/dd/yyyy" in JavaScript?

Moment is really a good one to resolve it. I don't see reason to add complexity just to check date... take a look on moment : http://momentjs.com/

HTML :

<input class="form-control" id="date" name="date" onchange="isValidDate(this);" placeholder="DD/MM/YYYY" type="text" value="">

Script :

 function isValidDate(dateString)  {
    var dateToValidate = dateString.value
    var isValid = moment(dateToValidate, 'MM/DD/YYYY',true).isValid()
    if (isValid) {
        dateString.style.backgroundColor = '#FFFFFF';
    } else {
        dateString.style.backgroundColor = '#fba';
    }   
};

100% width Twitter Bootstrap 3 template

Using Bootstrap 3.3.5 and .container-fluid, this is how I get full width with no gutters or horizontal scrolling on mobile. Note that .container-fluid was re-introduced in 3.1.

Full width on mobile/tablet, 1/4 screen on desktop

<div class="container-fluid"> <!-- Adds 15px left/right padding --> 
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div class="col-md-4 col-md-offset-4" style="padding-left: 0, padding-right: 0"> <!-- col classes adds 15px padding, so remove the same amount -->
      <!-- Full-width for mobile -->
      <!-- 1/4 screen width for desktop -->
    </div>
  </div>
</div>

Full width on all resolutions (mobile, table, desktop)

<div class="container-fluid"> <!-- Adds 15px left/right padding -->
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div>
      <!-- Full-width content -->
    </div>
  </div>
</div>

What is a singleton in C#?

What is a singleton :
It is a class which only allows one instance of itself to be created, and usually gives simple access to that instance.

When should you use :
It depends on the situation.

Note : please do not use on db connection, for a detailed answer please refer to the answer of @Chad Grant

Here is a simple example of a Singleton:

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

You can also use Lazy<T> to create your Singleton.

See here for a more detailed example using Lazy<T>

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

How can I see function arguments in IPython Notebook Server 3?

Shift-Tab works for me to view the dcoumentation

How to get UTC timestamp in Ruby?

time = Time.now.getutc

Rationale: In my eyes a timestamp is exactly that: A point in time. This can be accurately represented with an object. If you need anything else, a scalar value, e.g. seconds since the Unix epoch, 100-ns intervals since 1601 or maybe a string for display purposes or storing the timestamp in a database, you can readily get that from the object. But that depends very much on your intended use.

Saying that »a true timestamp is the number of seconds since the Unix epoch« is a little missing the point, as that is one way of representing a point in time, but it also needs additional information to even know that you're dealing with a time and not a number. A Time object solves this problem nicely by representing a point in time and also being explicit about what it is.

How do I access previous promise results in a .then() chain?

Another answer, using sequential executor nsynjs:

function getExample(){

  var response1 = returnPromise1().data;

  // promise1 is resolved at this point, '.data' has the result from resolve(result)

  var response2 = returnPromise2().data;

  // promise2 is resolved at this point, '.data' has the result from resolve(result)

  console.log(response, response2);

}

nynjs.run(getExample,{},function(){
    console.log('all done');
})

Update: added working example

_x000D_
_x000D_
function synchronousCode() {_x000D_
     var urls=[_x000D_
         "https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js",_x000D_
         "https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js",_x000D_
         "https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"_x000D_
     ];_x000D_
     for(var i=0; i<urls.length; i++) {_x000D_
         var len=window.fetch(urls[i]).data.text().data.length;_x000D_
         //             ^                   ^_x000D_
         //             |                   +- 2-nd promise result_x000D_
         //             |                      assigned to 'data'_x000D_
         //             |_x000D_
         //             +-- 1-st promise result assigned to 'data'_x000D_
         //_x000D_
         console.log('URL #'+i+' : '+urls[i]+", length: "+len);_x000D_
     }_x000D_
}_x000D_
_x000D_
nsynjs.run(synchronousCode,{},function(){_x000D_
    console.log('all done');_x000D_
})
_x000D_
<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>
_x000D_
_x000D_
_x000D_

How do I get milliseconds from epoch (1970-01-01) in Java?

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

How to ignore conflicts in rpm installs

The --force option will reinstall already installed packages or overwrite already installed files from other packages. You don't want this normally.

If you tell rpm to install all RPMs from some directory, then it does exactly this. rpm will not ignore RPMs listed for installation. You must manually remove the unneeded RPMs from the list (or directory). It will always overwrite the files with the "latest RPM installed" whichever order you do it in.

You can remove the old RPM and rpm will resolve the dependency with the newer version of the installed RPM. But this will only work, if none of the to be installed RPMs depends exactly on the old version.

If you really need different versions of the same RPM, then the RPM must be relocatable. You can then tell rpm to install the specific RPM to a different directory. If the files are not conflicting, then you can just install different versions with rpm -i (zypper in can not install different versions of the same RPM). I am packaging for example ruby gems as relocatable RPMs at work. So I can have different versions of the same gem installed.

I don't know on which files your RPMs are conflicting, but if all of them are "just" man pages, then you probably can simply overwrite the new ones with the old ones with rpm -i --replacefiles. The only problem with this would be, that it could confuse somebody who is reading the old man page and thinks it is for the actual version. Another problem would be the rpm --verify command. It will complain for the new package if the old one has overwritten some files.

Is this possibly a duplicate of https://serverfault.com/questions/522525/rpm-ignore-conflicts?

Is it possible to install another version of Python to Virtualenv?

First of all, Thank you DTing for awesome answer. It's pretty much perfect.

For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.

wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785

./install.sh

It will ask you path to python directory. Enter

../../.localpython

Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads

Based on URL you need to change the name of tar and cd command based on file received.

Change connection string & reload app.config at run time

You can also refresh the configuration in it's entirety:

ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName];

if (importToConnectionString == null)
{
    importToConnectionString = new ConnectionStringSettings();
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
    importToConnectionString.Name = newName;
    currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString);
}
else
{
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
}

Properties.Settings.Default.Reload();

What is the correct value for the disabled attribute?

I just tried all of these, and for IE11, the only thing that seems to work is disabled="true". Values of disabled or no value given didnt work. As a matter of fact, the jsp got an error that equal is required for all fields, so I had to specify disabled="true" for this to work.

How to catch and print the full exception traceback without halting/exiting the program?

First, don't use prints for logging, there is astable, proven and well-thought out stdlib module to do that: logging. You definitely should use it instead.

Second, don't be tempted to do a mess with unrelated tools when there is native and simple approach. Here it is:

log = logging.getLogger(__name__)

try:
    call_code_that_fails()
except MyError:
    log.exception('Any extra info you want to see in your logs')

That's it. You are done now.

Explanation for anyone who is interested in how things work under the hood

What log.exception is actually doing is just a call to log.error (that is, log event with level ERROR) and print traceback then.

Why is it better?

Well, here is some considerations:

  • it is just right;
  • it is straightforward;
  • it is simple.

Why should nobody use traceback or call logger with exc_info=True or get their hands dirty with sys.exc_info?

Well, just because! They all exist for different purposes. For example, traceback.print_exc's output is a little bit different from tracebacks produced by the interpreter itself. If you use it, you will confuse anyone who reads your logs, they will be banging their heads against them.

Passing exc_info=True to log calls is just inappropriate. But, it is useful when catching recoverable errors and you want to log them (using, e.g INFO level) with tracebacks as well, because log.exception produces logs of only one level - ERROR.

And you definitely should avoid messing with sys.exc_info as much as you can. It's just not a public interface, it's an internal one - you can use it if you definitely know what you are doing. It is not intended for just printing exceptions.

Convert an integer to a byte array

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)

How to make a <div> always full screen?

Unfortunately, the height property in CSS is not as reliable as it should be. Therefore, Javascript will have to be used to set the height style of the element in question to the height of the users viewport. And yes, this can be done without absolute positioning...

<!DOCTYPE html>

<html>
  <head>
    <title>Test by Josh</title>
    <style type="text/css">
      * { padding:0; margin:0; }
      #test { background:#aaa; height:100%; width:100%; }
    </style>
    <script type="text/javascript">
      window.onload = function() {
        var height = getViewportHeight();

        alert("This is what it looks like before the Javascript. Click OK to set the height.");

        if(height > 0)
          document.getElementById("test").style.height = height + "px";
      }

      function getViewportHeight() {
        var h = 0;

        if(self.innerHeight)
          h = window.innerHeight;
        else if(document.documentElement && document.documentElement.clientHeight)
          h = document.documentElement.clientHeight;
        else if(document.body) 
          h = document.body.clientHeight;

        return h;
      }
    </script>
  </head>
  <body>
    <div id="test">
      <h1>Test</h1>
    </div>
  </body>
</html>

How to extract numbers from a string and get an array of ints?

Fraction and grouping characters for representing real numbers may differ between languages. The same real number could be written in very different ways depending on the language.

The number two million in German

2,000,000.00

and in English

2.000.000,00

A method to fully extract real numbers from a given string in a language agnostic way:

public List<BigDecimal> extractDecimals(final String s, final char fraction, final char grouping) {
    List<BigDecimal> decimals = new ArrayList<BigDecimal>();
    //Remove grouping character for easier regexp extraction
    StringBuilder noGrouping = new StringBuilder();
    int i = 0;
    while(i >= 0 && i < s.length()) {
        char c = s.charAt(i);
        if(c == grouping) {
            int prev = i-1, next = i+1;
            boolean isValidGroupingChar =
                    prev >= 0 && Character.isDigit(s.charAt(prev)) &&
                    next < s.length() && Character.isDigit(s.charAt(next));                 
            if(!isValidGroupingChar)
                noGrouping.append(c);
            i++;
        } else {
            noGrouping.append(c);
            i++;
        }
    }
    //the '.' character has to be escaped in regular expressions
    String fractionRegex = fraction == POINT ? "\\." : String.valueOf(fraction);
    Pattern p = Pattern.compile("-?(\\d+" + fractionRegex + "\\d+|\\d+)");
    Matcher m = p.matcher(noGrouping);
    while (m.find()) {
        String match = m.group().replace(COMMA, POINT);
        decimals.add(new BigDecimal(match));
    }
    return decimals;
}

Array initialization in Perl

What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);

my @array = (); should work just fine -- it allocates a new array called @array, and then assigns it the empty list, (). Note that this is identical to simply saying my @array;, since the initial value of a new array is the empty list anyway.

Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings; in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

Review any .htaccess. Maybe, a .htaccess rule is interfering with the right output. Try browsing your CSS resource directly in your address bar, it must be presented in text format.

Confirm button before running deleting routine from website

_x000D_
_x000D_
<?php _x000D_
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));_x000D_
 if(isset($_POST[add]))_x000D_
 {_x000D_
 $sno = mysqli_real_escape_string($con,$_POST[sno]);_x000D_
   $name = mysqli_real_escape_string($con,$_POST[sname]);_x000D_
   $course = mysqli_real_escape_string($con,$_POST[course]);_x000D_
 _x000D_
   $query = "insert into students(sno,name,course) values($sno,'$name','$course')";_x000D_
   //echo $query;_x000D_
   $result = mysqli_query($con,$query);_x000D_
   printf ("New Record has id %d.\n", mysqli_insert_id($con));_x000D_
  mysqli_close($con);_x000D_
   _x000D_
 }  _x000D_
?>_x000D_
  
_x000D_
<html>_x000D_
<head>_x000D_
<title>mysql_insert_id Example</title>_x000D_
</head>_x000D_
<body>_x000D_
<form action="" method="POST">_x000D_
Enter S.NO: <input type="text" name="sno"/><br/>_x000D_
Enter Student Name: <input type="text" name="sname"/><br/>_x000D_
Enter Course: <input type="text" name="course"/><br/>_x000D_
<input type="submit" name="add" value="Add Student"/>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JQuery/Javascript: check if var exists

For your case, and 99.9% of all others elclanrs answer is correct.

But because undefined is a valid value, if someone were to test for an uninitialized variable

var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true

the only 100% reliable way to determine if a var exists is to catch the exception;

var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}

But I would never write it this way

The name 'controlname' does not exist in the current context

In my case, when I created the web form, it was named as WebForm1.aspx and respective names (WebForm1). Letter, I renamed that to something else. I renamed manually at almost all the places, but one place in designer file was still showing it as 'WebForm1'.

I changed that too and got rid of this error.

Git log out user from command line

I am in a corporate setting and was attempting a simple git pull after a recent change in password.

I got: remote: Invalid username or password.

Interestingly, the following did not work: git config --global --unset credential.helper

I use Windows-7, so, I went to control panel -> Credential Manager -> Generic Credentials.

From the credential manager list, delete the line items corresponding to git.

After the deletion, come back to gitbash and git pull should prompt the dialog for you to enter your credentials.

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

Generate signed apk android studio

The "official" way to configure the build.gradle file as recommended by Google is explained here.

Basically, you add a signingConfig, in where you specify the location an password of the keystore. Then, in the release build type, refer to that signing configuration.

...
android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("myreleasekey.keystore")
            storePassword "password"
            keyAlias "MyReleaseKey"
            keyPassword "password"
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
}
...

Pandas Merge - How to avoid duplicating columns

I use the suffixes option in .merge():

dfNew = df.merge(df2, left_index=True, right_index=True,
                 how='outer', suffixes=('', '_y'))
dfNew.drop(dfNew.filter(regex='_y$').columns.tolist(),axis=1, inplace=True)

Thanks @ijoseph

Replace substring with another substring C++

the impoved version by @Czarek Tomczak.
allow both std::string and std::wstring.

template <typename charType>
void ReplaceSubstring(std::basic_string<charType>& subject,
    const std::basic_string<charType>& search,
    const std::basic_string<charType>& replace)
{
    if (search.empty()) { return; }
    typename std::basic_string<charType>::size_type pos = 0;
    while((pos = subject.find(search, pos)) != std::basic_string<charType>::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

PHP Function with Optional Parameters

If you are commonly just passing in the 8th value, you can reorder your parameters so it is first. You only need to specify parameters up until the last one you want to set.

If you are using different values, you have 2 options.

One would be to create a set of wrapper functions that take different parameters and set the defaults on the others. This is useful if you only use a few combinations, but can get very messy quickly.

The other option is to pass an array where the keys are the names of the parameters. You can then just check if there is a value in the array with a key, and if not use the default. But again, this can get messy and add a lot of extra code if you have a lot of parameters.

Handling a Menu Item Click Event - Android

This is how it looks like in Kotlin

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_logout"
    android:orderInCategory="101"
    android:title="@string/sign_out"
    app:showAsAction="never" />

Then in MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

This is onOptionsItemSelected function

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId){
        R.id.action_settings -> {
            true
        }
        R.id.action_logout -> {
            signOut()
            true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

For starting new activity

private fun signOut(){
    MySharedPreferences.clearToken()
    startSplashScreenActivity()
}

private fun startSplashScreenActivity(){
    val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
    startActivity(intent)
    finish()
}

How can I clear console

You can use the operating system's clear console method via system("");
for windows it would be system("cls"); for example
and instead of releasing three different codes for different operating systems. just make a method to get what os is running.
you can do this by detecting if unique system variables exist with #ifdef
e.g.

enum OPERATINGSYSTEM = {windows = 0, mac = 1, linux = 2 /*etc you get the point*/};

void getOs(){
    #ifdef _WIN32
        return OPERATINGSYSTEM.windows
    #elif __APPLE__ //etc you get the point

    #endif
}

int main(){
    int id = getOs();
    if(id == OPERATINGSYSTEM.windows){
        system("CLS");
    }else if (id == OPERATINGSYSTEM.mac){
        system("CLEAR");
    } //etc you get the point

}

How to SUM and SUBTRACT using SQL?

An example for subtraction is given below:

Select value1 - (select value2 from AnyTable1) from AnyTable2

value1 & value2 can be count,sum,average output etc. But the values should be comapatible

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

Execute jar file with multiple classpath libraries from command prompt

Regardless of the OS the below command should work:

java -cp "MyJar.jar;lib/*" com.mainClass

Always use quotes and please take attention that lib/*.jar will not work.

Where does R store packages?

This is documented in the 'R Installation and Administration' manual that came with your installation.

On my Linux box:

R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"      
[3] "/usr/lib/R/library"           
R> 

meaning that the default path is the first of these. You can override that via an argument to both install.packages() (from inside R) or R CMD INSTALL (outside R).

You can also override by setting the R_LIBS_USER variable.

iOS app 'The application could not be verified' only on one device

I had something similar happen to me just recently. I updated my iPhone to 8.1.3, and started getting the 'application could not be verified' error message from Xcode on an app that installed just fine on the same iOS device from the same Mac just a few days ago.

I deleted the app from the device, restarted Xcode, and the app subsequently installed on the device just fine without any error message. Not sure if deleting the app was the fix, or the problem was due to "the phase of the moon".

Android view pager with page indicator

I know this has already been answered, but for anybody looking for a simple, no-frills implementation of a ViewPager indicator, I've implemented one that I've open sourced. For anyone finding Jake Wharton's version a bit complex for their needs, have a look at https://github.com/jarrodrobins/SimpleViewPagerIndicator.

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

I just had this problem on Ubuntu 14.10

Turns that mysql-server was no longer installed (somehow it had been removed) but I couldn't just install it because there were some broken packages and dependency issues/conflicts.

In the end I had to reinstall mysql

sudo apt-get remove mysql-client
sudo apt-get install mysql-server

Are string.Equals() and == operator really same?

It is clear that tvi.header is not a String. The == is an operator that is overloaded by String class, which means it will be working only if compiler knows that both side of the operator are String.

Run jQuery function onclick

Why do you need to attach it to the HTML? Just bind the function with hover

$("div.system_box").hover(function(){ mousin }, 
                          function() { mouseout });

If you do insist to have JS references inside the html, which is usualy a bad idea you can use:

onmouseover="yourJavaScriptCode()"

after topic edit:

<div class="system_box" data-target="sms_box">

...

$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });

How to append rows in a pandas dataframe in a for loop?

There are 2 reasons you may append rows in a loop, 1. add to an existing df, and 2. create a new df.

to create a new df, I think its well documented that you should either create your data as a list and then create the data frame:

cols = ['c1', 'c2', 'c3']
lst = []
for a in range(2):
    lst.append([1, 2, 3])
df1 = pd.DataFrame(lst, columns=cols)
df1
Out[3]: 
   c1  c2  c3
0   1   2   3
1   1   2   3

OR, Create the dataframe with an index and then add to it

cols = ['c1', 'c2', 'c3']
df2 = pd.DataFrame(columns=cols, index=range(2))
for a in range(2):
    df2.loc[a].c1 = 4
    df2.loc[a].c2 = 5
    df2.loc[a].c3 = 6
df2
Out[4]: 
  c1 c2 c3
0  4  5  6
1  4  5  6

If you want to add to an existing dataframe, you could use either method above and then append the df's together (with or without the index):

df3 = df2.append(df1, ignore_index=True)
df3
Out[6]: 
  c1 c2 c3
0  4  5  6
1  4  5  6
2  1  2  3
3  1  2  3

Or, you can also create a list of dictionary entries and append those as in the answer above.

lst_dict = []
for a in range(2):
    lst_dict.append({'c1':2, 'c2':2, 'c3': 3})
df4 = df1.append(lst_dict)
df4
Out[7]: 
   c1  c2  c3
0   1   2   3
1   1   2   3
0   2   2   3
1   2   2   3

Using the dict(zip(cols, vals)))

lst_dict = []
for a in range(2):
    vals = [7, 8, 9]
    lst_dict.append(dict(zip(cols, vals)))
df5 = df1.append(lst_dict)

Spring @Transactional - isolation, propagation

We can add for this:

@Transactional(readOnly = true)
public class Banking_CustomerService implements CustomerService {

    public Customer getDetail(String customername) {
        // do something
    }

    // these settings have precedence for this method
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void updateCustomer(Customer customer) {
        // do something
    }
}

Optimal number of threads per core

I agree with @Gonzalo's answer. I have a process that doesn't do I/O, and here is what I've found:

enter image description here

Note that all threads work on one array but different ranges (two threads do not access the same index), so the results may differ if they've worked on different arrays.

The 1.86 machine is a macbook air with an SSD. The other mac is an iMac with a normal HDD (I think it's 7200 rpm). The windows machine also has a 7200 rpm HDD.

In this test, the optimal number was equal to the number of cores in the machine.

How to import a .cer certificate into a java keystore?

An open source GUI tool is available at keystore-explorer.org

KeyStore Explorer

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.

Following screens will help (they are from the official site)

Default screen that you get by running the command:

shantha@shantha:~$./Downloads/kse-521/kse.sh

enter image description here

And go to Examine and Examine a URL option and then give the web URL that you want to import.

The result window will be like below if you give google site link. enter image description here

This is one of Use case and rest is up-to the user(all credits go to the keystore-explorer.org)

How to make CREATE OR REPLACE VIEW work in SQL Server?

How about something like this, comments should explain:

--DJ - 2015-07-15 Example for view CREATE or REPLACE

--Replace with schema and view names
DECLARE @viewName NVARCHAR(30)= 'T';
DECLARE @schemaName NVARCHAR(30)= 'dbo';

--Leave this section as-is
BEGIN TRY
    DECLARE @view AS NVARCHAR(100) = '
CREATE VIEW ' + @schemaName + '.' + @viewName + ' AS SELECT '''' AS [1]';
    EXEC sp_executesql
        @view;
END TRY
BEGIN CATCH
    PRINT 'View already exists';
END CATCH;
GO

--Put full select statement here after modifying the view & schema name appropriately
ALTER VIEW [dbo].[T]
AS
    SELECT  '' AS [2];
GO


--Verify results with select statement against the view
SELECT  *
FROM    [T];

Cheers -DJ

Disabling Minimize & Maximize On WinForm?

public Form1()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
}

How to join (merge) data frames (inner, outer, left, right)

Update join. One other important SQL-style join is an "update join" where columns in one table are updated (or created) using another table.

Modifying the OP's example tables...

sales = data.frame(
  CustomerId = c(1, 1, 1, 3, 4, 6), 
  Year = 2000:2005,
  Product = c(rep("Toaster", 3), rep("Radio", 3))
)
cust = data.frame(
  CustomerId = c(1, 1, 4, 6), 
  Year = c(2001L, 2002L, 2002L, 2002L),
  State = state.name[1:4]
)

sales
# CustomerId Year Product
#          1 2000 Toaster
#          1 2001 Toaster
#          1 2002 Toaster
#          3 2003   Radio
#          4 2004   Radio
#          6 2005   Radio

cust
# CustomerId Year    State
#          1 2001  Alabama
#          1 2002   Alaska
#          4 2002  Arizona
#          6 2002 Arkansas

Suppose we want to add the customer's state from cust to the purchases table, sales, ignoring the year column. With base R, we can identify matching rows and then copy values over:

sales$State <- cust$State[ match(sales$CustomerId, cust$CustomerId) ]

# CustomerId Year Product    State
#          1 2000 Toaster  Alabama
#          1 2001 Toaster  Alabama
#          1 2002 Toaster  Alabama
#          3 2003   Radio     <NA>
#          4 2004   Radio  Arizona
#          6 2005   Radio Arkansas

# cleanup for the next example
sales$State <- NULL

As can be seen here, match selects the first matching row from the customer table.


Update join with multiple columns. The approach above works well when we are joining on only a single column and are satisfied with the first match. Suppose we want the year of measurement in the customer table to match the year of sale.

As @bgoldst's answer mentions, match with interaction might be an option for this case. More straightforwardly, one could use data.table:

library(data.table)
setDT(sales); setDT(cust)

sales[, State := cust[sales, on=.(CustomerId, Year), x.State]]

#    CustomerId Year Product   State
# 1:          1 2000 Toaster    <NA>
# 2:          1 2001 Toaster Alabama
# 3:          1 2002 Toaster  Alaska
# 4:          3 2003   Radio    <NA>
# 5:          4 2004   Radio    <NA>
# 6:          6 2005   Radio    <NA>

# cleanup for next example
sales[, State := NULL]

Rolling update join. Alternately, we may want to take the last state the customer was found in:

sales[, State := cust[sales, on=.(CustomerId, Year), roll=TRUE, x.State]]

#    CustomerId Year Product    State
# 1:          1 2000 Toaster     <NA>
# 2:          1 2001 Toaster  Alabama
# 3:          1 2002 Toaster   Alaska
# 4:          3 2003   Radio     <NA>
# 5:          4 2004   Radio  Arizona
# 6:          6 2005   Radio Arkansas

The three examples above all focus on creating/adding a new column. See the related R FAQ for an example of updating/modifying an existing column.

How does delete[] know it's an array?

Semantically, both versions of delete operator in C++ can "eat" any pointer; however, if a pointer to a single object is given to delete[], then UB will result, meaning anything may happen, including a system crash or nothing at all.

C++ requires the programmer to choose the proper version of the delete operator depending on the subject of deallocation: array or single object.

If the compiler could automatically determine whether a pointer passed to the delete operator was a pointer array, then there would be only one delete operator in C++, which would suffice for both cases.

Django. Override save for model

What I did to achieve the goal was to make this..

# I added an extra_command argument that defaults to blank
def save(self, extra_command="", *args, **kwargs):

and below the save() method is this..

# override the save method to create an image thumbnail
if self.image and extra_command != "skip creating photo thumbnail":
    # your logic here

so when i edit some fields but not editing the image, I put this..

Model.save("skip creating photo thumbnail")

you can replace the "skip creating photo thumbnail" with "im just editing the description" or a more formal text.

Hope this one helps!

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }

decorate your model like this. can use a bootstrap date time picker I used this one. https://github.com/Eonasdan/bootstrap-datetimepicker/

I suppose you already have bundles for bootstrap css and js

Your date picker bundle entries

 bundles.Add(new ScriptBundle("~/bundles/datePicker").Include(
           "~/Scripts/moment.min.js",
           "~/Scripts/bootstrap-datetimepicker.min.js"));

        bundles.Add(new StyleBundle("~/Content/datepicker").Include(
                 "~/Content/bootstrap-datetimepicker.min.css"));

Render bundles on your Layout View

@Styles.Render("~/Content/datepicker")
@Scripts.Render("~/bundles/datePicker")

Your HTML in view

<div class="form-group">
        @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "lead col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.BirthDate, new { @class = "datetimepicker form-control" })
            @Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
        </div>
</div>

At the end of your view add this.

<script>
    $(document).ready(function () {
        $('.datetimepicker').datetimepicker({
            format: 'lll'
        });
    });
</script>

How to run C program on Mac OS X using Terminal?

A "C-program" is not supposed to be run. It is meant to be compiled into an "executable" program which then can be run from your terminal. You need a compiler for that.

Oh, and the answer to your last question ("Why?") is that the file you are trying to execute doesn't have the executable rights set (which a compiler usually does automatically with the binary, which let's infer that you were trying to run the source code as a script, hence the hint at compiling.)

How to compare binary files to check if they are the same?

The standard unix diff will show if the files are the same or not:

[me@host ~]$ diff 1.bin 2.bin
Binary files 1.bin and 2.bin differ

If there is no output from the command, it means that the files have no differences.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

EL access a map value by Integer key

Initial answer (EL 2.1, May 2009)

As mentioned in this java forum thread:

Basically autoboxing puts an Integer object into the Map. ie:

map.put(new Integer(0), "myValue")

EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:

map.get(new Long(0))

As a Long is never equal to an Integer object, it does not find the entry in the map.
That's it in a nutshell.


Update since May 2009 (EL 2.2)

Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:

you can call the method intValue on the Long object self inside EL 2.2:

<c:out value="${map[(1).intValue()]}"/>

That could be a good workaround here (also mentioned below in Tobias Liefke's answer)


Original answer:

EL uses the following wrappers:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP page demonstrating this:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 <%@ page import="java.util.*" %>

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
%>
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">
    <tr>      
      <td>${entry.key}</td>
      <td>${entry.value}</td>
      <td>${entry.key.class}</td>
    </tr>
    </c:forEach>
</table>

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    <p>
    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
    <p>

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>

CSS background image to fit width, height should auto-scale in proportion

Just add this one line:

    .your-class {
        height: 100vh;
    }

vh is viewport height. This will automatically scale to fit the device' browser window.

Check more here: Make div 100% height of browser window

How to convert Integer to int?

As already written elsewhere:

  • For Java 1.5 and later you don't need to do (almost) anything, it's done by the compiler.
  • For Java 1.4 and before, use Integer.intValue() to convert from Integer to int.

BUT as you wrote, an Integer can be null, so it's wise to check that before trying to convert to int (or risk getting a NullPointerException).

pstmt.setInt(1, (tempID != null ? tempID : 0));  // Java 1.5 or later

or

pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0));  // any version, no autoboxing  

* using a default of zero, could also do nothing, show a warning or ...

I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.

I want to truncate a text or line with ellipsis using JavaScript

Something like:

var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."

SQL: How do I SELECT only the rows with a unique value on certain column?

Sorry you're not using PostgreSQL...

SELECT DISTINCT ON contract, activity * FROM thetable ORDER BY contract, activity

http://www.postgresql.org/docs/8.3/static/sql-select.html#SQL-DISTINCT

Oh wait. You only want values with exactly one...

SELECT contract, activity, count() FROM thetable GROUP BY contract, activity HAVING count() = 1

Storing and displaying unicode string (??????) using PHP and MySQL

For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there

HTML image bottom alignment inside DIV container

Set the parent div as position:relative and the inner element to position:absolute; bottom:0

CSS Div stretch 100% page height

I ran into the same problem as you. I wanted to make a DIV as background, why, because its easy to manipulate div through javascript. Anyways three things I did in the css for that div.

CSS:

{    
position:absolute; 
display:block; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
z-index:-1;    
}

How to set image to UIImage

UIImage *img = [UIImage imageNamed:@"anyImageName"];

imageNamed:
Returns the image object associated with the specified filename.

    + (UIImage *)imageNamed:(NSString *)name

Parameters
name
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.
Return Value
The image object for the specified file, or nil if the method could not find the specified image.

Discussion
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

How to use moment.js library in angular 2 typescript app?

The angular2-moment library has pipes like {{myDate | amTimeAgo}} to use in .html files.

Those same pipes can also be accessed as Typescript functions within a component class (.ts) file. First install the library as instructed:

npm install --save angular2-moment

In the node_modules/angular2-moment will now be ".pipe.d.ts" files like calendar.pipe.d.ts, date-format.pipe.d.ts and many more.

Each of those contains the Typescript function name for the equivalent pipe, for example, DateFormatPipe() is the function for amDateFormatPipe.

To use DateFormatPipe in your project, import and add it to your global providers in app.module.ts:

import { DateFormatPipe } from "angular2-moment";
.....
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ...., DateFormatPipe]

Then in any component where you want to use the function, import it on top, inject into the constructor and use:

import { DateFormatPipe } from "angular2-moment";
....
constructor(.......,  public dfp: DateFormatPipe) {
    let raw = new Date(2015, 1, 12);
    this.formattedDate = dfp.transform(raw, 'D MMM YYYY');
}

To use any of the functions follow this process. It would be nice if there was one way to gain access to all the functions, but none of the above solutions worked for me.

How to send an email from JavaScript

There is a combination service. You can combine the above listed solutions like mandrill with a service EmailJS, which can make the system more secure. They have not yet started the service though.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

This should be rather a SuperUser question.

Right I have the exact same error inside MacOSX SourceTree, however, inside a iTerm2 terminal, things work just dandy.

However, the problem seemed to be that I've got two ssh-agents running ;(

The first being /usr/bin/ssh-agent (aka MacOSX's) and then also the HomeBrew installed /usr/local/bin/ssh-agent running.

Firing up a terminal from SourceTree, allowed me to see the differences in SSH_AUTH_SOCK, using lsof I found the two different ssh-agents and then I was able to load the keys (using ssh-add) into the system's default ssh-agent (ie. /usr/bin/ssh-agent), SourceTree was working again.

How do you implement a Stack and a Queue in JavaScript?

If you understand stacks with push() and pop() functions, then queue is just to make one of these operations in the oposite sense. Oposite of push() is unshift() and oposite of pop() es shift(). Then:

//classic stack
var stack = [];
stack.push("first"); // push inserts at the end
stack.push("second");
stack.push("last");
stack.pop(); //pop takes the "last" element

//One way to implement queue is to insert elements in the oposite sense than a stack
var queue = [];
queue.unshift("first"); //unshift inserts at the beginning
queue.unshift("second");
queue.unshift("last");
queue.pop(); //"first"

//other way to do queues is to take the elements in the oposite sense than stack
var queue = [];
queue.push("first"); //push, as in the stack inserts at the end
queue.push("second");
queue.push("last");
queue.shift(); //but shift takes the "first" element

Java, Simplified check if int array contains int

1.one-off uses

List<T> list=Arrays.asList(...)
list.contains(...)

2.use HashSet for performance consideration if you use more than once.

Set <T>set =new HashSet<T>(Arrays.asList(...));
set.contains(...)

How to get HTTP Response Code using Selenium WebDriver

You can use BrowserMob proxy to capture the requests and responses with a HttpRequestInterceptor. Here is an example in Java:

// Start the BrowserMob proxy
ProxyServer server = new ProxyServer(9978);
server.start();

server.addResponseInterceptor(new HttpResponseInterceptor()
{
    @Override
    public void process(HttpResponse response, HttpContext context)
        throws HttpException, IOException
    {
        System.out.println(response.getStatusLine());
    }
});

// Get selenium proxy
Proxy proxy = server.seleniumProxy();

// Configure desired capability for using proxy server with WebDriver
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);

// Set up driver
WebDriver driver = new FirefoxDriver(capabilities);

driver.get("http://stackoverflow.com/questions/6509628/webdriver-get-http-response-code");

// Close the browser
driver.quit();

How to create a multi line body in C# System.Net.Mail.MailMessage

In case you dont need the message body in html, turn it off:

message.IsBodyHtml = false;

then use e.g:

message.Body = "First line" + Environment.NewLine + 
               "Second line";

but if you need to have it in html for some reason, use the html-tag:

message.Body = "First line <br /> Second line";

How do I use reflection to call a generic method?

Nobody provided the "classic Reflection" solution, so here is a complete code example:

using System;
using System.Collections;
using System.Collections.Generic;

namespace DictionaryRuntime
{
    public class DynamicDictionaryFactory
    {
        /// <summary>
        /// Factory to create dynamically a generic Dictionary.
        /// </summary>
        public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)
        {
            //Creating the Dictionary.
            Type typeDict = typeof(Dictionary<,>);

            //Creating KeyValue Type for Dictionary.
            Type[] typeArgs = { keyType, valueType };

            //Passing the Type and create Dictionary Type.
            Type genericType = typeDict.MakeGenericType(typeArgs);

            //Creating Instance for Dictionary<K,T>.
            IDictionary d = Activator.CreateInstance(genericType) as IDictionary;

            return d;

        }
    }
}

The above DynamicDictionaryFactory class has a method

CreateDynamicGenericInstance(Type keyType, Type valueType)

and it creates and returns an IDictionary instance, the types of whose keys and values are exactly the specified on the call keyType and valueType.

Here is a complete example how to call this method to instantiate and use a Dictionary<String, int> :

using System;
using System.Collections.Generic;

namespace DynamicDictionary
{
    class Test
    {
        static void Main(string[] args)
        {
            var factory = new DictionaryRuntime.DynamicDictionaryFactory();
            var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));

            var typedDict = dict as Dictionary<String, int>;

            if (typedDict != null)
            {
                Console.WriteLine("Dictionary<String, int>");

                typedDict.Add("One", 1);
                typedDict.Add("Two", 2);
                typedDict.Add("Three", 3);

                foreach(var kvp in typedDict)
                {
                    Console.WriteLine("\"" + kvp.Key + "\": " + kvp.Value);
                }
            }
            else
                Console.WriteLine("null");
        }
    }
}

When the above console application is executed, we get the correct, expected result:

Dictionary<String, int>
"One": 1
"Two": 2
"Three": 3

CSS '>' selector; what is it?

As others have said, it's a direct child, but it's worth noting that this is different to just leaving a space... a space is for any descendant.

<div>
  <span>Some text</span>
</div>

div>span would match this, but it would not match this:

<div>
  <p><span>Some text</span></p>
</div>

To match that, you could do div>p>span or div span.

How do I sort strings alphabetically while accounting for value when a string is numeric?

And, how about this ...

string[] sizes = new string[] { "105", "101", "102", "103", "90" };

var size = from x in sizes
           orderby x.Length, x
           select x;

foreach (var p in size)
{
    Console.WriteLine(p);
}

Dynamic array in C#

Sometimes plain arrays are preferred to Generic Lists, since they are more convenient (Better performance for costly computation -Numerical Algebra Applications for example, or for exchanging Data with Statistics software like R or Matlab)

In this case you may use the ToArray() method after initiating your List dynamically

List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");

string[] array = list.ToArray();

Of course, this has sense only if the size of the array is never known nor fixed ex-ante. if you already know the size of your array at some point of the program it is better to initiate it as a fixed length array. (If you retrieve data from a ResultSet for example, you could count its size and initiate an array of that size, dynamically)

PHP Array to CSV

It worked for me.

 $f=fopen('php://memory','w');
 $header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );      
 fputcsv($f,$header);
 fputcsv($f,$header);
 fputcsv($f,$header); 
 fseek($f,0);
 header('content-type:text/csv'); 
 header('Content-Disposition: attachment; filename="' . $filename . '";');
 fpassthru($f);```

How to explicitly obtain post data in Spring MVC?

You can simply just pass the attribute you want without any annotations in your controller:

@RequestMapping(value = "/someUrl")
public String someMethod(String valueOne) {
 //do stuff with valueOne variable here
}

Works with GET and POST

Simple file write function in C++

The function declaration int writeFile () ; seems to be missing in the code. Add int writeFile () ; before the function main()

XPath selecting a node with some attribute value equals to some other node's attribute value

I think this is what you want:

/grand/parent/child[@id="#grand"]

cannot call member function without object

If you want to call them like that, you should declare them static.

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

Align button at the bottom of div using CSS

Parent container has to have this:

position: relative;

Button itself has to have this:

position: relative;
bottom: 20px;
right: 20px;

or whatever you like

How to insert values in two dimensional array programmatically?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

But you can chain the index operator for array element access.

String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];

x[0][0] = "a1";
    // No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";

Note the dimensions of the child arrays don't need to match.

Is there a way to ignore a single FindBugs warning?

Update Gradle

dependencies {
    compile group: 'findbugs', name: 'findbugs', version: '1.0.0'
}

Locate the FindBugs Report

file:///Users/your_user/IdeaProjects/projectname/build/reports/findbugs/main.html

Find the specific message

find bugs

Import the correct version of the annotation

import edu.umd.cs.findbugs.annotations.SuppressWarnings;

Add the annotation directly above the offending code

@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX")

See here for more info: findbugs Spring Annotation

HTML Script tag: type or language (or omit both)?

The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.

The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

How can I generate a list of consecutive numbers?

You can use list comprehensions for this problem as it will solve it in only two lines. Code-

n = int(input("Enter the range of the list:\n"))
l1 = [i for i in range(n)] #Creates list of numbers in the range 0 to n
if __name__ == "__main__":
    print(l1)

Thank you.

CSS - display: none; not working

In the HTML source provided, the element #tfl has an inline style "display:block". Inline style will always override stylesheets styles…

Then, you have some options (while as you said you can't modify the html code nor using javascript):

  • force display:none with !important rule (not recommended)
  • put the div offscreen with theses rules :

    #tfl {
        position: absolute;
        left: -9999px;
    }
    

How to overwrite existing files in batch?

You can refer Windows command prompt help using following command : xcopy /?

Converting array to list in Java

Another workaround if you use apache commons-lang:

int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(ArrayUtils.toObject(spam));

Where ArrayUtils.toObject converts int[] to Integer[]

How to make a cross-module variable?

You can pass the globals of one module to onother:

In Module A:

import module_b
my_var=2
module_b.do_something_with_my_globals(globals())
print my_var

In Module B:

def do_something_with_my_globals(glob): # glob is simply a dict.
    glob["my_var"]=3