Programs & Examples On #Svctraceviewer

WCF timeout exception detailed investigation

If you havn't tried it already - encapsulate your Server-side WCF Operations in try/finally blocks, and add logging to ensure they are actually returning.

If those show that the Operations are completing, then my next step would be to go to a lower level, and look at the actual transport layer.

Wireshark or another similar packet capturing tool can be quite helpful at this point. I'm assuming this is running over HTTP on standard port 80.

Run Wireshark on the client. In the Options when you start the capture, set the capture filter to tcp http and host service.example.com - this will reduce the amount of irrelevant traffic.

If you can, modify your client to notify you the exact start time of the call, and the time when the timeout occurred. Or just monitor it closely.

When you get an error, then you can trawl through the Wireshark logs to find the start of the call. Right click on the first packet that has your client calling out on it (Should be something like GET /service.svc or POST /service.svc) and select Follow TCP Stream.

Wireshark will decode the entire HTTP Conversation, so you can ensure that WCF is actually sending back responses.

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

jQuery Ajax error handling, show custom exception messages

ServerSide:

     doPost(HttpServletRequest request, HttpServletResponse response){ 
            try{ //logic
            }catch(ApplicationException exception){ 
               response.setStatus(400);
               response.getWriter().write(exception.getMessage());
               //just added semicolon to end of line

           }
 }

ClientSide:

 jQuery.ajax({// just showing error property
           error: function(jqXHR,error, errorThrown) {  
               if(jqXHR.status&&jqXHR.status==400){
                    alert(jqXHR.responseText); 
               }else{
                   alert("Something went wrong");
               }
          }
    }); 

Generic Ajax Error Handling

If I need to do some generic error handling for all the ajax requests. I will set the ajaxError handler and display the error on a div named errorcontainer on the top of html content.

$("div#errorcontainer")
    .ajaxError(
        function(e, x, settings, exception) {
            var message;
            var statusErrorMap = {
                '400' : "Server understood the request, but request content was invalid.",
                '401' : "Unauthorized access.",
                '403' : "Forbidden resource can't be accessed.",
                '500' : "Internal server error.",
                '503' : "Service unavailable."
            };
            if (x.status) {
                message =statusErrorMap[x.status];
                                if(!message){
                                      message="Unknown Error \n.";
                                  }
            }else if(exception=='parsererror'){
                message="Error.\nParsing JSON Request failed.";
            }else if(exception=='timeout'){
                message="Request Time out.";
            }else if(exception=='abort'){
                message="Request was aborted by the server";
            }else {
                message="Unknown Error \n.";
            }
            $(this).css("display","inline");
            $(this).html(message);
                 });

iPhone SDK on Windows (alternative solutions)

Technically you can write code in a .NET language and use the Mono Framework (http://www.mono-project.com/) to run it on the iPhone. I haven't ever seen someone do this from scratch, but the folks that write the Unity Game Development platform (http://unity3d.com/) use it to make their games iPhone-compatible. The game itself is written in .NET, and then they provide an iPhone shell with the Mono frameworks that allows everything to run on the iPhone. I don't know whether they've contributed all of their modifications to Mono back to the open-source repository, but if you're serious about writing iPhone apps outside the Mac environment, it might be possible.

That said, I think you could dump weeks into getting that to work, and it might be best to invest in a Mac instead :-)

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

If you use vagrant, try this:

First remove config.php in current/vendor.

Run these command:

php artisan config:clear
php artisan clear-compiled
php artisan optimize

NOT RUN php artisan config:cache.

Hope this help.

how to use php DateTime() function in Laravel 5

Best way is to use the Carbon dependency.

With Carbon\Carbon::now(); you get the current Datetime.

With Carbon you can do like enything with the DateTime. Event things like this:

$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

How to use Greek symbols in ggplot2?

You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
  geom_point() + 
  labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
color=expression(alpha*Omega), x=expression(Delta~price))

enter image description here

Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

enter image description here

Init array of structs in Go

Adding this just as an addition to @jimt's excellent answer:

one common way to define it all at initialization time is using an anonymous struct:

var opts = []struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}{
    {'a', "multiple", "Usage for a", false},
    {
        shortnm: 'b',
        longnm:  "b-option",
        needArg: false,
        help:    "Usage for b",
    },
}

This is commonly used for testing as well to define few test cases and loop through them.

How to split a string in Java

Here are two ways two achieve it.

WAY 1: As you have to split two numbers by a special character you can use regex

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TrialClass
{
    public static void main(String[] args)
    {
        Pattern p = Pattern.compile("[0-9]+");
        Matcher m = p.matcher("004-034556");

        while(m.find())
        {
            System.out.println(m.group());
        }
    }
}

WAY 2: Using the string split method

public class TrialClass
{
    public static void main(String[] args)
    {
        String temp = "004-034556";
        String [] arrString = temp.split("-");
        for(String splitString:arrString)
        {
            System.out.println(splitString);
        }
    }
}

How to get value of Radio Buttons?

An alterntive is to use an enum and a component class that extends the standard RadioButton.

public enum Genders
{
    Male,
    Female
}

[ToolboxBitmap(typeof(RadioButton))]
public partial class GenderRadioButton : RadioButton
{
    public GenderRadioButton()
    {
        InitializeComponent();
    }

    public GenderRadioButton (IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }

    public Genders gender{ get; set; }
}

Use a common event handler for the GenderRadioButtons

private void Gender_CheckedChanged(Object sender, EventArgs e)
{
    if (((RadioButton)sender).Checked)
    {
        //get selected value
        Genders myGender = ((GenderRadioButton)sender).Gender;
        //get the name of the enum value
        string GenderName = Enum.GetName(typeof(Genders ), myGender);
        //do any work required when you change gender
        switch (myGender)
        {
            case Genders.Male:
                break;
            case Genders.Female:
                break;
            default:
                break;
        }
    }
}

Convert Swift string to array

Updated for Swift 4

Here are 3 ways.

//array of Characters
let charArr1 = [Character](myString)

//array of String.element
let charArr2 = Array(myString)

for char in myString {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

//array of String
var strArr = myString.map { String($0)}

Swift 3

Here are 3 ways.

let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

var strArr = myString.characters.map { String($0)}

Or you can add an extension to String.

extension String {
   func letterize() -> [Character] {
     return Array(self.characters)
  }
}

Then you can call it like this:

let charArr = "Cat".letterize()

Read from file or stdin

Note that what you want is to know if stdin is connected to a terminal or not, not if it exists. It always exists but when you use the shell to pipe something into it or read a file, it is not connected to a terminal.

You can check that a file descriptor is connected to a terminal via the termios.h functions:

#include <termios.h>
#include <stdbool.h>

bool stdin_is_a_pipe(void)
{
    struct termios t;
    return (tcgetattr(STDIN_FILENO, &t) < 0);
}

This will try to fetch the terminal attributes of stdin. If it is not connected to a pipe, it is attached to a tty and the tcgetattr function call will succeed. In order to detect a pipe, we check for tcgetattr failure.

how to convert binary string to decimal?

The parseInt function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:

var digit = parseInt(binary, 2);

See it in action.

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

What sorted out things for me was to tick the checkbox "Use plugin registry" in Maven settings.

The path is: File -> Preferences -> Build, Execution, Deployment -> Build Tools -> Maven

JAX-WS client : what's the correct path to access the local WSDL?

For those who are still coming for solution here, the easiest solution would be to use <wsdlLocation>, without changing any code. Working steps are given below:

  1. Put your wsdl to resource directory like : src/main/resource
  2. In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.

    <wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
    <wsdlLocation>/mydir/my.wsdl</wsdlLocation>
    
  3. Then in your java code(with no-arg constructor):

    MyPort myPort = new MyPortService().getMyPort();
    
  4. For completeness, I am providing here full code generation part, with fluent api in generated code.

    <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.5</version>
    
    <dependencies>
        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-fluent-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-tools</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
    
    <executions>
        <execution>
            <id>wsdl-to-java-generator</id>
            <goals>
                <goal>wsimport</goal>
            </goals>
            <configuration>
                <xjcArgs>
                    <xjcArg>-Xfluent-api</xjcArg>
                </xjcArgs>
                <keep>true</keep>
                <wsdlDirectory>src/main/resources/package</wsdlDirectory>
                <wsdlLocation>/package/my.wsdl</wsdlLocation>
                <sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
                <packageName>full.package.here</packageName>
            </configuration>
        </execution>
    </executions>
    

Is there an easy way to reload css without reloading the page?

One more jQuery solution

For a single stylesheet with id "css" try this:

$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');

Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};

What's "P=NP?", and why is it such a famous question?

P stands for polynomial time. NP stands for non-deterministic polynomial time.

Definitions:

  • Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.

  • Complexity is time measured in the number of operations it would take, as a function of the number of data items.

  • Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.

Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.

There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.

It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.

NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.

An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.

C++ preprocessor __VA_ARGS__ number of arguments

You can stringfy and count tokens:

int countArgs(char *args)
{
  int result = 0;
  int i = 0;

  while(isspace(args[i])) ++i;
  if(args[i]) ++result;

  while(args[i]) {
    if(args[i]==',') ++result;
    else if(args[i]=='\'') i+=2;
    else if(args[i]=='\"') {
      while(args[i]) {
        if(args[i+1]=='\"' && args[i]!='\\') {
          ++i;
          break;
        }
        ++i;
      }
    }
    ++i;
  }

  return result;
}

#define MACRO(...) \
{ \
  int count = countArgs(#__VA_ARGS__); \
  printf("NUM ARGS: %d\n",count); \
}

"elseif" syntax in JavaScript

Just add a space:

if (...) {

} else if (...) {

} else {

}

Finding an elements XPath using IE Developer tool

If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):

http://westciv.com/mri/

For Xpath:

http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html

How do I check to see if a value is an integer in MySQL?

This also works:

CAST( coulmn_value AS UNSIGNED ) // will return 0 if not numeric string.

for example

SELECT CAST('a123' AS UNSIGNED) // returns 0
SELECT CAST('123' AS UNSIGNED) // returns 123 i.e. > 0

Possible heap pollution via varargs parameter

It's rather safe to add @SafeVarargs annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.

If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>) input instead of varargs (Type1<Type2>...).

As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.

nvm keeps "forgetting" node in new terminal session

I was facing the same issue while using the integrated terminal in VS Code editor. Restarting VS Code after changing the node version using nvm fixed the issue for me.

