Programs & Examples On #Powerbuilder conversion

Basic authentication with fetch?

A simple example for copy-pasting into Chrome console:

fetch('https://example.com/path', {method:'GET', 
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));

endforeach in loops?

It's just a different syntax. Instead of

foreach ($a as $v) {
    # ...
}

You could write this:

foreach ($a as $v):
    # ...
endforeach;

They will function exactly the same; it's just a matter of style. (Personally I have never seen anyone use the second form.)

How can you test if an object has a specific property?

Just to clarify given the following object

$Object

With the following properties

type        : message
user        : [email protected]
text        : 
ts          : 11/21/2016 8:59:30 PM

The following are true

$Object.text -eq $NULL
$Object.NotPresent -eq $NULL

-not $Object.text
-not $Object.NotPresent

So the earlier answers that explicitly check for the property by name is the most correct way to verify that that property is not present.

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Minimal settings to prevent resize events

form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

var dt = new Date();
    var h =  dt.getHours(), m = dt.getMinutes();
    var thistime = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
console.log(thistime);

Here is the Demo

Error importing SQL dump into MySQL: Unknown database / Can't create database

This is a known bug at MySQL.

bug 42996
bug 40477

As you can see this has been a known issue since 2008 and they have not fixed it yet!!!

WORK AROUND
You first need to create the database to import. It doesn't need any tables. Then you can import your database.

  1. first start your MySQL command line (apply username and password if you need to)
    C:\>mysql -u user -p

  2. Create your database and exit

    mysql> DROP DATABASE database;  
    mysql> CREATE DATABASE database;  
    mysql> Exit  
    
  3. Import your selected database from the dump file
    C:\>mysql -u user -p -h localhost -D database -o < dumpfile.sql

You can replace localhost with an IP or domain for any MySQL server you want to import to. The reason for the DROP command in the mysql prompt is to be sure we start with an empty and clean database.

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

If you see this probably you are building in release mode. For production you should publish instead of building in release mode. For local development build in debug mode.

Loop through a Map with JSTL

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>

multiprocessing: How do I share a dict among multiple processes?

A general answer involves using a Manager object. Adapted from the docs:

from multiprocessing import Process, Manager

def f(d):
    d[1] += '1'
    d['2'] += 2

