Programs & Examples On #Domain driven design

Domain-driven design (DDD) is an approach to developing software for complex needs by deeply connecting the implementation to an evolving model of the core business concepts. Note that conceptual DDD questions are better to be asked at softwareengineering.stackexchange.com.

Where do I find some good examples for DDD?

The difficulty with DDD samples is that they're often very domain specific and the technical implementation of the resulting system doesn't always show the design decisions and transitions that were made in modelling the domain, which is really at the core of DDD. DDD is much more about the process than it is the code. (as some say, the best DDD sample is the book itself!)

That said, a well commented sample app should at least reveal some of these decisions and give you some direction in terms of matching up your domain model with the technical patterns used to implement it.

You haven't specified which language you're using, but I'll give you a few in a few different languages:

DDDSample - a Java sample that reflects the examples Eric Evans talks about in his book. This is well commented and shows a number of different methods of solving various problems with separate bounded contexts (ie, the presentation layer). It's being actively worked on, so check it regularly for updates.

dddps - Tim McCarthy's sample C# app for his book, .NET Domain-Driven Design with C#

S#arp Architecture - a pragmatic C# example, not as "pure" a DDD approach perhaps due to its lack of a real domain problem, but still a nice clean approach.

With all of these sample apps, it's probably best to check out the latest trunk versions from SVN/whatever to really get an idea of the thinking and technology patterns as they should be updated regularly.

What is the difference between DAO and Repository patterns?

A DAO allows for a simpler way to get data from storage, hiding the ugly queries.

Repository deals with data too and hides queries and all that but, a repository deals with business/domain objects.

A repository will use a DAO to get the data from the storage and uses that data to restore a business object.

For example, A DAO can contain some methods like that -

 public abstract class MangoDAO{
   abstract List<Mango>> getAllMangoes();
   abstract Mango getMangoByID(long mangoID);
}

And a Repository can contain some method like that -

   public abstract class MangoRepository{
       MangoDao mangoDao = new MangDao;

       Mango getExportQualityMango(){

       for(Mango mango:mangoDao.getAllMangoes()){
        /*Here some business logics are being applied.*/
        if(mango.isSkinFresh()&&mangoIsLarge(){
           mango.setDetails("It is an export quality mango");
            return mango;
           }
       }
    }
}

This tutorial helped me to get the main concept easily.

What is Domain Driven Design?

Here is another good article that you may check out on Domain Driven Design. if your application is anything serious than college assignment. The basic premise is structure everything around your entities and have a strong domain model. Differentiate between services that provide infrastructure related things (like sending email, persisting data) and services that actually do things that are your core business requirments.

Hope that helps.

Flatten an irregular list of lists

Just use a funcy library: pip install funcy

import funcy


funcy.flatten([[[[1, 1], 1], 2], 3]) # returns generator
funcy.lflatten([[[[1, 1], 1], 2], 3]) # returns list

How do you modify the web.config appSettings at runtime?

You need to use WebConfigurationManager.OpenWebConfiguration(): For Example:

Dim myConfiguration As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
myConfiguration.ConnectionStrings.ConnectionStrings("myDatabaseName").ConnectionString = txtConnectionString.Text
myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text
myConfiguration.Save()

I think you might also need to set AllowLocation in machine.config. This is a boolean value that indicates whether individual pages can be configured using the element. If the "allowLocation" is false, it cannot be configured in individual elements.

Finally, it makes a difference if you run your application in IIS and run your test sample from Visual Studio. The ASP.NET process identity is the IIS account, ASPNET or NETWORK SERVICES (depending on IIS version).

Might need to grant ASPNET or NETWORK SERVICES Modify access on the folder where web.config resides.

React Native fetch() Network Request Failed

This worked for me, android uses a special type of IP address 10.0.2.2 then port number

import { Platform } from 'react-native';

export const baseUrl = Platform.OS === 'android' ?
    'http://10.0.2.2:3000/'
: 
'http://localhost:3000/';

Reading the selected value from asp:RadioButtonList using jQuery

Try this:

$("input[name='<%=RadioButtonList1.UniqueID %>']:checked").val()

How can I use ":" as an AWK field separator?

You can also use a regular expression as a field separator. The following will print "bar" by using a regular expression to set the number "10" as a separator.

echo "foo 10 bar" | awk -F'[0-9][0-9]' '{print $2}'

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How to center an element in the middle of the browser window?

To centre align a div you should apply the style

div 
{
    margin: 0 auto;
}

Is this a good way to clone an object in ES6?

if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:

function copy(item){
  let result = null;
  if(!item) return result;
  if(Array.isArray(item)){
    result = [];
    item.forEach(element=>{
      result.push(copy(element));
    });
  }
  else if(item instanceof Object && !(item instanceof Function)){ 
    result = {};
    for(let key in item){
      if(key){
        result[key] = copy(item[key]);
      }
    }
  }
  return result || item;
}

But the best way is to create a class that can return a clone of it self

class MyClass{
    data = null;
    constructor(values){ this.data = values }
    toString(){ console.log("MyClass: "+this.data.toString(;) }
    remove(id){ this.data = data.filter(d=>d.id!==id) }
    clone(){ return new MyClass(this.data) }
}

How can I detect browser type using jQuery?

Try to use it

$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){ 
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});

Python Database connection Close

You might try turning off pooling, which is enabled by default. See this discussion for more information.

import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
del csr

Implements vs extends: When to use? What's the difference?

A class can only "implement" an interface. A class only "extends" a class. Likewise, an interface can extend another interface.

A class can only extend one other class. A class can implement several interfaces.

If instead you are more interested in knowing when to use abstract classes and interfaces, refer to this thread: Interface vs Abstract Class (general OO)

How to fire AJAX request Periodically?

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval(). If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

background-image: url("images/plaid.jpg") no-repeat; wont show up

    <style>
    background: url(images/Untitled-2.fw.png);
background-repeat:no-repeat;
background-position:center;
background-size: cover;
    </style>

How to get the absolute coordinates of a view

You can get a View's coordinates using getLocationOnScreen() or getLocationInWindow()

Afterwards, x and y should be the top-left corner of the view. If your root layout is smaller than the screen (like in a Dialog), using getLocationInWindow will be relative to its container, not the entire screen.

Java Solution

int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];

NOTE: If value is always 0, you are likely changing the view immediately before requesting location.

To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post:

view.post(() -> {
    // Values should no longer be 0
    int[] point = new int[2];
    view.getLocationOnScreen(point); // or getLocationInWindow(point)
    int x = point[0];
    int y = point[1];
});

~~

Kotlin Solution

val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point

NOTE: If value is always 0, you are likely changing the view immediately before requesting location.

To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post:

view.post {
    // Values should no longer be 0
    val point = IntArray(2)
    view.getLocationOnScreen(point) // or getLocationInWindow(point)
    val (x, y) = point
}

I recommend creating an extension function for handling this:

// To use, call:
val (x, y) = view.screenLocation

val View.screenLocation get(): IntArray {
    val point = IntArray(2)
    getLocationOnScreen(point)
    return point
}

And if you require reliability, also add:

view.screenLocationSafe { x, y -> Log.d("", "Use $x and $y here") }

fun View.screenLocationSafe(callback: (Int, Int) -> Unit) {
    post {
        val (x, y) = screenLocation
        callback(x, y)
    }
}

How to properly compare two Integers in Java?

Calling

if (a == b)

Will work most of the time, but it's not guaranteed to always work, so do not use it.

The most proper way to compare two Integer classes for equality, assuming they are named 'a' and 'b' is to call:

if(a != null && a.equals(b)) {
  System.out.println("They are equal");
}

You can also use this way which is slightly faster.

   if(a != null && b != null && (a.intValue() == b.intValue())) {
      System.out.println("They are equal");
    } 

On my machine 99 billion operations took 47 seconds using the first method, and 46 seconds using the second method. You would need to be comparing billions of values to see any difference.

Note that 'a' may be null since it's an Object. Comparing in this way will not cause a null pointer exception.

For comparing greater and less than, use

if (a != null && b!=null) {
    int compareValue = a.compareTo(b);
    if (compareValue > 0) {
        System.out.println("a is greater than b");
    } else if (compareValue < 0) {
        System.out.println("b is greater than a");
    } else {
            System.out.println("a and b are equal");
    }
} else {
    System.out.println("a or b is null, cannot compare");
}

SELECT max(x) is returning null; how can I make it return 0?

Depends on what product you're using, but most support something like

SELECT IFNULL(MAX(X), 0, MAX(X)) AS MaxX FROM tbl WHERE XID = 1

or

SELECT CASE MAX(X) WHEN NULL THEN 0 ELSE MAX(X) FROM tbl WHERE XID = 1

How can I get the timezone name in JavaScript?

Retrieve timezone by name (i.e. "America/New York")

moment.tz.guess();

Sort a List of Object in VB.NET

try..

Dim sortedList = From entry In mylist Order By entry.name Ascending Select entry

mylist = sortedList.ToList

ng-options with simple array init

you could use something like

<select ng-model="myselect">
    <option ng-repeat="o in options" ng-selected="{{o==myselect}}" value="{{o}}">
        {{o}}
    </option>
</select>

using ng-selected you preselect the option in case myselect was prefilled.

I prefer this method over ng-options anyway, as ng-options only works with arrays. ng-repeat also works with json-like objects.

Unable to Resolve Module in React Native App

I was able to solve this issue by adding a file extension '.js'. I was using Intellij and created a js file, but it did not have the file extension. When I did a refractor rename and changed my component from 'List' to 'List.js' react native then knew how to resolve it.

Query to check index on a table

Here is what I used for TSQL which took care of the problem that my table name could contain the schema name and possibly the database name:

DECLARE @THETABLE varchar(100);
SET @THETABLE = 'theschema.thetable';
select i.*
  from sys.indexes i
 where i.object_id = OBJECT_ID(@THETABLE)
   and i.name is not NULL;

