Programs & Examples On #Nameservice

Angular no provider for NameService

You should be injecting NameService inside providers array of your AppModule's NgModule metadata.

@NgModule({
   providers: [MyService]
})

and be sure import in your component by same name (case sensitive),becouse SystemJs is case sensitive (by design). If you use different path name in your project files like this:

main.module.ts

import { MyService } from './MyService';

your-component.ts

import { MyService } from './Myservice';

then System js will make double imports

How to pass a JSON array as a parameter in URL

I encountered the same need and make a universal solution (node+browser) that works with the Next.js framework, for instance.

It even works with circular dependencies (thanks to json-stringify-safe).

Although, I also built a serializer on top of it to remove unnecessary data (because it's not recommended to use a url longer than 2k chars, see What is the maximum length of a URL in different browsers?)

import StringifySafe from 'json-stringify-safe';

export const encodeQueryParameter = (data: object): string => {
  return encodeURIComponent(StringifySafe(data)); // Use StringifySafe to avoid crash on circular dependencies
};

export const decodeQueryParameter = (query: string): object => {
  return JSON.parse(decodeURIComponent(query));
};

And the unit tests (jest):

import { decodeQueryParameter, encodeQueryParameter } from './url';

export const data = {
  'organisation': {
    'logo': {
      'id': 'ck2xjm2oj9lr60b32c6l465vx',
      'linkUrl': null,
      'linkTarget': '_blank',
      'classes': null,
      'style': null,
      'defaultTransformations': { 'width': 200, 'height': 200, '__typename': 'AssetTransformations' },
      'mimeType': 'image/png',
      '__typename': 'Asset',
    },
    'theme': {
      'primaryColor': '#1134e6',
      'primaryAltColor': '#203a51',
      'secondaryColor': 'white',
      'font': 'neuzeit-grotesk',
      '__typename': 'Theme',
      'primaryColorG1': '#ffffff',
    },
  },
};
export const encodedData = '%7B%22organisation%22%3A%7B%22logo%22%3A%7B%22id%22%3A%22ck2xjm2oj9lr60b32c6l465vx%22%2C%22linkUrl%22%3Anull%2C%22linkTarget%22%3A%22_blank%22%2C%22classes%22%3Anull%2C%22style%22%3Anull%2C%22defaultTransformations%22%3A%7B%22width%22%3A200%2C%22height%22%3A200%2C%22__typename%22%3A%22AssetTransformations%22%7D%2C%22mimeType%22%3A%22image%2Fpng%22%2C%22__typename%22%3A%22Asset%22%7D%2C%22theme%22%3A%7B%22primaryColor%22%3A%22%231134e6%22%2C%22primaryAltColor%22%3A%22%23203a51%22%2C%22secondaryColor%22%3A%22white%22%2C%22font%22%3A%22neuzeit-grotesk%22%2C%22__typename%22%3A%22Theme%22%2C%22primaryColorG1%22%3A%22%23ffffff%22%7D%7D%7D';

describe(`utils/url.ts`, () => {
  describe(`encodeQueryParameter`, () => {
    test(`should encode a JS object into a url-compatible string`, async () => {
      expect(encodeQueryParameter(data)).toEqual(encodedData);
    });
  });

  describe(`decodeQueryParameter`, () => {
    test(`should decode a url-compatible string into a JS object`, async () => {
      expect(decodeQueryParameter(encodedData)).toEqual(data);
    });
  });

  describe(`encodeQueryParameter <> decodeQueryParameter <> encodeQueryParameter`, () => {
    test(`should encode and decode multiple times without altering data`, async () => {
      const _decodedData: object = decodeQueryParameter(encodedData);
      expect(_decodedData).toEqual(data);

      const _encodedData: string = encodeQueryParameter(_decodedData);
      expect(_encodedData).toEqual(encodedData);

      const _decodedDataAgain: object = decodeQueryParameter(_encodedData);
      expect(_decodedDataAgain).toEqual(data);
    });
  });
});

Java ElasticSearch None of the configured nodes are available

I had the same problem. my problem was that the version of the dependency had conflict with the elasticsearch version. check the version in ip:9200 and use the dependency version that match it

Address already in use: JVM_Bind

You can try to use TCPView utility.

Try to find in the localport column is there any process worked on "busy" port. Right click and end the process. Then try to start the Tomcat.

Its really works for me.

Convert object string to JSON

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }" var fStr = str .replace(/([A-z]*)(:)/g, '"$1":') .replace(/'/g, "\"")

console.log(JSON.parse(fStr))enter image description here

Sorry I am on my phone, here is a pic.

How to hide a div from code (c#)

The above answers are fine but I would add to be sure the div is defined in the designer.cs file. This doesn't always happen when adding a div to the .aspx file. Not sure why but there are threads concerning this issue in this forum. Eg:

protected global::System.Web.UI.HtmlControls.HtmlGenericControl theDiv;

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

In my case I used sudo mkdir projectFolder to create folder. It was owned by root user and I was logged in using non root user.

So I changed the folder permission using command sudo chown mynonrootuser:mynonrootuser projectFolder and then it worked fine.

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

There are already a few good answers to this question, but for the sake of completeness I wanted to point out that the applicable section of the C standard is 5.1.2.2.3/15 (which is the same as section 1.9/9 in the C++11 standard). This section states that operators can only be regrouped if they are really associative or commutative.

Check if table exists

    /**
 * Method that checks if all tables exist
 * If a table doesnt exist it creates the table
 */
public void checkTables() {
    try {
        startConn();// method that connects with mysql database
        String useDatabase = "USE " + getDatabase() + ";";
        stmt.executeUpdate(useDatabase);
        String[] tables = {"Patients", "Procedures", "Payments", "Procedurables"};//thats table names that I need to create if not exists
        DatabaseMetaData metadata = conn.getMetaData();

        for(int i=0; i< tables.length; i++) {
            ResultSet rs = metadata.getTables(null, null, tables[i], null);
            if(!rs.next()) {
                createTable(tables[i]);
                System.out.println("Table " + tables[i] + " created");
            }
        }
    } catch(SQLException e) {
        System.out.println("checkTables() " + e.getMessage());
    }
    closeConn();// Close connection with mysql database
}

SQL Server: Filter output of sp_who2

A really easy way to do it is to create an ODBC link in EXCEL and run SP_WHO2 from there.

You can Refresh whenever you like and because it's EXCEL everything can be manipulated easily!

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

Less aggressive compilation with CSS3 calc

Less no longer evaluates expression inside calc by default since v3.00.


Original answer (Less v1.x...2.x):

Do this:

body { width: calc(~"100% - 250px - 1.5em"); }

In Less 1.4.0 we will have a strictMaths option which requires all Less calculations to be within brackets, so the calc will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.

How can I find the version of the Fedora I use?

The proposed standard file is /etc/os-release. See http://www.freedesktop.org/software/systemd/man/os-release.html

You can execute something like:

$ source /etc/os-release
$ echo $ID
fedora
$ echo $VERSION_ID
17
$ echo $VERSION
17 (Beefy Miracle)

Compare if BigDecimal is greater than zero

 BigDecimal obj = new BigDecimal("100");
 if(obj.intValue()>0)
    System.out.println("yes");

Fetch first element which matches criteria

When you write a lambda expression, the argument list to the left of -> can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:

this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));

is incorrect syntax; but

this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));

is correct. Or:

this.stops.stream().filter(s -> s.getStation().getName().equals(name));

is also correct if the compiler has enough information to figure out the types.

How can I get all the request headers in Django?

<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
  <code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}

LIKE operator in LINQ

Typically you use String.StartsWith/EndsWith/Contains. For example:

var portCode = Database.DischargePorts
                       .Where(p => p.PortName.Contains("BALTIMORE"))
                       .Single()
                       .PortCode;

I don't know if there's a way of doing proper regular expressions via LINQ to SQL though. (Note that it really does depend on which provider you're using - it would be fine in LINQ to Objects; it's a matter of whether the provider can convert the call into its native query format, e.g. SQL.)

EDIT: As BitKFu says, Single should be used when you expect exactly one result - when it's an error for that not to be the case. Options of SingleOrDefault, FirstOrDefault or First should be used depending on exactly what's expected.

Gitignore not working

@Ahmad's answer is working but if you just want to git ignore 1 specific file or few files do as @Nicolas suggests

step 1

add filename to .gitignore file

step 2

[remove filename (file path) from git cache

git rm --cached filename

setp 3

commit changes git add filename

git commit -m "add filename to .gitignore"

it will keep your git history clean because if you do git rm -r --cached . and add back all and commit them it will pollute your git history (it will show that you add a lot of files at one commit) not sure am I expressing my thought right but hope you get the point

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

What are the basic rules and idioms for operator overloading?

Why can't operator<< function for streaming objects to std::cout or to a file be a member function?

Let's say you have:

struct Foo
{
   int a;
   double b;

   std::ostream& operator<<(std::ostream& out) const
   {
      return out << a << " " << b;
   }
};

Given that, you cannot use:

Foo f = {10, 20.0};
std::cout << f;

Since operator<< is overloaded as a member function of Foo, the LHS of the operator must be a Foo object. Which means, you will be required to use:

Foo f = {10, 20.0};
f << std::cout

which is very non-intuitive.

If you define it as a non-member function,

struct Foo
{
   int a;
   double b;
};

std::ostream& operator<<(std::ostream& out, Foo const& f)
{
   return out << f.a << " " << f.b;
}

You will be able to use:

Foo f = {10, 20.0};
std::cout << f;

which is very intuitive.

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

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

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

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

How to stop a setTimeout loop?

I am not sure, but might be what you want:

var c = 0;
function setBgPosition()
{
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run()
    {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<=numbers.length)
        {
            setTimeout(run, 200);
        }
        else
        {
            Ext.get('common-spinner').setStyle('background-position', numbers[0] + 'px 0px');
        }
    }
    setTimeout(run, 200);
}
setBgPosition();