Twitter Bootstrap Datepicker within modal window

This solutions worked perfectly for me to render the datepicker on top of bootstrap modal.

http://jsfiddle.net/cmpgtuwy/654/

HTML

<br/>
<div class="wrapper">
Some content goes here<br />
Some more content.
<div class="row">
<div class="col-xs-4">

<!-- padding for jsfiddle -->
<div class="input-group date" id="dtp">
<input type="text" class="form-control" />  
<span class="input-group-addon">
  <span class="glyphicon-calendar glyphicon"></span>
</span>
</div>
</div>
</div>
</div>

Javascript

$('#dtp').datetimepicker({
format: 'MMM D, YYYY',
widgetParent: 'body'});


$('#dtp').on('dp.show', function() {
      var datepicker = $('body').find('.bootstrap-datetimepicker-widget:last');
      if (datepicker.hasClass('bottom')) {
        var top = $(this).offset().top + $(this).outerHeight();
        var left = $(this).offset().left;
        datepicker.css({
          'top': top + 'px',
          'bottom': 'auto',
          'left': left + 'px'
        });
      }
      else if (datepicker.hasClass('top')) {
        var top = $(this).offset().top - datepicker.outerHeight();
        var left = $(this).offset().left;
        datepicker.css({
          'top': top + 'px',
          'bottom': 'auto',
          'left': left + 'px'
        });
      }
    });

CSS

.wrapper {
height: 100px;
overflow: auto;}
body {
position: relative;
}

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

How do I bottom-align grid elements in bootstrap fluid layout

.align-bottom {
    position: absolute;
    bottom: 10px;
    right: 10px;
}

How do I run git log to see changes only for a specific branch?

For those using Magit, hit l and =m to toggle --no-merges and =pto toggle --first-parent.

Then either just hit l again to show commits from the current branch (with none of commits merged onto it) down to end of history, or, if you want the log to end where it was branched off from master, hit o and type master.. as your range:

enter image description here

Center an item with position: relative

Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:

#parent {
    -webkit-box-align:center;
    -webkit-box-pack:center;
    display:-webkit-box;
}

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

Get value of a specific object property in C# without knowing the class behind

Use reflection

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));

How to set bot's status

Simple way to initiate the message on startup:

bot.on('ready', () => {
    bot.user.setStatus('available')
    bot.user.setPresence({
        game: {
            name: 'with depression',
            type: "STREAMING",
            url: "https://www.twitch.tv/monstercat"
        }
    });
});

You can also just declare it elsewhere after startup, to change the message as needed:

bot.user.setPresence({ game: { name: 'with depression', type: "streaming", url: "https://www.twitch.tv/monstercat"}}); 

TSQL - Cast string to integer or return default value

Joseph's answer pointed out ISNUMERIC also handles scientific notation like '1.3e+3' but his answer doesn't handle this format of number.

Casting to a money or float first handles both the currency and scientific issues:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TryConvertInt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TryConvertInt]
GO

CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS bigint
AS
BEGIN
    DECLARE @IntValue bigint;

    IF (ISNUMERIC(@Value) = 1)
        IF (@Value like '%e%')
            SET @IntValue = CAST(Cast(@Value as float) as bigint);
        ELSE
            SET @IntValue = CAST(CAST(@Value as money) as bigint);
    ELSE
        SET @IntValue = NULL;

    RETURN @IntValue;
END

The function will fail if the number is bigger than a bigint.

If you want to return a different default value, leave this function so it is generic and replace the null afterwards:

SELECT IsNull(dbo.TryConvertInt('nan') , 1000);

Detect whether current Windows version is 32 bit or 64 bit

Here is a simpler method for batch scripts

    @echo off

    goto %PROCESSOR_ARCHITECTURE%

    :AMD64
    echo AMD64
    goto :EOF

    :x86 
    echo x86
    goto :EOF

How to delete file from public folder in laravel 5.1

For delete file from folder you can use unlink and if you want to delete data from database you can use delete() in laravel

Delete file from folder

unlink($image_path);

For delete record from database

$flight = Flight::find(1);

$flight->delete();

Sql query to insert datetime in SQL Server

you need to add it like

insert into table1(date1) values('12-mar-2013');

Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>

How to use Oracle's LISTAGG function with a unique filter?

I needed this peace of code as a subquery with some data filter before aggregation based on the outer most query but I wasn't able to do this using the chosen answer code because this filter should go in the inner most select (third level query) and the filter params was in the outer most select (first level query), which gave me the error ORA-00904: "TB_OUTERMOST"."COL": invalid identifier as the ANSI SQL states that table references (correlation names) are scoped to just one level deep.

I needed a solution with no levels of subquery and this one below worked great for me:

with

demotable as
(
  select 1 group_id, 'David'   name from dual union all
  select 1 group_id, 'John'    name from dual union all
  select 1 group_id, 'Alan'    name from dual union all
  select 1 group_id, 'David'   name from dual union all
  select 2 group_id, 'Julie'   name from dual union all
  select 2 group_id, 'Charlie' name from dual
)

select distinct 
  group_id, 
  listagg(name, ',') within group (order by name) over (partition by group_id) names
from demotable
-- where any filter I want
group by group_id, name
order by group_id;

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

Go To: File --> Setting --> Build, Execution, Deployment --> Gradle, then tick the use local Gradle distribution, then set Gradle home by giving path to Gradle. Tick offline work.

Like so:

html select only one checkbox in a group

$("#myform input:checkbox").change(function() {
    $("#myform input:checkbox").attr("checked", false);
    $(this).attr("checked", true);
});

This should work for any number of checkboxes in the form. If you have others that aren't part of the group, set up the selectors the applicable inputs.

How to install a private NPM module without my own registry?

In your private npm modules add

"private": true 

to your package.json

Then to reference the private module in another module, use this in your package.json

{
    "name": "myapp",
    "dependencies": {
        "private-repo": "git+ssh://[email protected]:myaccount/myprivate.git#v1.0.0",
    }
}

remove table row with specific id

ID attributes cannot start with a number and they should be unique. In any case, you can use :eq() to select a specific row using a 0-based integer:

// Remove the third row
$("#test tr:eq(2)").remove();

Alternatively, rewrite your HTML so that it's valid:

<table id="test">
 <tr id=test1><td>bla</td></tr>
 <tr id=test2><td>bla</td></tr>
 <tr id=test3><td>bla</td></tr>
 <tr id=test4><td>bla</td></tr>
</table>

And remove it referencing just the id:

$("#test3").remove();

Permission denied error while writing to a file in Python

In order to write on a file by using a Python script, you would have to create a text file first. Example A file such as C:/logs/logs.txt should exist. Only then the following code works:

logfile=open(r"C:/logs/logs.txt",'w')

So summary.

  1. A text file should exist on the specified location
  2. Make sure you close the file before running the Python script.

Attach Authorization header for all axios requests

There are multiple ways to achieve this. Here, I have explained the two most common approaches.

1. You can use axios interceptors to intercept any requests and add authorization headers.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    const token = store.getState().session.token;
    config.headers.Authorization =  token;

    return config;
});

2. From the documentation of axios you can see there is a mechanism available which allows you to set default header which will be sent with every request you make.

axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

So in your case:

axios.defaults.headers.common['Authorization'] = store.getState().session.token;

If you want, you can create a self-executable function which will set authorization header itself when the token is present in the store.

(function() {
     String token = store.getState().session.token;
     if (token) {
         axios.defaults.headers.common['Authorization'] = token;
     } else {
         axios.defaults.headers.common['Authorization'] = null;
         /*if setting null does not remove `Authorization` header then try     
           delete axios.defaults.headers.common['Authorization'];
         */
     }
})();

Now you no longer need to attach token manually to every request. You can place the above function in the file which is guaranteed to be executed every time (e.g: File which contains the routes).

Hope it helps :)

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

Although this question is fairly old, there is another possibility: If you are using Storyboards, you simply have to set the CellIdentifier in the Storyboard.

So if your CellIdentifier is "Cell", just set the "Identifier" property: enter image description here

Make sure to clean your build after doing so. XCode sometimes has some issues with Storyboard updates

setting min date in jquery datepicker

The problem is that the default option of "yearRange" is 10 years.

So 2012 - 10 = 2002.

So change the yearRange to c-20:c or just 1999 (yearRange: '1999:c'), and use that in combination with restrict dates (mindate, maxdate).

For more info: http://jqueryui.com/demos/datepicker/#option-yearRange


See example: http://jsfiddle.net/kGjdL/

And your code with the addition:

$(function () {
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
        showOn: "button",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        minDate: new Date(1999, 10 - 1, 25),
        maxDate: '+30Y',
        yearRange: '1999:c',
        inline: true
    });
});