The use case for this is that I wanted the list of indexes for a named table so I could write a procedure that would dynamically compress all indexes on a table.

How to extract the nth word and count word occurrences in a MySQL string?

No, there isn't a syntax for extracting text using regular expressions. You have to use the ordinary string manipulation functions.

Alternatively select the entire value from the database (or the first n characters if you are worried about too much data transfer) and then use a regular expression on the client.

Group by month and year in MySQL

SELECT YEAR(t.summaryDateTime) as yr, GROUP_CONCAT(MONTHNAME(t.summaryDateTime)) AS month 
FROM trading_summary t GROUP BY yr

Still you would need to process it in external script to get exactly the structure you're looking for.

For example use PHP's explode to create an array from list of month names and then use json_encode()

What is newline character -- '\n'

I see a lot of sed answers, but none for vim. To be fair, vim's treatment of newline characters is a little confusing. Search for \n but replace with \r. I recommend RTFM: :help pattern in general and :help NL-used-for-Nul in particular.

To do what you want with a :substitute command,

:%s/\_$/\r

although I think most people would use something like

:g/^/put=''

for the same effect.

Here is a way to find the answer for yourself. Run your file through xxd, which is part of the standard vim distribution.

:%!xxd

You get

0000000: 4361 6c69 666f 726e 6961 0a4d 6173 7361  California.Massa
0000010: 6368 7573 6574 7473 0a41 7269 7a6f 6e61  chusetts.Arizona
0000020: 0a                                       .

This shows that 46 is the hex code for C, 61 is the code for a, and so on. In particular, 0a (decimal 10) is the code for \n. Just for kicks, try

:set ff=dos

before filtering through xxd. You will see 0d0a (CRLF) as the line terminator.

:help /\_$
:help :g
:help :put
:help :!
:help 23.4

Bootstrap Responsive Text Size

Well, my solution is sort of hack, but it works and I am using it.

1vw = 1% of viewport width

1vh = 1% of viewport height

1vmin = 1vw or 1vh, whichever is smaller

1vmax = 1vw or 1vh, whichever is larger

h1 {
  font-size: 5.9vw;
}
h2 {
  font-size: 3.0vh;
}
p {
  font-size: 2vmin;
}

How to do a non-greedy match in grep?

grep

For non-greedy match in grep you could use a negated character class. In other words, try to avoid wildcards.

For example, to fetch all links to jpeg files from the page content, you'd use:

grep -o '"[^" ]\+.jpg"'

To deal with multiple line, pipe the input through xargs first. For performance, use ripgrep.

C# windows application Event: CLR20r3 on application start

I've seen this same problem when my application depended on a referenced assembly that was not present on the deployment machine. I'm not sure what you mean by "referencing DotNetBar out of the install directory" - make sure it's set to CopyLocal=true in your project, or exists at the same full path on both your development and production machine.

Virtual network interface in Mac OS X

Replying in particular to:

You can create a new interface in the networking panel, based on an existing interface, but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive).

This can be achieved using a Tun/Tap device as suggested by psv141, and manipulating the /Library/Preferences/SystemConfiguration/preferences.plist file to add a NetworkService based on either a tun or tap interface. Mac OS X will not allow the creation of a NetworkService based on a virtual network interface, but one can directly manipulate the preferences.plist file to add the NetworkService by hand. Basically you would open the preferences.plist file in Xcode (or edit the XML directly, but Xcode is likely to be more fool-proof), and copy the configuration from an existing Ethernet interface. The place to create the new NetworkService is under "NetworkServices", and if your Mac has an Ethernet device the NetworkService profile will also be under this property entry. The Ethernet entry can be copied pretty much verbatim, the only fields you would actually be changing are:

  • UUID
  • UserDefinedName
  • IPv4 configuration and set the interface to your tun or tap device (i.e. tun0 or tap0).
  • DNS server if needed.

Then you would also manipulate the particular Location you want this NetworkService for (remember Mac OS X can configure all network interfaces dependent on your "Location"). The default location UUID can be obtained in the root of the PropertyList as the key "CurrentSet". After figuring out which location (or set) you want, expand the Set property, and add entries under Global/IPv4/ServiceOrder with the UUID of the new NetworkService. Also under the Set property you need to expand the Service property and add the UUID here as a dictionary with one String entry with key __LINK__ and value as the UUID (use the other interfaces as an example).

After you have modified your preferences.plist file, just reboot, and the NetworkService will be available under SystemPreferences->Network. Note that we have mimicked an Ethernet device so Mac OS X layer of networking will note that "a cable is unplugged" and will not let you activate the interface through the GUI. However, since the underlying device is a tun/tap device and it has an IP address, the interface will become active and the proper routing will be added at the BSD level.

As a reference this is used to do special routing magic.

In case you got this far and are having trouble, you have to create the tun/tap device by opening one of the devices under /dev/. You can use any program to do this, but I'm a fan of good-old-fashioned C myself:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
   int fd = open("/dev/tun0", O_RDONLY);
   if (fd < 0)
   {
      printf("Failed to open tun/tap device. Are you root? Are the drivers installed?\n");
      return -1;
   }
   while (1)
   {
      sleep(100000);
   }
   return 0;
}

Detecting an undefined object property

function isUnset(inp) {
  return (typeof inp === 'undefined')
}

Returns false if variable is set, and true if is undefined.

Then use:

if (isUnset(var)) {
  // initialize variable here
}

How do I add my bot to a channel?

This is how I've added a bot to my channel and set up notifications:

  1. Make sure the channel is public (you can set it private later)
  2. Add administrators > Type the bot username and make it administrator
  3. Your bot will join your channel
  4. set a channel id by setting the channel url like

telegram.me/whateverIWantAndAvailable

the channel id will be @whateverIWantAndAvailable

Now set up your bot to send notifications by pusshing the messages here:

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test

the message which bot will notify is: Test

I strongly suggest an urlencode of the message like

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works

in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");

I hope it helps

Renaming part of a filename

I like to do this with sed. In you case:

for x in DET01-*.dat; do
    echo $x | sed -r 's/DET01-ABC-(.+)\.dat/mv -v "\0" "DET01-XYZ-\1.dat"/'
done | sh -e

It is best to omit the "sh -e" part first to see what will be executed.

Apache and IIS side by side (both listening to port 80) on windows2003

I found this post which suggested to have two separate IP addresses so that both could listen on port 80.

There was a caveat that you had to make a change in IIS because of socket pooling. Here are the instructions based on the link above:

  1. Extract the httpcfg.exe utility from the support tools area on the Win2003 CD.
  2. Stop all IIS services: net stop http /y
  3. Have IIS listen only on the IP address I'd designated for IIS: httpcfg set iplisten -i 192.168.1.253
  4. Make sure: httpcfg query iplisten (The IPs listed are the only IP addresses that IIS will be listening on and no other.)
  5. Restart IIS Services: net start w3svc
  6. Start the Apache service

Access nested dictionary items via a list of keys?

An alternative way if you don't want to raise errors if one of the keys is absent (so that your main code can run without interruption):

def get_value(self,your_dict,*keys):
    curr_dict_ = your_dict
    for k in keys:
        v = curr_dict.get(k,None)
        if v is None:
            break
        if isinstance(v,dict):
            curr_dict = v
    return v

In this case, if any of the input keys is not present, None is returned, which can be used as a check in your main code to perform an alternative task.

how to write an array to a file Java

Just loop over the elements in your array.

Ex:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here

Add data dynamically to an Array

Adding array elements dynamically to an Array And adding new element to an Array

$samplearr=array();
$count = 0;
foreach ($rslt as $row) {
        $arr['feeds'][$count]['feed_id'] = $row->feed_id;
        $arr['feeds'][$count]['feed_title'] = $row->feed_title;
        $arr['feeds'][$count]['feed_url'] = $row->feed_url;
        $arr['feeds'][$count]['cat_name'] = $this->get_catlist_details($row->feed_id);
        foreach ($newelt as $cat) {
            array_push($samplearr, $cat);              
        }
        ++$count;
}
$arr['categories'] = array_unique($samplearr); //,SORT_STRING

$response = array("status"=>"success","response"=>"Categories exists","result"=>$arr);

Angular cookies

I ended creating my own functions:

@Component({
    selector: 'cookie-consent',
    template: cookieconsent_html,
    styles: [cookieconsent_css]
})
export class CookieConsent {
    private isConsented: boolean = false;

    constructor() {
        this.isConsented = this.getCookie(COOKIE_CONSENT) === '1';
    }

    private getCookie(name: string) {
        let ca: Array<string> = document.cookie.split(';');
        let caLen: number = ca.length;
        let cookieName = `${name}=`;
        let c: string;

        for (let i: number = 0; i < caLen; i += 1) {
            c = ca[i].replace(/^\s+/g, '');
            if (c.indexOf(cookieName) == 0) {
                return c.substring(cookieName.length, c.length);
            }
        }
        return '';
    }

    private deleteCookie(name) {
        this.setCookie(name, '', -1);
    }

    private setCookie(name: string, value: string, expireDays: number, path: string = '') {
        let d:Date = new Date();
        d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
        let expires:string = `expires=${d.toUTCString()}`;
        let cpath:string = path ? `; path=${path}` : '';
        document.cookie = `${name}=${value}; ${expires}${cpath}`;
    }

    private consent(isConsent: boolean, e: any) {
        if (!isConsent) {
            return this.isConsented;
        } else if (isConsent) {
            this.setCookie(COOKIE_CONSENT, '1', COOKIE_CONSENT_EXPIRE_DAYS);
            this.isConsented = true;
            e.preventDefault();
        }
    }
}

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