Hidden Features of Java

Some control-flow tricks, finally around a return statement:

int getCount() { 
  try { return 1; }
  finally { System.out.println("Bye!"); }
}

The rules for definite assignment will check that a final variable is always assigned through a simple control-flow analysis:

final int foo;
if(...)
  foo = 1;
else
  throw new Exception();
foo+1;

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

How to add a response header on nginx when using proxy_pass?

add_header works as well with proxy_pass as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.

Right now I have a working configuration and it contains the following (among others):

server {
    server_name  .myserver.com
    location / {
        proxy_pass  http://mybackend;
        add_header  X-Upstream  $upstream_addr;
    }
}

Before nginx 1.7.5 add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.

Since nginx 1.7.5 you can use the keyword always to include custom headers even in error responses. For example:

add_header X-Upstream $upstream_addr always;

Limitation: You cannot override the server header value using add_header.

How to get only time from date-time C#

You can simply write

string time = dateTimeObect.ToString("HH:mm");

Should CSS always preceed Javascript?

Here is a SUMMARY of all the major answers above (or maybe below later :)

For modern browsers, put css wherever you like it. They would analyze your html file (which they call speculative parsing) and start downloading css in parallel with html parsing.

For old browsers keep putting css on top (if you don't want to show a naked but interactive page first).

For all browsers, put javascript as farther down on the page as possible, since it will halt parsing of your html. Preferably, download it asynchronously (i.e., ajax call)

There are also, some experimental results for a particular case which claims putting javascript first (as opposed to traditional wisdom of putting CSS first) gives better performance but there is no logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.

So, to answer the question: Yes. The recommendation to include the CSS before JS is invalid for the modern browsers. Put CSS wherever you like, and put JS towards the end, as possible.

Force a screen update in Excel VBA

Add a DoEvents function inside the loop, see below.

You may also want to ensure that the Status bar is visible to the user and reset it when your code completes.

Sub ProgressMeter()

Dim booStatusBarState As Boolean
Dim iMax As Integer
Dim i As Integer

iMax = 10000

    Application.ScreenUpdating = False
''//Turn off screen updating

    booStatusBarState = Application.DisplayStatusBar
''//Get the statusbar display setting

    Application.DisplayStatusBar = True
''//Make sure that the statusbar is visible

    For i = 1 To iMax ''// imax is usually 30 or so
        fractionDone = CDbl(i) / CDbl(iMax)
        Application.StatusBar = Format(fractionDone, "0%") & " done..."
        ''// or, alternatively:
        ''// statusRange.value = Format(fractionDone, "0%") & " done..."
        ''// Some code.......

        DoEvents
        ''//Yield Control

    Next i

    Application.DisplayStatusBar = booStatusBarState
''//Reset Status bar display setting

    Application.StatusBar = False
''//Return control of the Status bar to Excel

    Application.ScreenUpdating = True
''//Turn on screen updating

End Sub

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

How do I tell matplotlib that I am done with a plot?

You can use figure to create a new plot, for example, or use close after the first plot.

How to set a Default Route (To an Area) in MVC

routes.MapRoute(
                "Area",
                "{area}/",
                new { area = "AreaZ", controller = "ControlerX ", action = "ActionY " }
            );

Have you tried that ?

"The page has expired due to inactivity" - Laravel 5.5

set mbstring.func_overload = 2

it helped me

How to horizontally center an element

For a horizontally centered DIV:

#outer {
  width: 100%;
  text-align: center;
}
#inner {
  display: inline-block;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

Can I assume (bool)true == (int)1 for any C++ compiler?

Yes. The casts are redundant. In your expression:

true == 1

Integral promotion applies and the bool value will be promoted to an int and this promotion must yield 1.

Reference: 4.7 [conv.integral] / 4: If the source type is bool... true is converted to one.

What does elementFormDefault do in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).

By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.

It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.

Using UPDATE in stored procedure with optional parameters

Try this.

ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
    @id uniqueidentifier,
    @ordering smallint = NULL,
    @title nvarchar(20) = NULL,
    @content text = NULL
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE tbl_ClientNotes
    SET ordering=ISNULL(@ordering,ordering), 
        title=ISNULL(@title,title), 
        content=ISNULL(@content, content)
    WHERE id=@id
END

It might also be worth adding an extra part to the WHERE clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.

WHERE id=@id AND (@ordering IS NOT NULL OR
                  @title IS NOT NULL OR
                  @content IS NOT NULL)

I have Python on my Ubuntu system, but gcc can't find Python.h

Go to Synaptic package manager. Reload -> Search for python -> select the python package you want -> Submit -> Install Works for me ;)

Exactly, the package you need to install is python-dev.

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

How do I make a batch file terminate upon encountering an error?

@echo off

set startbuild=%TIME%

C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe c:\link.xml /flp1:logfile=c:\link\errors.log;errorsonly /flp2:logfile=c:\link\warnings.log;warningsonly || goto :error

copy c:\app_offline.htm "\\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm"

del \\lawpccnweb01\d$\websites\OperationsLinkWeb\bin\ /Q

echo Start Copy: %TIME%

set copystart=%TIME%

xcopy C:\link\_PublishedWebsites\OperationsLink \\lawpccnweb01\d$\websites\OperationsLinkWeb\ /s /y /d

del \\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm

echo Started Build: %startbuild%
echo Started Copy: %copystart%
echo Finished Copy: %TIME%

c:\link\warnings.log

:error

c:\link\errors.log

if var == False

Use not

var = False
if not var:
    print 'learnt stuff'

Could not reliably determine the server's fully qualified domain name

" To solve this problem You need set ServerName.

1: $ vim /etc/apache2/conf.d/name For example set add ServerName localhost or any other name:

2: ServerName localhost Restart Apache 2

3: $ service apache restart For this example I use Ubuntu 11.10.1.125"

Array or List in Java. Which is faster?

It you can live with a fixed size, arrays will will be faster and need less memory.

If you need the flexibility of the List interface with adding and removing elements, the question remains which implementation you should choose. Often ArrayList is recommended and used for any case, but also ArrayList has its performance problems if elements at the beginning or in the middle of the list must be removed or inserted.

You therefore may want to have a look at http://java.dzone.com/articles/gaplist-%E2%80%93-lightning-fast-list which introduces GapList. This new list implementation combines the strengths of both ArrayList and LinkedList resulting in very good performance for nearly all operations.

How to style the menu items on an Android action bar

Instead of having the android:actionMenuTextAppearance item under your action bar style, move it under your app theme.

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

In newer versions of CMake you can set compiler and linker flags for a single target with target_compile_options and target_link_libraries respectively (yes, the latter sets linker options too):

target_compile_options(first-test PRIVATE -fexceptions)

The advantage of this method is that you can control propagation of options to other targets that depend on this one via PUBLIC and PRIVATE.

As of CMake 3.13 you can also use target_link_options to add linker options which makes the intent more clear.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

Change control panel Java's option about proxy to "direct", change window's internet option to not use proxy and reboot. It worked for me.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

By typing 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10' in Anaconda PowerShell or prompt, the Jupyter notebook will open with the new configuration. Try now to run your query.

Converting a double to an int in Javascript without rounding

Similar to C# casting to (int) with just using standard lib:

Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

With Python 3 I had this problem:

 self.path = 'T:\PythonScripts\Projects\Utilities'

produced this error:

 self.path = 'T:\PythonScripts\Projects\Utilities'
            ^
 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
 position 25-26: truncated \UXXXXXXXX escape

the fix that worked is:

 self.path = r'T:\PythonScripts\Projects\Utilities'

It seems the '\U' was producing an error and the 'r' preceding the string turns off the eight-character Unicode escape (for a raw string) which was failing. (This is a bit of an over-simplification, but it works if you don't care about unicode)

Hope this helps someone

Bash script to cd to directory with spaces in pathname

I found the solution below on this page:

x="test\ me"  
eval cd $x

A combination of \ in a double-quoted text constant and an eval before cd makes it work like a charm!

AngularJS ng-repeat handle empty list case

With the newer versions of angularjs the correct answer to this question is to use ng-if:

<ul>
  <li ng-if="list.length === 0">( No items in this list yet! )</li>
  <li ng-repeat="item in list">{{ item }}</li>
</ul>

This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.

Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview

Tip: You can also show a loading text or spinner:

  <li ng-if="!list">( Loading... )</li>

SFTP file transfer using Java JSch

Usage:

sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");

Implementation

.war vs .ear file

Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html

tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge

Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure

war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes

ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files

How do you render primitives as wireframes in OpenGL?

You can use glut libraries like this:

  1. for a sphere:

    glutWireSphere(radius,20,20);
    
  2. for a Cylinder:

    GLUquadric *quadratic = gluNewQuadric();
    gluQuadricDrawStyle(quadratic,GLU_LINE);
    gluCylinder(quadratic,1,1,1,12,1);
    
  3. for a Cube:

    glutWireCube(1.5);
    

How to manually trigger validation with jQuery validate?

As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()

var validator = $( "#myform" ).validate();
validator.form();

C# Collection was modified; enumeration operation may not execute

The problem is where you are executing:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.

Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.

How to upper case every first letter of word in a string?

Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.

StringBuilder b = new StringBuilder(str);
int i = 0;
do {
  b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
  i =  b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());

System.out.println(b.toString());

It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

Insert picture into Excel cell

You can add the image into a comment.

Right-click cell > Insert Comment > right-click on shaded (grey area) on outside of comment box > Format Comment > Colors and Lines > Fill > Color > Fill Effects > Picture > (Browse to picture) > Click OK

Image will appear on hover over.

Microsoft Office 365 (2019) introduced new things called comments and renamed the old comments as "notes". Therefore in the steps above do New Note instead of Insert Comment. All other steps remain the same and the functionality still exists.


There is also a $20 product for Windows - Excel Image Assistant...

CSS fill remaining width

I know its quite late to answer this, but I guess it will help anyone ahead.

Well using CSS3 FlexBox. It can be acheived. Make you header as display:flex and divide its entire width into 3 parts. In the first part I have placed the logo, the searchbar in second part and buttons container in last part. apply justify-content: between to the header container and flex-grow:1 to the searchbar. That's it. The sample code is below.

_x000D_
_x000D_
#header {_x000D_
  background-color: #323C3E;_x000D_
  justify-content: space-between;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
#searchBar, img{_x000D_
  align-self: center;_x000D_
}_x000D_
_x000D_
#searchBar{_x000D_
  flex-grow:1;_x000D_
  background-color: orange;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