What is the alternative for ~ (user's home directory) on Windows command prompt?

You can %HOMEDRIVE%%HOMEPATH% for the drive + \docs settings\username or \users\username.

Unexpected end of file error

The line #include "stdafx.h" must be the first line at the top of each source file, before any other header files are included.

If what you've shown is the entire .cxx file, then you did forget to include stdafx.h in that file.

How do I get the last four characters from a string in C#?

You can simply use Substring method of C#. For ex.

string str = "1110000";
string lastFourDigits = str.Substring((str.Length - 4), 4);

It will return result 0000.

Why I cannot cout a string?

There are several problems with your code:

  1. WordList is not defined anywhere. You should define it before you use it.
  2. You can't just write code outside a function like this. You need to put it in a function.
  3. You need to #include <string> before you can use the string class and iostream before you use cout or endl.
  4. string, cout and endl live in the std namespace, so you can not access them without prefixing them with std:: unless you use the using directive to bring them into scope first.

How to parse a JSON Input stream

if you have JSON file you can set it on assets folder then call it using this code

InputStream in = mResources.getAssets().open("fragrances.json"); 
// where mResources object from Resources class

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

C99 stdint.h header and MS Visual Studio

Update: Visual Studio 2010 and Visual C++ 2010 Express both have stdint.h. It can be found in C:\Program Files\Microsoft Visual Studio 10.0\VC\include

Pandas groupby month and year

You can also do it by creating a string column with the year and month as follows:

df['date'] = df.index
df['year-month'] = df['date'].apply(lambda x: str(x.year) + ' ' + str(x.month))
grouped = df.groupby('year-month')

However this doesn't preserve the order when you loop over the groups, e.g.

for name, group in grouped:
    print(name)

Will give:

2007 11
2007 12
2008 1
2008 10
2008 11
2008 12
2008 2
2008 3
2008 4
2008 5
2008 6
2008 7
2008 8
2008 9
2009 1
2009 10

So then, if you want to preserve the order, you must do as suggested by @Q-man above:

grouped = df.groupby([df.index.year, df.index.month])

This will preserve the order in the above loop:

(2007, 11)
(2007, 12)
(2008, 1)
(2008, 2)
(2008, 3)
(2008, 4)
(2008, 5)
(2008, 6)
(2008, 7)
(2008, 8)
(2008, 9)
(2008, 10)

Django. Override save for model

Check the model's pk field. If it is None, then it is a new object.

class Model(model.Model):
    image=models.ImageField(upload_to='folder')
    thumb=models.ImageField(upload_to='folder')
    description=models.CharField()


    def save(self, *args, **kwargs):
        if 'form' in kwargs:
            form=kwargs['form']
        else:
            form=None

        if self.pk is None and form is not None and 'image' in form.changed_data:
            small=rescale_image(self.image,width=100,height=100)
            self.image_small=SimpleUploadedFile(name,small_pic)
        super(Model, self).save(*args, **kwargs)

Edit: I've added a check for 'image' in form.changed_data. This assumes that you're using the admin site to update your images. You'll also have to override the default save_model method as indicated below.

class ModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save(form=form)

Remove useless zero digits from decimals in PHP

Strange, when I get a number out of database with a "float" type and if my number is ex. 10000 when I floatval it, it becomes 1.

$number = $ad['price_month']; // 1000 from the database with a float type
echo floatval($number);
Result : 1

I've tested all the solutions above but didn't work.

How do I deal with corrupted Git object files?

In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.

The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75..., is our real problem. It can be found in .git/objects/d4/a0e75.... As I said above, it's going to be safe to remove, but just in case, back it up first.

At this point, a fresh git pull should succeed.

...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash, pull, stash pop was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)

How do I use Maven through a proxy?

Those are caused most likely by 2 issues:

  1. You need to add proxy configuration to your settings.xml. Here's a trick in your username field. Make sure it looks like domain\username. Setting domain there and putting this exact slash is important '\'. You might want to use <![CDATA[]]> tag if your password contains non xml-friendly characters.
  2. I've noticed maven 2.2.0 does not work sometimes through a proxy at all, where 2.2.1 works perfectly fine.

If some of those are omitted - maven could fail with random error messages.

Just hope I've saved somebody from googling around this issue for 6 hours, like I did.

How to use OR condition in a JavaScript IF statement?

here is my example:

if(userAnswer==="Yes"||"yes"||"YeS"){
 console.log("Too Bad!");   
}

This says that if the answer is Yes yes or YeS than the same thing will happen

os.walk without digging into directories below

If you have more complex requirements than just the top directory (eg ignore VCS dirs etc), you can also modify the list of directories to prevent os.walk recursing through them.

ie:

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        dirs[:] = [d for d in dirs if is_good(d)]
        for f in files:
            do_stuff()

Note - be careful to mutate the list, rather than just rebind it. Obviously os.walk doesn't know about the external rebinding.

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

Download JSON object as a file from browser

If you prefer console snippet, raser, than filename, you can do this:

window.open(URL.createObjectURL(
    new Blob([JSON.stringify(JSON)], {
      type: 'application/binary'}
    )
))

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

How to add scroll bar to the Relative Layout?

The following code should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >

<TextView
    android:id="@+id/textView1"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="64dp"
    android:text="Email" />

<TextView
    android:id="@+id/textView2"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="41dp"
    android:text="Password" />

<TextView
    android:id="@+id/textView3"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="47dp"
    android:text="Confirm Password" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textView4"
    android:inputType="textEmailAddress" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />


<TextView
    android:id="@+id/textView4"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="42dp"
    android:text="Date of Birth" />

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView4" />

<TextView
    android:id="@+id/textView5"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/datePicker1"
    android:layout_marginTop="60dp"
    android:layout_toLeftOf="@+id/datePicker1"
    android:text="Gender" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView5"
    android:layout_alignBottom="@+id/textView5"
    android:layout_alignLeft="@+id/editText3"
    android:layout_marginLeft="24dp"
    android:text="Male" />

<RadioButton
    android:id="@+id/radioButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/radioButton1"
    android:layout_below="@+id/radioButton1"
    android:layout_marginTop="14dp"
    android:text="Female" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="23dp"
    android:layout_toLeftOf="@+id/radioButton2"
    android:background="@drawable/rectbutton"
    android:text="Sign Up" />

How do you get the selected value of a Spinner?

mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()) works based on Rich's description.

UITapGestureRecognizer - single tap and double tap

You need to use the requireGestureRecognizerToFail: method. Something like this:

[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

UTF-8 encoding in JSP page

I used encoding filter which has solved my all encoding problem...

 package com.dina.filter;

    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;

    /**
     *
     * @author DINANATH
     */
    public class EncodingFilter implements Filter {

        private String encoding = "utf-8";

        public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
            request.setCharacterEncoding(encoding);
    //                response.setContentType("text/html;charset=UTF-8");
                    response.setCharacterEncoding(encoding);
            filterChain.doFilter(request, response);

        }

        public void init(FilterConfig filterConfig) throws ServletException {
            String encodingParam = filterConfig.getInitParameter("encoding");
            if (encodingParam != null) {
                encoding = encodingParam;
            }
        }

        public void destroy() {
            // nothing todo
        }

    }

in web.xml

    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>
        com.dina.filter.EncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

You have two options with simple and idiomatic Typescript:

  1. Use index type
DNATranscriber: { [char: string]: string } = {
  G: "C",
  C: "G",
  T: "A",
  A: "U",
};

This is the index signature the error message is talking about. Reference

  1. Type each property:
DNATranscriber: { G: string; C: string; T: string; A: string } = {
  G: "C",
  C: "G",
  T: "A",
  A: "U",
};

How to fetch JSON file in Angular 2

service.service.ts
--------------------------------------------------------------

import { Injectable } from '@angular/core';
import { Http,Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable({
  providedIn: 'root'
})
export class ServiceService {
 private url="some URL";

constructor(private http:Http) { }     

//getData() is a method to fetch the data from web api or json file

getData(){
           getData(){
          return this.http.get(this.url)
            .map((response:Response)=>response.json())
        }
          }
}






display.component.ts
--------------------------------------------

//In this component get the data using suscribe() and store it in local object as dataObject and display the data in display.component.html like {{dataObject .propertyName}}.

import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
      dataObject :any={};
constructor(private service:ServiceService) { }

  ngOnInit() {
    this.service.getData()
      .subscribe(resData=>this.dataObject =resData)
}
}

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

HTML CSS Button Positioning

try changing that line-height change to a margin-top or padding-top change instead

#btnhome:active{
margin-top : 25px;
}

Edit: You could also try adding a span inside the button

<div id="header">           
    <button id="btnhome"><span>Home</span></button>          
    <button id="btnabout">About</button>
    <button id="btncontact">Contact</button>
    <button id="btnsup">Help Us</button>           
</div>

Then style that

#btnhome span:active { padding-top:25px;}

How to create a backup of a single table in a postgres database?

Use --table to tell pg_dump what table it has to backup:

pg_dump --host localhost --port 5432 --username postgres --format plain --verbose --file "<abstract_file_path>" --table public.tablename dbname

How to wrap async function calls into a sync function in Node.js or Javascript?

Javascript is a single threaded language, you don't want to block your whole server! Async code eliminates, race conditions by making dependencies explicit.

Learn to love asynchronous code!

Have a look at promises for asynchronous code without creating a pyramid of callback hell. I recommend the promiseQ library for node.js

httpGet(url.parse("http://example.org/")).then(function (res) {
    console.log(res.statusCode);  // maybe 302
    return httpGet(url.parse(res.headers["location"]));
}).then(function (res) {
    console.log(res.statusCode);  // maybe 200
});

http://howtonode.org/promises

EDIT: this is by far my most controversial answer, node now has yield keyword, which allows you to treat async code as if it were sychronous. http://blog.alexmaccaw.com/how-yield-will-transform-node

How to fix "Headers already sent" error in PHP

A simple tip: A simple space (or invisible special char) in your script, right before the very first <?php tag, can cause this ! Especially when you are working in a team and somebody is using a "weak" IDE or has messed around in the files with strange text editors.

I have seen these things ;)

scp files from local to remote machine error: no such file or directory

i had a kind of similar problem. i tried to copy from a server to my desktop and always got the same message for the local path. the problem was, i already was logged in to my server per ssh, so it was searching for the local path in the server path.

solution: i had to log out and run the command again and it worked

How to remove new line characters from data rows in mysql?

update mytable set title=trim(replace(REPLACE(title,CHAR(13),''),CHAR(10),''));

Above is working for fine.

How to change the map center in Leaflet.js

Use map.panTo(); does not do anything if the point is in the current view. Use map.setView() instead.

I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/

mymap.setView(point, 11, { animation: true });        

BAD: https://jsfiddle.net/nstudor/Lgahv905/

mymap.panTo(point);
mymap.setZoom(11);

How to show full column content in a Spark Dataframe?

results.show(20,false) did the trick for me in Scala.

Get only the Date part of DateTime in mssql

This may not be as slick as a one-liner, but I use it to perform date manipulation mainly for reports:

DECLARE @Date datetime
SET @Date = GETDATE()

-- Set all time components to zero
SET @Date = DATEADD(ms, -DATEPART(ms, @Date), @Date) -- milliseconds = 0
SET @Date = DATEADD(ss, -DATEPART(ss, @Date), @Date) -- seconds = 0
SET @Date = DATEADD(mi, -DATEPART(mi, @Date), @Date) -- minutes = 0
SET @Date = DATEADD(hh, -DATEPART(hh, @Date), @Date) -- hours = 0

-- Extra manipulation for month and year
SET @Date = DATEADD(dd, -DATEPART(dd, @Date) + 1, @Date) -- day = 1
SET @Date = DATEADD(mm, -DATEPART(mm, @Date) + 1, @Date) -- month = 1

I use this to get hourly, daily, monthly, and yearly dates used for reporting and performance indicators, etc.

Why should I prefer to use member initialization lists?