IPython Notebook save location

  1. Based on my experience, if you use "ipython.exe" in python-2.7.5/Scripts from other directory, as typing at the comamnd prompt as ipython notebook, *.ipynb files will be loaded and saved in the current directory. ("notebook" is just a comamnd line parameter) I think the "ipython notebook.exe" in Winpython top directory is not relevant for your request. As for me, I added the ipython.exe directory to the Path only.
  2. If you want to make your profile in user directory, see below: https://code.google.com/p/winpython/wiki/Installation#Settings

SQL Server Management Studio alternatives to browse/edit tables and run queries

You can still install and use Query Analyzer from previous SQL Server versions.

Make a dictionary in Python from input values

record = int(input("Enter the student record need to add :"))

stud_data={}

for i in range(0,record):
    Name = input("Enter the student name :").split()
    Age = input("Enter the {} age :".format(Name))
    Grade = input("Enter the {} grade :".format(Name)).split()
    Nam_key =  Name[0]
    Age_value = Age[0]
    Grade_value = Grade[0]
    stud_data[Nam_key] = {Age_value,Grade_value}

print(stud_data)

React: how to update state.item[1] in state using setState?

According to the React documentation on setState, using Object.assign as suggested by other answers here is not ideal. Due to the nature of setState's asynchronous behavior, subsequent calls using this technique may override previous calls causing undesirable outcomes.

Instead, the React docs recommend to use the updater form of setState which operates on the previous state. Keep in mind that when updating an array or object you must return a new array or object as React requires us to preserve state immutability. Using ES6 syntax's spread operator to shallow copy an array, creating or updating a property of an object at a given index of the array would look like this:

this.setState(prevState => {
    const newItems = [...prevState.items];
    newItems[index].name = newName;
    return {items: newItems};
})

Laravel is there a way to add values to a request array

enough said on this subject but i couldn't resist to add my own answer. I believe the simplest approach is

request()->merge([ 'foo' => 'bar' ]);

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

What is the meaning of Bus: error 10 in C

string literals are non-modifiable in C

Which concurrent Queue implementation should I use in Java?

ConcurrentLinkedQueue is lock-free, LinkedBlockingQueue is not. Every time you invoke LinkedBlockingQueue.put() or LinkedBlockingQueue.take(), you need acquire the lock first. In other word, LinkedBlockingQueue has poor concurrency. If you care performance, try ConcurrentLinkedQueue + LockSupport.

What is the difference between angular-route and angular-ui-router?

Basic thing you have to know: ng-router uses $location.path() and ui-router uses $state.go

Rest us all features.

In Excel, sum all values in one column in each row where another column is a specific value

You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

=IF(B1="No", A1, 0)

and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

Strangest language feature

Another vote for JavaScript:

parseInt('08') == 0

because anything with a leading 0 is interpreted as octal (weird), and invalid octal numbers evaluate to zero (BAD). I discovered this one August when code I hadn't touched in months broke on its own. It would have fixed itself in October, as it turns out.

Octal support has apparently been deprecated, so future generations of JavaScripters will not have this rite of passage.

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

Main differences between SOAP and RESTful web services in Java

SOAP Web services:

  1. If your application needs a guaranteed level of reliability and security then SOAP offers additional standards to ensure this type of operation.
  2. If both sides (service provider and service consumer) have to agree on the exchange format then SOAP gives the rigid specifications for this type of interaction.

RestWeb services:

  1. Totally stateless operations: for stateless CRUD (Create, Read, Update, and Delete) operations.
  2. Caching situations: If the information needs to be cached.

Node/Express file upload

Here is an easier way that worked for me:

const express = require('express');
var app = express();
var fs = require('fs');

app.post('/upload', async function(req, res) {

  var file = JSON.parse(JSON.stringify(req.files))

  var file_name = file.file.name

  //if you want just the buffer format you can use it
  var buffer = new Buffer.from(file.file.data.data)

  //uncomment await if you want to do stuff after the file is created

  /*await*/
  fs.writeFile(file_name, buffer, async(err) => {

    console.log("Successfully Written to File.");


    // do what you want with the file it is in (__dirname + "/" + file_name)

    console.log("end  :  " + new Date())

    console.log(result_stt + "")

    fs.unlink(__dirname + "/" + file_name, () => {})
    res.send(result_stt)
  });


});

How do you implement a good profanity filter?

I don't know of any good libraries for this, but whatever you do, make sure that you err in the direction of letting stuff through. I've dealt with systems that wouldn't allow me to use "mpassell" as a username, because it contains "ass" as a substring. That's a great way to alienate users!

Reset the database (purge all), then seed a database

You can delete everything and recreate database + seeds with both:

  1. rake db:reset: loads from schema.rb
  2. rake db:drop db:create db:migrate db:seed: loads from migrations

Make sure you have no connections to db (rails server, sql client..) or the db won't drop.

schema.rb is a snapshot of the current state of your database generated by:

rake db:schema:dump

How to delete a file via PHP?

You can delete the file using

unlink($Your_file_path);

but if you are deleting a file from it's http path then this unlink is not work proper. You have to give a file path correct.

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

How can I copy a file on Unix using C?

There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.

Update:

As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile on OS X now requires the output to be a socket and the code won't work!

The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.

#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif

int OSCopyFile(const char* source, const char* destination)
{    
    int input, output;    
    if ((input = open(source, O_RDONLY)) == -1)
    {
        return -1;
    }    
    if ((output = creat(destination, 0660)) == -1)
    {
        close(input);
        return -1;
    }

    //Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
    //fcopyfile works on FreeBSD and OS X 10.5+ 
    int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
    //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
    off_t bytesCopied = 0;
    struct stat fileinfo = {0};
    fstat(input, &fileinfo);
    int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif

    close(input);
    close(output);

    return result;
}

EDIT: Replaced the opening of the destination with the call to creat() as we want the flag O_TRUNC to be specified. See comment below.

What is the string concatenation operator in Oracle?

Using CONCAT(CONCAT(,),) worked for me when concatenating more than two strings.

My problem required working with date strings (only) and creating YYYYMMDD from YYYY-MM-DD as follows (i.e. without converting to date format):

CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD

Is there a way to do repetitive tasks at intervals?

How about something like

package main

import (
    "fmt"
    "time"
)

func schedule(what func(), delay time.Duration) chan bool {
    stop := make(chan bool)

    go func() {
        for {
            what()
            select {
            case <-time.After(delay):
            case <-stop:
                return
            }
        }
    }()

    return stop
}

func main() {
    ping := func() { fmt.Println("#") }

    stop := schedule(ping, 5*time.Millisecond)
    time.Sleep(25 * time.Millisecond)
    stop <- true
    time.Sleep(25 * time.Millisecond)

    fmt.Println("Done")
}

Playground

how to increase java heap memory permanently?

The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes: -Xms and -Xmx. You can add a system environment variable named _JAVA_OPTIONS, and set the heap size values there.
For example if you want a 512Mb initial and 1024Mb maximum heap size you could use:

under Windows:

SET _JAVA_OPTIONS = -Xms512m -Xmx1024m

under Linux:

export _JAVA_OPTIONS="-Xms512m -Xmx1024m"

It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.

public class GetHeapSize {
    public static void main(String[]args){

        //Get the jvm heap size.
        long heapSize = Runtime.getRuntime().totalMemory();

        //Print the jvm heap size.
        System.out.println("Heap Size = " + heapSize);
    }
}

Create a simple 10 second countdown

This does it in text.

_x000D_
_x000D_
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
    var timeleft = 10;_x000D_
    var downloadTimer = setInterval(function(){_x000D_
    timeleft--;_x000D_
    document.getElementById("countdowntimer").textContent = timeleft;_x000D_
    if(timeleft <= 0)_x000D_
        clearInterval(downloadTimer);_x000D_
    },1000);_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to represent matrices in python

If you are not going to use the NumPy library, you can use the nested list. This is code to implement the dynamic nested list (2-dimensional lists).

Let r is the number of rows

let r=3

m=[]
for i in range(r):
    m.append([int(x) for x in raw_input().split()])

Any time you can append a row using

m.append([int(x) for x in raw_input().split()])

Above, you have to enter the matrix row-wise. To insert a column:

for i in m:
    i.append(x) # x is the value to be added in column

To print the matrix:

print m       # all in single row

for i in m:
    print i   # each row in a different line

Renaming files in a folder to sequential numbers

Try to use a loop, let, and printf for the padding:

a=1
for i in *.jpg; do
  new=$(printf "%04d.jpg" "$a") #04 pad to length of 4
  mv -i -- "$i" "$new"
  let a=a+1
done

using the -i flag prevents automatically overwriting existing files.

Finding element in XDocument?

Sebastian's answer was the only answer that worked for me while examining a xaml document. If, like me, you'd like a list of all the elements then the method would look a lot like Sebastian's answer above but just returning a list...

    private static List<XElement> GetElements(XDocument doc, string elementName)
    {
        List<XElement> elements = new List<XElement>();

        foreach (XNode node in doc.DescendantNodes())
        {
            if (node is XElement)
            {
                XElement element = (XElement)node;
                if (element.Name.LocalName.Equals(elementName))
                    elements.Add(element);
            }
        }
        return elements;
    }

Call it thus:

var elements = GetElements(xamlFile, "Band");

or in the case of my xaml doc where I wanted all the TextBlocks, call it thus:

var elements = GetElements(xamlFile, "TextBlock");

Compiled vs. Interpreted Languages

The extreme and simple cases:

  • A compiler will produce a binary executable in the target machine's native executable format. This binary file contains all required resources except for system libraries; it's ready to run with no further preparation and processing and it runs like lightning because the code is the native code for the CPU on the target machine.

  • An interpreter will present the user with a prompt in a loop where he can enter statements or code, and upon hitting RUN or the equivalent the interpreter will examine, scan, parse and interpretatively execute each line until the program runs to a stopping point or an error. Because each line is treated on its own and the interpreter doesn't "learn" anything from having seen the line before, the effort of converting human-readable language to machine instructions is incurred every time for every line, so it's dog slow. On the bright side, the user can inspect and otherwise interact with his program in all kinds of ways: Changing variables, changing code, running in trace or debug modes... whatever.