#searchBar input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.button {_x000D_
  padding: 22px;_x000D_
}_x000D_
_x000D_
.buttonsHolder{_x000D_
  display:flex;_x000D_
}
_x000D_
<div id="header" class="d-flex justify-content-between">_x000D_
    <img src="img/logo.png" />_x000D_
    <div id="searchBar">_x000D_
      <input type="text" />_x000D_
    </div>_x000D_
    <div class="buttonsHolder">_x000D_
      <div class="button orange inline" id="myAccount">_x000D_
        My Account_x000D_
      </div>_x000D_
      <div class="button red inline" id="basket">_x000D_
        Basket (2)_x000D_
      </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Does delete on a pointer to a subclass call the base class destructor?

The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed.

class A
{
    char *someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { delete[] someHeapMemory; }
};

class B
{
    A* APtr;
public:
    B() : APtr(new A()) {}
    ~B() { delete APtr; }
};

class C
{
    A Amember;
public:
    C() : Amember() {}
    ~C() {} // A is freed / destructed automatically.
};

int main()
{
    B* BPtr = new B();
    delete BPtr; // Calls ~B() which calls ~A() 
    C *CPtr = new C();
    delete CPtr;
    B b;
    C c;
} // b and c are freed/destructed automatically

In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it.

auto_ptr, unique_ptr and shared_ptr etc... are great for making this lifetime management much easier:

class A
{
    shared_array<char> someHeapMemory;
public:
    A() : someHeapMemory(new char[1000]) {}
    ~A() { } // someHeapMemory is delete[]d automatically
};

class B
{
    shared_ptr<A> APtr;
public:
    B() : APtr(new A()) {}
    ~B() {  } // APtr is deleted automatically
};

int main()
{
    shared_ptr<B> BPtr = new B();
} // BPtr is deleted automatically

How to delete a localStorage item when the browser window/tab is closed?

Here's a simple test to see if you have browser support when working with local storage:

if(typeof(Storage)!=="undefined") {
  console.log("localStorage and sessionStorage support!");
  console.log("About to save:");
  console.log(localStorage);
  localStorage["somekey"] = 'hello';
  console.log("Key saved:");
  console.log(localStorage);
  localStorage.removeItem("somekey");  //<--- key deleted here
  console.log("key deleted:");
  console.log(localStorage);
  console.log("DONE ===");
} else {
  console.log("Sorry! No web storage support..");
}

It worked for me as expected (I use Google Chrome). Adapted from: http://www.w3schools.com/html/html5_webstorage.asp.

Close pre-existing figures in matplotlib when running from eclipse

Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).

How to update a pull request from forked repo?

I did it using below steps:

  1. git reset --hard <commit key of the pull request>
  2. Did my changes in code I wanted to do
  3. git add
  4. git commit --amend
  5. git push -f origin <name of the remote branch of pull request>

Table column sizing

Another option is to apply flex styling at the table row, and add the col-classes to the table header / table data elements:

<table>
  <thead>
    <tr class="d-flex">
      <th class="col-3">3 columns wide header</th>
      <th class="col-sm-5">5 columns wide header</th>
      <th class="col-sm-4">4 columns wide header</th>
    </tr>
  </thead>
  <tbody>
    <tr class="d-flex">
      <td class="col-3">3 columns wide content</th>
      <td class="col-sm-5">5 columns wide content</th>
      <td class="col-sm-4">4 columns wide content</th>
    </tr>
  </tbody>
</table>

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

Android 6.0 Marshmallow. Cannot write to SD Card

Maybe you cannot use manifest class from generated code in your project. So, you can use manifest class from android sdk "android.Manifest.permission.WRITE_EXTERNAL_STORAGE". But in Marsmallow version have 2 permission must grant are WRITE and READ EXTERNAL STORAGE in storage category. See my program, my program will request permission until user choose yes and do something after permissions is granted.

            if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(LoginActivity.this,
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                            1);
                } else {
                    //do something
                }
            } else {
                    //do something
            }

Android Horizontal RecyclerView scroll Direction

Just add two lines of code to make orientation of recyclerview as horizontal. So add these lines when Initializing Recyclerview.

  LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);

my_recycler.setLayoutManager(linearLayoutManager);

How to store arbitrary data for some HTML tags

Why not make use of the meaningful data already there, instead of adding arbitrary data?

i.e. use <a href="/articles/5/page-title" class="article-link">, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/ against this.href).

import sun.misc.BASE64Encoder results in error compiled in Eclipse

That error is caused by your Eclipse configuration. You can reduce it to a warning. Better still, use a Base64 encoder that isn't part of a non-public API. Apache Commons has one, or when you're already on Java 1.8, then use java.util.Base64.

Javascript to export html table to Excel

If you add:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

in the head of the document it will start working as expected:

<script type="text/javascript">
var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()
</script>

Updated Fiddle Here.

LEFT OUTER JOIN in LINQ

Here's an example if you need to join more than 2 tables:

from d in context.dc_tpatient_bookingd
join bookingm in context.dc_tpatient_bookingm 
     on d.bookingid equals bookingm.bookingid into bookingmGroup
from m in bookingmGroup.DefaultIfEmpty()
join patient in dc_tpatient
     on m.prid equals patient.prid into patientGroup
from p in patientGroup.DefaultIfEmpty()

Ref: https://stackoverflow.com/a/17142392/2343

keycode and charcode

Handling key events consistently is not at all easy.

Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress event. Do not try to get character codes for keyup and keydown events.

Secondly, you get different sets of values in a keypress event to what you get in a keyup or keydown event.

I recommend this page as a useful resource. As a summary:

If you're interested in detecting a user typing a character, use the keypress event. IE bizarrely only stores the character code in keyCode while all other browsers store it in which. Some (but not all) browsers also store it in charCode and/or keyCode. An example keypress handler:

function(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);
  alert(charStr);
}

If you're interested in detecting a non-printable key (such as a cursor key), use the keydown event. Here keyCode is always the property to use. Note that keyup events have the same properties.

function(evt) {
  evt = evt || window.event;
  var keyCode = evt.keyCode;

  // Check for left arrow key
  if (keyCode == 37) {
    alert("Left arrow");
  }
}

How to copy a row and insert in same table with a autoincrement field in MySQL?

This helped and it supports a BLOB/TEXT columns.

CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id=2;
UPDATE temp_table SET id=NULL WHERE id=2;
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
USE source_table;

How can I have linebreaks in my long LaTeX equations?

This worked for me while using mathtools package.

\documentclass{article}
\usepackage{mathtools}
\begin{document}
    \begin{equation}
        \begin{multlined}
            first term \\
            second term                 
        \end{multlined}
    \end{equation}
\end{document}

keyword not supported data source

I know this is an old post but I got the same error recently so for what it's worth, here's another solution:

This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.

However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:

  1. First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:

  2. Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.

weirdness

How do I add a Maven dependency in Eclipse?

In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.

enter image description here

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

There seem to be a lot of issues related to the same error. For me it was the applications which I've installed from another iMac whose files where not present on my MacBook so Xcode was not able to find the files making the debugger to wait forever!

Solution: Deleting all the application which I've installed from the iMac helped me solve the problem.

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

The entity name must immediately follow the '&' in the entity reference

All answers posted so far are giving the right solutions, however no one answer was able to properly explain the underlying cause of the concrete problem.

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of & which is not followed by # (e.g. &#160;, &#xA0;, etc), the XML parser is implicitly looking for one of the five predefined entity names lt, gt, amp, quot and apos, or any manually defined entity name. However, in your particular case, you was using & as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The entity name must immediately follow the '&' in the entity reference

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The & must be escaped as &amp;.

So, in your particular case, the