Syntax:

  class Sample
  {
     public:
         int Sam_x;
         int Sam_y;

     Sample(): Sam_x(1), Sam_y(2)     /* Classname: Initialization List */
     {
           // Constructor body
     }
  };

Need of Initialization list:

 class Sample
 {
     public:
         int Sam_x;
         int Sam_y;

     Sample()     */* Object and variables are created - i.e.:declaration of variables */*
     { // Constructor body starts 

         Sam_x = 1;      */* Defining a value to the variable */* 
         Sam_y = 2;

     } // Constructor body ends
  };

in the above program, When the class’s constructor is executed, Sam_x and Sam_y are created. Then in constructor body, those member data variables are defined.

Use cases:

  1. Const and Reference variables in a Class

In C, variables must be defined during creation. the same way in C++, we must initialize the Const and Reference variable during object creation by using Initialization list. if we do initialization after object creation (Inside constructor body), we will get compile time error.

  1. Member objects of Sample1 (base) class which do not have default constructor

     class Sample1 
     {
         int i;
         public:
         Sample1 (int temp)
         {
            i = temp;
         }
     };
    
      // Class Sample2 contains object of Sample1 
     class Sample2
     {
      Sample1  a;
      public:
      Sample2 (int x): a(x)      /* Initializer list must be used */
      {
    
      }
     };
    

While creating object for derived class which will internally calls derived class constructor and calls base class constructor (default). if base class does not have default constructor, user will get compile time error. To avoid, we must have either

 1. Default constructor of Sample1 class
 2. Initialization list in Sample2 class which will call the parametric constructor of Sample1 class (as per above program)
  1. Class constructor’s parameter name and Data member of a Class are same:

     class Sample3 {
        int i;         /* Member variable name : i */  
        public:
        Sample3 (int i)    /* Local variable name : i */ 
        {
            i = i;
            print(i);   /* Local variable: Prints the correct value which we passed in constructor */
        }
        int getI() const 
        { 
             print(i);    /*global variable: Garbage value is assigned to i. the expected value should be which we passed in constructor*/
             return i; 
        }
     };
    

As we all know, local variable having highest priority then global variable if both variables are having same name. In this case, the program consider "i" value {both left and right side variable. i.e: i = i} as local variable in Sample3() constructor and Class member variable(i) got override. To avoid, we must use either

  1. Initialization list 
  2. this operator.

Jenkins could not run git

The solution for me was to set the git path in the Manage Jenkins > Global Tool Configuration settings. In the Git section, I changed the Path to Git executable to /usr/local/bin/git.

Global Tool Configuration

Validate phone number using javascript

This regular expression /^(\([0-9]{3}\)\s*|[0-9]{3}\-)[0-9]{3}-[0-9]{4}$/ validates all of the following:

'123-345-3456';
'(078)789-8908';
'(078) 789-8908'; // Note the space

To break down what's happening:

Regular expression visualization

  1. The group in the beginning validates two ways, either (XXX) or XXX-, with optionally spaces after the closing parenthesis.
  2. The part after the group checks for XXX-XXX

Variable name as a string in Javascript

This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:

_x000D_
_x000D_
   _x000D_
var myFirstName = "Danilo";_x000D_
var varName = Object.keys({myFirstName:0})[0];_x000D_
console.log(varName);
_x000D_
_x000D_
_x000D_

Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

How to set web.config file to show full error message

This can also help you by showing full details of the error on a client's browser.

<system.web>
    <customErrors mode="Off"/>
</system.web>
<system.webServer>
    <httpErrors errorMode="Detailed" />
</system.webServer>

Writing to CSV with Python adds blank lines

import csv

hello = [['Me','You'],['293', '219'],['13','15']]
length = len(hello[0])

with open('test1.csv', 'wb') as testfile:
    csv_writer = csv.writer(testfile)
    for y in range(length):
        csv_writer.writerow([x[y] for x in hello])

will produce an output like this

Me You
293 219
13 15

Hope this helps

Java unsupported major minor version 52.0

Your code was compiled with Java Version 1.8 while it is being executed with Java Version 1.7 or below.

In your case it seems that two different Java installations are used, the newer to compile and the older to execute your code.

Try recompiling your code with Java 1.7 or upgrade your Java Plugin.

Function stoi not declared

Install the latest version of TDM-GCC here is the link-http://wiki.codeblocks.org/index.php/MinGW_installation

Generics in C#, using type of a variable as parameter

One way to get around this is to use implicit casting:

bool DoesEntityExist<T>(T entity, Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;

calling it like so:

DoesEntityExist(entity, entityGuid, transaction);

Going a step further, you can turn it into an extension method (it will need to be declared in a static class):

static bool DoesEntityExist<T>(this T entity, Guid guid, ITransaction transaction) where T : IGloballyIdentifiable;

calling as so:

entity.DoesEntityExist(entityGuid, transaction);

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

What are the true benefits of ExpandoObject?

After valueTuples, what's the use of ExpandoObject class? this 6 lines code with ExpandoObject:

dynamic T = new ExpandoObject();
T.x = 1;
T.y = 2;
T.z = new ExpandoObject();
T.z.a = 3;
T.b= 4;

can be written in one line with tuples:

var T = (x: 1, y: 2, z: (a: 3, b: 4));

besides with tuple syntax you have strong type inference and intlisense support

Ternary operator in PowerShell

I too, looked for a better answer, and while the solution in Edward's post is "ok", I came up with a far more natural solution in this blog post

Short and sweet:

# ---------------------------------------------------------------------------
# Name:   Invoke-Assignment
# Alias:  =
# Author: Garrett Serack (@FearTheCowboy)
# Desc:   Enables expressions like the C# operators: 
#         Ternary: 
#             <condition> ? <trueresult> : <falseresult> 
#             e.g. 
#                status = (age > 50) ? "old" : "young";
#         Null-Coalescing 
#             <value> ?? <value-if-value-is-null>
#             e.g.
#                name = GetName() ?? "No Name";
#             
# Ternary Usage:  
#         $status == ($age > 50) ? "old" : "young"
#
# Null Coalescing Usage:
#         $name = (get-name) ? "No Name" 
# ---------------------------------------------------------------------------

# returns the evaluated value of the parameter passed in, 
# executing it, if it is a scriptblock   
function eval($item) {
    if( $item -ne $null ) {
        if( $item -is "ScriptBlock" ) {
            return & $item
        }
        return $item
    }
    return $null
}

# an extended assignment function; implements logic for Ternarys and Null-Coalescing expressions
function Invoke-Assignment {
    if( $args ) {
        # ternary
        if ($p = [array]::IndexOf($args,'?' )+1) {
            if (eval($args[0])) {
                return eval($args[$p])
            } 
            return eval($args[([array]::IndexOf($args,':',$p))+1]) 
        }

        # null-coalescing
        if ($p = ([array]::IndexOf($args,'??',$p)+1)) {
            if ($result = eval($args[0])) {
                return $result
            } 
            return eval($args[$p])
        } 

        # neither ternary or null-coalescing, just a value  
        return eval($args[0])
    }
    return $null
}

# alias the function to the equals sign (which doesn't impede the normal use of = )
set-alias = Invoke-Assignment -Option AllScope -Description "FearTheCowboy's Invoke-Assignment."

Which makes it easy to do stuff like (more examples in blog post):

$message == ($age > 50) ? "Old Man" :"Young Dude" 

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}

TypeScript for ... of with index / key?

Or another old school solution:

var someArray = [9, 2, 5];
let i = 0;
for (var item of someArray) {
    console.log(item); // 9,2,5
    i++;
}

Naming threads and thread-pools of ExecutorService

Executors.newSingleThreadExecutor(r -> new Thread(r, "someName")).submit(getJob());

Runnable getJob() {
        return () -> {
            // your job
        };
}

Pandas: Creating DataFrame from Series

Here is how to create a DataFrame where each series is a row.

For a single Series (resulting in a single-row DataFrame):

series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])

For multiple series with identical indices:

cols = ['a','b']
list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)

For multiple series with possibly different indices:

list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
df = pd.concat(list_of_series, axis=1).transpose()

To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose(). However, the latter approach is inefficient if the columns have different data types.

C# Parsing JSON array of objects

Use NewtonSoft JSON.Net library.

dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

Hope this helps.

CSS scale height to match width - possibly with a formfactor

Try viewports

You can use the width data and calculate the height accordingly

This example is for an 150x200px image

width: calc(100vw / 2 - 30px);
height: calc((100vw/2 - 30px) * 1.34);

How to make html table vertically scrollable

Why don't you place your table in a div?

<div style="height:100px;overflow:auto;">

 ... Your code goes here ...

</div>

ASP.NET MVC - Extract parameter of an URL

public ActionResult Index(int id,string value)

This function get values form URL After that you can use below function

Request.RawUrl - Return complete URL of Current page

RouteData.Values - Return Collection of Values of URL

Request.Params - Return Name Value Collections

Length of array in function argument

As stated by @Will, the decay happens during the parameter passing. One way to get around it is to pass the number of elements. To add onto this, you may find the _countof() macro useful - it does the equivalent of what you've done ;)

Removing Conda environment

You may try the following: Open anaconda command prompt and type

conda remove --name myenv --all

This will remove the entire environment.

Further reading: docs.conda.io > Manage Environments

good postgresql client for windows?

do you mean something like pgAdmin for administration?

Linux command line howto accept pairing for bluetooth device without pin

This worked like a charm for me, of-course it requires super-user privileges :-)

# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>

To get <target-bdaddr> you may issue below command:
$ hcitool scan

Note: Exclude # & $ as they are command line prompts.

Courtesy

Create Hyperlink in Slack

Recently it became possible (but with an odd workaround).

To do this you must first create text with the desired hyperlink in an editor that supports rich text formatting. This can be an advanced text editor, web browser, email client, web-development IDE, etc.). Then copypaste the text from the editor or rendered HTML from browser (or other). E.g. in the example below I copypasted the head of this StackOverflow page. As you may see, the hyperlink have been copied correctly and is clickable in the message (checked on Mac Desktop, browser, and iOS apps).

Message in Slack

On Mac

I was able to compose the desired link in the native Pages app as shown below. When you are done, copypaste your text into Slack app. This is the probably easiest way on Mac OS.

Link creation in Pages

On Windows

I have a strong suspicion that MS Word will do the same trick, but unfortunately I don't have an installed instance to check.

Universal