With those out of the way, let me explain that life ain't so simple any more. For instance,

  • Many interpreters will pre-compile the code they're given so the translation step doesn't have to be repeated again and again.
  • Some compilers compile not to CPU-specific machine instructions but to bytecode, a kind of artificial machine code for a ficticious machine. This makes the compiled program a bit more portable, but requires a bytecode interpreter on every target system.
  • The bytecode interpreters (I'm looking at Java here) recently tend to re-compile the bytecode they get for the CPU of the target section just before execution (called JIT). To save time, this is often only done for code that runs often (hotspots).
  • Some systems that look and act like interpreters (Clojure, for instance) compile any code they get, immediately, but allow interactive access to the program's environment. That's basically the convenience of interpreters with the speed of binary compilation.
  • Some compilers don't really compile, they just pre-digest and compress code. I heard a while back that's how Perl works. So sometimes the compiler is just doing a bit of the work and most of it is still interpretation.

In the end, these days, interpreting vs. compiling is a trade-off, with time spent (once) compiling often being rewarded by better runtime performance, but an interpretative environment giving more opportunities for interaction. Compiling vs. interpreting is mostly a matter of how the work of "understanding" the program is divided up between different processes, and the line is a bit blurry these days as languages and products try to offer the best of both worlds.

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

public class Book
{
    public int number;
    public String title;
    public String language;
    public int price;

    // Add constructor, get, set, as needed.
}

then declare your array as:

Book[] books = new Book[3];

EDIT: In response to O.P.'s confusion, Book should be an object, not an array. Each book should be created on it's own (via a properly designed constructor) and then added to the array. In fact, I wouldn't use an array, but an ArrayList. In other words, you are trying to force data into containers that aren't suitable for the task at hand.

I would venture that 50% of programming is choosing the right data structure for your data. Algorithms naturally follow if there is a good choice of structure.

When properly done, you get your UI class to look like: Edit: Generics added to the following code snippet.

...
ArrayList<Book> myLibrary = new ArrayList<Book>();
myLibrary.add(new Book(1, "Thinking In Java", "English", 4999));
myLibrary.add(new Book(2, "Hacking for Fun and Profit", "English", 1099);

etc.

now you can use the Collections interface and do something like:

int total = 0;
for (Book b : myLibrary)
{
   total += b.price;
   System.out.println(b); // Assuming a valid toString in the Book class
}
System.out.println("The total value of your library is " + total);

SQL to Query text in access with an apostrophe in it

Escape the apostrophe in O'Neal by writing O''Neal (two apostrophes).

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

Here's a shell script I made for myself:

#! /bin/sh

for device in `adb devices | awk '{print $1}'`; do
  if [ ! "$device" = "" ] && [ ! "$device" = "List" ]
  then
    echo " "
    echo "adb -s $device $@"
    echo "------------------------------------------------------"
    adb -s $device $@
  fi
done

How can I have two fixed width columns with one flexible column in the center?

Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means:

  • 0 = don't grow (shorthand for flex-grow)
  • 0 = don't shrink (shorthand for flex-shrink)
  • 230px = start at 230px (shorthand for flex-basis)

which means: always be 230px.

See fiddle, thanks @TylerH

Oh, and you don't need the justify-content and align-items here.

img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

How do I remove blank pages coming between two chapters in Appendix?

I put the \let\cleardoublepage\clearpage before \makeindex. Else, your content page will display page number based on the page number before you clear the blank page.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

I fixed it by manually selecting a provisioning profile in the build settings for the test target.

Test target settings -> Build settings -> Code signing -> Code sign identity. Previously, it was set to "Don't code sign".

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:

0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)

Then I can declare something like

typedef struct {
  uint8_t msgType;
  uint16_t targetAddr; // may have to bswap
  uint8_t data[12];
  uint8_t checksum;
} __attribute__((packed)) myStruct;

and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.

Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.

Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)

add/remove active class for ul list with jquery?

you can use siblings and removeClass method

$('.nav-link li').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

If you are using docker-compose, and in docker-compose.yml have: volumes: - .:/myapp That means you local workspace is mapped to the container's /myapp folder.

Anything in /myapp will not be deleted for the volumes define.

You can delete ./tmp/pids/server.pid in you local machine. Then the container's /myapp will not have this file.

jQuery UI autocomplete with item and id

This can be done without the use of hidden field. You have to take benefit of the JQuerys ability to make custom attributes on run time.

('#selector').autocomplete({
    source: url,
    select: function (event, ui) {
        $("#txtAllowSearch").val(ui.item.label); // display the selected text
        $("#txtAllowSearch").attr('item_id',ui.item.value); // save selected id to hidden input
    }
});

$('#button').click(function() {
    alert($("#txtAllowSearch").attr('item_id')); // get the id from the hidden input
}); 

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

If you have not changed the defaults of Spring Boot (meaning you are using @EnableAutoConfiguration or @SpringBootApplication and have not changed any Property Source handling), then it will look for properties with the following order (highest overrides lowest):

  1. A /config subdir of the current directory
  2. The current directory
  3. A classpath /config package
  4. The classpath root

The list above is mentioned in this part of the documentation

What that means is that if a property is found for example application.properties under src/resources is will be overridden by a property with the same name found in application.properties in the /config directory that is "next" to the packaged jar.

This default order used by Spring Boot allows for very easy configuration externalization which in turn makes applications easy to configure in multiple environments (dev, staging, production, cloud etc)

To see the whole set of features provided by Spring Boot for property reading (hint: there is a lot more available than reading from application.properties) check out this part of the documentation.

As one can see from my short description above or from the full documentation, Spring Boot apps are very DevOps friendly!

Is it possible to dynamically compile and execute C# code fragments?

Others have already given good answers on how to generate code at runtime so I thought I would address your second paragraph. I have some experience with this and just want to share a lesson I learned from that experience.

At the very least, I could define an interface that they would be required to implement, then they would provide a code 'section' that implemented that interface.

You may have a problem if you use an interface as a base type. If you add a single new method to the interface in the future all existing client-supplied classes that implement the interface now become abstract, meaning you won't be able to compile or instantiate the client-supplied class at runtime.

I had this issue when it came time to add a new method after about 1 year of shipping the old interface and after distributing a large amount of "legacy" data that needed to be supported. I ended up making a new interface that inherited from the old one but this approach made it harder to load and instantiate the client-supplied classes because I had to check which interface was available.

One solution I thought of at the time was to instead use an actual class as a base type such as the one below. The class itself can be marked abstract but all methods should be empty virtual methods (not abstract methods). Clients can then override the methods they want and I can add new methods to the base class without invalidating existing client-supplied code.

public abstract class BaseClass
{
    public virtual void Foo1() { }
    public virtual bool Foo2() { return false; }
    ...
}

Regardless of whether this problem applies you should consider how to version the interface between your code base and the client-supplied code.

How to get root view controller?

Objective-C

UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController;

Swift 2.0

let viewController = UIApplication.sharedApplication().keyWindow?.rootViewController

Swift 5

let viewController = UIApplication.shared.keyWindow?.rootViewController

C# Lambda expressions: Why should I use them?

It saves having to have methods that are only used once in a specific place from being defined far away from the place they are used. Good uses are as comparators for generic algorithms such as sorting, where you can then define a custom sort function where you are invoking the sort rather than further away forcing you to look elsewhere to see what you are sorting on.

And it's not really an innovation. LISP has had lambda functions for about 30 years or more.

Render HTML string as real HTML in a React component

If you have control to the {this.props.match.description} and if you are using JSX. I would recommend not to use "dangerouslySetInnerHTML".

// In JSX, you can define a html object rather than a string to contain raw HTML
let description = <h1>Hi there!</h1>;

// Here is how you print
return (
    {description}
);

Get first key in a (possibly) associative array?

Since PHP 7.3.0 function array_key_first() can be used.

There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:

<?php
if (!function_exists('array_key_first')) {
    function array_key_first(array $arr) {
        foreach($arr as $key => $unused) {
            return $key;
        }
        return NULL;
    }
}
?>

summing two columns in a pandas dataframe

Same think can be done using lambda function. Here I am reading the data from a xlsx file.

import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df

Output:

  cluster Unnamed: 1      date  budget  actual
0       a 2014-01-01  00:00:00   11000   10000
1       a 2014-02-01  00:00:00    1200    1000
2       a 2014-03-01  00:00:00     200     100
3       b 2014-04-01  00:00:00     200     300
4       b 2014-05-01  00:00:00     400     450
5       c 2014-06-01  00:00:00     700    1000
6       c 2014-07-01  00:00:00    1200    1000
7       c 2014-08-01  00:00:00     200     100
8       c 2014-09-01  00:00:00     200     300

Sum two columns into 3rd new one.

df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df

Output:

  cluster Unnamed: 1      date  budget  actual  variance
0       a 2014-01-01  00:00:00   11000   10000     21000
1       a 2014-02-01  00:00:00    1200    1000      2200
2       a 2014-03-01  00:00:00     200     100       300
3       b 2014-04-01  00:00:00     200     300       500
4       b 2014-05-01  00:00:00     400     450       850
5       c 2014-06-01  00:00:00     700    1000      1700
6       c 2014-07-01  00:00:00    1200    1000      2200
7       c 2014-08-01  00:00:00     200     100       300
8       c 2014-09-01  00:00:00     200     300       500

Validate date in dd/mm/yyyy format using JQuery Validate

This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

console.log(dateRegex.test('21/01/1986'));

enter image description here

http://regexper.com/....

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

In my case, its because I copied pasted the command from the browser and it turned out that the dash was not the ASCII dash, just delete and type the dash again.

http://www.toptip.ca/2017/04/maven-most-weird-error-causing-failure.html

How to delete large data of table in SQL without log?