if __name__ == '__main__':
    manager = Manager()

    d = manager.dict()
    d[1] = '1'
    d['2'] = 2

    p1 = Process(target=f, args=(d,))
    p2 = Process(target=f, args=(d,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    print d

Output:

$ python mul.py 
{1: '111', '2': 6}

Tool to generate JSON schema from JSON data

GenSON (PyPI | Github) is a JSON Schema generator that can generate a single schema from multiple objects. You can also merge schemas with it. It is written in Python and comes with a CLI tool.

(Full disclosure: I'm the author.)

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

CSS Div stretch 100% page height

Use position absolute. Note that this isn't how we are generally used to using position absolute which requires manually laying things out or having floating dialogs. This will automatically stretch when you resize the window or the content. I believe that this requires standards mode but will work in IE6 and above.

Just replace the div with id 'thecontent' with your content (the specified height there is just for illustration, you don't have to specify a height on the actual content.

<div style="position: relative; width: 100%;">
      <div style="position: absolute; left: 0px; right: 33%; bottom: 0px; top: 0px; background-color: blue; width: 33%;" id="navbar">nav bar</div>
      <div style="position: relative; left: 33%; width: 66%; background-color: yellow;" id="content">
         <div style="height: 10000px;" id="thecontent"></div>
      </div>
</div>

The way that this works is that the outer div acts as a reference point for the nav bar. The outer div is stretched out by the content of the 'content' div. The nav bar uses absolute positioning to stretch itself out to the height of its parent. For the horizontal alignment we make the content div offset itself by the same width of the navbar.

This is made much easier with CSS3 flex box model, but that's not available in IE yet and has some of it's own quirks.

Which Protocols are used for PING?

Netscantools Pro Ping can do ICMP, UDP, and TCP.

Iptables setting multiple multiports in one rule

As a workaround to this limitation, I use two rules to cover all the cases.

For example, if I want to allow or deny these 18 ports:

465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666

I use the below rules:

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT

iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT

The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.

getFilesDir() vs Environment.getDataDirectory()

Try this

getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()

Disable and later enable all table indexes in Oracle

From here: http://forums.oracle.com/forums/thread.jspa?messageID=2354075

alter session set skip_unusable_indexes = true;

alter index your_index unusable;

do import...

alter index your_index rebuild [online];

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

HTTP COOKIES

Cookies are key/value pairs used by websites to store state information on the browser. Say you have a website (example.com), when the browser requests a webpage the website can send cookies to store information on the browser.

Browser request example:

GET /index.html HTTP/1.1
Host: www.example.com

Example answer from the server:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=10
Set-Cookie: bar=20; Expires=Fri, 30 Sep 2011 11:48:00 GMT
... rest  of the response

Here two cookies foo=10 and bar=20 are stored on the browser. The second one will expire on 30 September. In each subsequent request the browser will send the cookies back to the server.

GET /spec.html HTTP/1.1
Host: www.example.com
Cookie: foo=10; bar=20
Accept: */*

SESSIONS: Server side cookies

Server side cookies are known as "sessions". The website in this case stores a single cookie on the browser containing a unique Session Identifier. Status information (foo=10 and bar=20 above) are stored on the server and the Session Identifier is used to match the request with the data stored on the server.

Examples of usage

You can use both sessions and cookies to store: authentication data, user preferences, the content of a chart in an e-commerce website, etc...

Pros and Cons

Below pros and cons of the solutions. These are the first that comes to my mind, there are surely others.

Cookie Pros:

  • scalability: all the data is stored in the browser so each request can go through a load balancer to different webservers and you have all the information needed to fullfill the request;
  • they can be accessed via javascript on the browser;
  • not being on the server they will survive server restarts;
  • RESTful: requests don't depend on server state

Cookie Cons:

Session Pros:

  • generally easier to use, in PHP there's probably not much difference.
  • unlimited storage

Session Cons:

  • more difficult to scale
  • on web server restarts you can lose all sessions or not depending on the implementation
  • not RESTful

How to get the latest tag name in current branch in Git?

git describe --tags

returns the last tag able to be seen by current branch

How to convert a string of bytes into an int?

I was struggling to find a solution for arbitrary length byte sequences that would work under Python 2.x. Finally I wrote this one, it's a bit hacky because it performs a string conversion, but it works.

Function for Python 2.x, arbitrary length

def signedbytes(data):
    """Convert a bytearray into an integer, considering the first bit as
    sign. The data must be big-endian."""
    negative = data[0] & 0x80 > 0

    if negative:
        inverted = bytearray(~d % 256 for d in data)
        return -signedbytes(inverted) - 1

    encoded = str(data).encode('hex')
    return int(encoded, 16)

This function has two requirements:

  • The input data needs to be a bytearray. You may call the function like this:

    s = 'y\xcc\xa6\xbb'
    n = signedbytes(s)
    
  • The data needs to be big-endian. In case you have a little-endian value, you should reverse it first:

    n = signedbytes(s[::-1])
    

Of course, this should be used only if arbitrary length is needed. Otherwise, stick with more standard ways (e.g. struct).

jQuery - getting custom attribute from selected option

Simpler syntax if one form.

var option = $('option:selected').attr('mytag')

... if more than one form.

var option = $('select#myform option:selected').attr('mytag')

Clip/Crop background-image with CSS

You can put the graphic in a pseudo-element with its own dimensional context:

#graphic {
  position: relative;
  width: 200px;
  height: 100px;
}
#graphic::before {
  position: absolute;
  content: '';
  z-index: -1;
  width: 200px;
  height: 50px;
  background-image: url(image.jpg);
}

_x000D_
_x000D_
#graphic {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
    content: '';_x000D_
    _x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    z-index: -1;_x000D_
    _x000D_
    background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
_x000D_
_x000D_

Browser support is good, but if you need to support IE8, use a single colon :before. IE has no support for either syntax in versions prior to that.

failed to open stream: HTTP wrapper does not support writeable connections

you could use fopen() function.

some example:

$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';


    $newfname = $destination_folder .'myfile.mp4'; //set your file ext

    $file = fopen ($url, "rb");

    if ($file) {
      $newf = fopen ($newfname, "a"); // to overwrite existing file

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );

      }
    }

    if ($file) {
      fclose($file);
    }

    if ($newf) {
      fclose($newf);
    }

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

How to convert array values to lowercase in PHP?

`$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');

$strtolower = array_map('strtolower', $Color);

$strtoupper = array_map('strtoupper', $Color);

print_r($strtolower); print_r($strtoupper);`

How could I use requests in asyncio?

There is a good case of async/await loops and threading in an article by Pimin Konstantin Kefaloukos Easy parallel HTTP requests with Python and asyncio:

To minimize the total completion time, we could increase the size of the thread pool to match the number of requests we have to make. Luckily, this is easy to do as we will see next. The code listing below is an example of how to make twenty asynchronous HTTP requests with a thread pool of twenty worker threads:

# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures
import requests

async def main():

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor, 
                requests.get, 
                'http://example.org/'
            )
            for i in range(20)
        ]
        for response in await asyncio.gather(*futures):
            pass


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Why is my asynchronous function returning Promise { <pending> } instead of a value?

Your Promise is pending, complete it by

userToken.then(function(result){
console.log(result)
})

after your remaining code. All this code does is that .then() completes your promise & captures the end result in result variable & print result in console. Keep in mind, you cannot store the result in global variable. Hope that explanation might help you.

How to resolve "gpg: command not found" error during RVM installation?

As the instruction said "might need gpg2"

In mac, you can try install it with homebrew

$ brew install gpg2 

How to use OrderBy with findAll in Spring Data

Combining all answers above, you can write reusable code with BaseEntity:

@Data
@NoArgsConstructor
@MappedSuperclass
public abstract class BaseEntity {

  @Transient
  public static final Sort SORT_BY_CREATED_AT_DESC = 
                        Sort.by(Sort.Direction.DESC, "createdAt");

  @Id
  private Long id;
  private LocalDateTime createdAt;
  private LocalDateTime updatedAt;

  @PrePersist
  void prePersist() {
    this.createdAt = LocalDateTime.now();
  }

  @PreUpdate
  void preUpdate() {
    this.updatedAt = LocalDateTime.now();
  }
}

DAO object overloads findAll method - basically, still uses findAll()

public interface StudentDAO extends CrudRepository<StudentEntity, Long> {

  Iterable<StudentEntity> findAll(Sort sort);

}

StudentEntity extends BaseEntity which contains repeatable fields (maybe you want to sort by ID, as well)

@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@Entity
class StudentEntity extends BaseEntity {

  String firstName;
  String surname;

}

Finally, the service and usage of SORT_BY_CREATED_AT_DESC which probably will be used not only in the StudentService.

@Service
class StudentService {

  @Autowired
  StudentDAO studentDao;

  Iterable<StudentEntity> findStudents() {
    return this.studentDao.findAll(SORT_BY_CREATED_AT_DESC);
  }
}

Collection was modified; enumeration operation may not execute in ArrayList

I like to iterate backward using a for loop, but this can get tedious compared to foreach. One solution I like is to create an enumerator that traverses the list backward. You can implement this as an extension method on ArrayList or List<T>. The implementation for ArrayList is below.

    public static IEnumerable GetRemoveSafeEnumerator(this ArrayList list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

The implementation for List<T> is similar.

    public static IEnumerable<T> GetRemoveSafeEnumerator<T>(this List<T> list)
    {
        for (int i = list.Count - 1; i >= 0; i--)
        {
            // Reset the value of i if it is invalid.
            // This occurs when more than one item
            // is removed from the list during the enumeration.
            if (i >= list.Count)
            {
                if (list.Count == 0)
                    yield break;

                i = list.Count - 1;
            }

            yield return list[i];
        }
    }

The example below uses the enumerator to remove all even integers from an ArrayList.

    ArrayList list = new ArrayList() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    foreach (int item in list.GetRemoveSafeEnumerator())
    {
        if (item % 2 == 0)
            list.Remove(item);
    }

Convert String to int array in java

Saul's answer can be better implemented splitting the string like this:

string = string.replaceAll("[\\p{Z}\\s]+", "");
String[] array = string.substring(1, string.length() - 1).split(",");

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I also occured the error,and I sloved it by removing the curly braces,hope it will help someone else.

You can see that ,I did not put the con in the curly brace,and the error occured ,when I remove the burly brace , the error disappeared.

const modal = (props) => {
const { show, onClose } = props;

let con = <div className="modal" onClick={onClose}>
        {props.children}
        </div>;

return show === true ? (
    {con}
) : (
    <div>hello</div>
);

There are an article about the usage of the curly brace.click here

Setting format and value in input type="date"

try this :)

function getDefaultDate(){

    var now = new Date();
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    var today = now.getFullYear()+"-"+(month)+"-"+(day) ;

    return today;
}

$(document).ready(function(){ 
    $("#dateid").val( getDefaultDate()); 
});

Persistent invalid graphics state error when using ggplot2

I ran into this same error and solved it by running:

dev.off()

and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.

How to convert the time from AM/PM to 24 hour format in PHP?

Try with this

echo date("G:i", strtotime($time));

or you can try like this also

echo date("H:i", strtotime("04:25 PM"));

Get element by id - Angular2

if you want to set value than you can do the same in some function on click or on some event fire.

also you can get value using ViewChild using local variable like this

<input type='text' id='loginInput' #abc/>

and get value like this

this.abc.nativeElement.value

here is working example

Update

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

ngAfterViewInit(){
    document.getElementById('loginInput').value = '123344565';
  }

ngAfterViewInit will not throw any error because it will render after template loading

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

calling Jquery function from javascript

var jqueryFunction;

$().ready(function(){
    //jQuery function
    jqueryFunction = function( _msg )
    {
        alert( _msg );
    }
})

//javascript function
function jsFunction()
{
    //Invoke jQuery Function
    jqueryFunction("Call from js to jQuery");
}

http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/

How to encode a string in JavaScript for displaying in HTML?

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);

What exactly is the meaning of an API?

An API defines the interfaces by which one piece of software communicates with another at the source level. It provides abstraction by providing a standard set of interfaces - usually functions - that one piece of software (typically a higher-level piece) can invoke from another piece of software (usually a lower-level piece).

For example, an API might abstract the concept of drawing text on the screen through a family of functions that provide everything needed to draw the text. The API merely defines the interface; the piece of software that actually provides the API is known as the implementation of the API.

It is common to call an API a "contract". This is not correct, at least in the legal sense of the term, as an API is not a two-way agreement. The API user (generally, the higher-level software) has zero input into the API and its implementation. It may use the API as-is, or not use it at all: take it or leave it!

A real-world example of an API is the interfaces defined by the C standard and implemented by the standard C library. This API defines a family of basic and essential functions, such as memory management and string manipulation routines.

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

How to make Firefox headless programmatically in Selenium with Python?

The first answer does't work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

What is the difference between a function expression vs declaration in JavaScript?

Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.

To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.

Replacement for deprecated sizeWithFont: in iOS 7?

boundingRectWithSize:options:attributes:context:

How can I create a marquee effect?

Based on the previous reply, mainly @fcalderan, this marquee scrolls when hovered, with the advantage that the animation scrolls completely even if the text is shorter than the space within it scrolls, also any text length takes the same amount of time (this may be a pros or a cons) when not hovered the text return in the initial position.

No hardcoded value other than the scroll time, best suited for small scroll spaces

_x000D_
_x000D_
.marquee {_x000D_
    width: 100%;_x000D_
    margin: 0 auto;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden;_x000D_
    box-sizing: border-box;_x000D_
    display: inline-flex;    _x000D_
}_x000D_
_x000D_
.marquee span {_x000D_
    display: flex;        _x000D_
    flex-basis: 100%;_x000D_
    animation: marquee-reset;_x000D_
    animation-play-state: paused;                _x000D_
}_x000D_
_x000D_
.marquee:hover> span {_x000D_
    animation: marquee 2s linear infinite;_x000D_
    animation-play-state: running;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }    _x000D_
    50% {_x000D_
        transform: translate(-100%, 0);_x000D_
    }_x000D_
    50.001% {_x000D_
        transform: translate(100%, 0);_x000D_
    }_x000D_
    100% {_x000D_
        transform: translate(0%, 0);_x000D_
    }_x000D_
}_x000D_
@keyframes marquee-reset {_x000D_
    0% {_x000D_
        transform: translate(0%, 0);_x000D_
    }  _x000D_
}
_x000D_
<span class="marquee">_x000D_
    <span>This is the marquee text</span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to send POST in angularjs with multiple params?

Client Side

Data needs to be grouped in an object array as payload - Indata:

var Indata = {'product': $scope.product, 'product2': $scope.product2 };

Pass the payload through $http.post as the second argument:

$http.post("http://localhost:53263/api/Products/", Indata).then(function (data, status, headers, config) { 
    alert("success"); 
},function (data, status, headers, config) { 
    alert("error"); 
});

Server Side

Create a Data Transfer Object(DTO) class as such:

public class ExampleRequest {
   public string product {get; set;};
   public string product2 {get; set;};
}

The class below accepts DTO with the same property names which the payload is carrying.

public void Post(ExampleRequest request)
{
    var productRepository = new ProductRepository();
    var newProduct = productRepository.Save(request.product);
}

In above class, request contains 2 properties with values of product and product2

Creating a copy of a database in PostgreSQL

What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?

Answer:

CREATE DATABASE newdb WITH TEMPLATE originaldb;

Tried and tested.

Reading a resource file from within jar

To access a file in a jar you have two options:

  • Place the file in directory structure matching your package name (after extracting .jar file, it should be in the same directory as .class file), then access it using getClass().getResourceAsStream("file.txt")

  • Place the file at the root (after extracting .jar file, it should be in the root), then access it using Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt")

The first option may not work when jar is used as a plugin.

Is jQuery $.browser Deprecated?

From the documentation:

The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery.

So, yes, it is deprecated, but your existing implementations will continue to work. If the functionality is removed, it will likely be easily accessible using a plugin.

As to whether there is an alternative... The answer is "yes, probably". It is far, far better to do feature detection using $.support rather than browser detection: detect the actual feature you need, not the browser that provides it. Most important features that vary from browser to browser are detected with that.


Update 16 February 2013: In jQuery 1.9, this feature was removed (docs). It is far better not to use it. If you really, really must use its functionality, you can restore it with the jQuery Migrate plugin.

How to get pip to work behind a proxy server

at least pip3 also works without "=", however, instead of "http" you might need "https"

Final command, which worked for me:

sudo pip3 install --proxy https://{proxy}:{port} {BINARY}

How to use if, else condition in jsf to display image

It is illegal to nest EL expressions: you should inline them. Using JSTL is perfectly valid in your situation. Correcting the mistake, you'll make the code working:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core">
    <c:if test="#{not empty user or user.userId eq 0}">
        <a href="Images/thumb_02.jpg" target="_blank" ></a>
        <img src="Images/thumb_02.jpg" />
    </c:if>
    <c:if test="#{empty user or user.userId eq 0}">
        <a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
        <img src="/DisplayBlobExample?userId=#{user.userId}" />
    </c:if>
</html>

Another solution is to specify all the conditions you want inside an EL of one element. Though it could be heavier and less readable, here it is:

<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>

Read properties file outside JAR file

I have a similar case: wanting my *.jar file to access a file in a directory next to said *.jar file. Refer to THIS ANSWER as well.

My file structure is:

./ - the root of your program
|__ *.jar
|__ dir-next-to-jar/some.txt

I'm able to load a file (say, some.txt) to an InputStream inside the *.jar file with the following:

InputStream stream = null;
    try{
        stream = ThisClassName.class.getClass().getResourceAsStream("/dir-next-to-jar/some.txt");
    }
    catch(Exception e) {
        System.out.print("error file to stream: ");
        System.out.println(e.getMessage());
    }

Then do whatever you will with the stream

How to create a file in a directory in java?

To create a file and write some string there:

BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write("");         // for empty file
bufferedWriter.close();

This works for Mac and PC.

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

How to remove word wrap from textarea?

I found a way to make a textarea with all this working at the same time:

  • With horizontal scrollbar
  • Supporting multiline text
  • Text not wrapping

It works well on:

  • Chrome 15.0.874.120
  • Firefox 7.0.1
  • Opera 11.52 (1100)
  • Safari 5.1 (7534.50)
  • IE 8.0.6001.18702

Let me explain how i get to that: I was using Chrome inspector integrated tool and I saw values on CSS styles, so I try these values, instead of normal ones... trial & errors till I got it reduced to minimum and here it is for anyone that wants it.

In the CSS section I used just this for Chrome, Firefox, Opera and Safari:

textarea {
  white-space:nowrap;
  overflow:scroll;
}

In the CSS section I used just this for IE:

textarea {
  overflow:scroll;
}

It was a bit tricky, but there is the CSS.

An (x)HTML tag like this:

<textarea id="myTextarea" rows="10" cols="15"></textarea>

And at the end of the <head> section a JavaScript like this:

 window.onload=function(){
   document.getElementById("myTextarea").wrap='off';
 }

The JavaScript is for making the W3C validator passing XHTML 1.1 Strict, since the wrap attribute is not official and thus cannot be an (x)HTML tag directly, but most browsers handle it, so after loading the page it sets that attribute.

Hope this can be tested on more browsers and versions and help someone to improve it and makes it fully cross-browser for all versions.

How do you create a Distinct query in HQL

You can you the distinct keyword in you criteria builder like this.

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Orders> query = builder.createQuery(Orders.class);
Root<Orders> root = query.from(Orders.class);
query.distinct(true).multiselect(root.get("cust_email").as(String.class));

And create the field constructor in your model class.

How do I set Tomcat Manager Application User Name and Password for NetBeans?

One simple way to check your changes to that file in Tomcat 8 + is to open a browser to: http://localhost:8080/manager/text/list

What is the difference between Jupyter Notebook and JupyterLab?

(I am using JupyterLab with Julia)

First thing is that Jupyter lab from my previous use offers more 'themes' which is great on the eyes, and also fontsize changes independent of the browser, so that makes it closer to that of an IDE. There are some specifics I like such as changing the 'code font size' and leaving the interface font size to be the same.

Major features that are great is

  • the drag and drop of cells so that you can easily rearrange the code
  • collapsing cells with a single mouse click and a small mark to remind of their placement

What is paramount though is the ability to have split views of the tabs and the terminal. If you use Emacs, then you probably enjoyed having multiple buffers with horizontal and vertical arrangements with one of them running a shell (terminal), and with jupyterlab this can be done, and the arrangement is made with drags and drops which in Emacs is typically done with sets of commands.

(I do not believe that there is a learning curve added to those that have not used the 'notebook' original version first. You can dive straight into this IDE experience)

Embed an External Page Without an Iframe?

You could load the external page with jquery:

<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script>
<div id="testLoad"></div>
//would this help

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

yield from basically chains iterators in a efficient way:

# chain from itertools:
def chain(*iters):
    for it in iters:
        for item in it:
            yield item

# with the new keyword
def chain(*iters):
    for it in iters:
        yield from it

As you can see it removes one pure Python loop. That's pretty much all it does, but chaining iterators is a pretty common pattern in Python.

Threads are basically a feature that allow you to jump out of functions at completely random points and jump back into the state of another function. The thread supervisor does this very often, so the program appears to run all these functions at the same time. The problem is that the points are random, so you need to use locking to prevent the supervisor from stopping the function at a problematic point.

Generators are pretty similar to threads in this sense: They allow you to specify specific points (whenever they yield) where you can jump in and out. When used this way, generators are called coroutines.

Read this excellent tutorials about coroutines in Python for more details

How to use timeit module

import timeit


def oct(x):
   return x*x


timeit.Timer("for x in range(100): oct(x)", "gc.enable()").timeit()

Add attribute 'checked' on click jquery

It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr() method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]

IE has some problems with the DOM setAttribute method but in this case it should be fine:

this.setAttribute("checked", "checked");

In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked attribute, you need to set the checked property as well:

this.setAttribute("checked", "checked");
this.checked = true;

To uncheck the checkbox and remove the attribute, do the following:

this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;

Best way to reverse a string

Sorry for posting on this old thread. I am practicing some code for an interview.

This was what I came up with for C#. My first version before refactoring was horrible.

static String Reverse2(string str)
{
    int strLen = str.Length, elem = strLen - 1;
    char[] charA = new char[strLen];

    for (int i = 0; i < strLen; i++)
    {
        charA[elem] = str[i];
        elem--;
    }

    return new String(charA);
}

In Contrast to the Array.Reverse method below, it appears faster with 12 characters or less in the string. After 13 characters, the Array.Reverse starts to get faster, and it eventually dominates pretty heavily on speed. I just wanted to point out approximately where the speed starts to change.

static String Reverse(string str)
{     
    char[] charA = str.ToCharArray();

    Array.Reverse(charA);

    return new String(charA);
}

At 100 characters in the string, it is faster than my version x 4. However, if I knew that the strings would always be less than 13 characters, I would use the one I made.

Testing was done with Stopwatch and 5000000 iterations. Also, I'm not sure if my version handles Surrogates or combined character situations with Unicode encoding.

Node update a specific package

Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).

npm update browser-sync
-------
yarn upgrade browser-sync
  • Use npm|yarn outdated to see which modules have newer versions
  • Use npm update|yarn upgrade (without a package name) to update all modules
  • Include --save-dev|--dev if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary for devDependencies).

Major version upgrades:

In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x by doing:

npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev

...or the latest 2.1.x by doing:

npm install [email protected] --save-dev
-------
yarn add [email protected] --dev

...or the latest and greatest by doing:

npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev

Note: the last one is no different than doing this:

npm uninstall browser-sync --save-dev
npm install browser-sync --save-dev
-------
yarn remove browser-sync --dev
yarn add browser-sync --dev

The --save-dev part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.

Redis: How to access Redis log file

The log file will be where the configuration file (usually /etc/redis/redis.conf) says it is :)

By default, logfile stdout which probably isn't what you are looking for. If redis is running daemonized, then that log configuration means logs will be sent to /dev/null, i.e. discarded.

Summary: set logfile /path/to/my/log/file.log in your config and redis logs will be written to that file.

How to print struct variables in console?

package main

import "fmt"

type Project struct {
    Id int64 `json:"id"`
    Title string `json:"title"`
}

func (p Project) String() string {
    return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title)
}

func main() {
    var instance Project
    Instance = Project{Id: 100, Title: "Print Struct"}
    fmt.Printf("%v\n", Instance)
}

Set 4 Space Indent in Emacs in Text Mode

Do not confuse variable tab-width with variable tab-stop-list. The former is used for the display of literal TAB characters. The latter controls what characters are inserted when you press the TAB character in certain modes.

-- GNU Emacs Manual

(customize-variable (quote tab-stop-list))

or add tab-stop-list entry to custom-set-variables in .emacs file:

(custom-set-variables
  ;; custom-set-variables was added by Custom.
  ;; If you edit it by hand, you could mess it up, so be careful.
  ;; Your init file should contain only one such instance.
  ;; If there is more than one, they won't work right.
 '(tab-stop-list (quote (4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120))))

Another way to edit the tab behavior is with with M-x edit-tab-stops.

See the GNU Emacs Manual on Tab Stops for more information on edit-tab-stops.

How can I perform a short delay in C# without using sleep?

You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.

PHP - remove <img> tag from string

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How to convert date to timestamp?

Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:

var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000

Sass Variable in CSS calc() function

To use $variables inside your calc() of the height property:

HTML:

<div></div>

SCSS:

$a: 4em;

div {
  height: calc(#{$a} + 7px);
  background: #e53b2c;
}

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

And what something like this?

public class Carrier : Entity
{
    public Carrier()
    {
         this.Id = Guid.NewGuid();
    }  
    public Guid Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

How to get sp_executesql result into a variable?

Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.

In the below, @i will return 2727

DECLARE @s NVARCHAR(500)
DECLARE @i INT;
SET @s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC @i = sys.sp_executesql @s
SELECT @i AS 'Blah'

SSMS will show this Msg 2727, Level 11, State 1, Line 1 Cannot find index 'NonExistantStaticsName'.

How to use Monitor (DDMS) tool to debug application

Could it be a problem with past preview versions of Android Studio ? nowadays "beta" has replaced the "preview". I try it out step by step debugging while using Memory Monitor at same time by Android Studio (Beta) 0.8.11 on OSX 10.9.5 without any problems.

The tutorial Debugging with Android Studio also helps, specially this paragraph :

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. On the Android DDMS tool window, select the Devices | logcat tab.
  4. Select your device from the dropdown list.
  5. Select your app by its package name from the list of running apps.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking

Here a couple of screenshot while debugging step by step on a breakpoint a monitoring the memory on the emulator:
breakpointmemory monitor

outline on only one border

I like to give my input field a border, remove the outline on focus, and "outline" the border instead:

input {
  border: 1px solid grey;

  &:focus {
    outline: none;
    border-left: 1px solid violet;
  }
 }

You can also do it with a transparent border:

input {
  border: 1px solid transparent;

  &:focus {
    outline: none;
    border-left: 1px solid violet;
  }
 }

How to register ASP.NET 2.0 to web server(IIS7)?

If you installed IIS after the .Net framework you can solve the porblem by re-installing the .Net framework. Part of its install detects whether IIS is present and updates IIS accordingly.

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  }
  document.write( html );
})();

¹ I haven't got enough reputation to comment on his answer

Using GSON to parse a JSON array

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

Seems to work fine. But there is an extra , Comma in your string.

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

The differences between initialize, define, declare a variable

For C, at least, per C11 6.7.5:

A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

  • for an object, causes storage to be reserved for that object;

  • for a function, includes the function body;

  • for an enumeration constant, is the (only) declaration of the identifier;

  • for a typedef name, is the first (or only) declaration of the identifier.

Per C11 6.7.9.8-10:

An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.

So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.

Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).

So, if you define an automatic variable without specifying an initial value for it, such as:

int myfunc(void) {
    int myvar;
    ...

You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.

How do I get the current time only in JavaScript

You can simply use this methods.

_x000D_
_x000D_
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit", hour12: false }));
console.log(new Date().toLocaleTimeString([], { hour: '2-digit', minute: "2-digit" }));
_x000D_
_x000D_
_x000D_

What does void mean in C, C++, and C#?

If you're explaining the concept to a beginner, it might be helpful to use an analogy. The use of void in all these cases is analogous in meaning to a page in a book which has the following words, "This page left intentionally blank." It is to differentiate to the compiler between something which should be flagged as an error, versus a type which is intentionally to be left blank because that is the behavior you want.

It always appears in code where normally you would expect to see a type appear, such as a return type or a pointer type. This is why in C#, void maps to an actual CLR type, System.Void because it is a type in itself.

Some programming languages never developed the concept of void, just like some human cultures never invented the concept of the number zero. Void represents the same advancement in a programming language as the concept of zero represents to human language.

Joining 2 SQL SELECT result sets into one

SELECT table1.col_a, table1.col_b, table2.col_c 
  FROM table1 
  INNER JOIN table2 ON table1.col_a = table2.col_a

Cannot implicitly convert type from Task<>

Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

How to check the differences between local and github before the pull

And another useful command to do this (after git fetch) is:

git log origin/master ^master

This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Table relationships vs. entity relationships

In a relational database system, there can be only three types of table relationships:

  • one-to-many (via a Foreign Key column)
  • one-to-one (via a shared Primary Key)
  • many-to-many (via a link table with two Foreign Keys referencing two separate parent tables)

So, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

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

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

So, you have two sides that can change the entity association:

  • By adding an entry in the comments child collection, a new post_comment row should be associated with the parent post entity via its post_id column.
  • By setting the post property of the PostComment entity, the post_id column should be updated as well.

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy (a.k.a the inverse side)

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

It's called the inverse side because it references the child entity property that manages this table relationship.

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

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

According to RFC 4329 the correct MIME type for JavaScript should be application/javascript. Howerver, older IE versions choke on this since they expect text/javascript.

alert() not working in Chrome

I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.

The solution was as simple as closing the tab and opening a fresh one!

Store text file content line by line into array

Try this:

String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
int i=0;
while((str = in.readLine()) != null)          
    arr[i++] = str;

System.out.println(Arrays.toString(arr));

How to disable gradle 'offline mode' in android studio?

On Windows:-

Go to File -> Settings.

And open the 'Build,Execution,Deployment'. Then open the

Build Tools -> Gradle

Then uncheck -> Offline work on the right.

Click the OK button.

Then Rebuild the Project.

On Mac OS:-

go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image

[For Mac go 1

enter image description here

Making a POST call instead of GET using urllib2

This may have been answered before: Python URLLib / URLLib2 POST.

Your server is likely performing a 302 redirect from http://myserver/post_service to http://myserver/post_service/. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url to http://myserver/post_service/.

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

Instead of using For each loop, use normal for loop. for example,the below code removes all the element in the array list without giving java.util.ConcurrentModificationException. You can modify the condition in the loop according to your use case.

for(int i=0; i<abc.size(); i++)  {
       e.remove(i);
 }

In .NET, which loop runs faster, 'for' or 'foreach'?

Jeffrey Richter talked the performance difference between for and foreach on a recent podcast: http://pixel8.infragistics.com/shows/everything.aspx#Episode:9317

Superscript in markdown (Github flavored)?

<sup> and <sub> tags work and are your only good solution for arbitrary text. Other solutions include:

Unicode

If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.

I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:

  • ° SUPERSCRIPT ZERO (U+2070)
  • ¹ SUPERSCRIPT ONE (U+00B9)
  • ² SUPERSCRIPT TWO (U+00B2)
  • ³ SUPERSCRIPT THREE (U+00B3)
  • n SUPERSCRIPT LATIN SMALL LETTER N (U+207F)

People also often reach for <sup> and <sub> tags in an attempt to render specific symbols like these:

  • TRADE MARK SIGN (U+2122)
  • ® REGISTERED SIGN (U+00AE)
  • ? SERVICE MARK (U+2120)

Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.

Alternatively, you could use the hex values above in an HTML character escape. Eg, &#x00B2; instead of ². This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.

Images

If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:

![Alt text goes here, if you'd like](path/to/image.png) 

You can use a full path (eg. starting with https:// or http://) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.

If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.

How to TryParse for Enum value?

This method will convert a type of enum:

  public static TEnum ToEnum<TEnum>(object EnumValue, TEnum defaultValue)
    {
        if (!Enum.IsDefined(typeof(TEnum), EnumValue))
        {
            Type enumType = Enum.GetUnderlyingType(typeof(TEnum));
            if ( EnumValue.GetType() == enumType )
            {
                string name = Enum.GetName(typeof(HLink.ViewModels.ClaimHeaderViewModel.ClaimStatus), EnumValue);
                if( name != null)
                    return (TEnum)Enum.Parse(typeof(TEnum), name);
                return defaultValue;
            }
        }
        return (TEnum)Enum.Parse(typeof(TEnum), EnumValue.ToString());
    } 

It checks the underlying type and get the name against it to parse. If everything fails it will return default value.

How to check if a variable is an integer or a string?

Depending on your definition of shortly, you could use one of the following options:

Use of for_each on map elements

You can iterate through a std::map object. Each iterator will point to a std::pair<const T,S> where T and S are the same types you specified on your map.

Here this would be:

for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)
{
  it->second.Method();
}

If you still want to use std::for_each, pass a function that takes a std::pair<const int, MyClass>& as an argument instead.

Example:

void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well
{
  pair.second.Method();
}

And pass it to std::for_each:

std::for_each(Map.begin(), Map.end(), CallMyMethod);

XAMPP - Apache could not start - Attempting to start Apache service

I had the same issue, executing "setup_xampp.bat" in xampp folder solved my issue.

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

How to use a filter in a controller?

It seems nobody has mentioned that you can use a function as arg2 in $filter('filtername')(arg1,arg2);

For example:

$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});

RegEx - Match Numbers of Variable Length

{[0-9]+:[0-9]+}

try adding plus(es)

Get product id and product type in magento?

you can get all product information from following code

$product_id=6//Suppose
$_product=Mage::getModel('catalog/product')->load($product_id);


    $product_data["id"]=$_product->getId();
    $product_data["name"]=$_product->getName();
    $product_data["short_description"]=$_product->getShortDescription();
    $product_data["description"]=$_product->getDescription();
    $product_data["price"]=$_product->getPrice();
    $product_data["special price"]=$_product->getFinalPrice();
    $product_data["image"]=$_product->getThumbnailUrl();
    $product_data["model"]=$_product->getSku();
    $product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value


    $storeId = Mage::app()->getStore()->getId();
    $summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
    $product_data["rating"]=($summaryData['rating_summary']*5)/100;

    $product_data["shipping"]=Mage::getStoreConfig('carriers/flatrate/price');

    if($_product->isSalable() ==1)
        $product_data["in_stock"]=1;
    else
        $product_data["in_stock"]=0;


    echo "<pre>";
    print_r($product_data);
    //echo "</pre>";

How to use multiple databases in Laravel

Also you can use postgres fdw system

https://www.postgresql.org/docs/9.5/postgres-fdw.html

You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Java, unlike languages like C and C++, treats boolean as a completely separate data type which has 2 distinct values: true and false. The values 1 and 0 are of type int and are not implicitly convertible to boolean.

How to use a RELATIVE path with AuthUserFile in htaccess?

1) Note that it is considered insecure to have the .htpasswd file below the server root.

2) The docs say this about relative paths, so it looks you're out of luck:

File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the ServerRoot.

3) While the answers recommending the use of environment variables work perfectly fine, I would prefer to put a placeholder in the .htaccess file, or have different versions in my codebase, and have the deployment process set it all up (i. e. replace placeholders or rename / move the appropriate file).

On Java projects, I use Maven to do this type of work, on, say, PHP projects, I like to have a build.sh and / or install.sh shell script that tunes the deployed files to their environment. This decouples your codebase from the specifics of its target environment (i. e. its environment variables and configuration parameters). In general, the application should adapt to the environment, if you do it the other way around, you might run into problems once the environment also has to cater for different applications, or for completely unrelated, system-specific requirements.

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

Java 7 introduced stricter verification and changed the class format a bit—to contain a stack map used to verify that code is correct. The exception you see means that some method doesn't have a valid stack map.

Java version or bytecode instrumentation could both be to blame. Usually this means that a library used by the application generates invalid bytecode that doesn't pass the stricter verification. So nothing else than reporting it as a bug to the library can be done by the developer.

As a workaround you can add -noverify to the JVM arguments in order to disable verification. In Java 7 it was also possible to use -XX:-UseSplitVerifier to use the less strict verification method, but that option was removed in Java 8.

Convert JSON array to an HTML table in jQuery

One simple way of doing this is:

_x000D_
_x000D_
var data = [{_x000D_
  "Total": 34,_x000D_
  "Version": "1.0.4",_x000D_
  "Office": "New York"_x000D_
}, {_x000D_
  "Total": 67,_x000D_
  "Version": "1.1.0",_x000D_
  "Office": "Paris"_x000D_
}];_x000D_
_x000D_
drawTable(data);_x000D_
_x000D_
function drawTable(data) {_x000D_
_x000D_
  // Get Table headers and print_x000D_
  var head = $("<tr />")_x000D_
  $("#DataTable").append(head);_x000D_
  for (var j = 0; j < Object.keys(data[0]).length; j++) {_x000D_
    head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));_x000D_
  }_x000D_
_x000D_
  // Print the content of rows in DataTable_x000D_
  for (var i = 0; i < data.length; i++) {_x000D_
    drawRow(data[i]);_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function drawRow(rowData) {_x000D_
  var row = $("<tr />")_x000D_
  $("#DataTable").append(row);_x000D_
  row.append($("<td>" + rowData["Total"] + "</td>"));_x000D_
  row.append($("<td>" + rowData["Version"] + "</td>"));_x000D_
  row.append($("<td>" + rowData["Office"] + "</td>"));_x000D_
}
_x000D_
table {_x000D_
  border: 1px solid #666;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
th {_x000D_
  background: #f8f8f8;_x000D_
  font-weight: bold;_x000D_
  padding: 2px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table id="DataTable"></table>
_x000D_
_x000D_
_x000D_

Convert List<Object> to String[] in Java

Using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());

Does file_get_contents() have a timeout setting?

The default timeout is defined by default_socket_timeout ini-setting, which is 60 seconds. You can also change it on the fly:

ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes

Another way to set a timeout, would be to use stream_context_create to set the timeout as HTTP context options of the HTTP stream wrapper in use:

$ctx = stream_context_create(array('http'=>
    array(
        'timeout' => 1200,  //1200 Seconds is 20 Minutes
    )
));

echo file_get_contents('http://example.com/', false, $ctx);

%i or %d to print integer in C using printf()?

%d seems to be the norm for printing integers, I never figured out why, they behave identically.

SQLite: How do I save the result of a query as a CSV file?

All the existing answers only work from the sqlite command line, which isn't ideal if you'd like to build a reusable script. Python makes it easy to build a script that can be executed programatically.

import pandas as pd
import sqlite3

conn = sqlite3.connect('your_cool_database.sqlite')

df = pd.read_sql('SELECT * from orders', conn)
df.to_csv('orders.csv', index = False)

You can customize the query to only export part of the sqlite table to the CSV file.

You can also run a single command to export all sqlite tables to CSV files:

for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
    t = table[0]
    df = pd.read_sql('SELECT * from ' + t, conn)
    df.to_csv(t + '_one_command.csv', index = False)

See here for more info.

How to convert a Title to a URL slug in jQuery?

function slugify(text){
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\u0100-\uFFFF\w\-]/g,'-') // Remove all non-word chars ( fix for UTF-8 chars )
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}

*based on https://gist.github.com/mathewbyrne/1280286

now you can transform this string:

Barack_Obama       ?????_????? ~!@#$%^&*()+/-+?><:";'{}[]\|`

into:

barack_obama-?????_?????

applying to your code:

$("#Restaurant_Name").keyup(function(){
    var Text = $(this).val();
    Text = slugify(Text);
    $("#Restaurant_Slug").val(Text);
});

Unzip files programmatically in .net

Standard zip files normally use the deflate algorithm.

To extract files without using third party libraries use DeflateStream. You'll need a bit more information about the zip file archive format as Microsoft only provides the compression algorithm.

You may also try using zipfldr.dll. It is Microsoft's compression library (compressed folders from the Send to menu). It appears to be a com library but it's undocumented. You may be able to get it working for you through experimentation.

Find object by its property in array of objects with AngularJS way

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73}) 

or in your HTML

{{ myArray | filter : {'id':73} }}

Pandas: convert dtype 'object' to int

Documenting the answer that worked for me based on the comment by @piRSquared.

I needed to convert to a string first, then an integer.

>>> df['purchase'].astype(str).astype(int)

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

I was able to solve this problem with these steps:

  1. Uninstall JDK java
  2. Reinstall java, download JDK installer
  3. Add/Update the JAVA_HOME variable to JDK install folder

How to insert newline in string literal?

I like more the "pythonic way"

List<string> lines = new List<string> {
    "line1",
    "line2",
    String.Format("{0} - {1} | {2}", 
        someVar,
        othervar, 
        thirdVar
    )
};

if(foo)
    lines.Add("line3");

return String.Join(Environment.NewLine, lines);

What are some reasons for jquery .focus() not working?

Only "keyboard focusable" elements can be focused with .focus(). div aren't meant to be natively focusable. You have to add tabindex="0" attributes to it to achieve that. input, button, a etc... are natively focusable.

How should I store GUID in MySQL tables?

The GuidToBinary routine posted by KCD should be tweaked to account for the bit layout of the timestamp in the GUID string. If the string represents a version 1 UUID, like those returned by the uuid() mysql routine, then the time components are embedded in letters 1-G, excluding the D.

12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
12345678 = least significant 4 bytes of the timestamp in big endian order
9ABC     = middle 2 timestamp bytes in big endian
D        = 1 to signify a version 1 UUID
EFG      = most significant 12 bits of the timestamp in big endian

When you convert to binary, the best order for indexing would be: EFG9ABC12345678D + the rest.

You don't want to swap 12345678 to 78563412 because big endian already yields the best binary index byte order. However, you do want the most significant bytes moved in front of the lower bytes. Hence, EFG go first, followed by the middle bits and lower bits. Generate a dozen or so UUIDs with uuid() over the course of a minute and you should see how this order yields the correct rank.

select uuid(), 0
union 
select uuid(), sleep(.001)
union 
select uuid(), sleep(.010)
union 
select uuid(), sleep(.100)
union 
select uuid(), sleep(1)
union 
select uuid(), sleep(10)
union
select uuid(), 0;

/* output */
6eec5eb6-9755-11e4-b981-feb7b39d48d6
6eec5f10-9755-11e4-b981-feb7b39d48d6
6eec8ddc-9755-11e4-b981-feb7b39d48d6
6eee30d0-9755-11e4-b981-feb7b39d48d6
6efda038-9755-11e4-b981-feb7b39d48d6
6f9641bf-9755-11e4-b981-feb7b39d48d6
758c3e3e-9755-11e4-b981-feb7b39d48d6 

The first two UUIDs were generated closest in time. They only vary in the last 3 nibbles of the first block. These are the least significant bits of the timestamp, which means we want to push them to the right when we convert this to an indexable byte array. As a counter example, the last ID is the most current, but the KCD's swapping algorithm would put it before the 3rd ID (3e before dc, last bytes from the first block).

The correct order for indexing would be:

1e497556eec5eb6... 
1e497556eec5f10... 
1e497556eec8ddc... 
1e497556eee30d0... 
1e497556efda038... 
1e497556f9641bf... 
1e49755758c3e3e... 

See this article for supporting information: http://mysql.rjweb.org/doc.php/uuid

*** note that I don't split the version nibble from the high 12 bits of the timestamp. This is the D nibble from your example. I just throw it in front. So my binary sequence ends up being DEFG9ABC and so on. This implies that all my indexed UUIDs start with the same nibble. The article does the same thing.

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Try the following way:

<input type="submit" value="Search" class="search-btn" />
<a href="javascript:;" onclick="$('.search-btn').click();">Go</a>

In Java, what is the best way to determine the size of an object?

If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();

edit: I thought this might be helpful as the question author also stated he would like to have logic that handles "read as many rows as possible until I've used 32MB of memory."

adb uninstall failed

Try disable "Instant run" from settings window

Convert php array to Javascript

You do not have to call parseJSON since the output of json_encode is a javascript literal. Just assign it to a js variable.

<script type="text/javascript">
    //Assign php generated json to JavaScript variable
    var tempArray = <?php echo json_encode($php_array); ?>;

   //You will be able to access the properties as 
    alert(tempArray[0].Key);
</script>

How do I do a multi-line string in node.js?

Take a look at the mstring module for node.js.

This is a simple little module that lets you have multi-line strings in JavaScript.

Just do this:

var M = require('mstring')

var mystring = M(function(){/*** Ontario Mining and Forestry Group ***/})

to get

mystring === "Ontario\nMining and\nForestry\nGroup"

And that's pretty much it.

How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.

Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.


note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.

Here are some options that I use.

  1. Test your web page locally on Firefox, then deploy to your host.
  2. or: Run a local server

Test on Firefox, Deploy to Host

  1. Firefox currently allows Cross Origin Requests from files served from your hard drive
  2. Your web hosting site will allow requests to files in folders as configured by the manifest file

Run a Local Server

  • Run a server on your computer, like Apache or Python
  • Python isn't a server, but it will run a simple server

Run a Local Server with Python

Get your IP address:

  • On Windows: Open up the 'Command Prompt'. All Programs, Accessories, Command Prompt
  • I always run the Command Prompt as Administrator. Right click the Command Prompt menu item and look for Run As Administrator
  • Type the command: ipconfig and hit Enter.
  • Look for: IPv4 Address . . . . . . . . 12.123.123.00
  • There are websites that will also display your IP address

If you don't have Python, download and install it.

Using the 'Command Prompt' you must go to the folder where the files are that you want to serve as a webpage.

  • If you need to get back to the C:\ Root directory - type cd/
  • type cd Drive:\Folder\Folder\etc to get to the folder where your .Html file is (or php, etc)
  • Check the path. type: path at the command prompt. You must see the path to the folder where python is located. For example, if python is in C:\Python27, then you must see that address in the paths that are listed.
  • If the path to the Python directory is not in the path, you must set the path. type: help path and hit Enter. You will see help for path.
  • Type something like: path c:\python27 %path%
  • %path% keeps all your current paths. You don't want to wipe out all your current paths, just add a new path.
  • Create the new path FROM the folder where you want to serve the files.
  • Start the Python Server: Type: python -m SimpleHTTPServer port Where 'port' is the number of the port you want, for example python -m SimpleHTTPServer 1337
  • If you leave the port empty, it defaults to port 8000
  • If the Python server starts successfully, you will see a msg.

Run You Web Application Locally

  • Open a browser
  • In the address line type: http://your IP address:port
  • http://xxx.xxx.x.x:1337 or http://xx.xxx.xxx.xx:8000 for the default
  • If the server is working, you will see a list of your files in the browser
  • Click the file you want to serve, and it should display.

More advanced solutions

  • Install a code editor, web server, and other services that are integrated.

You can install Apache, PHP, Python, SQL, Debuggers etc. all separately on your machine, and then spend lots of time trying to figure out how to make them all work together, or look for a solution that combines all those things.

I like using XAMPP with NetBeans IDE. You can also install WAMP which provides a User Interface for managing and integrating Apache and other services.

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

How to semantically add heading to a list

I put the heading inside the ul. There's no rule that says UL must contain only LI elements.

In c# is there a method to find the max of 3 numbers?

You could try this code:

private float GetBrightestColor(float r, float g, float b) { 
    if (r > g && r > b) {
        return r;
    } else if (g > r && g > b) { 
        return g;
    } else if (b > r && b > g) { 
        return b;
    }
}

How to keep the local file or the remote file during merge using Git and the command line?

git checkout {branch-name} -- {file-name}

This will use the file from the branch of choice.

I like this because posh-git autocomplete works great with this. It also removes any ambiguity as to which branch is remote and which is local. And --theirs didn't work for me anyways.

HTML Entity Decode

I know I'm a bit late to the game, but I thought I might provide the following snippet as an example of how I decode HTML entities using jQuery:

var varTitleE = "Chris&apos; corner";
var varTitleD = $("<div/>").html(varTitleE).text();

console.log(varTitleE + " vs. " + varTitleD);???????????

Don't forget to fire-up your inspector/firebug to see the console results -- or simply replace console.log(...) w/alert(...)

That said, here's what my console via the Google Chrome inspector read:

Chris&apos; corner vs. Chris' corner

Add characters to a string in Javascript

It sounds like you want to use join, e.g.:

var text = list.join();

Can I install the "app store" in an IOS simulator?

No, according to Apple here:

Note: You cannot install apps from the App Store in simulation environments.

What is the easiest way to get the current day of the week in Android?

Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
// 3 letter name form of the day
System.out.println(new SimpleDateFormat("EE", Locale.ENGLISH).format(date.getTime()));
// full name form of the day
System.out.println(new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date.getTime()));

Result (for today):

Sat
Saturday

UPDATE: java8

LocalDate date = LocalDate.now();
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Enum = " + dow);

String dayName = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println("FULL = " + dayName);

dayName = dow.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println("FULL_STANDALONE = " + dayName);

dayName = dow.getDisplayName(TextStyle.NARROW, Locale.ENGLISH);
System.out.println("NARROW = " + dayName);

dayName = dow.getDisplayName(TextStyle.NARROW_STANDALONE, Locale.ENGLISH);
System.out.println("NARROW_STANDALONE = " + dayName);

dayName = dow.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
System.out.println("SHORT = " + dayName);

dayName = dow.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH);
System.out.println("SHORT_STANDALONE = " + dayName);

Result (for today):

Enum = SATURDAY
FULL = Saturday
FULL_STANDALONE = Saturday
NARROW = S
NARROW_STANDALONE = 6
SHORT = Sat
SHORT_STANDALONE = Sat

How to obtain the number of CPUs/cores in Linux from the command line?

The following should give you the number of "real" cores on both a hyperthreaded and non-hyperthreaded system. At least it worked in all my tests.

awk -F: '/^physical/ && !ID[$2] { P++; ID[$2]=1 }; /^cpu cores/ { CORES=$2 };  END { print CORES*P }' /proc/cpuinfo

Sort divs in jQuery based on attribute 'data-sort'?

Use this function

   var result = $('div').sort(function (a, b) {

      var contentA =parseInt( $(a).data('sort'));
      var contentB =parseInt( $(b).data('sort'));
      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
   });

   $('#mylist').html(result);

You can call this function just after adding new divs.

If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:

$(targetSelector).sort(function (a, b) {
    // ...
}).appendTo($container);

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

Display two fields side by side in a Bootstrap Form

Just put two inputs inside a div with class form-group and set display flex on the div style

<form method="post">
<div class="form-group" style="display: flex;"><input type="text" class="form-control" name="nome" placeholder="Nome e sobrenome" style="margin-right: 4px;" /><input type="text" class="form-control" style="margin-left: 4px;" name="cpf" placeholder="CPF" /></div>
<div class="form-group" style="display: flex;"><input type="email" class="form-control" name="email" placeholder="Email" style="margin-right: 4px;" /><input type="tel" class="form-control" style="margin-left: 4px;" name="telephone" placeholder="Telefone" /></div>
<div class="form-group"><input type="password" class="form-control" name="password" placeholder="Password" /></div>
<div class="form-group"><input type="password" class="form-control" name="password-repeat" placeholder="Password (repeat)" /></div>
<div class="form-group">
    <div class="form-check"><label class="form-check-label"><input type="checkbox" class="form-check-input" />I agree to the license terms.</label></div>
</div>
<div class="form-group"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></div><a class="already" href="#">You already have an account? Login here.</a></form>

Jquery-How to grey out the background while showing the loading icon over it

Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.

If the gif is displayed but not animating, see reference links at very bottom of this answer.

Displaying the gif + overlay, however, is easier than you might think.

All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.

So, when the button is pressed, just unhide those two divs. That's it!

jsFiddle Demo

_x000D_
_x000D_
$("#button").click(function() {_x000D_
    $('#myOverlay').show();_x000D_
    $('#loadingGIF').show();_x000D_
    setTimeout(function(){_x000D_
   $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    },2500);_x000D_
});_x000D_
/*  Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
 $('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Update:

You might enjoy playing with the new backdrop-filter:blur(_px) css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)

References:

http://www.paulirish.com/2007/animated-gif-not-animating/

Animated GIF while loading page does not animate

https://wordpress.org/support/topic/animated-gif-not-working

http://forums.mozillazine.org/viewtopic.php?p=987829

Commenting out a set of lines in a shell script

You can use a 'here' document with no command to send it to.

#!/bin/bash
echo "Say Something"
<<COMMENT1
    your comment 1
    comment 2
    blah
COMMENT1
echo "Do something else"

Wikipedia Reference

What do numbers using 0x notation mean?

SIMPLE

It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.

Example :

0x6400 translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600. When compiler reads 0x6400, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8 or any base ..

Hope Helped in some way.

Good day,

Determine the process pid listening on a certain port

netstat -p -l | grep $PORT and lsof -i :$PORT solutions are good but I prefer fuser $PORT/tcp extension syntax to POSIX (which work for coreutils) as with pipe:

pid=`fuser $PORT/tcp`

it prints pure pid so you can drop sed magic out.

One thing that makes fuser my lover tools is ability to send signal to that process directly (this syntax is also extension to POSIX):

$ fuser -k $port/tcp       # with SIGKILL
$ fuser -k -15 $port/tcp   # with SIGTERM
$ fuser -k -TERM $port/tcp # with SIGTERM

Also -k is supported by FreeBSD: http://www.freebsd.org/cgi/man.cgi?query=fuser

Deck of cards JAVA

There are many errors in your code, for example you are not really calling your deck by just typing deck in your Shuffle method. You can only call it by typing theCard.deck

I have changed your shuffle method:

public void Shuffle(){
    for (int i = 0; i < theCard.deck.length; i++) {
        int index = (int)(Math.random()*theCard.deck.length );
        int temp = theCard.deck[i];
        theCard.deck[i] = theCard.deck[index];
        theCard.deck[index] = temp;
        remainingCards--;
    }
}

Also, as it is said you have structural problem. You should name classes as you understand in real life, for example, when you say card, it is only one card, when you say deck it is supposed to be 52+2 cards. In this way your code would be more understandable.

How to clone a Date object?

This is the cleanest approach

_x000D_
_x000D_
let dat = new Date() _x000D_
let copyOf = new Date(dat.valueOf())_x000D_
_x000D_
console.log(dat);_x000D_
console.log(copyOf);
_x000D_
_x000D_
_x000D_

Adding a dictionary to another

Create an Extension Method most likely you will want to use this more than once and this prevents duplicate code.

Implementation:

 public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
 {
        if (collection == null)
        {
            throw new ArgumentNullException("Collection is null");
        }

        foreach (var item in collection)
        {
            if(!source.ContainsKey(item.Key)){ 
               source.Add(item.Key, item.Value);
            }
            else
            {
               // handle duplicate key issue here
            }  
        } 
 }

Usage:

Dictionary<string,string> animals = new Dictionary<string,string>();
Dictionary<string,string> newanimals = new Dictionary<string,string>();

animals.AddRange(newanimals);

How to check if a subclass is an instance of a class at runtime?

You have to read the API carefully for this methods. Sometimes you can get confused very easily.

It is either:

if (B.class.isInstance(view))

API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)

or:

if (B.class.isAssignableFrom(view.getClass()))

API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter

or (without reflection and the recommended one):

if (view instanceof B)

Execute a command line binary with Node.js

Since version 4 the closest alternative is child_process.execSync method:

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

?? Note that execSync call blocks event loop.

HttpClient - A task was cancelled?

Promoting @JobaDiniz's comment to an answer:

Do not do the obvious thing and dispose the HttpClient instance, even though the code "looks right":

async Task<HttpResponseMessage> Method() {
  using (var client = new HttpClient())
    return client.GetAsync(request);
}

The same happens with C#'s new RIAA syntax; slightly less obvious:

async Task<HttpResponseMessage> Method() {
  using var client = new HttpClient();
  return client.GetAsync(request);
}

Instead, cache a static instance of HttpClient for your app or library, and reuse it:

static HttpClient client = new HttpClient();

async Task<HttpResponseMessage> Method() {
  return client.GetAsync(request);
}

(The Async() request methods are all thread safe.)

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

in SQL*Plus you could also use a REFCURSOR variable:

SQL> VARIABLE x REFCURSOR
SQL> DECLARE
  2   V_Sqlstatement Varchar2(2000);
  3  BEGIN
  4   V_Sqlstatement := 'SELECT * FROM DUAL';
  5   OPEN :x for v_Sqlstatement;
  6  End;
  7  /

ProcÚdure PL/SQL terminÚe avec succÞs.

SQL> print x;

D
-
X

How is using OnClickListener interface different via XML and Java code?

Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

How do I serialize a C# anonymous type to a JSON string?

For those checking this around the year 2020:

Microsoft's System.Text.Json namespace is the new king in town. In terms of performance, it is the best as far as I can tell:

var model = new Model
{
    Name = "Test Name",
    Age = 5
};

string json = JsonSerializer.Serialize(model);

As some others have mentioned, NewtonSoft.Json is a very nice library as well.

Differences between action and actionListener

As BalusC indicated, the actionListener by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.

This happens through a call like this:

context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,                                                          
    new ExceptionQueuedEventContext(context, exception, source, phaseId)
);

The default listener for this event is the ExceptionHandler which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.

This ExceptionHandler can be replaced however in faces-config.xml with a custom implementation:

<exception-handlerfactory>
   com.foo.myExceptionHandler
</exception-handlerfactory>

Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:

@ManagedBean
@RequestScoped
public class MyBean {

    public void actionMethod(ActionEvent event) {

        FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
            throw new RuntimeException(content.getException());
        }

        @Override
        public boolean isListenerForSource(Object source) {
            return true;
        }
        });

        throw new RuntimeException("test");
    }

}

(note, this is not how one should normally code listeners, this is only for demonstration purposes!)

Calling this from a Facelet like this:

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
        </h:form>
    </h:body>
</html>

Will result in an error page being displayed.

Set the space between Elements in Row Flutter

To make an exact spacing, I use Padding. An example with two images:

Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: <Widget>[
      Expanded(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Image.asset('images/user1.png'),
        ),
      ),
      Expanded(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Image.asset('images/user2.png'),
        ),
      )
    ],
  ),

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

Find if a String is present in an array

This is what you're looking for:

List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());

If you have a list of not repeated values, prefer using a Set<String> which has the same contains method

Is there a way to create and run javascript in Chrome?

Usually one uses text editor to create source files (like JavaScript). I use VisualStudio which have intellisence supprt for JavaScript, but any other editor will do (vim or notepad on Windows are both fine).

To run JavaScript by itself you need something that can do that. I.e. on Windows you can directly run script from console using CScript script.js command. There are other ways to run JavaScript on Windows and other OS.

Browsers (like Chrome) do not run JavaScript by itself, only as part of a page or extensions. It is unclear what one would expect of browser to do with JavaScript by itself.

Javascript Equivalent to C# LINQ Select

Dinqyjs has a linq-like syntax and provides polyfills for functions like map and indexOf, and has been designed specifically for working with arrays in Javascript.

IOException: Too many open files

As you are running on Linux I suspect you are running out of file descriptors. Check out ulimit. Here is an article that describes the problem: http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/

How to Diff between local uncommitted changes and origin

I know it's not an answer to the exact question asked, but I found this question looking to diff a file in a branch and a local uncommitted file and I figured I would share

Syntax:

git diff <commit-ish>:./ -- <path>

Examples:

git diff origin/master:./ -- README.md
git diff HEAD^:./ -- README.md
git diff stash@{0}:./ -- README.md
git diff 1A2B3C4D:./ -- README.md

(Thanks Eric Boehs for a way to not have to type the filename twice)

Change EditText hint color when using TextInputLayout

With the Material Components library you can customize the TextInputLayout the hint text color using:

  • In the layout:

    • app:hintTextColor attribute : the color of the label when it is collapsed and the text field is active
    • android:textColorHint attribute: the color of the label in all other text field states (such as resting and disabled)

Something like:

<com.google.android.material.textfield.TextInputLayout
     app:hintTextColor="@color/mycolor"
     android:textColorHint="@color/text_input_hint_selector"
     .../>

enter image description hereenter image description here

JMS Topic vs Queues

Queues

Pros

  • Simple messaging pattern with a transparent communication flow
  • Messages can be recovered by putting them back on the queue

Cons

  • Only one consumer can get the message
  • Implies a coupling between producer and consumer as it’s an one-to-one relation

Topics

Pros

  • Multiple consumers can get a message
  • Decoupling between producer and consumers (publish-and-subscribe pattern)

Cons

  • More complicated communication flow
  • A message cannot be recovered for a single listener

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I have changed in my activity but effected. Here is my code:

View layout = getLayoutInflater().inflate(R.layout.list_group,null);
        try {
            LinearLayout linearLayout = (LinearLayout) layout.findViewById(R.id.ldrawernav);
            linearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
        }
        catch (Exception e) {

        }

    }

How do I download a package from apt-get without installing it?

Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).

apt-get install -d -o=dir::cache=/tmp whateveryouwant

How to Detect Browser Back Button event - Cross Browser

Here's my take at it. The assumption is, when the URL changes but there has no click within the document detected, it's a browser back (yes, or forward). A users click is reset after 2 seconds to make this work on pages that load content via Ajax:

(function(window, $) {
  var anyClick, consoleLog, debug, delay;
  delay = function(sec, func) {
    return setTimeout(func, sec * 1000);
  };
  debug = true;
  anyClick = false;
  consoleLog = function(type, message) {
    if (debug) {
      return console[type](message);
    }
  };
  $(window.document).click(function() {
    anyClick = true;
    consoleLog("info", "clicked");
    return delay(2, function() {
      consoleLog("info", "reset click state");
      return anyClick = false;
    });
  });
  return window.addEventListener("popstate", function(e) {
    if (anyClick !== true) {
      consoleLog("info", "Back clicked");
      return window.dataLayer.push({
        event: 'analyticsEvent',
        eventCategory: 'test',
        eventAction: 'test'
      });
    }
  });
})(window, jQuery);

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Import a file from a subdirectory?

  • Create a subdirectory named lib.
  • Create an empty file named lib\__init__.py.
  • In lib\BoxTime.py, write a function foo() like this:

    def foo():
        print "foo!"
    
  • In your client code in the directory above lib, write:

    from lib import BoxTime
    BoxTime.foo()
    
  • Run your client code. You will get:

    foo!
    

Much later -- in linux, it would look like this:

% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc>     print "foo!"
heredoc> EOF
% tree lib
lib
+-- BoxTime.py
+-- __init__.py

0 directories, 2 files
% python 
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!

App crashing when trying to use RecyclerView on android 5.0

My problem was in my XML lyout I have an android:animateLayoutChanges set to true and I've called notifyDataSetChanged() on the RecyclerView's adapter in the Java code.

So, I've just removed android:animateLayoutChanges from my layout and that resloved my problem.

base_url() function not working in codeigniter

First of all load URL helper. you can load in "config/autoload.php" file and add following code $autoload['helper'] = array('url');

or in controller add following code

$this->load->helper('url');

then go to config.php in cofig folder and set

$config['base_url'] = 'http://urlbaseurl.com/';

hope this will help thanks

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

DISABLE the Horizontal Scroll

this is the nasty child of your code :)

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 1170px;
}

replace it with

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 100%;
}

Set textarea width to 100% in bootstrap modal

I am new to .NET/MVC programming, but my understanding is that the Site.css file (under the Content folder in MVC) is a site-level override for Bootstrap CSS, allowing you to override bootstrap native settings in a portable and non-destructive manner (e.g. you can easily save and reapply your site.css changes when updating Bootstrap on your system.)

In Bootstrap 3.0.0, Site.css has the following style setting:

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

Other blogs have suggested that this 280px width was added in haste near a release date, in a desire to make the UI look better than it does with 100% width input. Fortunately it was placed in a "visible" location in the site file so you would notice it.

Simply change the width setting, either for all three input types, or pull out textarea and give it its own setting if you want to leave the others alone.

How to split strings into text and number?

>>> def mysplit(s):
...     head = s.rstrip('0123456789')
...     tail = s[len(head):]
...     return head, tail
... 
>>> [mysplit(s) for s in ['foofo21', 'bar432', 'foobar12345']]
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
>>> 

Generating random numbers in C

You need to seed your PRNG so it starts with a different value each time.

A simple but low quality seed is to use the current time:

srand(time(0));

This will get you started but is considered low quality (i.e. for example, don't use that if you are trying to generate RSA keys).

Background. Pseudo-random number generators do not create true random number sequences but just simulate them. Given a starting point number, a PRNG will always return the same sequence of numbers. By default, they start with the same internal state so will return the same sequence.

To not get the same sequence, you change the internal state. The act of changing the internal state is called "seeding".

Count unique values in a column in Excel

You can do the following steps:

  1. First isolate the column (by inserting a blank column before and/or after the column you want to count the unique values if there are any adjacent columns;

  2. Then select the whole column, go to 'Data' > 'Advanced Filter' and check the checkbox 'Unique records only'. This will hide all non-unique records so you can count the unique ones by selecting the whole column.

In android app Toolbar.setTitle method has no effect – application name is shown as title

Simply you can change any activity name by using

Activityname.this.setTitle("Title Name");

How do you fadeIn and animate at the same time?

$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');

However, this doesn't appear to work on display: none elements (as fadeIn does). So, you might need to put this beforehand:

$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

How to use Angular4 to set focus by element id

Here is a directive that you can use in any component:

import { NgZone, Directive, ElementRef, AfterContentInit, Renderer2 } from '@angular/core';

@Directive({
    selector: '[appFocus]'
})
export class FocusDirective implements AfterContentInit {
    constructor(private el: ElementRef, private zone: NgZone, private renderer: Renderer2) {}

    ngAfterContentInit() {
        this.zone.runOutsideAngular(() => setTimeout(() => {
            this.renderer.selectRootElement(this.el.nativeElement).focus();
        }, 0));
    }
}

Use:

<input type="text" appFocus>

Post order traversal of binary tree without recursion

Simple Intuitive solution in python.

        while stack:
            node = stack.pop()
            if node:
                if isinstance(node,TreeNode):
                    stack.append(node.val)
                    stack.append(node.right)
                    stack.append(node.left)
                else:
                    post.append(node)
        return post

onclick go full screen

Here are a couple of ways to do that:

I'd suggest, provide a popup asking the user if s/he wants to go full screen and then call this javascript accordingly.

Passing javascript variable to html textbox

This was a problem for me, too. One reason for doing this (in my case) was that I needed to convert a client-side event (a javascript variable being modified) to a server-side variable (for that variable to be used in php). Hence populating a form with a javascript variable (eg a sessionStorage key/value) and converting it to a $_POST variable.

<form name='formName'>
<input name='inputName'>
</form>

<script>
document.formName.inputName.value=var
</script>

How to get a json string from url?

If you're using .NET 4.5 and want to use async then you can use HttpClient in System.Net.Http:

using (var httpClient = new HttpClient())
{
    var json = await httpClient.GetStringAsync("url");

    // Now parse with JSON.Net
}

How to Upload Image file in Retrofit 2

@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
                                       @Part("full_name") RequestBody fullName,
                                       @Part MultipartBody.Part image,
                                       @Part("other") RequestBody other);

//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
        MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
RequestBody fullName = 
        RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

service.updateProfile(id, fullName, body, other);

Look at the way I am passing the multipart and string params. Hope this will help you!

The requested operation cannot be performed on a file with a user-mapped section open

I encountered this error and it turned out the issue was FxCop was running against my project. I closed FxCop and then I could compile again.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

I honestly fount the best way to get around this was to just create another model with all the fields that you require and named slightly different. Run migrations. Delete unused model and run migrations again. Voila.

Circle button css

The problem is that the actual width of an a tag depends on its contents. Your code has no text in the a tag, so it appears like a hunger-sunken circle. If you use the div tag along the a, you get the desired results.

Check this code out:

_x000D_
_x000D_
.btn {
  background-color: green;
  border-radius: 50%;
  /*this will rounden-up the button*/
  width: 80px;
  height: 80px;
  /*keep the height and width equal*/
}
_x000D_
<a href="#">
 <!--use the URL you want to use-->
 <button class="btn">press me</button>
 </a>
_x000D_
_x000D_
_x000D_

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

PyCharm shows unresolved references error for valid code

I find myself removing and re-adding the remote interpreter to fix this problem when Invalidating Caches or Refreshing Paths does not work.

I use vagrant and every once and awhile if I add a new VM to my multi-vm setup, the forwarded port changes and this seems to confuse PyCharm when it tries to use the wrong port for SSH. Changing the port doesn't seem to help the broken references.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Ok, I just faced this problem and tried all of the steps mentioned above but didn't help. So what I did, I checked what image extension it was before I renamed it to .png. In my case it was .jpeg. So I renamed it back to .jpeg and kept the same original file in drawable. And bingo, it just worked fine.

So the solution is, use the file without changing extension, be it .png or .jpeg, keep it the original way.

Thought to share if it helps anyone. Thanks.

How do I delete from multiple tables using INNER JOIN in SQL server

  1. You can always set up cascading deletes on the relationships of the tables.

  2. You can encapsulate the multiple deletes in one stored procedure.

  3. You can use a transaction to ensure one unit of work.

How to return a dictionary | Python


def query(id):
    for line in file:
        table = line.split(";")
        if id == int(table[0]):
             yield table
    
    

id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
  print("ID: " + id_)
  print("Name: " + name)
  print("City: " + city)
file.close()

Using yield..

Passing base64 encoded strings in URL

No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.

Valid base64 characters are below.

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=

Split page vertically using CSS

There can also be a solution by having both float to left.

Try this out:

Working Demo

P.S. This is just an improvement of Ankit's Answer

How to get input text value from inside td

Maybe this will help.

var inputVal = $(this).closest('tr').find("td:eq(x) input").val();

How do I add a new sourceset to Gradle?

Here's what works for me as of Gradle 4.0.

sourceSets {
  integrationTest {
    compileClasspath += sourceSets.test.compileClasspath
    runtimeClasspath += sourceSets.test.runtimeClasspath
  }
}

task integrationTest(type: Test) {
  description = "Runs the integration tests."
  group = 'verification'
  testClassesDirs = sourceSets.integrationTest.output.classesDirs
  classpath = sourceSets.integrationTest.runtimeClasspath
}

As of version 4.0, Gradle now uses separate classes directories for each language in a source set. So if your build script uses sourceSets.integrationTest.output.classesDir, you'll see the following deprecation warning.

Gradle now uses separate output directories for each JVM language, but this build assumes a single directory for all classes from a source set. This behaviour has been deprecated and is scheduled to be removed in Gradle 5.0

To get rid of this warning, just switch to sourceSets.integrationTest.output.classesDirs instead. For more information, see the Gradle 4.0 release notes.

Failed to load ApplicationContext from Unit Test: FileNotFound

For me, I was missing @ActiveProfile at my test class

@ActiveProfiles("sandbox")
class MyTestClass...