Create text in an online editor, such as Google Documents. Use Insert -> Link, modify the text and web URL, then copypaste into Slack.

enter image description here

Display help message with python argparse when script is called without any arguments

Instead of writing a class, a try/except can be used instead

try:
    options = parser.parse_args()
except:
    parser.print_help()
    sys.exit(0)

The upside is that the workflow is clearer and you don't need a stub class. The downside is that the first 'usage' line is printed twice.

This will need at least one mandatory argument. With no mandatory arguments, providing zero args on the commandline is valid.

how to call a variable in code behind to aspx page

For

<%=clients%>

to work you need to have a public or protected variable clients in the code-behind.

Here is an article that explains it: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

How to match hyphens with Regular Expression?

[-a-z0-9]+,[a-z0-9-]+,[a-z-0-9]+ and also [a-z-0-9]+ all are same.The hyphen between two ranges considered as a symbol.And also [a-z0-9-+()]+ this regex allow hyphen.

Add days to JavaScript Date

Some implementations to extend Date https://gist.github.com/netstart/c92e09730f3675ba8fb33be48520a86d

/**
 * just import, like
 *
 * import './../shared/utils/date.prototype.extendions.ts';
 */
declare global {
  interface Date {
    addDays(days: number, useThis?: boolean): Date;

    addSeconds(seconds: number): Date;

    addMinutes(minutes: number): Date;

    addHours(hours: number): Date;

    addMonths(months: number): Date;

    isToday(): boolean;

    clone(): Date;

    isAnotherMonth(date: Date): boolean;

    isWeekend(): boolean;

    isSameDate(date: Date): boolean;

    getStringDate(): string;
  }
}

Date.prototype.addDays = function(days: number): Date {
  if (!days) {
    return this;
  }
  this.setDate(this.getDate() + days);
  return this;
};

Date.prototype.addSeconds = function(seconds: number) {
  let value = this.valueOf();
  value += 1000 * seconds;
  return new Date(value);
};

Date.prototype.addMinutes = function(minutes: number) {
  let value = this.valueOf();
  value += 60000 * minutes;
  return new Date(value);
};

Date.prototype.addHours = function(hours: number) {
  let value = this.valueOf();
  value += 3600000 * hours;
  return new Date(value);
};

Date.prototype.addMonths = function(months: number) {
  const value = new Date(this.valueOf());

  let mo = this.getMonth();
  let yr = this.getYear();

  mo = (mo + months) % 12;
  if (0 > mo) {
    yr += (this.getMonth() + months - mo - 12) / 12;
    mo += 12;
  } else {
    yr += ((this.getMonth() + months - mo) / 12);
  }

  value.setMonth(mo);
  value.setFullYear(yr);
  return value;
};

Date.prototype.isToday = function(): boolean {
  const today = new Date();
  return this.isSameDate(today);
};

Date.prototype.clone = function(): Date {
  return new Date(+this);
};

Date.prototype.isAnotherMonth = function(date: Date): boolean {
  return date && this.getMonth() !== date.getMonth();
};

Date.prototype.isWeekend = function(): boolean {
  return this.getDay() === 0 || this.getDay() === 6;
};

Date.prototype.isSameDate = function(date: Date): boolean {
  return date && this.getFullYear() === date.getFullYear() && this.getMonth() === date.getMonth() && this.getDate() === date.getDate();
};

Date.prototype.getStringDate = function(): string {
  // Month names in Brazilian Portuguese
  const monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
  // Month names in English
  // let monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const today = new Date();
  if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay()) {
    return 'Hoje';
    // return "Today";
  } else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() + 1) {
    return 'Amanhã';
    // return "Tomorrow";
  } else if (this.getMonth() === today.getMonth() && this.getDay() === today.getDay() - 1) {
    return 'Ontem';
    // return "Yesterday";
  } else {
    return this.getDay() + ' de ' + this.monthNames[this.getMonth()] + ' de ' + this.getFullYear();
    // return this.monthNames[this.getMonth()] + ' ' + this.getDay() + ', ' +  this.getFullYear();
  }
};


export {};

How to set default vim colorscheme

You can try too to put this into your ~/.vimrc file:

colorscheme Solarized

How to enable external request in IIS Express?

You may try setting up port forwarding instead of trying to modify your IIS Express config, adding new HTTP.sys rules or running Visual Studio as an Admin.

Basically you need to forward the IP:PORT your website runs at to some other free port on your machine but on the external network adapter, not localhost.

The thing is that IIS Express (at least on Windows 10) binds to [::1]:port meaning it listens on IPv6 port. You need to take this into account.

Here is how I made this work - http://programmingflow.com/2017/02/25/iis-express-on-external-ip.html

Hope it helps.

Rename a dictionary key

Suppose you want to rename key k3 to k4:

temp_dict = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
temp_dict['k4']= temp_dict.pop('k3')

How to set an image as a background for Frame in Swing GUI of java?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
  JButton b1;
  JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
 One way
-----------------*/
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);

// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads  \\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
  setSize(399,399);
   setSize(400,400);
   }
   public static void main(String args[])
  {
   new BackgroundImageJFrame();
 }
 }

Searching a list of objects in Python

You can get a list of all matching elements with a list comprehension:

[x for x in myList if x.n == 30]  # list of all elements with .n==30

If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do

def contains(list, filter):
    for x in list:
        if filter(x):
            return True
    return False

if contains(myList, lambda x: x.n == 3)  # True if any element has .n==3
    # do stuff

How to find out the server IP address (using JavaScript) that the browser is connected to?

I am sure the following code will help you to get ip address.

<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

you have to include two more jar files.

xmlbeans-2.3.0.jar and dom4j-1.6.1.jar Add try it will work.

Note: It is required for the files with .xlsx formats only, not for just .xlt formats.

A Generic error occurred in GDI+ in Bitmap.Save method

I had a different issue with the same exception.

In short:

Make sure that the Bitmap's object Stream is not being disposed before calling .Save .

Full story:

There was a method that returned a Bitmap object, built from a MemoryStream in the following way:

private Bitmap getImage(byte[] imageBinaryData){
    .
    .
    .
    Bitmap image;
    using (var stream = new MemoryStream(imageBinaryData))
    {
        image = new Bitmap(stream);
    }
    return image;
}

then someone used the returned image to save it as a file

image.Save(path);

The problem was that the original stream was already disposed when trying to save the image, throwing the GDI+ exeption.

A fix to this problem was to return the Bitmap without disposing the stream itself but the returned Bitmap object.

private Bitmap getImage(byte[] imageBinaryData){
   .
   .
   .
   Bitmap image;
   var stream = new MemoryStream(imageBinaryData))
   image = new Bitmap(stream);

   return image;
}

then:

using (var image = getImage(binData))
{
   image.Save(path);
}

How can I list the contents of a directory in Python?

In Python 3.4+, you can use the new pathlib package:

from pathlib import Path
for path in Path('.').iterdir():
    print(path)

Path.iterdir() returns an iterator, which can be easily turned into a list:

contents = list(Path('.').iterdir())

How to create an Observable from static data similar to http one in Angular?

Perhaps you could try to use the of method of the Observable class:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return Observable.of(new TestModel()).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

How to access a value defined in the application.properties file in Spring Boot

You can do it this way as well....

@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {

    @Autowired
    private Environment env;

    public String getConfigValue(String configKey){
        return env.getProperty(configKey);
    }
}

Then wherever you want to read from application.properties, just pass the key to getConfigValue method.

@Autowired
ConfigProperties configProp;

// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port"); 

How do you specify the Java compiler version in a pom.xml file?

I faced same issue in eclipse neon simple maven java project

But I add below details inside pom.xml file

   <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

After right click on project > maven > update project (checked force update)

Its resolve me to display error on project

Hope it's will helpful

Thansk

Why does JPA have a @Transient annotation?

As others have said, @Transient is used to mark fields which shouldn't be persisted. Consider this short example:

public enum Gender { MALE, FEMALE, UNKNOWN }

@Entity
public Person {
    private Gender g;
    private long id;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public Gender getGender() { return g; }    
    public void setGender(Gender g) { this.g = g; }

    @Transient
    public boolean isMale() {
        return Gender.MALE.equals(g);
    }

    @Transient
    public boolean isFemale() {
        return Gender.FEMALE.equals(g);
    }
}

When this class is fed to the JPA, it persists the gender and id but doesn't try to persist the helper boolean methods - without @Transient the underlying system would complain that the Entity class Person is missing setMale() and setFemale() methods and thus wouldn't persist Person at all.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

On your solution explorer window, right click to References, select Add Reference, go to .NET tab, find and add Microsoft.CSharp.

Alternatively add the Microsoft.CSharp NuGet package.

Install-Package Microsoft.CSharp

Differences between key, superkey, minimal superkey, candidate key and primary key

Superkey - An attribute or set of attributes that uniquely defines a tuple within a relation. However, a superkey may contain additional attributes that are not necessary for unique identification.

Candidate key - A superkey such that no proper subset is a superkey within the relation. So, basically has two properties: Each candidate key uniquely identifies tuple in the relation ; & no proper subset of the composite key has the uniqueness property.

Composite key - When a candidate key consists of more than one attribute.

Primary key - The candidate key chosen to identify tuples uniquely within the relation.

Alternate key - Candidate key that is not a primary key.

Foreign key - An attribute or set of attributes within a relation that matches the candidate key of some relation.

How to remove an element from an array in Swift

As of Xcode 10+, and according to the WWDC 2018 session 223, "Embracing Algorithms," a good method going forward will be mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows

Apple's example:

var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]

phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."

see Apple's Documentation

So in the OP's example, removing animals[2], "chimps":

var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }

This method may be preferred because it scales well (linear vs quadratic), is readable and clean. Keep in mind that it only works in Xcode 10+, and as of writing this is in Beta.

String.Format for Hex

You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

I would do something like this:

;WITH x 
 AS (SELECT *, 
            Row_number() 
              OVER( 
                partition BY employeeid 
                ORDER BY datestart) rn 
     FROM   employeehistory) 
SELECT * 
FROM   x x1 
   LEFT OUTER JOIN x x2 
                ON x1.rn = x2.rn + 1 

Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

PYTHONPATH vs. sys.path

Along with the many other reasons mentioned already, you could also point outh that hard-coding

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

is brittle because it presumes the location of script.py -- it will only work if script.py is located in Project/package. It will break if a user decides to move/copy/symlink script.py (almost) anywhere else.