@Francisco Goldenstein, just a minor correction. The COMMIT must be used after you set the variable, otherwise the WHILE will be executed just once:

DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;

WHILE (@Deleted_Rows > 0)
BEGIN
    BEGIN TRANSACTION

    -- Delete some small number of rows at a time
    DELETE TOP (10000)  LargeTable 
    WHERE readTime < dateadd(MONTH,-7,GETDATE())

    SET @Deleted_Rows = @@ROWCOUNT;

    COMMIT TRANSACTION
    CHECKPOINT -- for simple recovery model

END

Check if a Bash array contains a value

Combining a few of the ideas presented here you can make an elegant if statment without loops that does exact word matches.

find="myword"
array=(value1 value2 myword)
if [[ ! -z $(printf '%s\n' "${array[@]}" | grep -w $find) ]]; then
  echo "Array contains myword";
fi

This will not trigger on word or val, only whole word matches. It will break if each array value contains multiple words.

iOS 7's blurred overlay effect using CSS?

I've been using svg filters to achieve similar effects for sprites

<svg id="gray_calendar" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 48 48 48">
  <filter id="greyscale">
    <feColorMatrix type="saturate" values="0"/>
  </filter>
  <image width="48" height="10224" xlink:href="tango48i.png" filter="url(#greyscale)"/>
</svg>
  • The viewBox attribute will select just the portion of your included image that you want.
  • Just change the filter to any that you want, such as Keith's <feGaussianBlur stdDeviation="10"/> example.
  • Use the <image ...> tag to apply it to any image or even use multiple images.
  • You can build this up with js and use it as an image or use the id in your css.

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Example

//In Model

public class MyModel
{  
   [Required]
    public string Name{ get; set; }
}

//In PartailView //PartailView.cshtml

@model MyModel

<div>
    <div>
      @Html.LabelFor(model=>model.Name)
    </div>
    <div>
        @Html.EditorFor(model=>model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
</div>

In Index.cshtml view

@model MyModel
<div id="targetId">
    @{Html.RenderPartial("PartialView",Model)}
</div>

@using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" }))
{
     <div>
        <input type="submit" value="Add Unit" />
    </div>
}

In Controller

public ActionResult Index()
{
  return View(new MyModel());
}


public string AddName(MyModel model)
{
   string HtmlString = RenderPartialViewToString("PartailView",model);
   return HtmlString;
}


protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model and append the content in "targetId" div in Index.cshtml. I this way by catching RenderHtml of partial view you can apply validation.

How to check if type is Boolean

The most reliable way to check type of a variable in JavaScript is the following:

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
toType(new Boolean(true)) // returns "boolean"
toType(true); // returns "boolean"

The reason for this complication is that typeof true returns "boolean" while typeof new Boolean(true) returns "object".

How can I check whether an array is null / empty?

In Java 8+ you achieve this with the help of streams allMatch method.

For primitive:

int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)

For Object:

Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)

Visual Studio Expand/Collapse keyboard shortcuts

I have always wanted Visual Studio to include an option to just collapse / expand the regions. I have the following macros which will do just that.

Imports EnvDTE
Imports System.Diagnostics
' Macros for improving keyboard support for "#region ... #endregion"
Public Module CollapseExpandRegions
' Expands all regions in the current document
  Sub ExpandAllRegions()

    Dim objSelection As TextSelection ' Our selection object

    DTE.SuppressUI = True ' Disable UI while we do this
    objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
    objSelection.StartOfDocument() ' Shoot to the start of the document

    ' Loop through the document finding all instances of #region. This action has the side benefit
    ' of actually zooming us to the text in question when it is found and ALSO expanding it since it
    ' is an outline.
    Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
        ' This next command would be what we would normally do *IF* the find operation didn't do it for us.
        'DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
    Loop
    objSelection.StartOfDocument() ' Shoot us back to the start of the document
    DTE.SuppressUI = False ' Reenable the UI

    objSelection = Nothing ' Release our object

  End Sub

  ' Collapses all regions in the current document
  Sub CollapseAllRegions()
    Dim objSelection As TextSelection ' Our selection object

    ExpandAllRegions() ' Force the expansion of all regions

    DTE.SuppressUI = True ' Disable UI while we do this
    objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
    objSelection.EndOfDocument() ' Shoot to the end of the document

    ' Find the first occurence of #region from the end of the document to the start of the document. Note:
    ' Note: Once a #region is "collapsed" .FindText only sees it's "textual descriptor" unless
    ' vsFindOptions.vsFindOptionsMatchInHiddenText is specified. So when a #region "My Class" is collapsed,
    ' .FindText would subsequently see the text 'My Class' instead of '#region "My Class"' for the subsequent
    ' passes and skip any regions already collapsed.
    Do While (objSelection.FindText("#region", vsFindOptions.vsFindOptionsBackwards))
        DTE.ExecuteCommand("Edit.ToggleOutliningExpansion") ' Collapse this #region
        'objSelection.EndOfDocument() ' Shoot back to the end of the document for
        ' another pass.
    Loop
    objSelection.StartOfDocument() ' All done, head back to the start of the doc
    DTE.SuppressUI = False ' Reenable the UI

    objSelection = Nothing ' Release our object

  End Sub
End Module

EDIT: There is now a shortcut called Edit.ToggleOutliningExpansion (Ctrl+M, Ctrl+M) for doing just that.

What is cURL in PHP?

Firstly let us understand the concepts of curl, libcurl and PHP/cURL.

  1. curl: A command line tool for getting or sending files using URL syntax.

  2. libcurl: a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

  3. PHP/cURL: The module for PHP that makes it possible for PHP programs to use libcurl.

How to use it:

step1: Initialize a curl session use curl_init().

step2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to.Append a search term "curl" using parameter "q=".Set option CURLOPT_RETURNTRANSFER, true will tell curl to return the string instead ofprint it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.

step3: Execute the curl session using curl_exec().

step4: Close the curl session we have created.

step5: Output the return string.

Make DEMO :

You will need to create two PHP files and place them into a folder that your web server can serve PHP files from. In my case I put them into /var/www/ for simplicity.

1. helloservice.php and 2. demo.php

helloservice.php is very simple and essentially just echoes back any data it gets:

<?php
  // Here is the data we will be sending to the service
  $some_data = array(
    'message' => 'Hello World', 
    'name' => 'Anand'
  );  

  $curl = curl_init();
  // You can also set the URL you want to communicate with by doing this:
  // $curl = curl_init('http://localhost/echoservice');

  // We POST the data
  curl_setopt($curl, CURLOPT_POST, 1);
  // Set the url path we want to call
  curl_setopt($curl, CURLOPT_URL, 'http://localhost/demo.php');  
  // Make it so the data coming back is put into a string
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  // Insert the data
  curl_setopt($curl, CURLOPT_POSTFIELDS, $some_data);

  // You can also bunch the above commands into an array if you choose using: curl_setopt_array

  // Send the request
  $result = curl_exec($curl);

  // Get some cURL session information back
  $info = curl_getinfo($curl);  
  echo 'content type: ' . $info['content_type'] . '<br />';
  echo 'http code: ' . $info['http_code'] . '<br />';

  // Free up the resources $curl is using
  curl_close($curl);

  echo $result;
?>

2.demo.php page, you can see the result:

<?php 
   print_r($_POST);
   //content type: text/html; charset=UTF-8
   //http code: 200
   //Array ( [message] => Hello World [name] => Anand )
?>

Jump to function definition in vim

To second Paul's response: yes, ctags (especially exuberant-ctags (http://ctags.sourceforge.net/)) is great. I have also added this to my vimrc, so I can use one tags file for an entire project:

set tags=tags;/

Finding duplicate integers in an array and display how many times they occurred

int[] arr = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var result = arr.GroupBy(x => x).Select(x => new { key = x.Key, val = x.Count() });       
foreach (var item in result)
{
    if(item.val > 1)
    {                
        Console.WriteLine("Duplicate value : {0}", item.key);
        Console.WriteLine("MaxCount : {0}", item.val);
    }

}

Console.ReadLine();

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

How to get a user's client IP address in ASP.NET?

Its easy.Try it:

var remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;

just it :))

Javascript Image Resize

I have answered this question here: How to resize images proportionally / keeping the aspect ratio?. I am copying it here because I really think it is a very reliable method :)

 /**
  * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
  * images to fit into a certain area.
  *
  * @param {Number} srcWidth width of source image
  * @param {Number} srcHeight height of source image
  * @param {Number} maxWidth maximum available width
  * @param {Number} maxHeight maximum available height
  * @return {Object} { width, height }
  */
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }

Can we pass parameters to a view in SQL?

You can bypass just to run the view, SQL will wine and cry but just do this and run it! You can't save.

create or replace view v_emp(eno number) as select * from emp where (emp_id = @Parameter1);

Execute command on all files in a directory

How about this:

find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
  • -maxdepth 1 argument prevents find from recursively descending into any subdirectories. (If you want such nested directories to get processed, you can omit this.)
  • -type -f specifies that only plain files will be processed.
  • -exec cmd option {} tells it to run cmd with the specified option for each file found, with the filename substituted for {}
  • \; denotes the end of the command.
  • Finally, the output from all the individual cmd executions is redirected to results.out

However, if you care about the order in which the files are processed, you might be better off writing a loop. I think find processes the files in inode order (though I could be wrong about that), which may not be what you want.

PHP CURL & HTTPS

One important note, the solution mentioned above will not work on local host, you have to upload your code to server and then it will work. I was getting no error, than bad request, the problem was I was using localhost (test.dev,myproject.git). Both solution above work, the solution that uses SSL cert is recommended.

  1. Go to https://curl.haxx.se/docs/caextract.html, download the latest cacert.pem. Store is somewhere (not in public folder - but will work regardless)

  2. Use this code