if (Modernizr.canvas && Modernizr.localstorage && 

must become

if (Modernizr.canvas &amp;&amp; Modernizr.localstorage &amp;&amp;

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="onload.js" target="body" />

(note the target="body"; this way JSF will automatically render the <script> at the very end of <body>, regardless of where <h:outputScript> itself is located, hereby achieving the same effect as with window.onload and $(document).ready(); so you don't need to use those anymore in that script)

This way you don't need to worry about XML-special characters in your JS code. As an additional bonus, this gives you the opportunity to let the browser cache the JS file so that total response size is smaller.

See also:

HTML text input field with currency symbol

I just used :before with the input and passed $ as the content

input{ 
   margin-left: 20px;
 }
input:before {
  content: "$";
  position: absolute;
}

How do I compare two strings in Perl?

And if you'd like to extract the differences between the two strings, you can use String::Diff.

How to debug SSL handshake using cURL?

curl -iv https://your.domain.io

That will give you cert and header output if you do not wish to use openssl command.

How to add "active" class to Html.ActionLink in ASP.NET MVC

You can try this: In my case i am loading menu from database based on role based access, Write the code on your every view which menu your want to active based on your view.

<script type="text/javascript">
        $(document).ready(function () {         
            $('li.active active-menu').removeClass('active active-menu');
            $('a[href="/MgtCustomer/Index"]').closest('li').addClass('active active-menu');
        });
</script>

Pretty-Print JSON in Java

In JSONLib you can use this:

String jsonTxt = JSONUtils.valueToString(json, 8, 4);

From the Javadoc:

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

How to send POST in angularjs with multiple params?

If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:

Api Controller:

public class ProductController : ApiController
{
    [HttpPost]
    public void Post(Newtonsoft.Json.Linq.JObject data)
    {
        System.Diagnostics.Debugger.Break();

        Product product = data["product"].ToObject<Product>();
        Product product2 = data["product2"].ToObject<Product>();

        int someRandomNumber = data["randomNumber"].ToObject<int>();
        string productName = product.ProductName;
        string product2Name = product2.ProductName;
    }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

View:

<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);
    myApp.controller('controller', function ($scope, $http) {

        $scope.AddProducts = function () {
            var product = {
                ProductID: 0,
                ProductName: "Orange",
            }

            var product2 = {
                ProductID: 1,
                ProductName: "Mango",
            }

            var data = {
                product: product,
                product2: product2,
                randomNumber:12345
            };

            $http.post("/api/Product", data).
            success(function (data, status, headers, config) {
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });
        }
    });
</script>
<div ng-app="app" ng-controller="controller">
    <input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>

T-SQL string replace in Update

update YourTable
    set YourColumn = replace(YourColumn, '@domain2', '@domain1')
    where charindex('@domain2', YourColumn) <> 0

Alter table to modify default value of column

ALTER TABLE *table_name*
MODIFY *column_name* DEFAULT *value*;

worked in Oracle

e.g:

ALTER TABLE MY_TABLE
MODIFY MY_COLUMN DEFAULT 1;

Manually type in a value in a "Select" / Drop-down HTML list?

It can be done now with HTML5

See this post here HTML select form with option to enter custom value

<input type="text" list="cars" />
<datalist id="cars">
  <option>Volvo</option>
  <option>Saab</option>
  <option>Mercedes</option>
  <option>Audi</option>
</datalist>

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

Centering a button vertically in table cell, using Twitter Bootstrap

So why is td default set to vertical-align: top;? I really don't know that yet. I would not dare to touch it. Instead add this to your stylesheet. It alters the buttons in the tables.

table .btn{
  vertical-align: top;
}

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Finding all the subsets of a set

An elegant recursive solution that corresponds to the best answer explanation above. The core vector operation is only 4 lines. credit to "Guide to Competitive Programming" book from Laaksonen, Antti.

// #include <iostream>
#include <vector>
using namespace std;

vector<int> subset;
void search(int k, int n) {
    if (k == n+1) {
    // process subset - put any of your own application logic
    // for (auto i : subset) cout<< i << " ";
    // cout << endl;
    }
    else {
        // include k in the subset
        subset.push_back(k);
        search(k+1, n);
        subset.pop_back();
        // don't include k in the subset
        search(k+1,n);
    }
}

int main() {
    // find all subset between [1,3]
    search(1, 3);
}

How do I get bit-by-bit data from an integer value in C?

Here's a very simple way to do it;

int main()
{
    int s=7,l=1;
    vector <bool> v;
    v.clear();
    while (l <= 4)
    {
        v.push_back(s%2);
        s /= 2;
        l++;
    }
    for (l=(v.size()-1); l >= 0; l--)
    {
        cout<<v[l]<<" ";
    }
    return 0;
}

Simplest way to merge ES6 Maps/Sets?

Based off of Asaf Katz's answer, here's a typescript version:

export function union<T> (...iterables: Array<Set<T>>): Set<T> {
  const set = new Set<T>()
  iterables.forEach(iterable => {
    iterable.forEach(item => set.add(item))
  })
  return set
}

How to set up file permissions for Laravel?

Most folders should be normal "755" and files, "644"

Laravel requires some folders to be writable for the web server user. You can use this command on unix based OSs.

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

How to create Android Facebook Key Hash?

I ran into the same problem and here's how I was able to fix it

keytool -list -alias androiddebugkey -keystore <project_file\android\app\debug.keystore>

java.nio.file.Path for a classpath resource

I wrote a small helper method to read Paths from your class resources. It is quite handy to use as it only needs a reference of the class you have stored your resources as well as the name of the resource itself.

public static Path getResourcePath(Class<?> resourceClass, String resourceName) throws URISyntaxException {
    URL url = resourceClass.getResource(resourceName);
    return Paths.get(url.toURI());
}  

Select Last Row in the Table

You'll need to order by the same field you're ordering by now, but descending. As an example, if you have a time stamp when the upload was done called upload_time, you'd do something like this;

For Pre-Laravel 4

return DB::table('files')->order_by('upload_time', 'desc')->first();

For Laravel 4 and onwards

return DB::table('files')->orderBy('upload_time', 'desc')->first();

For Laravel 5.7 and onwards

return DB::table('files')->latest('upload_time')->first();

This will order the rows in the files table by upload time, descending order, and take the first one. This will be the latest uploaded file.

How to calculate growth with a positive and negative number?

I was fumbling for answers today, and think this would work...

=IF(C5=0, B5/1, IF(C5<0, (B5+ABS(C5)/1), IF(C5>0, (B5/C5)-1)))

C5 = Last Year, B5 = This Year

We have 3 IF statements in the cell.

IF Last Year is 0, then This Year divided by 1

IF Last Year is less than 0, then This Year + ABSolute value of Last Year divided by 1

IF Last Year is greater than 0, then This Year divided by Last Year minus 1

Set auto height and width in CSS/HTML for different screen sizes

Using bootstrap with a little bit of customization, the following seems to work for me:

I need 3 partitions in my container and I tried this:

CSS:

.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
  padding-top: 20px;
  border: 1px solid #cecece;
  height: 100%;
}
.midnav {
  padding: 0px;
}

HTML:

  <div class="container-fluid text-center"> 
    <div class="row content">
    <div class="col-md-2 sidenav text-left">Some content 1</div>
    <div class="col-md-9 midnav text-left">Some content 2</div>
    <div class="col-md-1 sidenav text-center">Some content 3</div>
    </div>
  </div>

Bulk Insertion in Laravel using eloquent ORM

Maybe a more Laravel way to solve this problem is to use a collection and loop it inserting with the model taking advantage of the timestamps.

<?php

use App\Continent;
use Illuminate\Database\Seeder;

class InitialSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        collect([
            ['name' => 'América'],
            ['name' => 'África'],
            ['name' => 'Europa'],
            ['name' => 'Asia'],
            ['name' => 'Oceanía'],
        ])->each(function ($item, $key) {
            Continent::forceCreate($item);
        });
    }
}

EDIT:

Sorry for my misunderstanding. For bulk inserting this could help and maybe with this you can make good seeders and optimize them a bit.

<?php

use App\Continent;
use Carbon\Carbon;
use Illuminate\Database\Seeder;

class InitialSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $timestamp = Carbon::now();
        $password = bcrypt('secret');

        $continents = [
            [
                'name' => 'América'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'África'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'Europa'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'Asia'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
            [
                'name' => 'Oceanía'
                'password' => $password,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ],
        ];

        Continent::insert($continents);
    }
}

How can I obtain the element-wise logical NOT of a pandas Series?

To invert a boolean Series, use ~s:

In [7]: s = pd.Series([True, True, False, True])

In [8]: ~s
Out[8]: 
0    False
1    False
2     True
3    False
dtype: bool

Using Python2.7, NumPy 1.8.0, Pandas 0.13.1:

In [119]: s = pd.Series([True, True, False, True]*10000)

In [10]:  %timeit np.invert(s)
10000 loops, best of 3: 91.8 µs per loop

In [11]: %timeit ~s
10000 loops, best of 3: 73.5 µs per loop

In [12]: %timeit (-s)
10000 loops, best of 3: 73.5 µs per loop

As of Pandas 0.13.0, Series are no longer subclasses of numpy.ndarray; they are now subclasses of pd.NDFrame. This might have something to do with why np.invert(s) is no longer as fast as ~s or -s.

Caveat: timeit results may vary depending on many factors including hardware, compiler, OS, Python, NumPy and Pandas versions.

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

Check if Internet Connection Exists with jQuery?

5 years later-version:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.

Show / hide div on click with CSS

You're going to have to either use JS or write a function/method in whatever non-markup language you're using to do this. For instance you could write something that will save the status to a cookie or session variable then check for it on page load. If you want to do it without reloading the page then JS is going to be your only option.

Get value when selected ng-option changes

I am late here but I resolved same kind of problem in this way that is simple and easy.

<select ng-model="blisterPackTemplateSelected" ng-change="selectedBlisterPack(blisterPackTemplateSelected)">
<option value="">Select Account</option>
<option ng-repeat="blisterPacks in blisterPackTemplates" value="{{blisterPacks.id}}">{{blisterPacks.name}}</option>

and the function for ng-change is as follows;

 $scope.selectedBlisterPack= function (value) {  

        console.log($scope.blisterPackTemplateSelected);

    };

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

IE8 css selector

In the ASP.NET world, I've tended to use the built-in BrowserCaps feature to write out a set of classes onto the body tag that enable you to target any combination of browser and platform.

So in pre-render, I would run something like this code (assuming you give your tag an ID and make it runat the server):

HtmlGenericControl _body = (HtmlGenericControl)this.FindControl("pageBody");
_body.Attributes.Add("class", Request.Browser.Platform + " " + Request.Browser.Browser + Request.Browser.MajorVersion);

This code enables you to then target a specific browser in your CSS like this:

.IE8 #nav ul li { .... }
.IE7 #nav ul li { .... }
.MacPPC.Firefox #nav ul li { .... }

We create a sub-class of System.Web.UI.MasterPage and make sure all of our master pages inherit from our specialised MasterPage so that every page gets these classes added on for free.

If you're not in an ASP.NET environment, you could use jQuery which has a browser plugin that dynamically adds similar class names on page-load.