brew install mysql on macOS

Okay I had the same issue and solved it. For some reason the mysql_secure_installation script doesn't work out of the box when using Homebrew to install mysql, so I did it manually. On the CLI enter:

mysql -u root

That should get you into mysql. Now do the following (taken from mysql_secure_installation):

UPDATE mysql.user SET Password=PASSWORD('your_new_pass') WHERE User='root';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'
DROP DATABASE test;
FLUSH PRIVILEGES;

Now exit and get back into mysql with: mysql -u root -p

How to get key names from JSON using jq

You need to use jq 'keys[]'. For example:

echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'

Will output a line separated list:

"example1"
"example2"
"example3"

rsync: how can I configure it to create target directory on server?

Assuming you are using ssh to connect rsync, what about to send a ssh command before:

ssh user@server mkdir -p existingdir/newdir

if it already exists, nothing happens

Jenkins returned status code 128 with github

In my case I had to add the public key to my repo (at Bitbucket) AND use git clone once via ssh to answer yes to the "known host" question the first time.

error, string or binary data would be truncated when trying to insert

I used a different tactic, fields that are allocated 8K in some places. Here only about 50/100 are used.

declare @NVPN_list as table 
nvpn            varchar(50)
,nvpn_revision  varchar(5)
,nvpn_iteration INT
,mpn_lifecycle  varchar(30)
,mfr            varchar(100)
,mpn            varchar(50)
,mpn_revision   varchar(5)
,mpn_iteration  INT
-- ...
) INSERT INTO @NVPN_LIST 
SELECT  left(nvpn           ,50)    as nvpn
        ,left(nvpn_revision ,10)    as nvpn_revision
        ,nvpn_iteration
        ,left(mpn_lifecycle ,30)
        ,left(mfr           ,100)
        ,left(mpn           ,50)
        ,left(mpn_revision  ,5)
        ,mpn_iteration
        ,left(mfr_order_num ,50)
FROM [DASHBOARD].[dbo].[mpnAttributes] (NOLOCK) mpna

I wanted speed, since I have 1M total records, and load 28K of them.

How do I undo 'git add' before commit?

One of the most intuitive solutions is using Sourcetree.

You can just drag and drop files from staged and unstaged

Enter image description here

Python find min max and average of a list (array)

Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...

from operator import lt, gt
def ultimate (l,op,c=1,u=0):
    try:
        if op(l[c],l[u]): 
            u = c
        c += 1
        return ultimate(l,op,c,u)
    except IndexError:
        return l[u]
def minimum (l):
    return ultimate(l,lt)
def maximum (l):
    return ultimate(l,gt)

The solution is simple. Use this to set yourself apart from obvious choices.

Fatal error: Class 'ZipArchive' not found in

If you have WHM available it is easier.

Log in to WHM.

Go to EasyApache 4 (or whatever version u have) under Software tab.

Under Currently Installed Packages click Customize.

Go to PHP Extensions, in search type "zip" (without quotes),

you should see 3 modules

check all of them,

click blue button few times to finish the process.

This worked for me. Thankfully I've WHM available.

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());

This works for me.

How to convert current date into string in java?

// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}

Taken from here

MySQL load NULL values from CSV data

The behaviour is different depending upon the database configuration. In the strict mode this would throw an error else a warning. Following query may be used for identifying the database configuration.

mysql> show variables like 'sql_mode';

Laravel - display a PDF file in storage without forcing download?

Since Laravel 5.2 you can use File Responses
Basically you can call it like this:

return response()->file($pathToFile);

and it will display files as PDF and images inline in the browser.

Multi-character constant warnings

If you want to disable this warning it is important to know that there are two related warning parameters in GCC and Clang: GCC Compiler options -wno-four-char-constants and -wno-multichar

Invoking JavaScript code in an iframe from the parent page

Use following to call function of a frame in parent page

parent.document.getElementById('frameid').contentWindow.somefunction()

did you register the component correctly? For recursive components, make sure to provide the "name" option

Wasted almost one hour, didn't find a solution, so I wanted to contribute =)

In my case, I was importing WRONGLY the component.. like below:

import { MyComponent } from './components/MyComponent'

But the CORRECT is (without curly braces):

import MyComponent from './components/MyComponent'

Why is there no xrange function in Python3?

Python3's range is Python2's xrange. There's no need to wrap an iter around it. To get an actual list in Python3, you need to use list(range(...))

If you want something that works with Python2 and Python3, try this

try:
    xrange
except NameError:
    xrange = range

jquery change button color onclick

$('input[type="submit"]').click(function(){
$(this).css('color','red');
});

Use class, Demo:- http://jsfiddle.net/BX6Df/

   $('input[type="submit"]').click(function(){
          $(this).addClass('red');
});

if you want to toggle the color each click, you can try this:- http://jsfiddle.net/SMNks/

$('input[type="submit"]').click(function(){
  $(this).toggleClass('red');
});


.red
{
    background-color:red;
}

Updated answer for your comment.

http://jsfiddle.net/H2Xhw/

$('input[type="submit"]').click(function(){
    $('input[type="submit"].red').removeClass('red')
        $(this).addClass('red');
});

Check if table exists

I don't actually find any of the presented solutions here to be fully complete so I'll add my own. Nothing new here. You can stitch this together from the other presented solutions plus various comments.

There are at least two things you'll have to make sure:

  1. Make sure you pass the table name to the getTables() method, rather than passing a null value. In the first case you let the database server filter the result for you, in the second you request a list of all tables from the server and then filter the list locally. The former is much faster if you are only searching for a single table.

  2. Make sure to check the table name from the resultset with an equals match. The reason is that the getTables() does pattern matching on the query for the table and the _ character is a wildcard in SQL. Suppose you are checking for the existence of a table named EMPLOYEE_SALARY. You'll then get a match on EMPLOYEESSALARY too which is not what you want.

Ohh, and do remember to close those resultsets. Since Java 7 you would want to use a try-with-resources statement for that.

Here's a complete solution:

public static boolean tableExist(Connection conn, String tableName) throws SQLException {
    boolean tExists = false;
    try (ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null)) {
        while (rs.next()) { 
            String tName = rs.getString("TABLE_NAME");
            if (tName != null && tName.equals(tableName)) {
                tExists = true;
                break;
            }
        }
    }
    return tExists;
}

You may want to consider what you pass as the types parameter (4th parameter) on your getTables() call. Normally I would just leave at null because you don't want to restrict yourself. A VIEW is as good as a TABLE, right? These days many databases allow you to update through a VIEW so restricting yourself to only TABLE type is in most cases not the way to go. YMMV.

"CASE" statement within "WHERE" clause in SQL Server 2008

SELECT * from TABLE 
              WHERE 1 = CASE when TABLE.col = 100 then 1 
                     when TABLE.col = 200 then 2 else 3 END 
                  and TABLE.col2 = 'myname';

Use in this way.

How to change Vagrant 'default' machine name?

I specify the name by defining inside the VagrantFile and also specify the hostname so i enjoy seeing the name of my project while executing Linux commands independently from my device's OS. ??

config.vm.define "abc"
config.vm.hostname = "abc"

Android getResources().getDrawable() deprecated API 22

Edit: see my blog post on the subject for a more complete explanation


You should use the following code from the support library instead:

ContextCompat.getDrawable(context, R.drawable.***)

Using this method is equivalent to calling:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}

As of API 21, you should use the getDrawable(int, Theme) method instead of getDrawable(int), as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int) method is equivalent to calling getDrawable(int, null).

Getting values from JSON using Python

Using Python to extract a value from the provided Json

Working sample:-

import json
import sys

//load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

//dumps the json object into an element
json_str = json.dumps(data)

//load the json to a string
resp = json.loads(json_str)

//print the resp
print (resp)

//extract an element in the response
print (resp['test1'])

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

Find the smallest positive integer that does not occur in a given sequence

In Kotlin with %100 score Detected time complexity: O(N) or O(N * log(N))

fun solution(A: IntArray): Int {
    var min = 1
    val b = A.sortedArray()
    for (i in 0 until b.size) {
        if (b[i] == min) {
            min++
        }
    }
    return min
}

Netbeans 8.0.2 The module has not been deployed

In my case I had to run Netbeans as administrator, that solved the problem for me. I'm using Apache Netbeans IDE 11.0

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

Disclaimer: this answer does not endorse the use of the Date class (in fact it’s long outdated and poorly designed, so I’d rather discourage it completely). I try to answer a regularly recurring question about date and time objects with a format. For this purpose I am using the Date class as example. Other classes are treated at the end.

You don’t want to

You don’t want a Date with a specific format. Good practice in all but the simplest throw-away programs is to keep your user interface apart from your model and your business logic. The value of the Date object belongs in your model, so keep your Date there and never let the user see it directly. When you adhere to this, it will never matter which format the Date has got. Whenever the user should see the date, format it into a String and show the string to the user. Similarly if you need a specific format for persistence or exchange with another system, format the Date into a string for that purpose. If the user needs to enter a date and/or time, either accept a string or use a date picker or time picker.

Special case: storing into an SQL database. It may appear that your database requires a specific format. Not so. Use yourPreparedStatement.setObject(yourParamIndex, yourDateOrTimeObject) where yourDateOrTimeObject is a LocalDate, Instant, LocalDateTime or an instance of an appropriate date-time class from java.time. And again don’t worry about the format of that object. Search for more details.

You cannot

A Date hasn’t got, as in cannot have a format. It’s a point in time, nothing more, nothing less. A container of a value. In your code sdf1.parse converts your string into a Date object, that is, into a point in time. It doesn’t keep the string nor the format that was in the string.

To finish the story, let’s look at the next line from your code too:

    System.out.println("Current date in Date Format: "+date);

In order to perform the string concatenation required by the + sign Java needs to convert your Date into a String first. It does this by calling the toString method of your Date object. Date.toString always produces a string like Thu Jan 05 21:10:17 IST 2012. There is no way you could change that (except in a subclass of Date, but you don’t want that). Then the generated string is concatenated with the string literal to produce the string printed by System.out.println.

In short “format” applies only to the string representations of dates, not to the dates themselves.

Isn’t it strange that a Date hasn’t got a format?