".$result; //echo "
Path:".$_SERVER['DOCUMENT_ROOT'] . "/ssl/cacert.pem"; // this is for troubleshooting only ?>
  1. Upload the code to live server and test.

String replacement in batch file

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%

Copy row but with new id

SET @table = 'the_table';
SELECT GROUP_CONCAT(IF(COLUMN_NAME IN ('id'), 0, CONCAT("\`", COLUMN_NAME, "\`"))) FROM INFORMATION_SCHEMA.COLUMNS
                  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = @table INTO @columns;
SET @s = CONCAT('INSERT INTO ', @table, ' SELECT ', @columns,' FROM ', @table, ' WHERE id=1');
PREPARE stmt FROM @s;
EXECUTE stmt;

Convert timestamp to date in MySQL query

If the registration field is indeed of type TIMESTAMP you should be able to just do:

$sql = "SELECT user.email, 
           info.name, 
           DATE(user.registration), 
           info.news
      FROM user, 
           info 
     WHERE user.id = info.id ";

and the registration should be showing as yyyy-mm-dd

How do you specify a different port number in SQL Management Studio?

Using the client manager affects all connections or sets a client machine specific alias.

Use the comma as above: this can be used in an app.config too

It's probably needed if you have firewalls between you and the server too...

gdb: "No symbol table is loaded"

Whenever gcc on the compilation machine and gdb on the testing machine have differing versions, you may be facing debuginfo format incompatibility.

To fix that, try downgrading the debuginfo format:

gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...

Or match gdb to the gcc you're using.

Customize UITableView header section

If you just want to add title to the tableView header dont add a view. In swift 3.x the code goes like this:

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    var lblStr = ""
    if section == 0 {
        lblStr = "Some String 1"
    }
    else if section == 1{
        lblStr = "Some String 2"
    }
    else{
        lblStr = "Some String 3"
    }
    return lblStr
}

You may implement an array to fetch the title for the headers.

how do I get the bullet points of a <ul> to center with the text?

I found the answer today. Maybe its too late but still I think its a much better one. Check this one https://jsfiddle.net/Amar_newDev/khb2oyru/5/

Try to change the CSS code : <ul> max-width:1%; margin:auto; text-align:left; </ul>

max-width:80% or something like that.

Try experimenting you might find something new.

Finding whether a point lies inside a rectangle or not

How is the rectangle represented? Three points? Four points? Point, sides and angle? Two points and a side? Something else? Without knowing that, any attempts to answer your question will have only purely academic value.

In any case, for any convex polygon (including rectangle) the test is very simple: check each edge of the polygon, assuming each edge is oriented in counterclockwise direction, and test whether the point lies to the left of the edge (in the left-hand half-plane). If all edges pass the test - the point is inside. If at least one fails - the point is outside.

In order to test whether the point (xp, yp) lies on the left-hand side of the edge (x1, y1) - (x2, y2), you just need to calculate

D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)

If D > 0, the point is on the left-hand side. If D < 0, the point is on the right-hand side. If D = 0, the point is on the line.


The previous version of this answer described a seemingly different version of left-hand side test (see below). But it can be easily shown that it calculates the same value.

... In order to test whether the point (xp, yp) lies on the left-hand side of the edge (x1, y1) - (x2, y2), you need to build the line equation for the line containing the edge. The equation is as follows

A * x + B * y + C = 0

where

A = -(y2 - y1)
B = x2 - x1
C = -(A * x1 + B * y1)

Now all you need to do is to calculate

D = A * xp + B * yp + C

If D > 0, the point is on the left-hand side. If D < 0, the point is on the right-hand side. If D = 0, the point is on the line.

However, this test, again, works for any convex polygon, meaning that it might be too generic for a rectangle. A rectangle might allow a simpler test... For example, in a rectangle (or in any other parallelogram) the values of A and B have the same magnitude but different signs for opposing (i.e. parallel) edges, which can be exploited to simplify the test.

How to make PyCharm always show line numbers

For version 3.0 (Community Edition):

File -> Settings -> Editor (under IDE Settings) -> Appearance -> check 'Show line numbers'

PHP - remove <img> tag from string

I would suggest using the strip_tags method.

"Faceted Project Problem (Java Version Mismatch)" error message

In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.

Thanks & Regards Vengat Maran

Does a valid XML file require an XML declaration?

In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.

Note that in an XML Declaration the encoding and standalone are both optional. Only the version is mandatory. Also, these are not attributes, so if they are present they must be in that order: version, followed by any encoding, followed by any standalone.

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

If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.

The standalone indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.

Update:

A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.

Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?> which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding and simply say <?xml version="1.0"?>. You could also edit it to say encoding="UTF-16" but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.

Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!

rsync error: failed to set times on "/foo/bar": Operation not permitted

I had the same problem. For me the solution is to delete the remote file and let rsync create again.

Iterating through a string word by word

Using nltk.

from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)

You may use TweetTokenizer for parsing casual text with emoticons and such.

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

How can I ping a server port with PHP?

You can use exec function

 exec("ping ".$ip);

here an example

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

A comparison between the different Visual Studio Express editions can be found at Visual Studio Express (archive.org link). The difference between Windows and Windows Desktop is that with the Windows edition you can build Windows Store Apps (using .NET, WPF/XAML) while the Windows Desktop edition allows you to write classic Windows Desktop applications. It is possible to install both products on the same machine.

Visual Studio Express 2010 allows you to build Windows Desktop applications. Writing Windows Store applications is not possible with this product.

For learning I would suggest Notepad and the command line. While an IDE provides significant productivity enhancements to professionals, it can be intimidating to a beginner. If you want to use an IDE nevertheless I would recommend Visual Studio Express 2013 for Windows Desktop.


Update 2015-07-27: In addition to the Express Editions, Microsoft now offers Community Editions. These are still free for individual developers, open source contributors, and small teams. There are no Web, Windows, and Windows Desktop releases anymore either; the Community Edition can be used to develop any app type. In addition, the Community Edition does support (3rd party) Add-ins. The Community Edition offers the same functionality as the commercial Professional Edition.

Attempted to read or write protected memory

I was using OLEDB and I switched to SQL Client and it solved my problem with this error.

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

You just need to 'capture' the bit between the brackets.

\[(.*?)\]

To capture you put it inside parentheses. You do not say which language this is using. In Perl for example, you would access this using the $1 variable.

my $string ='This is the match [more or less]';
$string =~ /\[(.*?)\]/;
print "match:$1\n";

Other languages will have different mechanisms. C#, for example, uses the Match collection class, I believe.

How to add /usr/local/bin in $PATH on Mac

I've had the same problem with you.

cd to ../etc/ then use ls to make sure your "paths" file is in , vim paths, add "/usr/local/bin" at the end of the file.

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

annotation to make a private method public only for test classes

We recently released a library that helps a lot to access private fields, methods and inner classes through reflection : BoundBox

For a class like

public class Outer {
    private static class Inner {
        private int foo() {return 2;}
    }
}

It provides a syntax like :

Outer outer = new Outer();
Object inner = BoundBoxOfOuter.boundBox_new_Inner();
new BoundBoxOfOuter.BoundBoxOfInner(inner).foo();

The only thing you have to do to create the BoundBox class is to write @BoundBox(boundClass=Outer.class) and the BoundBoxOfOuter class will be instantly generated.

How to set default value to the input[type="date"]

You can do something like this:

<input type="date" value="<?php echo date("Y-m-d");?>" name="inicio">

Append integer to beginning of list in Python

list_1.insert(0,ur_data)

make sure that ur_data is of string type so if u have data= int(5) convert it to ur_data = str(data)

CodeIgniter Active Record not equal

According to the manual this should work:

Custom key/value method:

You can include an operator in the first parameter in order to control the comparison:

$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45

Search for $this->db->where(); and look at item #2.

This Handler class should be static or leaks might occur: IncomingHandler

I'm confused. The example I found avoids the static property entirely and uses the UI thread:

    public class example extends Activity {
        final int HANDLE_FIX_SCREEN = 1000;
        public Handler DBthreadHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                int imsg;
                imsg = msg.what;
                if (imsg == HANDLE_FIX_SCREEN) {
                    doSomething();
                }
            }
        };
    }

The thing I like about this solution is there is no problem trying to mix class and method variables.

How do I format date in jQuery datetimepicker?

this worked for me.