This method has the benefit of removing conditional comments from your markup, and also of keeping both your main styles and your browser-specific styles in roughly the same place in your CSS files. It also means your CSS is more future-proof (since it doesn't rely on bugs that may be fixed) and helps your CSS code make much more sense since you only have to see

.IE8 #container { .... }

Instead of

* html #container { .... }

or worse!

How to pass a variable to the SelectCommand of a SqlDataSource?

You need to define a valid type of SelectParameter. This MSDN article describes the various types and how to use them.

Git log to get commits only for a specific branch

I needed to export log in one line for a specific branch.

So I probably came out with a simpler solution.
When doing git log --pretty=oneline --graph we can see that all commit not done in the current branch are lines starting with |

So a simple grep -v do the job:
git log --pretty=oneline --graph | grep -v "^|"

Of course you can change the pretty parameter if you need other info, as soon as you keep it in one line.

You probably want to remove merge commit too.
As the message start with "Merge branch", pipe another grep -v and you're done.

In my specific ase, the final command was:
git log --pretty="%ad : %an, %s" --graph | grep -v "^|" | grep -v "Merge branch"

How to download all files (but not HTML) from a website using wget?

This downloaded the entire website for me:

wget --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://site/path/

Set div height equal to screen size

Use simple CSS height: 100%; matches the height of the parent and using height: 100vh matches the height of the viewport.

Use vh instead of %;

Description for event id from source cannot be found

How about a real world solution.

If all you need is a "quick and dirty" way to write something to the event log without registering "custom sources" (requires admin rights), or providing "message files" (requires work and headache) just do this:

EventLog.WriteEntry(
    ".NET Runtime", //magic
    "Your error message goes here!!",
    EventLogEntryType.Warning,
    1000); //magic

This way you'll be writing to an existing "Application" log without the annoying "The description for Event ID 0 cannot be found"

If you want the "magic" part explained I blogged about it here

How to access ssis package variables inside script component

Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: screenshot of Script Transformation Editor properties page Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:

// Modify as necessary
public override void PreExecute()
{
    base.PreExecute();
    string thePath = Variables.FilePath;
    // Do something ...
}

public override void PostExecute()
{
    base.PostExecute();
    string theNewValue = "";
    // Do something to figure out the new value...
    Variables.FilePath = theNewValue;
}

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    string thePath = Variables.FilePath;
    // Do whatever needs doing here ...
}

One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.

Regarding the code snippet:

IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;

XlsFile = varCollection["User::FilePath"].Value.ToString();

varCollection is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.

How to get the type of T from a member of a generic class or method?

I use this extension method to accomplish something similar:

public static string GetFriendlyTypeName(this Type t)
{
    var typeName = t.Name.StripStartingWith("`");
    var genericArgs = t.GetGenericArguments();
    if (genericArgs.Length > 0)
    {
        typeName += "<";
        foreach (var genericArg in genericArgs)
        {
            typeName += genericArg.GetFriendlyTypeName() + ", ";
        }
        typeName = typeName.TrimEnd(',', ' ') + ">";
    }
    return typeName;
}

public static string StripStartingWith(this string s, string stripAfter)
{
    if (s == null)
    {
        return null;
    }
    var indexOf = s.IndexOf(stripAfter, StringComparison.Ordinal);
    if (indexOf > -1)
    {
        return s.Substring(0, indexOf);
    }
    return s;
}

You use it like this:

[TestMethod]
public void GetFriendlyTypeName_ShouldHandleReallyComplexTypes()
{
    typeof(Dictionary<string, Dictionary<string, object>>).GetFriendlyTypeName()
        .ShouldEqual("Dictionary<String, Dictionary<String, Object>>");
}

This isn't quite what you're looking for, but it's helpful in demonstrating the techniques involved.

AngularJs: How to check for changes in file input fields?

Working Demo of "files-input" Directive that Works with ng-change1

To make an <input type=file> element work the ng-change directive, it needs a custom directive that works with the ng-model directive.

<input type="file" files-input ng-model="fileList" 
       ng-change="onInputChange()" multiple />

The DEMO

_x000D_
_x000D_
angular.module("app",[])_x000D_
.directive("filesInput", function() {_x000D_
  return {_x000D_
    require: "ngModel",_x000D_
    link: function postLink(scope,elem,attrs,ngModel) {_x000D_
      elem.on("change", function(e) {_x000D_
        var files = elem[0].files;_x000D_
        ngModel.$setViewValue(files);_x000D_
      })_x000D_
    }_x000D_
  }_x000D_
})_x000D_
_x000D_
.controller("ctrl", function($scope) {_x000D_
     $scope.onInputChange = function() {_x000D_
         console.log("input change");_x000D_
     };_x000D_
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>_x000D_
  <body ng-app="app" ng-controller="ctrl">_x000D_
    <h1>AngularJS Input `type=file` Demo</h1>_x000D_
    _x000D_
    <input type="file" files-input ng-model="fileList" _x000D_
           ng-change="onInputChange()" multiple />_x000D_
    _x000D_
    <h2>Files</h2>_x000D_
    <div ng-repeat="file in fileList">_x000D_
      {{file.name}}_x000D_
    </div>_x000D_
  </body>
_x000D_
_x000D_
_x000D_

How can I delete a newline if it is the last character in a file?

ruby:

ruby -ne 'print $stdin.eof ? $_.strip : $_'

or:

ruby -ane 'q=p;p=$_;puts q if $.>1;END{print p.strip!}'

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?

using xl = Microsoft.Office.Interop.Excel;

xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;

Simple as that!

HTH, Z

How many spaces will Java String.trim() remove?

If your String input is:

String a = "   abc   ";
System.out.println(a);

Yes, output will be, "abc"; But if your String input is:

String b = "    This  is  a  test  "
System.out.println(b);

Output will be This is a test So trim only removes spaces before your first character and after your last character in the string and ignores the inner spaces. This is a piece of my code that slightly optimizes the built in String trim method removing the inner spaces and removes spaces before and after your first and last character in the string. Hope it helps.

public static String trim(char [] input){
    char [] output = new char [input.length];
    int j=0;
    int jj=0;
    if(input[0] == ' ' )    {
        while(input[jj] == ' ') 
            jj++;       
    }
    for(int i=jj; i<input.length; i++){
      if(input[i] !=' ' || ( i==(input.length-1) && input[input.length-1] == ' ')){
        output[j]=input[i];
        j++;
      }
      else if (input[i+1]!=' '){
        output[j]=' ';
        j++;
      }      
    }
    char [] m = new char [j];
    int a=0;
    for(int i=0; i<m.length; i++){
      m[i]=output[a];
      a++;
    }
    return new String (m);
  }

Git Clone from GitHub over https with two-factor authentication

It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.

How to Authenticate Git using Access Tokens

  1. Go to https://github.com/settings/tokens
  2. Click Generate New Token button on top right.
  3. Give your token a descriptive name.
  4. Set all required permissions for the token.
  5. Click Generate token button at the bottom.
  6. Copy the generated token to a safe place.
  7. Use this token instead of password when you use git clone.

Wow, it works!

What is the iOS 5.0 user agent string?

This site seems to keep a complete list that's still maintained

iPhone, iPod Touch, and iPad from iOS 2.0 - 5.1.1 (to date).

You do need to assemble the full user-agent string out of the information listed in the page's columns.

How can I read input from the console using the Scanner class in Java?

You can use the Scanner class in Java

Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);

What is this weird colon-member (" : ") syntax in the constructor?

This is called an initialization list. It is a way of initializing class members. There are benefits to using this instead of simply assigning new values to the members in the body of the constructor, but if you have class members which are constants or references they must be initialized.

How to create a numeric vector of zero length in R

Suppose you want to create a vector x whose length is zero. Now let v be any vector.

> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0

WordPress path url in js script file

    wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
    wp_enqueue_script('custom-js');

    $wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
    wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );

and in custom.js

alert(wnm_custom.template_url);

How to sort a List of objects by their date (java collections, List<Object>)

You're using Comparators incorrectly.

 Collections.sort(movieItems, new Comparator<Movie>(){
           public int compare (Movie m1, Movie m2){
               return m1.getDate().compareTo(m2.getDate());
           }
       });

How to force garbage collector to run?

Since I'm too low reputation to comment, I will post this as an answer since it saved me after hours of struggeling and it may help somebody else:

As most people state GC.Collect(); is NOT recommended to do this normally, except in edge cases. As an example of this running garbage collection was exactly the solution to my scenario.

My program runs a long running operation on a file in a thread and afterwards deletes the file from the main thread. However: when the file operation throws an exception .NET does NOT release the filelock until the garbage is actually collected, EVEN when the long running task is encapsulated in a using statement. Therefore the program has to force garbage collection before attempting to delete the file.

In code:

        var returnvalue = 0;
        using (var t = Task.Run(() => TheTask(args, returnvalue)))
        {
            //TheTask() opens a file and then throws an exception. The exception itself is handled within the task so it does return a result (the errorcode)
            returnvalue = t.Result;
        }
        //Even though at this point the Thread is closed the file is not released untill garbage is collected
        System.GC.Collect();
        DeleteLockedFile();

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Controller trying to find the "action" value in bean but according to your example you have not set any bean name of "action". try to do name="action". @RequestParam always find in the bean class.

Moving uncommitted changes to a new branch

Just create a new branch with git checkout -b ABC_1; your uncommitted changes will be kept, and you then commit them to that branch.

Format numbers in JavaScript similar to C#

May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.

How can I force a hard reload in Chrome for Android

I'm using window.location.reload(true) according to MDN (and this similar question) it forces page to reload from server.

You can execute this code in the browser by typing javascript:location.reload(true) in the address bar.

How to use Bootstrap 4 in ASP.NET Core

Try Libman, it's as simple as Bower and you can specify wwwroot/lib/ as the download folder.

How to fix Subversion lock error