I think what I’ve written is quite as we should expect. It’s similar to other types. Think of an int. The same int may be formatted into strings like 53,551, 53.551 (with a dot as thousands separator), 00053551, +53 551 or even 0x0000_D12F. All of this formatting produces strings, while the int just stays the same and doesn’t change its format. With a Date object it’s exactly the same: you can format it into many different strings, but the Date itself always stays the same.

Can I then have a LocalDate, a ZonedDateTime, a Calendar, a GregorianCalendar, an XMLGregorianCalendar, a java.sql.Date, Time or Timestamp in the format of my choice?

No, you cannot, and for the same reasons as above. None of the mentioned classes, in fact no date or time class I have ever met, can have a format. You can have your desired format only in a String outside your date-time object.

Links

How to install both Python 2.x and Python 3.x in Windows

I just had to install them. Then I used the free (and portable) soft at http://defaultprogramseditor.com/ under "File type settings"/"Context menu"/search:"py", chose .py file and added an 'open' command for the 2 IDLE by copying the existant command named 'open with IDLE, changing names to IDLE 3.4.1/2.7.8, and remplacing the files numbers of their respective versions in the program path. Now I have just to right click the .py file and chose which IDLE I want to use. Can do the same with direct interpreters if you prefer.

How to create a CPU spike with a bash command

I think this one is more simpler. Open Terminal and type the following and press Enter.

yes > /dev/null &

To fully utilize modern CPUs, one line is not enough, you may need to repeat the command to exhaust all the CPU power.

To end all of this, simply put

killall yes

The idea was originally found here, although it was intended for Mac users, but this should work for *nix as well.

Using mysql concat() in WHERE clause?

you can do that (work in mysql) probably other SQL too.. just try this:

select * from table where concat(' ',first_name,last_name) 
    like '%$search_term%';

How do I URL encode a string

Swift 2.0 Example (iOS 9 Compatiable)

extension String {

  func stringByURLEncoding() -> String? {

    let characters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet

    characters.removeCharactersInString("&")

    guard let encodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(characters) else {
      return nil
    }

    return encodedString

  }

}

SQL to add column and comment in table in single command

No, you can't.

There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.

If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.


In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.

SQL> desc sys.com$
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OBJ#                                      NOT NULL NUMBER
 COL#                                               NUMBER
 COMMENT$                                           VARCHAR2(4000)

SQL>

The column is optional and sys.col$ does not contain comment information.

I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

You can use the Set-Variable cmdlet. Passing $global:var3 sends the value of $var3, which is not what you want. You want to send the name.

$global:var1 = $null

function foo ($a, $b, $varName)
{
   Set-Variable -Name $varName -Value ($a + $b) -Scope Global
}

foo 1 2 var1

This is not very good programming practice, though. Below would be much more straightforward, and less likely to introduce bugs later:

$global:var1 = $null

function ComputeNewValue ($a, $b)
{
   $a + $b
}

$global:var1 = ComputeNewValue 1 2

How do I debug Node.js applications?

Assuming you have node-inspector installed on your computer (if not, just type 'npm install -g node-inspector') you just have to run:

node-inspector & node --debug-brk scriptFileName.js

And paste the URI from the command line into a WebKit (Chrome / Safari) browser.

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

Taking a point from both Boycs Answer and mtmurdock's subsequent answer I have the following stored proc on all of my development or staging databases. I've added some switches to fit my own requirement if I need to add in statements to reseed the data for certain columns.

(Note: I would have added this as a comment to Boycs brilliant answer but I haven't got enough reputation to do that yet. So please accept my apologies for adding this as an entirely new answer.)

ALTER PROCEDURE up_ResetEntireDatabase
@IncludeIdentReseed BIT,
@IncludeDataReseed BIT
AS

EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'

IF @IncludeIdentReseed = 1
BEGIN
    EXEC sp_MSForEachTable 'DBCC CHECKIDENT (''?'' , RESEED, 1)'
END

EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

IF @IncludeDataReseed = 1
BEGIN
    -- Populate Core Data Table Here
END
GO

And then once ready the execution is really simple:

EXEC up_ResetEntireDatabase 1, 1

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Here is the solution I found:

How to fix the missing MSVCR711.dll problem

You can find MSVCR71.dll file in following location of your installed SQL Developer 2.1 directory:

sqldeveloper-2.1.0.63.10\sqldeveloper\jdk\jre\bin\MSVCR71.dll

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

How do I add a custom script to my package.json file that runs a javascript file?

I have created the following, and it's working on my system. Please try this:

package.json:

{
  "name": "test app",
  "version": "1.0.0",
  "scripts": {
    "start": "node script1.js"   
  }
}

script1.js:

console.log('testing')

From your command line run the following command:

npm start

Additional use case

My package.json file has generally the following scripts, which enable me to watch my files for typescript, sass compilations and running a server as well.

 "scripts": {
    "start": "concurrently \"sass --watch ./style/sass:./style/css\" \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w", 
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  }

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

Converting of Uri to String

If you want to pass a Uri to another activity, try the method intent.setData(Uri uri) https://developer.android.com/reference/android/content/Intent.html#setData(android.net.Uri)

In another activity, via intent.getData() to obtain the Uri.

Find the IP address of the client in an SSH session

You could use the command:

server:~# pinky

that will give to you somehting like this:

Login      Name                 TTY    Idle   When                 Where 

root       root                 pts/0         2009-06-15 13:41     192.168.1.133

How to extract request http headers from a request using NodeJS connect

If you use Express 4.x, you can use the req.get(headerName) method as described in Express 4.x API Reference

PHP: How to check if a date is today, yesterday or tomorrow

<?php 
 $current = strtotime(date("Y-m-d"));
 $date    = strtotime("2014-09-05");

 $datediff = $date - $current;
 $difference = floor($datediff/(60*60*24));
 if($difference==0)
 {
    echo 'today';
 }
 else if($difference > 1)
 {
    echo 'Future Date';
 }
 else if($difference > 0)
 {
    echo 'tomorrow';
 }
 else if($difference < -1)
 {
    echo 'Long Back';
 }
 else
 {
    echo 'yesterday';
 }  
?>

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

Following is the best way to get of the issue , check following on classpath:

  1. Make sure JAVA_HOME system variable must have till jdk e.g C:\Program Files\Java\jdk1.7.0_80 , don't append bin here.

  2. Because MAVEN will look for jre which is under C:\Program Files\Java\jdk1.7.0_80

  3. Set %JAVA_HOME%\bin in classpath .

Then try Maven version .

Hope it will help .

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC LIMIT 50

save resources make one query, there is no need to make nested queries

How to include an HTML page into another HTML page without frame/iframe?

If you mean client side then you will have to use JavaScript or frames.
Simple way to start, try jQuery

$("#links").load("/Main_Page #jq-p-Getting-Started li");

More at jQuery Docs

If you want to use IFrames then start with Wikipedia on IFrames

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
        <title>Example</title>
  </head>
  <body>
        The material below comes from the website http://example.com/
        <iframe src="http://example.com/" height="200">
            Alternative text for browsers that do not understand IFrames.
        </iframe>
   </body>
</html>

How do you remove a specific revision in the git history?

If all you want to do is remove the changes made in revision 3, you might want to use git revert.

Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.

What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.

This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.

Implementing INotifyPropertyChanged - does a better way exist?

I created an Extension Method in my base Library for reuse:

public static class INotifyPropertyChangedExtensions
{
    public static bool SetPropertyAndNotify<T>(this INotifyPropertyChanged sender,
               PropertyChangedEventHandler handler, ref T field, T value, 
               [CallerMemberName] string propertyName = "",
               EqualityComparer<T> equalityComparer = null)
    {
        bool rtn = false;
        var eqComp = equalityComparer ?? EqualityComparer<T>.Default;
        if (!eqComp.Equals(field,value))
        {
            field = value;
            rtn = true;
            if (handler != null)
            {
                var args = new PropertyChangedEventArgs(propertyName);
                handler(sender, args);
            }
        }
        return rtn;
    }
}

This works with .Net 4.5 because of CallerMemberNameAttribute. If you want to use it with an earlier .Net version you have to change the method declaration from: ...,[CallerMemberName] string propertyName = "", ... to ...,string propertyName, ...

Usage:

public class Dog : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    string _name;

    public string Name
    {
        get { return _name; }
        set
        {
            this.SetPropertyAndNotify(PropertyChanged, ref _name, value);
        }
    }
}

How to reverse a 'rails generate'

rails destroy controller lalala
rails destroy model yadayada
rails destroy scaffold hohoho

Rails 3.2 adds a new d shortcut to the command, so now you can write:

rails d controller lalala
rails d model yadayada
rails d scaffold hohoho

Is there a 'box-shadow-color' property?

No:

http://www.w3.org/TR/css3-background/#the-box-shadow

You can verify this in Chrome and Firefox by checking the list of computed styles. Other properties that have shorthand methods (like border-radius) have their variations defined in the spec.

As with most missing "long-hand" CSS properties, CSS variables can solve this problem:

#el {
    --box-shadow-color: palegoldenrod;
    box-shadow: 1px 2px 3px var(--box-shadow-color);
}

#el:hover {
    --box-shadow-color: goldenrod;
}

Add a border outside of a UIView (instead of inside)

Increase the width and height of view's frame with border width before adding the border:

float borderWidth = 2.0f
CGRect frame = self.frame;
frame.width += borderWidth;
frame.height += borderWidth;
 self.layer.borderColor = [UIColor yellowColor].CGColor;
 self.layer.borderWidth = 2.0f;

Getting all request parameters in Symfony 2

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

Get value of c# dynamic property via string

Similar to the accepted answer, you can also try GetField instead of GetProperty.

d.GetType().GetField("value2").GetValue(d);

Depending on how the actual Type was implemented, this may work when GetProperty() doesn't and can even be faster.

LINQ .Any VS .Exists - What's the difference?

See documentation

List.Exists (Object method - MSDN)

Determines whether the List(T) contains elements that match the conditions defined by the specified predicate.

This exists since .NET 2.0, so before LINQ. Meant to be used with the Predicate delegate, but lambda expressions are backward compatible. Also, just List has this (not even IList)

IEnumerable.Any (Extension method - MSDN)

Determines whether any element of a sequence satisfies a condition.

This is new in .NET 3.5 and uses Func(TSource, bool) as argument, so this was intended to be used with lambda expressions and LINQ.

In behaviour, these are identical.

How can I force component to re-render with hooks in React?

You can simply define the useState like that:

const [, forceUpdate] = React.useState(0);