$(document).ready(function () {
    $("#datePicker").datetimepicker({
        format: 'DD/MM/YYYY HH:mm:ss',
        defaultDate: new Date(),
    });
}

here are the CDN links

<!-- datetime picker -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/css/bootstrap-datetimepicker.min.css"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.4/js/bootstrap-datetimepicker.min.js"></script>

How to retrieve value from elements in array using jQuery?

Use: http://jsfiddle.net/xH79d/

var n = $("input[name^='card']").length;
var array = $("input[name^='card']");

for(i=0; i < n; i++) {

   // use .eq() within a jQuery object to navigate it by Index

   card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
   // otherwise it'd be .eq(i).val(); (if you wanted the text value)
   alert(card_value);
}

?

CodeIgniter activerecord, retrieve last insert id?

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

Information from executing a query

How to get selected value from Dropdown list in JavaScript

According to Html5 specs you should use -- element.options[e.selectedIndex].text

e.g. if you have select box like below :

<select id="selectbox1">
    <option value="1">First</option>
    <option value="2" selected="selected">Second</option>
    <option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>

you can get value using following script :

<script>
 function GetItemValue(q) {
   var e = document.getElementById(q);
   var selValue = e.options[e.selectedIndex].text ;
   alert("Selected Value: "+selValue);
 }
</script>

Tried and tested.

Encrypting & Decrypting a String in C#

You may be looking for the ProtectedData class, which encrypts data using the user's logon credentials.

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Configuring Git over SSH to login once

Make sure that when you cloned the repository, you did so with the SSH URL and not the HTTPS; in the clone URL box of the repo, choose the SSH protocol before copying the URL. See image below:

enter image description here

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Ubuntu 10.04 comes with the Suhosin patch only, which does not give you configuration options. But you can install php5-suhosin to solve this:

apt-get update
apt-get install php5-suhosin

Now you can edit /etc/php5/conf.d/suhosin.ini and set:

suhosin.memory_limit = 1G

Then using ini_set will work in a script:

ini_set('memory_limit', '256M');

Calling a function every 60 seconds

A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function myTimer() {

}

var timer = setInterval(myTimer, 5000);

call this line to stop the loop:

clearInterval(timer);

Can't specify the 'async' modifier on the 'Main' method of a console app

In my case I had a list of jobs that I wanted to run in async from my main method, have been using this in production for quite sometime and works fine.

static void Main(string[] args)
{
    Task.Run(async () => { await Task.WhenAll(jobslist.Select(nl => RunMulti(nl))); }).GetAwaiter().GetResult();
}
private static async Task RunMulti(List<string> joblist)
{
    await ...
}

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I had this due to a simple ordering mistake on my end. I called

[WRONG] docker run <image> <arguments> <command>

When I should have used

docker run <arguments> <image> <command>

Same resolution on similar question: https://stackoverflow.com/a/50762266/6278

Access props inside quotes in React JSX

Instead of adding variables and strings, you can use the ES6 template strings! Here is an example:

<img className="image" src={`images/${this.props.image}`} />

As for all other JavaScript components inside JSX, use template strings inside of curly braces. To "inject" a variable use a dollar sign followed by curly braces containing the variable you would like to inject. For example:

{`string ${variable} another string`}

How to change the style of alert box?

I don't think you could change the style of browsers' default alert boxes.

You need to create your own or use a simple and customizable library like xdialog. Following is a example to customize the alert box. More demos can be found here.

_x000D_
_x000D_
function show_alert() {_x000D_
    xdialog.alert("Hello! I am an alert box!");_x000D_
}
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.css"/>_x000D_
    <script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.js"></script>_x000D_
    _x000D_
    <style>_x000D_
        .xd-content .xd-body .xd-body-inner {_x000D_
            max-height: unset;_x000D_
        }_x000D_
        .xd-content .xd-body p {_x000D_
            color: #f0f;_x000D_
            text-shadow: 0 0 5px rgba(0, 0, 0, 0.75);_x000D_
        }_x000D_
        .xd-content .xd-button.xd-ok {_x000D_
            background: #734caf;_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
<body>_x000D_
    <input type="button" onclick="show_alert()" value="Show alert box" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

Can I use an image from my local file system as background in HTML?

background: url(../images/backgroundImage.jpg) no-repeat center center fixed;

this should help

How to pattern match using regular expression in Scala?

You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.

val Pattern = "([a-cA-C])".r
word.firstLetter match {
   case Pattern(c) => c bound to capture group here
   case _ =>
}

Java word count program

You can use this code.It may help you:

public static void main (String[] args)
{

   System.out.println("Simple Java Word Count Program");

   String str1 = "Today is Holdiay Day";
   int count=0;
   String[] wCount=str1.split(" ");

   for(int i=0;i<wCount.length;i++){
        if(!wCount[i].isEmpty())
        {
            count++;
        }
   }
   System.out.println(count);
}

Html.EditorFor Set Default Value

In the constructor method of your model class set the default value whatever you want. Then in your first action create an instance of the model and pass it to your view.

    public ActionResult VolunteersAdd()
    {
        VolunteerModel model = new VolunteerModel(); //to set the default values
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult VolunteersAdd(VolunteerModel model)
    {


        return View(model);
    }

Set custom attribute using JavaScript

Use the setAttribute method:

document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");

But you really should be using data followed with a dash and with its property, like:

<li ... data-icon="base.gif" ...>

And to do it in JS use the dataset property:

document.getElementById('item1').dataset.icon = "base.gif";

Reverse HashMap keys and values in Java

Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)

Sample code

HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap) 

Select folder dialog WPF

The FolderBrowserDialog class from System.Windows.Forms is the recommended way to display a dialog that allows a user to select a folder.

Until recently, the appearance and behaviour of this dialog was not in keeping with the other filesystem dialogs, which is one of the reasons why people were reluctant to use it.

The good news is that FolderBrowserDialog was "modernized" in NET Core 3.0, so is now a viable option for those writing either Windows Forms or WPF apps targeting that version or later.

In .NET Core 3.0, Windows Forms users [sic] a newer COM-based control that was introduced in Windows Vista: FolderBrowserDialog in NET Core 3.0

To reference System.Windows.Forms in a NET Core WPF app, it is necessary to edit the project file and add the following line:

<UseWindowsForms>true</UseWindowsForms>

This can be placed directly after the existing <UseWPF> element.

Then it's just a case of using the dialog:

using System;
using System.Windows.Forms;

...

using var dialog = new FolderBrowserDialog
{
    Description = "Time to select a folder",
    UseDescriptionForTitle = true,
    SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
        + Path.DirectorySeparatorChar,
    ShowNewFolderButton = true
};

if (dialog.ShowDialog() == DialogResult.OK)
{
    ...
}

FolderBrowserDialog has a RootFolder property that supposedly "sets the root folder where the browsing starts from" but whatever I set this to it didn't make any difference; SelectedPath seemed to be the better property to use for this purpose, however the trailing backslash is required.

Also, the ShowNewFolderButton property seems to be ignored as well, the button is always shown regardless.

Pass an array of integers to ASP.NET Web API?

I have created a custom model binder which converts any comma separated values (only primitive, decimal, float, string) to their corresponding arrays.

public class CommaSeparatedToArrayBinder<T> : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            Type type = typeof(T);
            if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String) || type == typeof(float))
            {
                ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (val == null) return false;

                string key = val.RawValue as string;
                if (key == null) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type"); return false; }

                string[] values = key.Split(',');
                IEnumerable<T> result = this.ConvertToDesiredList(values).ToArray();
                bindingContext.Model = result;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Only primitive, decimal, string and float data types are allowed...");
            return false;
        }

        private IEnumerable<T> ConvertToDesiredArray(string[] values)
        {
            foreach (string value in values)
            {
                var val = (T)Convert.ChangeType(value, typeof(T));
                yield return val;
            }
        }
    }

And how to use in Controller:

 public IHttpActionResult Get([ModelBinder(BinderType = typeof(CommaSeparatedToArrayBinder<int>))] int[] ids)
        {
            return Ok(ids);
        }

What is the difference between varchar and varchar2 in Oracle?

Currently VARCHAR behaves exactly the same as VARCHAR2. However, the type VARCHAR should not be used as it is reserved for future usage.

Taken from: Difference Between CHAR, VARCHAR, VARCHAR2

How do I run pip on python for windows?

I have a Mac, but luckily this should work the same way:

pip is a command-line thing. You don't run it in python.

For example, on my Mac, I just say:

$pip install somelib

pretty easy!

How to set the 'selected option' of a select dropdown list with jquery

The match between .val('Bruce jones') and value="Bruce Jones" is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase() on both.

Nginx not running with no error message

Check the daemon option in nginx.conf file. It has to be ON. Or you can simply rip out this line from config file. This option is fully described here http://nginx.org/en/docs/ngx_core_module.html#daemon

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect

    <?php