Just Right Click on Project

  1. Click on Team

  2. Click Refresh/Cleaup

this will remove all the current lock files created by SVN

hope this will help !!!!

Installation of SQL Server Business Intelligence Development Studio

I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.

I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.

I hope this helps.

Is it possible to start activity through adb shell?

Launch adb shell and enter the command as follows

am start -n yourpackagename/.activityname

Using ORDER BY and GROUP BY together

One way to do this that correctly uses group by:

select l.* 
from table l
inner join (
  select 
    m_id, max(timestamp) as latest 
  from table 
  group by m_id
) r
  on l.timestamp = r.latest and l.m_id = r.m_id
order by timestamp desc

How this works:

  • selects the latest timestamp for each distinct m_id in the subquery
  • only selects rows from table that match a row from the subquery (this operation -- where a join is performed, but no columns are selected from the second table, it's just used as a filter -- is known as a "semijoin" in case you were curious)
  • orders the rows

What is the difference between server side cookie and client side cookie?

All cookies are client and server

There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.

But essentially it's the same cookie.

But, behavior can change

A cookie is basically a name=value pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server). Those attributes can be about lifetime, context and various security settings.

HTTP-only (is not server-only)

One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!

So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.

Alternatives to achieve 'only-ness'

If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.

How to find whether a number belongs to a particular range in Python?

if num in range(min, max):
  """do stuff..."""
else:
  """do other stuff..."""

List and kill at jobs on UNIX

First

ps -ef

to list all processes. Note the the process number of the one you want to kill. Then

kill 1234

were you replace 1234 with the process number that you want.

Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name

killall processname

How to hide underbar in EditText

To retain both the margins and background color use:

background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <padding
        android:bottom="10dp"
        android:left="4dp"
        android:right="8dp"
        android:top="10dp" />

    <solid android:color="@android:color/transparent" />

</shape>

Edit Text:

<androidx.appcompat.widget.AppCompatEditText
    android:id="@+id/none_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:inputType="text"
    android:text="First Name And Last Name"
    android:textSize="18sp" />

C++ Remove new line from multiline string

Use std::algorithms. This question has some suitably reusable suggestions Remove spaces from std::string in C++

how to install tensorflow on anaconda python 3.6

I will simply leave this here because none of the other approaches worked for me. Also, I can look it up myself when I need it for new devices.

THIS IS THE WAY IT WORKS:

  1. Install Anaconda
  2. Open Anaconda Prompt
  3. conda create --name tensorflow
  4. conda activate tensorflow
  5. Search with conda search tensorflow for all available TensorFlow versions
  6. Choose the one you need (usually the newest one)
  7. Explicitly name the version now (otherwise it happened to me that version 1.14 was installed): conda install -c conda-forge tensorflow=YOUR_VERSION
  8. Open Anaconda, choose the new environment and install Spyder
  9. Install Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019
  10. Download msvcp140.dll and add the .dll-File to the Windows\System32 folder

Now it should work like a charm!

TROUBLESHOOTING:

If it still doesn't work, try this, it worked for me:

Open Anaconda-Prompt:

  1. Create an environment with Python 3.6 like this: conda create --name tensorflow_env python=3.6
  2. conda activate tensorflow
  3. Steps 6. and 6. from the list above
  4. conda install tensorflow=YOUR_VERSION(not forge, just like this!)
  5. Now do steps 8, 9, 10 from above

TENSORFLOW GPU:

If you want to use your GPU, do it the same way as described above, with the only difference to install tensorflow-gpu instead if tensorflow.

And, you must install the newest NVIDIA driver for your GPU, you can find and choose the right one here.

(Yes, in TF 2 there's both, a CPU and GPU support, in the "normal" library. However, if you install tensorflow-gpu via conda, it installs the CUDA and cudNN etc. you need automatically for you - also the right versions. This way easier and faster.)

Center Div inside another (100% width) div

Just add margin: 0 auto; to the inside div.

How to set height property for SPAN

span { display: table-cell; height: (your-height + px); vertical-align: middle; }

For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.

ActivityCompat.requestPermissions not showing dialog box

I had this same issue.I updated to buildToolsVersion "23.0.3" It all of a sudden worked. Hope this helps anyone having this issue.

Set IDENTITY_INSERT ON is not working

The relevant part of the error message is

...when a column list is used...

You are not using a column list, you are using SELECT *. Use a column list instead:

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON 

INSERT INTO [MyDB].[dbo].[Equipment] (Col1, Col2, ...)
SELECT Col1, Col2, ... FROM [MyDBQA].[dbo].[Equipment] 

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF 

How to detect a mobile device with JavaScript?

if(navigator.userAgent.match(/iPad/i)){
 //code for iPad here 
}

if(navigator.userAgent.match(/iPhone/i)){
 //code for iPhone here 
}


if(navigator.userAgent.match(/Android/i)){
 //code for Android here 
}



if(navigator.userAgent.match(/BlackBerry/i)){
 //code for BlackBerry here 
}


if(navigator.userAgent.match(/webOS/i)){
 //code for webOS here 
}

How do I get a YouTube video thumbnail from the YouTube API?

Method 1:

You can find all information for a YouTube video with a JSON page which has even "thumbnail_url", http://www.youtube.com/oembed?format=json&url={your video URL goes here}

Like final URL look + PHP test code

$data = file_get_contents("https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/watch?v=_7s-6V_0nwA");
$json = json_decode($data);
var_dump($json);

Output

object(stdClass)[1]
  public 'width' => int 480
  public 'version' => string '1.0' (length=3)
  public 'thumbnail_width' => int 480
  public 'title' => string 'how to reminder in window as display message' (length=44)
  public 'provider_url' => string 'https://www.youtube.com/' (length=24)
  public 'thumbnail_url' => string 'https://i.ytimg.com/vi/_7s-6V_0nwA/hqdefault.jpg' (length=48)
  public 'author_name' => string 'H2 ZONE' (length=7)
  public 'type' => string 'video' (length=5)
  public 'author_url' => string 'https://www.youtube.com/channel/UC9M35YwDs8_PCWXd3qkiNzg' (length=56)
  public 'provider_name' => string 'YouTube' (length=7)
  public 'height' => int 270
  public 'html' => string '<iframe width="480" height="270" src="https://www.youtube.com/embed/_7s-6V_0nwA?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>' (length=171)
  public 'thumbnail_height' => int 360

For details, you can also see How to get a YouTube video thumbnail using id or https://www.youtube.com/watch?v=mXde7q59BI8 video tutorial 1

Method 2:

Using YouTube image link, https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg

Method 3:

Using browser source code for getting thumbnail using video URL link -go to video source code and search for thumbnailurl. Now you can use this URL into your source code:

{img src="https://img.youtube.com/vi/"insert-youtube-video-id-here"/default.jpg"}

For details you can also see How to get a YouTube video thumbnail using id or https://www.youtube.com/watch?v=9f6E8MeM6PI video tutorial 2

PHP cURL vs file_get_contents

This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.

On your exampe I would like to do this setup:

$ch =  curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);

This request will return data in 0.10 second max

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

Can I make a function available in every controller in angular?

You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.factory('myService', function() {
        return {
            foo: function() {
                alert("I'm foo!");
            }
        };
    });

    myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
        $scope.callFoo = function() {
            myService.foo();
        }
    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="callFoo()">Call foo</button>
</body>
</html>

If that's not an option for you, you can add it to the root scope like this:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.run(function($rootScope) {
        $rootScope.globalFoo = function() {
            alert("I'm global foo!");
        };
    });

    myApp.controller('MainCtrl', ['$scope', function($scope){

    }]);
    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="globalFoo()">Call global foo</button>
</body>
</html>

That way, all of your templates can call globalFoo() without having to pass it to the template from the controller.

jQuery removing '-' character from string

$mylabel.text("-123456");
var string = $mylabel.text().replace('-', '');

if you have done it that way variable string now holds "123456"

you can also (i guess the better way) do this...

$mylabel.text("-123456");
$mylabel.text(function(i,v){
   return v.replace('-','');
});

The most accurate way to check JS object's type?

Old question I know. You don't need to convert it. See this function:

function getType( oObj )
{
    if( typeof oObj === "object" )
    {
          return ( oObj === null )?'Null':
          // Check if it is an alien object, for example created as {world:'hello'}
          ( typeof oObj.constructor !== "function" )?'Object':
          // else return object name (string)
          oObj.constructor.name;              
    }   

    // Test simple types (not constructed types)
    return ( typeof oObj === "boolean")?'Boolean':
           ( typeof oObj === "number")?'Number':
           ( typeof oObj === "string")?'String':
           ( typeof oObj === "function")?'Function':false;

}; 

Examples:

function MyObject() {}; // Just for example

console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() );         // Function
console.log( getType( {} ));                    // Object
console.log( getType( [] ));                    // Array
console.log( getType( new MyObject() ));        // MyObject

var bTest = false,
    uAny,  // Is undefined
    fTest  function() {};

 // Non constructed standard types
console.log( getType( bTest ));                 // Boolean
console.log( getType( 1.00 ));                  // Number
console.log( getType( 2000 ));                  // Number
console.log( getType( 'hello' ));               // String
console.log( getType( "hello" ));               // String
console.log( getType( fTest ));                 // Function
console.log( getType( uAny ));                  // false, cannot produce
                                                // a string

Low cost and simple.

How can I install a CPAN module into a local directory?

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

Escape quotes in JavaScript

If you're assembling the HTML in Java, you can use this nice utility class from Apache commons-lang to do all the escaping correctly:

org.apache.commons.lang.StringEscapeUtils
Escapes and unescapes Strings for Java, Java Script, HTML, XML, and SQL.

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

When and where to use GetType() or typeof()?

typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.

GetType() is a method you call on individual objects, to get the execution-time type of the object.

Note that unless you only want exactly instances of TextBox (rather than instances of subclasses) you'd usually use:

if (myControl is TextBox)
{
    // Whatever
}

Or

TextBox tb = myControl as TextBox;
if (tb != null)
{
    // Use tb
}

Determine if two rectangles overlap each other?

Easiest way is

/**
 * Check if two rectangles collide
 * x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
 * x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
 */
boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)
{
  return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}

first of all put it in to your mind that in computers the coordinates system is upside down. x-axis is same as in mathematics but y-axis increases downwards and decrease on going upward.. if rectangle are drawn from center. if x1 coordinates is greater than x2 plus its its half of widht. then it means going half they will touch each other. and in the same manner going downward + half of its height. it will collide..

Generate random array of floats between a range

Why not use a list comprehension?

In Python 2

ran_floats = [random.uniform(low,high) for _ in xrange(size)]

In Python 3, range works like xrange(ref)

ran_floats = [random.uniform(low,high) for _ in range(size)]

How Should I Set Default Python Version In Windows?

Check which one the system is currently using:

python --version

Add the main folder location (e.g. C/ProgramFiles) and Scripts location (C/ProgramFiles/Scripts) to Environment Variables of the system. Add both 3.x version and 2.x version

Path location is ranked inside environment variable. If you want to use Python 2.x simply put path of python 2.x first, if you want for Python 3.x simply put 3.x first

This uses python 2

Is String.Contains() faster than String.IndexOf()?

If you really want to micro optimise your code your best approach is always benchmarking.

The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

I checked the line 35 of xampp/apache/conf/httpd.conf and it was:

ServerRoot "/xampp/apache"

Which doesn't exist. ...

Create the directory, or change the path to the directory that contains your hypertext documents.

What is a smart pointer and when should I use one?

Most kinds of smart pointers handle disposing of the pointer-to object for you. It's very handy because you don't have to think about disposing of objects manually anymore.

The most commonly-used smart pointers are std::tr1::shared_ptr (or boost::shared_ptr), and, less commonly, std::auto_ptr. I recommend regular use of shared_ptr.

shared_ptr is very versatile and deals with a large variety of disposal scenarios, including cases where objects need to be "passed across DLL boundaries" (the common nightmare case if different libcs are used between your code and the DLLs).

What is an abstract class in PHP?

  • Abstract Class contains only declare the method's signature, they can't define the implementation.
  • Abstraction class are defined using the keyword abstract .
  • Abstract Class is not possible to implement multiple inheritance.
  • Latest version of PHP 5 has introduces abstract classes and methods.
  • Classes defined as abstract , we are unable to create the object ( may not instantiated )

Jquery - How to make $.post() use contentType=application/json?

$.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
    ...
  }
})

See : jQuery.ajax()

Write variable to file, including name

Is something like this what you're looking for?

def write_vars_to_file(f, **vars):
    for name, val in vars.items():
        f.write("%s = %s\n" % (name, repr(val)))

Usage:

>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}

Initialize Array of Objects using NSArray

This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.

NSArray *data = @[@"The String Value"];

if you need to send more than just 1 string value, you could also use

NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];

then you can send it to the function like below

theFunction(data);

How to debug PDO database queries?

How to debug PDO mysql database queries in Ubuntu

TL;DR Log all your queries and tail the mysql log.

These directions are for my install of Ubuntu 14.04. Issue command lsb_release -a to get your version. Your install might be different.

Turn on logging in mysql

  1. Go to your dev server cmd line
  2. Change directories cd /etc/mysql. You should see a file called my.cnf. That’s the file we’re gonna change.
  3. Verify you’re in the right place by typing cat my.cnf | grep general_log. This filters the my.cnf file for you. You should see two entries: #general_log_file = /var/log/mysql/mysql.log && #general_log = 1.
  4. Uncomment those two lines and save via your editor of choice.
  5. Restart mysql: sudo service mysql restart.
  6. You might need to restart your webserver too. (I can’t recall the sequence I used). For my install, that’s nginx: sudo service nginx restart.

Nice work! You’re all set. Now all you have to do is tail the log file so you can see the PDO queries your app makes in real time.

Tail the log to see your queries

Enter this cmd tail -f /var/log/mysql/mysql.log.

Your output will look something like this:

73 Connect  xyz@localhost on your_db
73 Query    SET NAMES utf8mb4
74 Connect  xyz@localhost on your_db
75 Connect  xyz@localhost on your_db
74 Quit 
75 Prepare  SELECT email FROM customer WHERE email=? LIMIT ?
75 Execute  SELECT email FROM customer WHERE email='[email protected]' LIMIT 5
75 Close stmt   
75 Quit 
73 Quit 

Any new queries your app makes will automatically pop into view, as long as you continue tailing the log. To exit the tail, hit cmd/ctrl c.

Notes

  1. Careful: this log file can get huge. I’m only running this on my dev server.
  2. Log file getting too big? Truncate it. That means the file stays, but the contents are deleted. truncate --size 0 mysql.log.
  3. Cool that the log file lists the mysql connections. I know one of those is from my legacy mysqli code from which I'm transitioning. The third is from my new PDO connection. However, not sure where the second is coming from. If you know a quick way to find it, let me know.

Credit & thanks

Huge shout out to Nathan Long’s answer above for the inspo to figure this out on Ubuntu. Also to dikirill for his comment on Nathan’s post which lead me to this solution.

Love you stackoverflow!

Can we import XML file into another XML file?

Mads Hansen's solution is good but to succeed in reading the external file in .NET 4 took some time to figure out using hints in the comments about resolvers, ProhibitDTD and so on.

This is how it's done:

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Parse;
        XmlUrlResolver resolver = new XmlUrlResolver();
        resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
        settings.XmlResolver = resolver;
        var reader = XmlReader.Create("logfile.xml", settings);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        foreach (XmlElement element in doc.SelectNodes("//event"))
        {
            var ch = element.ChildNodes;
            var count = ch.Count;
        }

logfile.xml:

<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY events    
 SYSTEM "events.txt">
]>
<logfile>
&events;
</logfile>

events.txt:

<event>
    <item1>item1</item1>
    <item2>item2</item2>
</event>

Does List<T> guarantee insertion order?

As Bevan said, but keep in mind, that the list-index is 0-based. If you want to move an element to the front of the list, you have to insert it at index 0 (not 1 as shown in your example).

Difference between application/x-javascript and text/javascript content types

Use type="application/javascript"

In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.

http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Use "application/javascript", because "text/javascript" is obsolete:

RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt

  1. Deployed Scripting Media Types and Compatibility

    Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:

    +-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+

Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.

x-javascript is experimental, don't use it.

Wait for Angular 2 to load/resolve model before rendering view/template

Try {{model?.person.name}} this should wait for model to not be undefined and then render.

Angular 2 refers to this ?. syntax as the Elvis operator. Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it:

The Elvis Operator ( ?. ) and null property paths

The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

The current hero's name is {{currentHero?.firstName}}

Let’s elaborate on the problem and this particular solution.

What happens when the following data bound title property is null?

The title is {{ title }}

The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.

Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero.

The null hero's name is {{nullHero.firstName}}

JavaScript throws a null reference error and so does Angular:

TypeError: Cannot read property 'firstName' of null in [null]

Worse, the entire view disappears.

We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do.

On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually.

While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does.

Unfortunately, our app crashes when the currentHero is null.

We could code around that problem with NgIf

<!--No hero, div not displayed, no error --> <div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div>

Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.

The null hero's name is {{nullHero && nullHero.firstName}}

These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.

The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors.

<!-- No hero, no problem! --> The null hero's name is {{nullHero?.firstName}}

It works perfectly with long property paths too:

a?.b?.c?.d

Best way to store chat messages in a database?

You could create a database for x conversations which contains all messages of these conversations. This would allow you to add a new Database (or server) each time x exceeds. X is the number conversations your infrastructure supports (depending on your hardware,...).

The problem is still, that there may be big conversations (with a lot of messages) on the same database. e.g. you have database A and database B an each stores e.g. 1000 conversations. It my be possible that there are far more "big" conversations on server A than on server B (since this is user created content). You could add a "master" database that contains a lookup, on which database/server the single conversations can be found (or you have a schema to assign a database from hash/modulo or something).

Maybe you can find real world architectures that deal with the same problems (you may not be the first one), and that have already been solved.

React-Native: Module AppRegistry is not a registered callable module

restart packager worked for me. just kill react native packager and run it again.

WCF gives an unsecured or incorrectly secured fault error

I was getting this error due to the BasicHttpBinding not sending a compatible messageVersion to the service i was calling. My solution was to use a custom binding like below

 <bindings>
  <customBinding>
    <binding name="Soap11UserNameOverTransport" openTimeout="00:01:00" receiveTimeout="00:1:00" >
      <security authenticationMode="UserNameOverTransport">
      </security>          
      <textMessageEncoding messageVersion="Soap11WSAddressing10" writeEncoding="utf-8" />
      <httpsTransport></httpsTransport>
    </binding>
  </customBinding>      
</bindings>

Multipart forms from C# client

Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)

To send the data:

HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create("http://you.url.here");
oRequest.ContentType = "multipart/form-data; boundary=" + PostData.boundary;
oRequest.Method = "POST";
PostData pData = new PostData();
Encoding encoding = Encoding.UTF8;
Stream oStream = null;

/* ... set the parameters, read files, etc. IE:
   pData.Params.Add(new PostDataParam("email", "[email protected]", PostDataParamType.Field));
   pData.Params.Add(new PostDataParam("fileupload", "filename.txt", "filecontents" PostDataParamType.File));
*/

byte[] buffer = encoding.GetBytes(pData.GetPostData());

oRequest.ContentLength = buffer.Length;

oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();

HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();

The PostData class should look like:

public class PostData
{
    // Change this if you need to, not necessary
    public static string boundary = "AaB03x";

    private List<PostDataParam> m_Params;