And usage: forceUpdate(n => !n)

Hope this help !

Closing Twitter Bootstrap Modal From Angular Controller

You can add data-dismiss="modal" to your button attributes which call angularjs funtion.

Such as;

<button type="button" class="btn btn-default" data-dismiss="modal">Send Form</button>

Real time data graphing on a line chart with html5

Addition from 2015 As far as I know there is still no runtime oriented line chart lib. I mean chart which behaviors "request new points each N sec", "purge old data" you could setup "declarative" way.

Instead there is graphite api http://graphite-api.readthedocs.org/en/latest/ for server side, and number of client side plugins that uses it. But actually they are quite limited, absent advanced features that we like: data scroller, range charts, axeX segmentation on phases, etc..

It seems there is fundamental difference between tasks "show me reach chart" and have "real time chart".

How to stop event propagation with inline onclick attribute?

Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:

e.cancelBubble = true

Or, you can use the W3C standard for FireFox:

e.stopPropagation();

If you want to get fancy, you can do this:

function myEventHandler(e)
{
    if (!e)
      e = window.event;

    //IE9 & Other Browsers
    if (e.stopPropagation) {
      e.stopPropagation();
    }
    //IE8 and Lower
    else {
      e.cancelBubble = true;
    }
}

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

I had the same error while including file from root of my project in codeigniter.I was using this in common.php of my project.

<?php include_once base_url().'csrf-magic-master/csrf-magic.php';  ?>

i changed it to

<?php include_once ('csrf-magic-master/csrf-magic.php');  ?>

Working fine now.

Easiest way to open a download window without navigating away from the page

How about:

<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">

This way works on all browsers (i think) and let you put a message like: "If the download doesn't start in five seconds, click here."

If you need it to be with javascript.. well...

document.write('<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">');

Regards

Generate fixed length Strings filled with whitespaces

Here is the code with tests cases ;) :

@Test
public void testNullStringShouldReturnStringWithSpaces() throws Exception {
    String fixedString = writeAtFixedLength(null, 5);
    assertEquals(fixedString, "     ");
}

@Test
public void testEmptyStringReturnStringWithSpaces() throws Exception {
    String fixedString = writeAtFixedLength("", 5);
    assertEquals(fixedString, "     ");
}

@Test
public void testShortString_ReturnSameStringPlusSpaces() throws Exception {
    String fixedString = writeAtFixedLength("aa", 5);
    assertEquals(fixedString, "aa   ");
}

@Test
public void testLongStringShouldBeCut() throws Exception {
    String fixedString = writeAtFixedLength("aaaaaaaaaa", 5);
    assertEquals(fixedString, "aaaaa");
}


private String writeAtFixedLength(String pString, int lenght) {
    if (pString != null && !pString.isEmpty()){
        return getStringAtFixedLength(pString, lenght);
    }else{
        return completeWithWhiteSpaces("", lenght);
    }
}

private String getStringAtFixedLength(String pString, int lenght) {
    if(lenght < pString.length()){
        return pString.substring(0, lenght);
    }else{
        return completeWithWhiteSpaces(pString, lenght - pString.length());
    }
}

private String completeWithWhiteSpaces(String pString, int lenght) {
    for (int i=0; i<lenght; i++)
        pString += " ";
    return pString;
}

I like TDD ;)

Posting parameters to a url using the POST method without using a form

You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check this link out. Keep in mind that you will need JavaScript enabled in your browser though.

Multiline TextView in Android?

First replace "\n" with its Html equavalent "&lt;br&gt;" then call Html.fromHtml() on the string. Follow below steps:

String text= model.getMessageBody().toString().replace("\n", "&lt;br&gt;")
textView.setText(Html.fromHtml(Html.fromHtml(text).toString()))

This works perfectly.

UINavigationBar Hide back Button Text

Setting title of the back button to @"" or nil won't work. You need to set the entire button empty (without a title or image):

Objective-C

[self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil]];

Swift

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)

This should be done on the view controller that's on top of your view controller in navigation stack (i.e. from where you navigate to your VC via pushViewController method)

Calculating sum of repeated elements in AngularJS ng-repeat

I prefer elegant solutions

In Template

<td>Total: {{ totalSum }}</td>

In Controller

$scope.totalSum = Object.keys(cart.products).map(function(k){
    return +cart.products[k].price;
}).reduce(function(a,b){ return a + b },0);

If you're using ES2015 (aka ES6)

$scope.totalSum = Object.keys(cart.products)
  .map(k => +cart.products[k].price)
  .reduce((a, b) => a + b);

Leave out quotes when copying from cell

Possible problem in relation to answer from "user3616725":
Im on Windows 8.1 and there seems to be a problem with the linked VBA code from accepted answer from "user3616725":

Sub CopyCellContents()
 ' !!! IMPORTANT !!!:
 ' CREATE A REFERENCE IN THE VBE TO "Microsft Forms 2.0 Library" OR "Microsft Forms 2.0 Object Library"
 ' DO THIS BY (IN VBA EDITOR) CLICKING TOOLS -> REFERENCES & THEN TICKING "Microsoft Forms 2.0 Library" OR "Microsft Forms 2.0 Object Library"
 Dim objData As New DataObject
 Dim strTemp As String
 strTemp = ActiveCell.Value
 objData.SetText (strTemp)
 objData.PutInClipboard
End Sub

Details:
Running above code and pasting clipboard into a cell in Excel I get two symbols composed of squares with a question mark inside, like this: ??. Pasting into Notepad doesn't even show anything.

Solution:
After searching for quite some time I found another VBA script from user "Nepumuk" which makes use of the Windows API. Here's his code that finally worked for me:

Option Explicit

Private Declare Function OpenClipboard Lib "user32.dll" ( _
    ByVal hwnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32.dll" () As Long
Private Declare Function EmptyClipboard Lib "user32.dll" () As Long
Private Declare Function SetClipboardData Lib "user32.dll" ( _
    ByVal wFormat As Long, _
    ByVal hMem As Long) As Long
Private Declare Function GlobalAlloc Lib "kernel32.dll" ( _
    ByVal wFlags As Long, _
    ByVal dwBytes As Long) As Long
Private Declare Function GlobalLock Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function GlobalFree Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function lstrcpy Lib "kernel32.dll" ( _
    ByVal lpStr1 As Any, _
    ByVal lpStr2 As Any) As Long

Private Const CF_TEXT As Long = 1&

Private Const GMEM_MOVEABLE As Long = 2

Public Sub Beispiel()
    Call StringToClipboard("Hallo ...")
End Sub

Private Sub StringToClipboard(strText As String)
    Dim lngIdentifier As Long, lngPointer As Long
    lngIdentifier = GlobalAlloc(GMEM_MOVEABLE, Len(strText) + 1)
    lngPointer = GlobalLock(lngIdentifier)
    Call lstrcpy(ByVal lngPointer, strText)
    Call GlobalUnlock(lngIdentifier)
    Call OpenClipboard(0&)
    Call EmptyClipboard
    Call SetClipboardData(CF_TEXT, lngIdentifier)
    Call CloseClipboard
    Call GlobalFree(lngIdentifier)
End Sub

To use it the same way like the first VBA code from above, change the Sub "Beispiel()" from:

Public Sub Beispiel()
    Call StringToClipboard("Hallo ...")
End Sub

To:

Sub CopyCellContents()
    Call StringToClipboard(ActiveCell.Value)
End Sub

And run it via Excel macro menu like suggested from "user3616725" from accepted answer:

Back in Excel, go Tools>Macro>Macros and select the macro called "CopyCellContents" and then choose Options from the dialog. Here you can assign the macro to a shortcut key (eg like Ctrl+c for normal copy) - I used Ctrl+q.

Then, when you want to copy a single cell over to Notepad/wherever, just do Ctrl+q (or whatever you chose) and then do a Ctrl+v or Edit>Paste in your chosen destination.


Edit (21st of November in 2015):
@ comment from "dotctor":
No, this seriously is no new question! In my opinion it is a good addition for the accepted answer as my answer addresses problems that you can face when using the code from the accepted answer. If I would have more reputation, I would have created a comment.
@ comment from "Teepeemm":
Yes, you are right, answers beginning with title "Problem:" are misleading. Changed to: "Possible problem in relation to answer from "user3616725":". As a comment I certainly would have written much more compact.

How to fix "unable to open stdio.h in Turbo C" error?

Check if you have anything like those stdio.h file and other header files under INCLUDE folder and LIB folder. LIB contains some files. In my case, I had the same issue but both of these folder were blank.. good to know. Steps:

  1. Press: ALT + O + D (i.e. press ATL (keep pressed) and then O english character) and then D).
  2. You'll see a popup window.
  3. This window will have values for INCLUDE and LIB directories. The by default value for these two boxes in the popup window are: Drive leter where you installed TC... i.e. C:\ or D:\ or whatever followed by the path for INCLUDE and LIB folder. So, in my case,

    INCLUDE box was set to: "C:\TC\INCLUDE" and LIB directory value box was set to: "C:\TC\LIB" (without quotes). Steps to resolve:

  4. Press ALT + C.

  5. Set your current directory as C:\TC\BGI
  6. Press ALT + O + D, and put ../INCLUDE and ../LIB in Include/Lib directory values.
  7. and now... when you'll run your progress, you'll say thanks to me. I like the archduchess C fractal graphics that I'm running on DOS Turbo C right now. Lol.

String compare in Perl with "eq" vs "=="

Did you try to chomp the $str1 and $str2?

I found a similar issue with using (another) $str1 eq 'Y' and it only went away when I first did:

chomp($str1);
if ($str1 eq 'Y') {
....
}

works after that.

Hope that helps.

Git 'fatal: Unable to write new index file'

In my case, the solution was only adding permission to the new user.

When I installed new OS, moved my repos around and it was showing this exact error I selected the root folder and then added authenticated the user to check all enter image description here

No more data to read from socket error

For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.

You have two ways to address this:

  • upgrade to 11.2
  • set oracle parameter _optim_peek_user_binds = false

Of course underscore parameters should only be set if advised by oracle support

How to get primary key column in Oracle?

Try This Code Here I created a table for get primary key column in oracle which is called test and then query

create table test
(
id int,
name varchar2(20),
city varchar2(20),
phone int,
constraint pk_id_name_city primary key (id,name,city)
);

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner  ORDER BY cols.table_name, cols.position;