$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion        = $_POST['seccion'];
$precio         = $_POST['precio'];
$fecha          = $_POST['fecha'];
$importado      = $_POST['importado'];
$paisdeorigen   = $_POST['paisdeorigen'];
try {

  $server = 'mysql: host=localhost; dbname=usuarios';
  $user   = 'root';
  $pass   = '';
  $base   = new PDO($server, $user, $pass);

  $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $base->query("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $base->exec("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $sql = "
  INSERT INTO productos
  (CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
  VALUES
  (:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
  $result = $base->prepare($sql);
//  se pasan por parametros aqui
  $result->bindParam(':c_art', $codigoarticulo);
  $result->bindParam(':n_art', $nombrearticulo);
  $result->bindParam(':sec', $seccion);
  $result->bindParam(':pre', $precio);
  $result->bindParam(':fecha_art', $fecha);
  $result->bindParam(':import', $importado);
  $result->bindParam(':p_orig', $paisdeorigen);
  $result->execute();
  echo 'Articulo agregado';
} catch (Exception $e) {

  echo 'Error';
  echo $e->getMessage();
} finally {

}

?>

How do shift operators work in Java?

The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.

For example,

i >>= 2

produces the same result as

i = i >> 2

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Consider the partial map.cshtml at Partials/Map.cshtml. This can be called from the Page where the partial is to be rendered, simply by using the <partial> tag:

<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />

This is one of the easiest methods I encountered (although I am using razor pages, I am sure same is for MVC too)

How can I pass POST parameters in a URL?

No, you cannot do that. I invite you to read a POST definition.

Or this page: HTTP, request methods

Retina displays, high-res background images

If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200 and have two icons in top row and two icon in bottom row. So, it's four quadrants.

.sprite-of-icons {
  background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
  background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}

.sp-logo-1 { background-position: 0 0; }

/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }

Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.


Another handy SCSS mixin solution by Ryan Benhase.

/****************************
 HIGH PPI DISPLAY BACKGROUNDS
*****************************/

@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {

  $at1x_path: "#{$path}.#{$ext}";
  $at2x_path: "#{$path}@2x.#{$ext}";

  background-image: url("#{$at1x_path}");
  background-size: $w $h;
  background-position: $pos;
  background-repeat: $repeat;

  @media all and (-webkit-min-device-pixel-ratio : 1.5),
  all and (-o-min-device-pixel-ratio: 3/2),
  all and (min--moz-device-pixel-ratio: 1.5),
  all and (min-device-pixel-ratio: 1.5) {
    background-image: url("#{$at2x_path}"); 
  }
}

div.background {
  @include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}

For more info about above mixin READ HERE.

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I had the same issue after an upgrade from VS2013 to VS2015.

The project I was working at referenced itself. While VS2013 didn't care, VS2015 didn't like that and I got that error. After deleting the reference, the error was gone. It took me around 4 hours to find that out...

Null or empty check for a string variable

declare @sexo as char(1)

select @sexo='F'

select * from pessoa

where isnull(Sexo,0) =isnull(@Sexo,0)

SSIS Text was truncated with status value 4

If all other options have failed, trying recreating the data import task and/or the connection manager. If you've made any changes since the task was originally created, this can sometimes do the trick. I know it's the equivalent of rebooting, but, hey, if it works, it works.

Java String - See if a string contains only numbers and not letters

This is how I would do it:

if(text.matches("^[0-9]*$") && text.length() > 2){
    //...
}

The $ will avoid a partial match e.g; 1B.

Appending a line to a file only if it does not already exist

If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>. A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"

How do I keep CSS floats in one line?

Another option: Do not float your right column; just give it a left margin to move it beyond the float. You'll need a hack or two to fix IE6, but that's the basic idea.

Using Case/Switch and GetType to determine the object

One approach is to add a pure virtual GetNodeType() method to NodeDTO and override it in the descendants so that each descendant returns actual type.

How to center images on a web page for all screen sizes

text-align:center

Applying the text-align:center style to an element containing elements will center those elements.

<div id="method-one" style="text-align:center">
  CSS `text-align:center`
</div>

Thomas Shields mentions this method



margin:0 auto

Applying the margin:0 auto style to a block element will center it within the element it is in.

<div id="method-two" style="background-color:green">
  <div style="margin:0 auto;width:50%;background-color:lightblue">
    CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
  </div>
</div>

user1468562 mentions this method


Center tag

My original answer was that you can use the <center></center> tag. To do this, just place the content you want centered between the tags. As of HTML4, this tag has been deprecated, though. <center> is still technically supported today (9 years later at the time of updating this), but I'd recommend the CSS alternatives I've included above.

<h3>Method 3</h1>
<div id="method-three">
  <center>Center tag (not recommended and deprecated in HTML4)</center>
</div>

You can see these three code samples in action in this jsfiddle.

I decided I should revise this answer as the previous one I gave was outdated. It was already deprecated when I suggested it as a solution and that's all the more reason to avoid it now 9 years later.

How to initialize std::vector from C-style array?

Don't forget that you can treat pointers as iterators:

w_.assign(w, w + len);

Placeholder in UITextView

Hi you can use IQTextView available in IQKeyboard Manager it's simple to use and integrate just set class of your textview to IQTextView and you can use its property for setting placeholder label with color you want. You can download the library from IQKeyboardManager

or you can install it from cocoapods.

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

:q! will force an unconditional no-save exit

How do I test axios in Jest?

I've done this with nock, like so:

import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'

axios.defaults.adapter = httpAdapter

describe('foo', () => {
    it('bar', () => {
        nock('https://example.com:443')
            .get('/example')
            .reply(200, 'some payload')

        // test...
    })
})

How can I disable ARC for a single file in a project?

  1. select project -> targets -> build phases -> compiler sources
  2. select file -> compiler flags
  3. add -fno-objc-arc

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

In my case I was trying to test SSL in my Visual Studio environment using IIS 7.

This is what I ended up doing to get it to work:

  • Under my site in the 'Bindings...' section on the right in IIS, I had to add the 'https' binding to port 443 and select "IIS Express Developement Certificate".

  • Under my site in the 'Advanced Settings...' section on the right I had to change the 'Enabled Protocols' from "http" to "https".

  • Under the 'SSL Settings' icon I selected 'Accept' for client certificates.

  • Then I had to recycle the app pool.

  • I also had to import the local host certificate into my personal store using mmc.exe.

My web.config file was already configured correctly, so after I got all the above sorted out, I was able to continue my testing.

SQL Server Regular expressions in T-SQL

How about the PATINDEX function?

The pattern matching in TSQL is not a complete regex library, but it gives you the basics.

(From Books Online)

Wildcard  Meaning  
% Any string of zero or more characters.

_ Any single character.

[ ] Any single character within the specified range 
    (for example, [a-f]) or set (for example, [abcdef]).

[^] Any single character not within the specified range 
    (for example, [^a - f]) or set (for example, [^abcdef]).

How can I get a count of the total number of digits in a number?

Using recursion (sometimes asked on interviews)

public int CountDigits(int number)
{
    // In case of negative numbers
    number = Math.Abs(number);

    if (number >= 10)
        return CountDigits(number / 10) + 1;
    return 1;
 }

swift UITableView set rowHeight

Put the default rowHeight in viewDidLoad or awakeFromNib. As pointed out by Martin R., you cannot call cellForRowAtIndexPath from heightForRowAtIndexPath

self.tableView.rowHeight = 44.0

jquery get all form elements: input, textarea & select

all inputs:

var inputs = $("#formId :input");

all buttons

var button = $("#formId :button")

Appending to an existing string

you can also use the following:

s.concat("world")

Rebase array keys after unsetting elements

I use $arr = array_merge($arr); to rebase an array. Simple and straightforward.

Find size of object instance in bytes in c#

You may be able to approximate the size by pretending to serializing it with a binary serializer (but routing the output to oblivion) if you're working with serializable objects.

class Program
{
    static void Main(string[] args)
    {
        A parent;
        parent = new A(1, "Mike");
        parent.AddChild("Greg");
        parent.AddChild("Peter");
        parent.AddChild("Bobby");

        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
           new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        SerializationSizer ss = new SerializationSizer();
        bf.Serialize(ss, parent);
        Console.WriteLine("Size of serialized object is {0}", ss.Length);
    }
}

[Serializable()]
class A
{
    int id;
    string name;
    List<B> children;
    public A(int id, string name)
    {
        this.id = id;
        this.name = name;
        children = new List<B>();
    }

    public B AddChild(string name)
    {
        B newItem = new B(this, name);
        children.Add(newItem);
        return newItem;
    }
}

[Serializable()]
class B
{
    A parent;
    string name;
    public B(A parent, string name)
    {
        this.parent = parent;
        this.name = name;
    }
}

class SerializationSizer : System.IO.Stream
{
    private int totalSize;
    public override void Write(byte[] buffer, int offset, int count)
    {
        this.totalSize += count;
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override void Flush()
    {
        // Nothing to do
    }

    public override long Length
    {
        get { return totalSize; }
    }

    public override long Position
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        throw new NotImplementedException();
    }

    public override long Seek(long offset, System.IO.SeekOrigin origin)
    {
        throw new NotImplementedException();
    }

    public override void SetLength(long value)
    {
        throw new NotImplementedException();
    }
}

What is the return value of os.system() in Python?

os.system() returns some unix output, not the command output. So, if there is no error then exit code written as 0.

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

Leap year calculation

In the Gregorian calendar 3 criteria must be taken into account to identify leap years:

  1. The year is evenly divisible by 4;
  2. If the year can be evenly divided by 100, it is NOT a leap year, unless;
  3. The year is also evenly divisible by 400. Then it is a leap year. Why the year divided by 100 is not leap year

How to check if a socket is connected/disconnected in C#?

Use Socket.Connected Property.

--UPDATE--

As Paul Turner answered Socket.Connected cannot be used in this situation. You need to poll connection every time to see if connection is still active. See 2

Android eclipse DDMS - Can't access data/data/ on phone to pull files

Much simpler than messing around with permissions in the android FS (which always feels like
a hack for me - because i believe there must be a kind of integrated way) is just to:

Allow ADB root access and Restart the deamon with root permissions.

  1. First be sure that ADB can have root access on your device (or emulator):
    (Settings -> Developer Options -> Root-Access for ADB or Apps & ADB.
  2. Restart the ADB-Service with root-permissions:
    Open a command prompt and type: adb.exe root
  3. Restart ADM (Android Device Manager):
    Enjoy browsing all files
  4. To negate this process:
    Type adb.exe unroot in your command prompt.

Calculating how many days are between two dates in DB2?

It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,

So your Query will be

select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';

How to solve java.lang.NullPointerException error?

Just a shot in the dark(since you did not share the compiler initialization code with us): the way you retrieve the compiler causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE.

How to test valid UUID/GUID?

Use the .match() method to check whether String is UUID.

public boolean isUUID(String s){
    return s.match("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
}

OnClick in Excel VBA

Just a follow-up to dbb's accepted answer: Rather than adding the immediate cell on the right to the selection, why not select a cell way off the working range (i.e. a dummy cell that you know the user will never need). In the following code cell ZZ1 is the dummy cell

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Application.EnableEvents = False
  Union(Target, Me.Range("ZZ1")).Select
  Application.EnableEvents = True

  ' Respond to click/selection-change here

End Sub

How to create a thread?

The following ways work.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

How to change the color of winform DataGridview header?

The way to do this is to set the EnableHeadersVisualStyles flag for the data grid view to False, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):

_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;

If you do not set the EnableHeadersVisualStyles flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.

Performing user authentication in Java EE / JSF using j_security_check

It should be mentioned that it is an option to completely leave authentication issues to the front controller, e.g. an Apache Webserver and evaluate the HttpServletRequest.getRemoteUser() instead, which is the JAVA representation for the REMOTE_USER environment variable. This allows also sophisticated log in designs such as Shibboleth authentication. Filtering Requests to a servlet container through a web server is a good design for production environments, often mod_jk is used to do so.

Only Add Unique Item To List

If your requirements are to have no duplicates, you should be using a HashSet.

HashSet.Add will return false when the item already exists (if that even matters to you).

You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice (GetHashCode & Equals).

Initialize a vector array of strings

In C++0x you will be able to initialize containers just like arrays

http://www2.research.att.com/~bs/C++0xFAQ.html#init-list

Replace Both Double and Single Quotes in Javascript String

You don't escape quotes in regular expressions

this.Vals.replace(/["']/g, "")