    public List<PostDataParam> Params
    {
        get { return m_Params; }
        set { m_Params = value; }
    }

    public PostData()
    {
        m_Params = new List<PostDataParam>();
    }

    /// <summary>
    /// Returns the parameters array formatted for multi-part/form data
    /// </summary>
    /// <returns></returns>
    public string GetPostData()
    {
        StringBuilder sb = new StringBuilder();
        foreach (PostDataParam p in m_Params)
        {
            sb.AppendLine("--" + boundary);

            if (p.Type == PostDataParamType.File)
            {
                sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
                sb.AppendLine("Content-Type: application/octet-stream");
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
            else
            {
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
        }

        sb.AppendLine("--" + boundary + "--");

        return sb.ToString();
    }
}

public enum PostDataParamType
{
    Field,
    File
}

public class PostDataParam
{
    public PostDataParam(string name, string value, PostDataParamType type)
    {
        Name = name;
        Value = value;
        Type = type;
    }

    public PostDataParam(string name, string filename, string value, PostDataParamType type)
    {
        Name = name;
        Value = value;
        FileName = filename;
        Type = type;
    }

    public string Name;
    public string FileName;
    public string Value;
    public PostDataParamType Type;
}

How to group by month from Date field using sql

SQL Server 2012 version above,

SELECT  format(Closing_Date,'yyyy-MM') as ClosingMonth,
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY format(Closing_Date,'yyyy-MM'), Category;

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

Example for boost shared_mutex (multiple reads/one write)?

Just to add some more empirical info, I have been investigating the whole issue of upgradable locks, and Example for boost shared_mutex (multiple reads/one write)? is a good answer adding the important info that only one thread can have an upgrade_lock even if it is not upgraded, that is important as it means you cannot upgrade from a shared lock to a unique lock without releasing the shared lock first. (This has been discussed elsewhere but the most interesting thread is here http://thread.gmane.org/gmane.comp.lib.boost.devel/214394)

However I did find an important (undocumented) difference between a thread waiting for an upgrade to a lock (ie needs to wait for all readers to release the shared lock) and a writer lock waiting for the same thing (ie a unique_lock).

  1. The thread that is waiting for a unique_lock on the shared_mutex blocks any new readers coming in, they have to wait for the writers request. This ensures readers do not starve writers (however I believe writers could starve readers).

  2. The thread that is waiting for an upgradeable_lock to upgrade allows other threads to get a shared lock, so this thread could be starved if readers are very frequent.

This is an important issue to consider, and probably should be documented.

Proper way to restrict text input values (e.g. only numbers)

You can use the HTML5 input of type number

It does not accept any characters in its declaration

<input type="number" [(model)]='myvar' min=0 max=100 step=5 />

Here is an example of its usage with angular 2 [(model)]

http://www.webpackbin.com/VJNUNF0M-

How to delete a workspace in Eclipse?

I'm not sure about older versions, but from NEON onward, you can just right click on workspace and select Remove from launcher selection option.

Eclipse Neon - Remove Workspace

of course this won't remove the original files. It simply removes it from the list of suggested workspaces.

Best way to randomize an array with .NET

You don't need complicated algorithms.

Just one simple line:

Random random = new Random();
array.ToList().Sort((x, y) => random.Next(-1, 1)).ToArray();

Note that we need to convert the Array to a List first, if you don't use List in the first place.

Also, mind that this is not efficient for very large arrays! Otherwise it's clean & simple.

How to recursively download a folder via FTP on Linux

Just to complement the answer given by Thibaut Barrère.

I used

wget -r -nH --cut-dirs=5 -nc ftp://user:pass@server//absolute/path/to/directory

Note the double slash after the server name. If you don't put an extra slash the path is relative to the home directory of user.

  • -nH avoids the creation of a directory named after the server name
  • -nc avoids creating a new file if it already exists on the destination (it is just skipped)
  • --cut-dirs=5 allows to take the content of /absolute/path/to/directory and to put it in the directory where you launch wget. The number 5 is used to filter out the 5 components of the path. The double slash means an extra component.

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

Set a thin border using .css() in javascript

After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:

border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.

How to run bootRun with spring profile via gradle task

Simplest way would be to define default and allow it to be overridden. I am not sure what is the use of systemProperty in this case. Simple arguments will do the job.

def profiles = 'prod'

bootRun {
  args = ["--spring.profiles.active=" + profiles]
}

To run dev:

./gradlew bootRun -Pdev

To add dependencies on your task you can do something like this:

task setDevProperties(dependsOn: bootRun) << {
  doFirst {
    System.setProperty('spring.profiles.active', profiles)
  }
}

There are lots of ways achieving this in Gradle.

Edit:

Configure separate configuration files per environment.

if (project.hasProperty('prod')) {
  apply from: 'gradle/profile_prod.gradle'
} else {
  apply from: 'gradle/profile_dev.gradle'
}

Each configuration can override tasks for example:

def profiles = 'prod'
bootRun {
  systemProperty "spring.profiles.active", activeProfile
}

Run by providing prod flag in this case just like that:

./gradlew <task> -Pprod

PostgreSQL unnest() with element number

Postgres 9.4 or later

Use WITH ORDINALITY for set-returning functions:

When a function in the FROM clause is suffixed by WITH ORDINALITY, a bigint column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such as unnest().

In combination with the LATERAL feature in pg 9.3+, and according to this thread on pgsql-hackers, the above query can now be written as:

SELECT t.id, a.elem, a.nr
FROM   tbl AS t
LEFT   JOIN LATERAL unnest(string_to_array(t.elements, ','))
                    WITH ORDINALITY AS a(elem, nr) ON TRUE;

LEFT JOIN ... ON TRUE preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL:

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr);

Or simpler if based off an actual array (arr being an array column):

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr);

Or even, with minimal syntax:

SELECT id, a, ordinality
FROM   tbl, unnest(arr) WITH ORDINALITY a;

a is automatically table and column alias. The default name of the added ordinality column is ordinality. But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns.

Postgres 8.4 - 9.3

With row_number() OVER (PARTITION BY id ORDER BY elem) you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string.

You can simply omit ORDER BY:

SELECT *, row_number() OVER (PARTITION by id) AS nr
FROM  (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;

While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY. It happens to work due to an implementation detail.

To guarantee ordinal numbers of elements in the blank-separated string:

SELECT id, arr[nr] AS elem, nr
FROM  (
   SELECT *, generate_subscripts(arr, 1) AS nr
   FROM  (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
   ) sub;

Or simpler if based off an actual array:

SELECT id, arr[nr] AS elem, nr
FROM  (SELECT *, generate_subscripts(arr, 1) AS nr FROM tbl) t;

Related answer on dba.SE:

Postgres 8.1 - 8.4

None of these features are available, yet: RETURNS TABLE, generate_subscripts(), unnest(), array_length(). But this works:

CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function:

CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1, i
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

SELECT id, arr, (rec).*
FROM  (
   SELECT *, f_unnest_ord_idx(arr) AS rec
   FROM  (VALUES (1, '{a,b,c}'::text[])  --  short for: '[1:3]={a,b,c}'
               , (2, '[5:7]={a,b,c}')
               , (3, '[-9:-7]={a,b,c}')
      ) t(id, arr)
   ) sub;

 id |       arr       | val | ordinality | idx
----+-----------------+-----+------------+-----
  1 | {a,b,c}         | a   |          1 |   1
  1 | {a,b,c}         | b   |          2 |   2
  1 | {a,b,c}         | c   |          3 |   3
  2 | [5:7]={a,b,c}   | a   |          1 |   5
  2 | [5:7]={a,b,c}   | b   |          2 |   6
  2 | [5:7]={a,b,c}   | c   |          3 |   7
  3 | [-9:-7]={a,b,c} | a   |          1 |  -9
  3 | [-9:-7]={a,b,c} | b   |          2 |  -8
  3 | [-9:-7]={a,b,c} | c   |          3 |  -7

Compare:

ssh: The authenticity of host 'hostname' can't be established

Depending on your ssh client, you can set the StrictHostKeyChecking option to no on the command line, and/or send the key to a null known_hosts file. You can also set these options in your config file, either for all hosts or for a given set of IP addresses or host names.

ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no

EDIT

As @IanDunn notes, there are security risks to doing this. If the resource you're connecting to has been spoofed by an attacker, they could potentially replay the destination server's challenge back to you, fooling you into thinking that you're connecting to the remote resource while in fact they are connecting to that resource with your credentials. You should carefully consider whether that's an appropriate risk to take on before altering your connection mechanism to skip HostKeyChecking.

Reference.

Optimum way to compare strings in JavaScript?

You can use the localeCompare() method.

string_a.localeCompare(string_b);

/* Expected Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_a > string_b

 */

Further Reading:

Splitting strings in PHP and get last part

You can use array_pop combined with explode

Code:

$string = 'abc-123-xyz-789';
$output = array_pop(explode("-",$string));
echo $output;

DEMO: Click here

FontAwesome icons not showing. Why?

Make sure you include the rel and type as in " rel="stylesheet" type='text/css'" in the link to the awesomefont css file. Without these the file wasn't loading correctly for me.

Read text file into string. C++ ifstream

getline(fin, buffer, '\n')
where fin is opened file(ifstream object) and buffer is of string/char type where you want to copy line.

Hibernate SessionFactory vs. JPA EntityManagerFactory

I want to add on this that you can also get Hibernate's session by calling getDelegate() method from EntityManager.

ex:

Session session = (Session) entityManager.getDelegate();

Catching errors in Angular HttpClient

You probably want to have something like this:

this.sendRequest(...)
.map(...)
.catch((err) => {
//handle your error here
})

It highly depends also how do you use your service but this is the basic case.

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

fastest MD5 Implementation in JavaScript

js-md5 supports UTF-8 string, array, ArrayBuffer, AMD....

and fast. jsperf

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here