Programs & Examples On #Moss

Microsoft Office SharePoint Server (previously known as Microsoft Office SharePoint Server, or MOSS) is a member of Microsoft's SharePoint server product family.

Where is the default log location for SharePoint/MOSS?

For SharePoint 2016

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs

For SharePoint 2013

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\15\Logs

For SharePoint 2010

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\14\Logs

For SharePoint 2007

%COMMONPROGRAMFILES%\Microsoft Shared\Web Server Extensions\12\Logs

Note: The sharePoint Trace log path can be changed by opening Central Administration > Monitoring > Reporting > Configure Diagnostic Logs

For more details check SHAREPOINT ULS VIEWER

Auto number column in SharePoint list

If you want to control the formatting of the unique identifier you can create your own <FieldType> in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.

WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.

A solution might exist without creating a custom <FieldType>. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]). I haven't tried this, but this should work :)

SQL Server: Filter output of sp_who2

based on http://web.archive.org/web/20080218124946/http://sqlserver2005.databases.aspfaq.com/how-do-i-mimic-sp-who2.html

i have created following script ,
which resolves finding active connections to any datbase using DMV this works under sql 2005 , 2008 and 2008R2

Following script uses sys.dm_exec_sessions , sys.dm_exec_requests , sys.dm_exec_connections , sys.dm_tran_locks

Declare @dbName varchar(1000)
set @dbName='abc'

;WITH DBConn(SPID,[Status],[Login],HostName,DBName,Command,LastBatch,ProgramName)
As
(
SELECT 
    SPID = s.session_id,
    Status = UPPER(COALESCE
        (
            r.status,
            ot.task_state,
            s.status, 
        '')),
    [Login] = s.login_name,
    HostName = COALESCE
        (
            s.[host_name],
            '  .'
        ),
    DBName = COALESCE
        (
            DB_NAME(COALESCE
            (
                r.database_id,
                t.database_id
            )),
            ''
        ),
    Command = COALESCE
        (
            r.Command,
            r.wait_type,
            wt.wait_type,
            r.last_wait_type,
            ''
        ),
    LastBatch = COALESCE
        (
            r.start_time,
            s.last_request_start_time
        ),
    ProgramName = COALESCE
        (
            s.program_name, 
            ''
        )
FROM
    sys.dm_exec_sessions s
LEFT OUTER JOIN
    sys.dm_exec_requests r
ON
    s.session_id = r.session_id
LEFT OUTER JOIN
    sys.dm_exec_connections c
ON
    s.session_id = c.session_id
LEFT OUTER JOIN
(
    SELECT 
        request_session_id,
        database_id = MAX(resource_database_id)
    FROM
        sys.dm_tran_locks
    GROUP BY
        request_session_id
) t
ON
    s.session_id = t.request_session_id
LEFT OUTER JOIN
    sys.dm_os_waiting_tasks wt
ON 
    s.session_id = wt.session_id
LEFT OUTER JOIN
    sys.dm_os_tasks ot
ON 
    s.session_id = ot.session_id
LEFT OUTER JOIN
(
    SELECT
        ot.session_id,
        CPU_Time = MAX(usermode_time)
    FROM
        sys.dm_os_tasks ot
    INNER JOIN
        sys.dm_os_workers ow
    ON
        ot.worker_address = ow.worker_address
    INNER JOIN
        sys.dm_os_threads oth
    ON
        ow.thread_address = oth.thread_address
    GROUP BY
        ot.session_id
) tt
ON
    s.session_id = tt.session_id
WHERE
    COALESCE
    (
        r.command,
        r.wait_type,
        wt.wait_type,
        r.last_wait_type,
        'a'
    ) >= COALESCE
    (
        '', 
        'a'
    )
)

Select * from DBConn
where DBName like '%'+@dbName+'%'

What does SQL clause "GROUP BY 1" mean?

It will group by the column position you put after the group by clause.

for example if you run 'SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1' it will group by SALESMAN_NAME.

One risk on doing that is if you run 'Select *' and for some reason you recreate the table with columns on a different order, it will give you a different result than you would expect.

Creating a UIImage from a UIColor to use as a background image for UIButton

I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0

"git pull" or "git merge" between master and development branches

The best approach for this sort of thing is probably git rebase. It allows you to pull changes from master into your development branch, but leave all of your development work "on top of" (later in the commit log) the stuff from master. When your new work is complete, the merge back to master is then very straightforward.

pandas how to check dtype for all columns in a dataframe?

Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:

df.info()

Android how to convert int to String?

Use this String.valueOf(value);

How to style an asp.net menu with CSS

There are well achieved third-party tools, but i usually use superfish http://www.conceptdevelopment.net/Fun/Superfish/ it's cool, free and easy ;)

Python os.path.join on Windows

To be pedantic, it's probably not good to hardcode either / or \ as the path separator. Maybe this would be best?

mypath = os.path.join('c:%s' % os.sep, 'sourcedir')

or

mypath = os.path.join('c:' + os.sep, 'sourcedir')

Appending to an empty DataFrame in Pandas?

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

According to this issue comment, editing cross-env path will fix the problem. Change cross-env to node node_modules/cross-env/dist/bin/cross-env.js in package.json like this:

    "dev": "npm run development",
    "development": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

For OSX your path needs to include /Users/yourusername

their example: /Development/adt-bundle/sdk/platform-tools
needs to be: /Users/yourusername/Development/adt-bundle/sdk/platform-tools

Convert command line arguments into an array in Bash

Easier Yet, you can operate directly on $@ ;)

Here is how to do pass a a list of args directly from the prompt:

function echoarg { for stuff in "$@" ; do echo $stuff ; done ; } 
    echoarg Hey Ho Lets Go
    Hey
    Ho
    Lets
    Go

Laravel: Auth::user()->id trying to get a property of a non-object

Your question and code sample are a little vague, and I believe the other developers are focusing on the wrong thing. I am making an application in Laravel, have used online tutorials for creating a new user and authentication, and seemed to have noticed that when you create a new user in Laravel, no Auth object is created - which you use to get the (new) logged-in user's ID in the rest of the application. This is a problem, and I believe what you may be asking. I did this kind of cludgy hack in userController::store :

$user->save();

Session::flash('message','Successfully created user!');

//KLUDGE!! rest of site depends on user id in auth object - need to force/create it here
Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), true);

Redirect::to('users/' . Auth::user()->id);

Shouldn't have to create and authenticate, but I didn't know what else to do.

JSON parsing using Gson for Java

One way would be created a JsonObject and iterating through the parameters. For example

JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);

Then you can extract bean values like:

String fieldValue = jobj.get(fieldName).getAsString();
boolean fieldValue = jobj.get(fieldName).getAsBoolean();
int fieldValue = jobj.get(fieldName).getAsInt();

Hope this helps.

Convert timestamp to readable date/time PHP

echo 'Le '.date('d/m/Y', 1234567890).' &agrave; '.date('H:i:s', 1234567890);

Passing parameters on button action:@selector

UIButton responds to addTarget:action:forControlEvents: since it inherits from UIControl. But it does not respond to addTarget:action:withObject:forControlEvents:

see reference for the method and for UIButton

You could extend UIButton with a category to implement that method, thought.

Cannot delete directory with Directory.Delete(path, true)

I have spent few hours to solve this problem and other exceptions with deleting the directory. This is my solution

 public static void DeleteDirectory(string target_dir)
    {
        DeleteDirectoryFiles(target_dir);
        while (Directory.Exists(target_dir))
        {
            lock (_lock)
            {
                DeleteDirectoryDirs(target_dir);
            }
        }
    }

    private static void DeleteDirectoryDirs(string target_dir)
    {
        System.Threading.Thread.Sleep(100);

        if (Directory.Exists(target_dir))
        {

            string[] dirs = Directory.GetDirectories(target_dir);

            if (dirs.Length == 0)
                Directory.Delete(target_dir, false);
            else
                foreach (string dir in dirs)
                    DeleteDirectoryDirs(dir);
        }
    }

    private static void DeleteDirectoryFiles(string target_dir)
    {
        string[] files = Directory.GetFiles(target_dir);
        string[] dirs = Directory.GetDirectories(target_dir);

        foreach (string file in files)
        {
            File.SetAttributes(file, FileAttributes.Normal);
            File.Delete(file);
        }

        foreach (string dir in dirs)
        {
            DeleteDirectoryFiles(dir);
        }
    }

This code has the small delay, which is not important for my application. But be careful, the delay may be a problem for you if you have a lot of subdirectories inside the directory you want to delete.

What character represents a new line in a text area

By HTML specifications, browsers are required to canonicalize line breaks in user input to CR LF (\r\n), and I don’t think any browser gets this wrong. Reference: clause 17.13.4 Form content types in the HTML 4.01 spec.

In HTML5 drafts, the situation is more complicated, since they also deal with the processes inside a browser, not just the data that gets sent to a server-side form handler when the form is submitted. According to them (and browser practice), the textarea element value exists in three variants:

  1. the raw value as entered by the user, unnormalized; it may contain CR, LF, or CR LF pair;
  2. the internal value, called “API value”, where line breaks are normalized to LF (only);
  3. the submission value, where line breaks are normalized to CR LF pairs, as per Internet conventions.

What is the most efficient way to get first and last line of a text file?

Nobody mentioned using reversed:

f=open(file,"r")
r=reversed(f.readlines())
last_line_of_file = r.next()

Grouping functions (tapply, by, aggregate) and the *apply family

I recently discovered the rather useful sweep function and add it here for the sake of completeness:

sweep

The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):

Let's say you have a matrix and want to standardize it column-wise:

dataPoints <- matrix(4:15, nrow = 4)

# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)

# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)

# Center the points 
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")

# Return the result
dataPoints_Trans1
##      [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,]  0.5  0.5  0.5
## [4,]  1.5  1.5  1.5

# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")

# Return the result
dataPoints_Trans2
##            [,1]       [,2]       [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,]  0.3872983  0.3872983  0.3872983
## [4,]  1.1618950  1.1618950  1.1618950

NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)

Positioning <div> element at center of screen

try this

<table style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%;">
 <tr>
  <td>
   <div style="text-align: left; display: inline-block;">
    Your Html code Here
   </div>
  </td>
 </tr>
</table>

Or this

<div style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%; display: table">
 <div style="display: table-row">
  <div style="display: table-cell; vertical-align:middle;">
   <div style="text-align: left; display: inline-block;">
    Your Html code here
   </div>
  </div>
 </div>
</div>

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

How can I concatenate strings in VBA?

There is the concatenate function. For example

=CONCATENATE(E2,"-",F2)
But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.

Check to see if cURL is installed locally?

Another way, say in CentOS, is:

$ yum list installed '*curl*'
Loaded plugins: aliases, changelog, fastestmirror, kabi, langpacks, priorities, tmprepo, verify,
              : versionlock
Loading support for Red Hat kernel ABI
Determining fastest mirrors
google-chrome                                                                                    3/3
152 packages excluded due to repository priority protections
Installed Packages
curl.x86_64                                        7.29.0-42.el7                                @base
libcurl.x86_64                                     7.29.0-42.el7                                @base
libcurl-devel.x86_64                               7.29.0-42.el7                                @base
python-pycurl.x86_64                               7.19.0-19.el7                                @base

Count number of matches of a regex in Javascript

tl;dr: Generic Pattern Counter

// THIS IS WHAT YOU NEED
const count = (str) => {
  const re = /YOUR_PATTERN_HERE/g
  return ((str || '').match(re) || []).length
}

For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration:

_x000D_
_x000D_
/*_x000D_
 *  Example_x000D_
 */_x000D_
_x000D_
const count = (str) => {_x000D_
  const re = /[a-z]{3}/g_x000D_
  return ((str || '').match(re) || []).length_x000D_
}_x000D_
_x000D_
const str1 = 'abc, def, ghi'_x000D_
const str2 = 'ABC, DEF, GHI'_x000D_
_x000D_
console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)_x000D_
console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)
_x000D_
_x000D_
_x000D_

Original Answer

The problem with your initial code is that you are missing the global identifier:

>>> 'hi there how are you'.match(/\s/g).length;
4

Without the g part of the regex it will only match the first occurrence and stop there.

Also note that your regex will count successive spaces twice:

>>> 'hi  there'.match(/\s/g).length;
2

If that is not desirable, you could do this:

>>> 'hi  there'.match(/\s+/g).length;
1

Button Center CSS

I realize this is a very old question, but I stumbled across this problem today and I got it to work with

<div style="text-align:center;">
    <button>button1</button>
    <button>button2</button>
</div>

Cheers, Mark

Changing ViewPager to enable infinite page scrolling

All you need to do is look at the example here

You will find that in line 295 the page is always set to 1 so that it is scrollable and that the count of pages is 3 in getCount() method.

Those are the 2 main things you need to change, the rest is your logic and you can handle them differently.

Just make a personal counter that counts the real page you are on because position will no longer be usable after always setting current page to 1 on line 295.

p.s. this code is not mine it was referenced in the question you linked in your question

how to select first N rows from a table in T-SQL?

You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad

SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate

SET ROWCOUNT 0

Get int from String, also containing letters, in Java

Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?

Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.

If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.

Specify an SSH key for git push for a given domain

Configure your repository using git config. For example:

git config --add --local core.sshCommand 'ssh -i ~/.ssh/<<<PATH_TO_SSH_KEY>>>'

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

Mail multipart/alternative vs multipart/mixed

Great Answer Lain!

There were a couple things I did to make this work in a broader set of devices. At the end I will list the clients I tested on.

  1. I added a new build constructor that did not contain the parameter attachments and did not use MimeMultipart("mixed"). There is no need for mixed if you are sending only inline images.

    public Multipart build(String messageText, String messageHtml, List<URL> messageHtmlInline) throws MessagingException {
    
        final Multipart mpAlternative = new MimeMultipart("alternative");
        {
            //  Note: MUST RENDER HTML LAST otherwise iPad mail client only renders 
            //  the last image and no email
                addTextVersion(mpAlternative,messageText);
                addHtmlVersion(mpAlternative,messageHtml, messageHtmlInline);
        }
    
        return mpAlternative;
    }
    
  2. In addTextVersion method I added charset when adding content this probably could/should be passed in, but I just added it statically.

    textPart.setContent(messageText, "text/plain");
    to
    textPart.setContent(messageText, "text/plain; charset=UTF-8");
    
  3. The last item was adding to the addImagesInline method. I added setting the image filename to the header by the following code. If you don't do this then at least on Android default mail client it will have inline images that have a name of Unknown and will not automatically download them and present in email.

    for (URL img : embeded) {
        final MimeBodyPart htmlPartImg = new MimeBodyPart();
        DataSource htmlPartImgDs = new URLDataSource(img);
        htmlPartImg.setDataHandler(new DataHandler(htmlPartImgDs));
        String fileName = img.getFile();
        fileName = getFileName(fileName);
        String newFileName = cids.get(fileName);
        boolean imageNotReferencedInHtml = newFileName == null;
        if (imageNotReferencedInHtml) continue;
        htmlPartImg.setHeader("Content-ID", "<"+newFileName+">");
        htmlPartImg.setDisposition(BodyPart.INLINE);
        **htmlPartImg.setFileName(newFileName);**
        parent.addBodyPart(htmlPartImg);
    }
    

So finally, this is the list of clients I tested on. Outlook 2010, Outlook Web App, Internet Explorer 11, Firefox, Chrome, Outlook using Apple’s native app, Email going through Gmail - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client, Gmail mail client on Android, Gmail mail client on IPhone, Email going through Yahoo - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client.

Hope that helps anyone else.

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

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

What does the construct x = x || y mean?

It means the title argument is optional. So if you call the method with no arguments it will use a default value of "Error".

It's shorthand for writing:

if (!title) {
  title = "Error";
}

This kind of shorthand trick with boolean expressions is common in Perl too. With the expression:

a OR b

it evaluates to true if either a or b is true. So if a is true you don't need to check b at all. This is called short-circuit boolean evaluation so:

var title = title || "Error";

basically checks if title evaluates to false. If it does, it "returns" "Error", otherwise it returns title.

Pygame mouse clicking detection

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

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

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

    def update(self, event_list):

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

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

# [...]

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

    group.update(event_list)

    # [...]

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

import pygame

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

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

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

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

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

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

    group.update(event_list)

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

pygame.quit()
exit()

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


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

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

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

    def update(self, event_list):

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

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

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

# [...]

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

    group.update(event_list)

    # [...]

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

import pygame

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

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

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

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

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

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

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

    group.update()

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

pygame.quit()
exit()

how do you increase the height of an html textbox

<input type="text" style="font-size:xxpt;height:xxpx">

Just replace "xx" with whatever values you wish.

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:

http://localhost:8080/YourProject/yourfile.jsp

then your problem will be solved.

Jenkins not executing jobs (pending - waiting for next executor)

In my case it was caused by number of executors (I had 1) and running Jenkins Job (Project) from Pipeline (my pipeline script started other Job in Jenkins). It caused deadlock - my pipeline held executor and was waiting for its job, but the job was waiting for free executor.

The solution may be increasing of # of executors in Jenkins -> Manage Jenkins -> Manage Nodes -> Configure (icon on required node).

Style jQuery autocomplete in a Bootstrap input field

Try this (demo):

.ui-autocomplete {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1000;
  display: none;
  float: left;
  min-width: 160px;
  padding: 5px 0;
  margin: 2px 0 0;
  list-style: none;
  font-size: 14px;
  text-align: left;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
  background-clip: padding-box;
}

.ui-autocomplete > li > div {
  display: block;
  padding: 3px 20px;
  clear: both;
  font-weight: normal;
  line-height: 1.42857143;
  color: #333333;
  white-space: nowrap;
}

.ui-state-hover,
.ui-state-active,
.ui-state-focus {
  text-decoration: none;
  color: #262626;
  background-color: #f5f5f5;
  cursor: pointer;
}

.ui-helper-hidden-accessible {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

Date format in dd/MM/yyyy hh:mm:ss

The chapter on CAST and CONVERT on MSDN Books Online, you've missed the right answer by one line.... you can use style no. 121 (ODBC canonical (with milliseconds)) to get the result you're looking for:

SELECT CONVERT(VARCHAR(30), GETDATE(), 121)

This gives me the output of:

2012-04-14 21:44:03.793

Update: based on your updated question - of course this won't work - you're converting a string (this: '4/14/2012 2:44:01 PM' is just a string - it's NOT a datetime!) to a string......

You need to first convert the string you have to a DATETIME and THEN convert it back to a string!

Try this:

SELECT CONVERT(VARCHAR(30), CAST('4/14/2012 2:44:01 PM' AS DATETIME), 121) 

Now you should get:

2012-04-14 14:44:01.000

All zeroes for the milliseconds, obviously, since your original values didn't include any ....

How do I find which program is using port 80 in Windows?

Start menu → Accessories → right click on "Command prompt". In the menu, click "Run as Administrator" (on Windows XP you can just run it as usual), run netstat -anb, and then look through output for your program.

BTW, Skype by default tries to use ports 80 and 443 for incoming connections.

You can also run netstat -anb >%USERPROFILE%\ports.txt followed by start %USERPROFILE%\ports.txt to open the port and process list in a text editor, where you can search for the information you want.

You can also use PowerShell to parse netstat output and present it in a better way (or process it any way you want):

$proc = @{};
Get-Process | ForEach-Object { $proc.Add($_.Id, $_) };
netstat -aon | Select-String "\s*([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+)?\s+([^\s]+)" | ForEach-Object {
    $g = $_.Matches[0].Groups;
    New-Object PSObject |
        Add-Member @{ Protocol =           $g[1].Value  } -PassThru |
        Add-Member @{ LocalAddress =       $g[2].Value  } -PassThru |
        Add-Member @{ LocalPort =     [int]$g[3].Value  } -PassThru |
        Add-Member @{ RemoteAddress =      $g[4].Value  } -PassThru |
        Add-Member @{ RemotePort =         $g[5].Value  } -PassThru |
        Add-Member @{ State =              $g[6].Value  } -PassThru |
        Add-Member @{ PID =           [int]$g[7].Value  } -PassThru |
        Add-Member @{ Process = $proc[[int]$g[7].Value] } -PassThru;
#} | Format-Table Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,State -GroupBy @{Name='Process';Expression={$p=$_.Process;@{$True=$p.ProcessName; $False=$p.MainModule.FileName}[$p.MainModule -eq $Null] + ' PID: ' + $p.Id}} -AutoSize
} | Sort-Object PID | Out-GridView

Also it does not require elevation to run.

Get content of a DIV using JavaScript

You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2 is DIV2. Also, you should use document, not Document:

var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML; 

Here is a JSFiddle: http://jsfiddle.net/gFN6r/.

Create table (structure) from existing table

Copy the table structure:-
select * into newtable from oldtable where 1=2;

Copy the table structure along with table data:-
select * into newtable from oldtable where 1=1;

How to inject window into a service?

To get it to work on Angular 2.1.1 I had to @Inject window using a string

  constructor( @Inject('Window') private window: Window) { }

and then mock it like this

beforeEach(() => {
  let windowMock: Window = <any>{ };
  TestBed.configureTestingModule({
    providers: [
      ApiUriService,
      { provide: 'Window', useFactory: (() => { return windowMock; }) }
    ]
  });

and in the ordinary @NgModule I provide it like this

{ provide: 'Window', useValue: window }

Column/Vertical selection with Keyboard in SublimeText 3

In my case (Linux) is alt+shift up/down

 { "keys": ["alt+shift+up"], "command": "select_lines", "args": {"forward": false} },
 { "keys": ["alt+shift+down"], "command": "select_lines", "args": {"forward": true} },    

Disable double-tap "zoom" option in browser on touch devices

Using CSS touch-events: none Completly takes out all the touch events. Just leaving this here in case someone also has this problems, took me 2 hours to find this solution and it's only one line of css. https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action

LIMIT 10..20 in SQL Server

SELECT TOP 10 *
FROM TABLE
WHERE IDCOLUMN NOT IN (SELECT TOP 10 IDCOLUMN FROM TABLE)

Should give records 11-20. Probably not too efficient if incrementing to get further pages, and not sure how it might be affected by ordering. Might have to specify this in both WHERE statements.

Custom "confirm" dialog in JavaScript?

Faced with the same problem, I was able to solve it using only vanilla JS, but in an ugly way. To be more accurate, in a non-procedural way. I removed all my function parameters and return values and replaced them with global variables, and now the functions only serve as containers for lines of code - they're no longer logical units.

In my case, I also had the added complication of needing many confirmations (as a parser works through a text). My solution was to put everything up to the first confirmation in a JS function that ends by painting my custom popup on the screen, and then terminating.

Then the buttons in my popup call another function that uses the answer and then continues working (parsing) as usual up to the next confirmation, when it again paints the screen and then terminates. This second function is called as often as needed.

Both functions also recognize when the work is done - they do a little cleanup and then finish for good. The result is that I have complete control of the popups; the price I paid is in elegance.

How to get milliseconds from LocalDateTime in Java 8

  default LocalDateTime getDateFromLong(long timestamp) {
    try {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC);
    } catch (DateTimeException tdException) {
      //  throw new 
    }
}

default Long getLongFromDateTime(LocalDateTime dateTime) {
    return dateTime.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
}

PHP: date function to get month of the current date

As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.

<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";

// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);

// Output it month is various formats according to http://php.net/date

echo date('M',$dateAsUnixTimestamp);
// Will output Apr

echo date('n',$dateAsUnixTimestamp);
// Will output 4

echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>

Get operating system info

When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:

GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1  
Host: stackoverflow.com  
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 
            (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
Accept-Language: en-us,en;q=0.5  
Accept-Encoding: gzip,deflate,sdch  
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7  
Keep-Alive: 300  
Connection: keep-alive  
Cookie: <cookie data removed> 
Pragma: no-cache  
Cache-Control: no-cache

These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.

In PHP, all this information is stored in the $_SERVER array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.

<pre><?php print_r($_SERVER); ?></pre>

This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT'] to get the operating system and browser.

Unity Scripts edited in Visual studio don't provide autocomplete

This page helped me fix the issue.

Fix for Unity disconnected from Visual Studio

enter image description here

In the Unity Editor, select the Edit > Preferences menu..

Select the External Tools tab on the left.

Select unity version from drop down list on the right

Click regenerate Files

You Done

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

How to get the return value from a thread in python?

My solution to the problem is to wrap the function and thread in a class. Does not require using pools,queues, or c type variable passing. It is also non blocking. You check status instead. See example of how to use it at end of code.

import threading

class ThreadWorker():
    '''
    The basic idea is given a function create an object.
    The object can then run the function in a thread.
    It provides a wrapper to start it,check its status,and get data out the function.
    '''
    def __init__(self,func):
        self.thread = None
        self.data = None
        self.func = self.save_data(func)

    def save_data(self,func):
        '''modify function to save its returned data'''
        def new_func(*args, **kwargs):
            self.data=func(*args, **kwargs)

        return new_func

    def start(self,params):
        self.data = None
        if self.thread is not None:
            if self.thread.isAlive():
                return 'running' #could raise exception here

        #unless thread exists and is alive start or restart it
        self.thread = threading.Thread(target=self.func,args=params)
        self.thread.start()
        return 'started'

    def status(self):
        if self.thread is None:
            return 'not_started'
        else:
            if self.thread.isAlive():
                return 'running'
            else:
                return 'finished'

    def get_results(self):
        if self.thread is None:
            return 'not_started' #could return exception
        else:
            if self.thread.isAlive():
                return 'running'
            else:
                return self.data

def add(x,y):
    return x +y

add_worker = ThreadWorker(add)
print add_worker.start((1,2,))
print add_worker.status()
print add_worker.get_results()

Using the RUN instruction in a Dockerfile with 'source' does not work

If you have SHELL available you should go with this answer -- don't use the accepted one, which forces you to put the rest of the dockerfile in one command per this comment.

If you are using an old Docker version and don't have access to SHELL, this will work so long as you don't need anything from .bashrc (which is a rare case in Dockerfiles):

ENTRYPOINT ["bash", "--rcfile", "/usr/local/bin/virtualenvwrapper.sh", "-ci"]

Note the -i is needed to make bash read the rcfile at all.

Create a List that contain each Line of a File

It's a lot easier than that:

List = open("filename.txt").readlines()

This returns a list of each line in the file.

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

How to drop a database with Mongoose?

An updated answer, for 4.6.0+, if you have a preference for promises (see docs):

mongoose.connect('mongodb://localhost/mydb', { useMongoClient: true })
.then((connection) => {
   connection.db.dropDatabase();
   // alternatively:
   // mongoose.connection.db.dropDatabase();
});

I tested this code in my own code, using mongoose 4.13.6. Also, note the use of the useMongoClient option (see docs). Docs indicate:

Mongoose's default connection logic is deprecated as of 4.11.0. Please opt in to the new connection logic using the useMongoClient option, but make sure you test your connections first if you're upgrading an existing codebase!

Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

Removing nan values from an array

For me the answer by @jmetz didn't work, however using pandas isnull() did.

x = x[~pd.isnull(x)]

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

The following code can cause similar error:

  using (var session = SessionFactory.OpenSession())
  using (var tx = session.BeginTransaction())
  {
      movie = session.Get<Movie>(movieId);
      tx.Commit();
  }
  Assert.That(movie.Actors.Count == 1);

You can fix it simply:

  using (var session = SessionFactory.OpenSession())
  using (var tx = session.BeginTransaction())
  {
      movie = session.Get<Movie>(movieId);
      Assert.That(movie.Actors.Count == 1);
      tx.Commit();
  }

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Setting the focus to a text field

I did it by setting an AncesterAdded event on the textField and the requesting focus in the window.

Visual Studio replace tab with 4 spaces?

First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces

Conditional Count on a field

You could join the table against itself:

select
   t.jobId, t.jobName,
   count(p1.jobId) as Priority1,
   count(p2.jobId) as Priority2,
   count(p3.jobId) as Priority3,
   count(p4.jobId) as Priority4,
   count(p5.jobId) as Priority5
from
   theTable t
   left join theTable p1 on p1.jobId = t.jobId and p1.jobName = t.jobName and p1.Priority = 1
   left join theTable p2 on p2.jobId = t.jobId and p2.jobName = t.jobName and p2.Priority = 2
   left join theTable p3 on p3.jobId = t.jobId and p3.jobName = t.jobName and p3.Priority = 3
   left join theTable p4 on p4.jobId = t.jobId and p4.jobName = t.jobName and p4.Priority = 4
   left join theTable p5 on p5.jobId = t.jobId and p5.jobName = t.jobName and p5.Priority = 5
group by
   t.jobId, t.jobName

Or you could use case inside a sum:

select
   jobId, jobName,
   sum(case Priority when 1 then 1 else 0 end) as Priority1,
   sum(case Priority when 2 then 1 else 0 end) as Priority2,
   sum(case Priority when 3 then 1 else 0 end) as Priority3,
   sum(case Priority when 4 then 1 else 0 end) as Priority4,
   sum(case Priority when 5 then 1 else 0 end) as Priority5
from
   theTable
group by
   jobId, jobName

How to index characters in a Golang string?

Another Solution to isolate a character in a string

package main
import "fmt"

   func main() {
        var word string = "ZbjTS"

       // P R I N T 
       fmt.Println(word)
       yo := string([]rune(word)[0])
       fmt.Println(yo)

       //I N D E X 
       x :=0
       for x < len(word){
           yo := string([]rune(word)[x])
           fmt.Println(yo)
           x+=1
       }

}

for string arrays also:

fmt.Println(string([]rune(sArray[0])[0]))

// = commented line

Firebug-like debugger for Google Chrome

You can set this bookmarklet in your "Bookmarks Bar" in order to have Firebug lite always available in Chrome/Chromium browser (put this as the URL):

javascript:var firebug=document.createElement('script');firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');document.body.appendChild(firebug);(function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug);

unix diff side-to-side results?

Try cdiff - View colored, incremental diff in workspace or from stdin with side by side and auto pager support.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

I found mine here on a OSX system /usr/local/var/mongodb

How to manage a redirect request after a jQuery Ajax call

Additionally you will probably want to redirect user to the given in headers URL. So finally it will looks like this:

$.ajax({
    //.... other definition
    complete:function(xmlHttp){
        if(xmlHttp.status.toString()[0]=='3'){
        top.location.href = xmlHttp.getResponseHeader('Location');
    }
});

UPD: Opps. Have the same task, but it not works. Doing this stuff. I'll show you solution when I'll find it.

Get rid of "The value for annotation attribute must be a constant expression" message

This is what a constant expression in Java looks like:

package com.mycompany.mypackage;

public class MyLinks {
  // constant expression
  public static final String GUESTBOOK_URL = "/guestbook";
}

You can use it with annotations as following:

import com.mycompany.mypackage.MyLinks;

@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
  // ...
}

How to read a configuration file in Java

It depends.

Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding

And if none of those meet your particular needs, you could even look at using some kind of Database

How to launch jQuery Fancybox on page load?

Window.load (as opposed to document.ready()) appears to the be the trick used in the JSFiddler onload demos of Fancybox 2.0:

$(window).load(function()
{
    $.fancybox("test");
});

Bare in mind you may be using document.ready() elsewhere, and IE9 gets upset with the load order of the two. This leaves you with two options: change everything to window.load or use a setTimer().

Filtering collections in C#

Here is a code block / example of some list filtering using three different methods that I put together to show Lambdas and LINQ based list filtering.

#region List Filtering

static void Main(string[] args)
{
    ListFiltering();
    Console.ReadLine();
}

private static void ListFiltering()
{
    var PersonList = new List<Person>();

    PersonList.Add(new Person() { Age = 23, Name = "Jon", Gender = "M" }); //Non-Constructor Object Property Initialization
    PersonList.Add(new Person() { Age = 24, Name = "Jack", Gender = "M" });
    PersonList.Add(new Person() { Age = 29, Name = "Billy", Gender = "M" });

    PersonList.Add(new Person() { Age = 33, Name = "Bob", Gender = "M" });
    PersonList.Add(new Person() { Age = 45, Name = "Frank", Gender = "M" });

    PersonList.Add(new Person() { Age = 24, Name = "Anna", Gender = "F" });
    PersonList.Add(new Person() { Age = 29, Name = "Sue", Gender = "F" });
    PersonList.Add(new Person() { Age = 35, Name = "Sally", Gender = "F" });
    PersonList.Add(new Person() { Age = 36, Name = "Jane", Gender = "F" });
    PersonList.Add(new Person() { Age = 42, Name = "Jill", Gender = "F" });

    //Logic: Show me all males that are less than 30 years old.

    Console.WriteLine("");
    //Iterative Method
    Console.WriteLine("List Filter Normal Way:");
    foreach (var p in PersonList)
        if (p.Gender == "M" && p.Age < 30)
            Console.WriteLine(p.Name + " is " + p.Age);

    Console.WriteLine("");
    //Lambda Filter Method
    Console.WriteLine("List Filter Lambda Way");
    foreach (var p in PersonList.Where(p => (p.Gender == "M" && p.Age < 30))) //.Where is an extension method
        Console.WriteLine(p.Name + " is " + p.Age);

    Console.WriteLine("");
    //LINQ Query Method
    Console.WriteLine("List Filter LINQ Way:");
    foreach (var v in from p in PersonList
                      where p.Gender == "M" && p.Age < 30
                      select new { p.Name, p.Age })
        Console.WriteLine(v.Name + " is " + v.Age);
}

private class Person
{
    public Person() { }
    public int Age { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
}

#endregion

Using Python's list index() method on a list of tuples or objects?

Inspired by this question, I found this quite elegant:

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> next(i for i, t in enumerate(tuple_list) if t[1] == 7)
1
>>> next(i for i, t in enumerate(tuple_list) if t[0] == "kumquat")
2

Return anonymous type results?

You could do something like this:


public System.Collections.IEnumerable GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result.ToList();
}

File content into unix variable with newlines

This is due to IFS (Internal Field Separator) variable which contains newline.

$ cat xx1
1
2

$ A=`cat xx1`
$ echo $A
1 2

$ echo "|$IFS|"
|       
|

A workaround is to reset IFS to not contain the newline, temporarily:

$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK

To REVERT this horrible change for IFS:

IFS=$IFSBAK

Byte[] to ASCII

You can use:

System.Text.Encoding.ASCII.GetString(buf);

But sometimes you will get a weird number instead of the string you want. In that case, your original string may have some hexadecimal character when you see it. If it's the case, you may want to try this:

System.Text.Encoding.UTF8.GetString(buf);

Or as a last resort:

System.Text.Encoding.Default.GetString(bytearray);

Passing structs to functions

bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.

Note: In this case, you will need to define the struct prior to the method for it to be recognized.

Example:

struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

std::enable_if to conditionally compile a member function

I made this short example which also works.

#include <iostream>
#include <type_traits>

class foo;
class bar;

template<class T>
struct is_bar
{
    template<class Q = T>
    typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
    {
        return true;
    }

    template<class Q = T>
    typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
    {
        return false;
    }
};

int main()
{
    is_bar<foo> foo_is_bar;
    is_bar<bar> bar_is_bar;
    if (!foo_is_bar.check() && bar_is_bar.check())
        std::cout << "It works!" << std::endl;

    return 0;
}

Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)

You can see it in action here.

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

  1. Search "sqlLocalDb" from start menu,
  2. Click on the run command,
  3. Go back to VS 2015 tools/connect to database,
  4. select MSSQL server,
  5. enter (localdb)\MSSQLLocalDB as server name

Select your database and ready to go.

MVC 4 client side validation not working

you may have already solved this, but I had some luck by changing the order of the jqueryval item in the BundleConfig with App_Start. The client-side validation would not work even on a fresh out-of-the-box MVC 4 internet solution. So I changed the default:

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

to

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/jquery.unobtrusive*"));

and now my client-side validation is working. You just want to make sure the unobtrusive file is at the end (so it's not intrusive, hah :)

IPython Notebook save location

Just cd to your working folder and then start the IPython notebook server. This way you can be mobile.

Forking / Multi-Threaded Processes | Bash

With GNU Parallel you can do:

cat file | parallel 'foo {}; foo2 {}; foo3 {}'

This will run one job on each cpu core. To run 50 do:

cat file | parallel -j 50 'foo {}; foo2 {}; foo3 {}'

Watch the intro videos to learn more:

http://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

Python foreach equivalent

This worked for me:

def smallest_missing_positive_integer(A):
A.sort()
N = len(A)

now = A[0]
for i in range(1, N, 1):
  next = A[i]
  
  #check if there is no gap between 2 numbers and if positive
  # "now + 1" is the "gap"
  if (next > now + 1):
    if now + 1 > 0:
      return now + 1 #return the gap
  now = next
    
return max(1, A[N-1] + 1) #if there is no positive number returns 1, otherwise the end of A+1

How to find files modified in last x minutes (find -mmin does not work as expected)

The problem is that

find . -mmin -60

outputs:

.
./file1
./file2

Note the line with one dot?
That makes ls list the whole directory exactly the same as when ls -l . is executed.

One solution is to list only files (not directories):

find . -mmin -60 -type f | xargs ls -l

But it is better to use directly the option -exec of find:

find . -mmin -60 -type f -exec ls -l {} \;

Or just:

find . -mmin -60 -type f -ls

Which, by the way is safe even including directories:

find . -mmin -60 -ls

Why java.security.NoSuchProviderException No such provider: BC?

My experience with this was that when I had this in every execution it was fine using the provider as a string like this

Security.addProvider(new BounctCastleProvider());
new JcaPEMKeyConverter().setProvider("BC");

But when I optimized and put the following in the constructor:

   if(bounctCastleProvider == null) {
      bounctCastleProvider = new BouncyCastleProvider();
    }

    if(Security.getProvider(bouncyCastleProvider.getName()) == null) {
      Security.addProvider(bouncyCastleProvider);
    }

Then I had to use provider like this or I would get the above error:

new JcaPEMKeyConverter().setProvider(bouncyCastleProvider);

I am using bcpkix-jdk15on version 1.65

How can you profile a Python script?

Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations.

You can call it from within your code, or from the interpreter, like this:

import cProfile
cProfile.run('foo()')

Even more usefully, you can invoke the cProfile when running a script:

python -m cProfile myscript.py

To make it even easier, I made a little batch file called 'profile.bat':

python -m cProfile %1

So all I have to do is run:

profile euler048.py

And I get this:

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

EDIT: Updated link to a good video resource from PyCon 2013 titled Python Profiling
Also via YouTube.

How to upgrade docker-compose to latest version

Here is another oneliner to install the latest version of docker-compose using curl and sed.

curl -L "https://github.com/docker/compose/releases/download/`curl -fsSLI -o /dev/null -w %{url_effective} https://github.com/docker/compose/releases/latest | sed 's#.*tag/##g' && echo`/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose && chmod +x /usr/local/bin/docker-compose

hidden field in php

Yes, you can access it through GET and POST (trying this simple task would have made you aware of that).

Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.

What to gitignore from the .idea folder?

The official support page should answer your question.

So in your .gitignore you might ignore the files ending with .iws, and the workspace.xml and tasks.xml files.

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:

 <?php 
    require_once('mylib.php');
    session_start();
 ?>

In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.

HTH

How can I kill whatever process is using port 8080 so that I can vagrant up?

try netstat

netstat -vanp tcp | grep 3000

if your netstat doesn't support -p , use lsof

sudo lsof -i tcp:3000 

For Centos 7 use

netstat -vanp --tcp | grep 3000

Simple way to check if a string contains another string in C?

if (strstr(request, "favicon") != NULL) {
    // contains
}

Generic Interface

Here's another suggestion:

public interface Service<T> {
   T execute();
}

using this simple interface you can pass arguments via constructor in the concrete service classes:

public class FooService implements Service<String> {

    private final String input1;
    private final int input2;

    public FooService(String input1, int input2) {
       this.input1 = input1;
       this.input2 = input2;
    }

    @Override
    public String execute() {
        return String.format("'%s%d'", input1, input2);
    }
}

Is there a JavaScript function that can pad a string to get to a determined length?

padding string has been inplemented in new javascript version.

str.padStart(targetLength [, padString])

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/padStart

If you want your own function check this example:

const myString = 'Welcome to my house';
String.prototype.padLeft = function(times = 0, str = ' ') {
    return (Array(times).join(str) + this);
}
console.log(myString.padLeft(12, ':'));
//:::::::::::Welcome to my house

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Was having an issue getting the "Run in Postman" links to work with the browsers until I added this to the .desktop file

MimeType=application/postman;x-scheme-handler/postman;

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

if you want to change menu item icons, arrow icon (back/up), and 3 dots icon you can use android:tint

  <style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:tint">@color/your_color</item>
  </style>

jQuery - Get Width of Element when Not Visible (Display: None)

Before take the width make the parent display show ,then take the width and finally make the parent display hide. Just like following

$('#parent').show();
var tableWidth = $('#parent').children('table').outerWidth();
 $('#parent').hide();
if (tableWidth > $('#parent').width())
{
    $('#parent').width() = tableWidth;
}

Is there a better way to compare dictionary values

>>> a = {'x': 1, 'y': 2}
>>> b = {'y': 2, 'x': 1}
>>> print a == b
True
>>> c = {'z': 1}
>>> print a == c
False
>>> 

ToggleClass animate jQuery?

Should have checked, Once I included the jQuery UI Library it worked fine and was animating...

What is the difference between a 'closure' and a 'lambda'?

A Lambda expression is just an anonymous function. in plain java, for example, you can write it like this:

Function<Person, Job> mapPersonToJob = new Function<Person, Job>() {
    public Job apply(Person person) {
        Job job = new Job(person.getPersonId(), person.getJobDescription());
        return job;
    }
};

where the class Function is just built in java code. Now you can call mapPersonToJob.apply(person) somewhere to use it. thats just one example. Thats a lambda before there was syntax for it. Lambdas a short cut for this.

Closure:

a Lambda becomes a closure when it can access the variables outside of this scope. i guess you can say its magic, it magically can wrap around the environment it was created in and use the variables outside of its scope(outer scope. so to be clear, a closure means a lambda can access its OUTER SCOPE.

in Kotlin, a lambda can always access its closure (the variables that are in its outer scope)

See line breaks and carriage returns in editor

:set list in Vim will show whitespace. End of lines show as '$' and carriage returns usually show as '^M'.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[] in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer (expecting Serializable, and using ObjectOutputStream). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.

I guess you can copy the entire package and make use of it.

How to use opencv in using Gradle?

If you don't want to use JavaCV this works for me...

Step 1- Download the Resources

Download OpenCV Android SDK from http://opencv.org/downloads.html

Step 2 - Copying the OpenCV binaries into your APK

Copy libopencv_info.so & libopencv_java.so from

OpenCV-2.?.?-android-sdk -> sdk -> native -> libs -> armeabi-v7a

to

Project Root -> Your Project -> lib - > armeabi-v7a

Zip the lib folder up and rename that zip to whatever-v7a.jar.

Copy this .jar file and place it in here in your project

Project Root -> Your Project -> libs

Add this line to your projects build.gradle in the dependencies section

compile files('libs/whatever-v7a.jar')

When you compile now you will probably see your .apk is about 4mb bigger.

(Repeat for "armeabi" if you want to support ARMv6 too, likely not needed anymore.)

Step 3 - Adding the java sdk to your project

Copy the java folder from here

OpenCV-2.?.?-android-sdk -> sdk

to

Project Root -> Your Project -> libs (Same place as your .jar file);

(You can rename the 'java' folder name to 'OpenCV')

In this freshly copied folder add a typical build.gradle file; I used this:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}

apply plugin: 'android-library'

repositories {
    mavenCentral();
}

android {
    compileSdkVersion 19
    buildToolsVersion "19"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 19
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

In your Project Root settings.gradle file change it too look something like this:

include ':Project Name:libs:OpenCV', ':Project Name'

In your Project Root -> Project Name -> build.gradle file in the dependencies section add this line:

compile project(':Project Name:libs:OpenCV')

Step 4 - Using OpenCV in your project

Rebuild and you should be able to import and start using OpenCV in your project.

import org.opencv.android.OpenCVLoader;
...
if (!OpenCVLoader.initDebug()) {}

I know this if a bit of hack but I figured I would post it anyway.

How can I get zoom functionality for images?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageDetail = (ImageView) findViewById(R.id.imageView1);
    imageDetail.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            System.out.println("matrix=" + savedMatrix.toString());
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    savedMatrix.set(matrix);
                    startPoint.set(event.getX(), event.getY());
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    if (oldDist > 10f) {
                        savedMatrix.set(matrix);
                        midPoint(midPoint, event);
                        mode = ZOOM;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        matrix.set(savedMatrix);
                        matrix.postTranslate(event.getX() - startPoint.x, event.getY() - startPoint.y);
                    } else if (mode == ZOOM) {
                        float newDist = spacing(event);
                        if (newDist > 10f) {
                            matrix.set(savedMatrix);
                            float scale = newDist / oldDist;
                            matrix.postScale(scale, scale, midPoint.x, midPoint.y);
                        }
                    }
                    break;
            }
            view.setImageMatrix(matrix);
            return true;

        }

        @SuppressLint("FloatMath")
        private float spacing(MotionEvent event) {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return FloatMath.sqrt(x * x + y * y);
        }

        private void midPoint(PointF point, MotionEvent event) {
            float x = event.getX(0) + event.getX(1);
            float y = event.getY(0) + event.getY(1);
            point.set(x / 2, y / 2);
        }
    });
}

and drawable folder should have bticn image file. perfectly works :)

How to use onClick with divs in React.js

Your box doesn't have a size. If you set the width and height, it works just fine:

_x000D_
_x000D_
var Box = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return {_x000D_
            color: 'black'_x000D_
        };_x000D_
    },_x000D_
_x000D_
    changeColor: function() {_x000D_
        var newColor = this.state.color == 'white' ? 'black' : 'white';_x000D_
        this.setState({_x000D_
            color: newColor_x000D_
        });_x000D_
    },_x000D_
_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <div_x000D_
                    style = {{_x000D_
                        background: this.state.color,_x000D_
                        width: 100,_x000D_
                        height: 100_x000D_
                    }}_x000D_
                    onClick = {this.changeColor}_x000D_
                >_x000D_
                </div>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Box />,_x000D_
  document.getElementById('box')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='box'></div>
_x000D_
_x000D_
_x000D_

How to generate javadoc comments in Android Studio

  • Another way to add java docs comment is press : Ctrl + Shift + A >> show a popup >> type : Add javadocs >> Enter .

  • Ctrl + Shirt + A: Command look-up (autocomplete command name)

enter image description here

What is the difference between MySQL, MySQLi and PDO?

Specifically, the MySQLi extension provides the following extremely useful benefits over the old MySQL extension..

OOP Interface (in addition to procedural) Prepared Statement Support Transaction + Stored Procedure Support Nicer Syntax Speed Improvements Enhanced Debugging

PDO Extension

PHP Data Objects extension is a Database Abstraction Layer. Specifically, this is not a MySQL interface, as it provides drivers for many database engines (of course including MYSQL).

PDO aims to provide a consistent API that means when a database engine is changed, the code changes to reflect this should be minimal. When using PDO, your code will normally "just work" across many database engines, simply by changing the driver you're using.

In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more, whilst using the MySQL Driver.

What is the correct value for the disabled attribute?

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

Using SUMIFS with multiple AND OR conditions

You can use DSUM, which will be more flexible. Like if you want to change the name of Salesman or the Quote Month, you need not change the formula, but only some criteria cells. Please see the link below for details...Even the criteria can be formula to copied from other sheets

http://office.microsoft.com/en-us/excel-help/dsum-function-HP010342460.aspx?CTT=1

pandas DataFrame: replace nan values with average of columns

Try:

sub2['income'].fillna((sub2['income'].mean()), inplace=True)

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Target parameters:

float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);

Your original file:

var image = new Bitmap(file);

Target sizing (scale factor):

float scale = Math.Min(width / image.Width, height / image.Height);

The resize including brushing canvas first:

var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);

// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;

var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);

graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);

And don't forget to do a bmp.Save(filename) to save the resulting file.

How and where are Annotations used in Java?

Following are some of the places where you can use annotations.

a. Annotations can be used by compiler to detect errors and suppress warnings
b. Software tools can use annotations to generate code, xml files, documentation etc., For example, Javadoc use annotations while generating java documentation for your class.
c. Runtime processing of the application can be possible via annotations.
d. You can use annotations to describe the constraints (Ex: @Null, @NotNull, @Max, @Min, @Email).
e. Annotations can be used to describe type of an element. Ex: @Entity, @Repository, @Service, @Controller, @RestController, @Resource etc.,
f. Annotation can be used to specify the behaviour. Ex: @Transactional, @Stateful
g. Annotation are used to specify how to process an element. Ex: @Column, @Embeddable, @EmbeddedId
h. Test frameworks like junit and testing use annotations to define test cases (@Test), define test suites (@Suite) etc.,
i. AOP (Aspect Oriented programming) use annotations (@Before, @After, @Around etc.,)
j. ORM tools like Hibernate, Eclipselink use annotations

You can refer this link for more details on annotations.

You can refer this link to see how annotations are used to build simple test suite.

Adding new files to a subversion repository

Before you can add files in an unversioned directory, you have to add the directory itself to the versioning:

svn add directory_name

will add the directory directory_name and all sub-directories: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.add.html

Curl command without using cache

The -H 'Cache-Control: no-cache' argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.

curl "http://www.example.com?foo123"

You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s, which will return the seconds since epoch.

curl "http://www.example.com?$(date +%s)"

rename the columns name after cbind the data

You can also name columns directly in the cbind call, e.g.

cbind(date=c(0,1), high=c(2,3))

Output:

     date high
[1,]    0    2
[2,]    1    3

Navigation bar with UIImage for title

let's do try and checkout

let image = UIImage(named: "Navbar_bg.png")
navigationItem.titleView = UIImageView(image: image)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .ScaleAspectFit

How to get multiline input from user

Use the input() built-in function to get a input line from the user.

You can read the help here.

You can use the following code to get several line at once (finishing by an empty one):

while input() != '':
    do_thing

How can I format decimal property to currency?

You can use String.Format, see the code [via How-to Geek]:

decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
// Output: $1,921.39

See also:

Get the first item from an iterable that matches a condition

I would write this

next(x for x in xrange(10) if x > 3)

Comparing Dates in Oracle SQL

Single quote must be there, since date converted to character.

Select employee_id, count(*)
From Employee
Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95';

What is the proper way to URL encode Unicode characters?

The general rule seems to be that browsers encode form responses according to the content-type of the page the form was served from. This is a guess that if the server sends us "text/xml; charset=iso-8859-1", then they expect responses back in the same format.

If you're just entering a URL in the URL bar, then the browser doesn't have a base page to work on and therefore just has to guess. So in this case it seems to be doing utf-8 all the time (since both your inputs produced three-octet form values).

The sad truth is that AFAIK there's no standard for what character set the values in a query string, or indeed any characters in the URL, should be interpreted as. At least in the case of values in the query string, there's no reason to suppose that they necessarily do correspond to characters.

It's a known problem that you have to tell your server framework which character set you expect the query string to be encoded as--- for instance, in Tomcat, you have to call request.setEncoding() (or some similar method) before you call any of the request.getParameter() methods. The dearth of documentation on this subject probably reflects the lack of awareness of the problem amongst many developers. (I regularly ask Java interviewees what the difference between a Reader and an InputStream is, and regularly get blank looks)

'git' is not recognized as an internal or external command

If you're using Windows 10, do this:

  1. Go to Start

  2. Start typing 'This PC'

  3. Right-click This PC, choose Properties

  4. On the left side of the window that pops up, click on Advanced System Settings

  5. Click on the Advanced tab

  6. Click on the Environmental Variables button at the bottom

  7. Down in the System Variables section, double-click Path

  8. Click the New button in the top right corner

  9. Add this path: C:\Program Files\Git\bin\ then click the enter key

  10. Add another path: C:\Program Files\Git\cmd

  11. Close & re-open the console if it's already open.

I stepped you through the long way so you gain exposure to the different Windows/menus. Good luck.

Chrome Extension: Make it run every page load

You can put your script into a content-script, see

Pandas: sum DataFrame rows for given columns

This is a simpler way using iloc to select which columns to sum:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

Produces:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

I can't find a way to combine a range and specific columns that works e.g. something like:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

Is there a Python equivalent to Ruby's string interpolation?

You can also have this

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings

Bootstrap full-width text-input within inline-form

The bootstrap docs says about this:

Requires custom widths Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.

The default width of 100% as all form elements gets when they got the class form-control didn't apply if you use the form-inline class on your form.

You could take a look at the bootstrap.css (or .less, whatever you prefer) where you will find this part:

.form-inline {

  // Kick in the inline
  @media (min-width: @screen-sm-min) {
    // Inline-block all the things for "inline"
    .form-group {
      display: inline-block;
      margin-bottom: 0;
      vertical-align: middle;
    }

    // In navbar-form, allow folks to *not* use `.form-group`
    .form-control {
      display: inline-block;
      width: auto; // Prevent labels from stacking above inputs in `.form-group`
      vertical-align: middle;
    }
    // Input groups need that 100% width though
    .input-group > .form-control {
      width: 100%;
    }

    [...]
  }
}

Maybe you should take a look at input-groups, since I guess they have exactly the markup you want to use (working fiddle here):

<div class="row">
   <div class="col-lg-12">
    <div class="input-group input-group-lg">
      <input type="text" class="form-control input-lg" id="search-church" placeholder="Your location (City, State, ZIP)">
      <span class="input-group-btn">
        <button class="btn btn-default btn-lg" type="submit">Search</button>
      </span>
    </div>
  </div>
</div>

How to create an empty array in PHP with predefined size?

PHP provides two types of array.

  • normal array
  • SplFixedArray

normal array : This array is dynamic.

SplFixedArray : this is a standard php library which provides the ability to create array of fix size.

What is the difference between HTTP status code 200 (cache) vs status code 304?

200 (cache) means Firefox is simply using the locally cached version. This is the fastest because no request to the Web server is made.

304 means Firefox is sending a "If-Modified-Since" conditional request to the Web server. If the file has not been updated since the date sent by the browser, the Web server returns a 304 response which essentially tells Firefox to use its cached version. It is not as fast as 200 (cache) because the request is still sent to the Web server, but the server doesn't have to send the contents of the file.

To your last question, I don't know why the two JavaScript files in the same directory are returning different results.

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

jQuery doesn't have any Date utilities at all. If you don't use any additional libraries, the usual way is to create a JavaScript Date object and then extract the data from it and format it yourself.

For creating the Date object you can either make sure that your date string in the JSON is in a form that Date understands, which is IETF standard (which is basically RFC 822 section 5). So if you have the chance to change your JSON, that would be easiest. (EDIT: Your format may actually work the way it is.)

If you can't change your JSON, then you'll need to parse the string yourself and get day, mouth, year, hours, minutes and seconds as integers and create the Date object with that.

Once you have your Date object you'll need to extract the data you need and format it:

   var myDate = new Date("4 Feb 2011, 19:00:00");
   var hours = myDate.getHours();
   var am = true;
   if (hours > 12) {
      am = false;
      hours -= 12;
   } else (hours == 12) {
      am = false;
   } else (hours == 0) {
      hours = 12;
   }

   var minutes = myDate.getMinutes();
   alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

How to decide when to use Node.js?

I have one real-world example where I have used Node.js. The company where I work got one client who wanted to have a simple static HTML website. This website is for selling one item using PayPal and the client also wanted to have a counter which shows the amount of sold items. Client expected to have huge amount of visitors to this website. I decided to make the counter using Node.js and the Express.js framework.

The Node.js application was simple. Get the sold items amount from a Redis database, increase the counter when item is sold and serve the counter value to users via the API.

Some reasons why I chose to use Node.js in this case

  1. It is very lightweight and fast. There has been over 200000 visits on this website in three weeks and minimal server resources has been able to handle it all.
  2. The counter is really easy to make to be real time.
  3. Node.js was easy to configure.
  4. There are lots of modules available for free. For example, I found a Node.js module for PayPal.

In this case, Node.js was an awesome choice.

Kotlin unresolved reference in IntelliJ

A possible solution for standalone Kotlin projects is to include Kotlin standard libs explicitliy inside the root project.

To do that in IntelliJ IDEA:

  • press Ctrl+Shift+A (Search actions or options)
  • type in "Configure kotlin in project" and let it include standard libs for you

How to filter JSON Data in JavaScript or jQuery?

I know the question explicitly says JS or jQuery, but anyway using lodash is always on the table for other searchers I suppose.

From the source docs:

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']

// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']

// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']

// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']

So the solution for the original question would be just one liner:

var result = _.filter(data, ['website', 'yahoo']);

How do I get the currently-logged username from a Windows service in .NET?

Just in case someone is looking for user Display Name as opposed to User Name, like me.

Here's the treat :

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName.

Add Reference to System.DirectoryServices.AccountManagement in your project.

Random number generator only generating one random number

Always get a positive random number.

 var nexnumber = Guid.NewGuid().GetHashCode();
        if (nexnumber < 0)
        {
            nexnumber *= -1;
        }

Is there any way to call a function periodically in JavaScript?

function test() {
 alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
   clearInterval(id);
}

How to generate .json file with PHP?

Here is a sample code:

<?php 
$sql="select * from Posts limit 20"; 

$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) { 
  $title=$row['title']; 
  $url=$row['url']; 

  $posts[] = array('title'=> $title, 'url'=> $url);
} 

$response['posts'] = $posts;

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);


?> 

Constructors in Go

I am new to go. I have another pattern taken from other languages, that have constructors. And will work in go.

  1. Create an init method.
  2. Make the init method an (object) once routine. It only runs the first time it is called (per object).
func (d *my_struct) Init (){
    //once
    if !d.is_inited {
        d.is_inited = true
        d.value1 = 7
        d.value2 = 6
    }
}
  1. Call init at the top of every method of this class.

This pattern is also useful, when you need late initialisation (constructor is too early).

Advantages: it hides all the complexity in the class, clients don't need to do anything.

Disadvantages: you must remember to call Init at the top of every method of the class.

What is a vertical tab?

In the medical industry, VT is used as the start of frame character in the MLLP/LLP/HLLP protocols that are used to frame HL-7 data, which has been a standard for medical exchange since the late 80s and is still in wide use.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Make sure the user you are using to access your database has the privileges to do so.
GRANT ALL PRIVILEGES ON * . * TO 'user'@'localhost';
Where the first star can be replaced by database name, second star specifies table. Make sure to flush privileges after.

How to position a Bootstrap popover?

Popover's Viewport (Bootstrap v3)

The best solution that will work for you in all occassions, especially if your website has a fluid width, is to use the viewport option of the Bootstrap Popover.

This will make the popover take width inside a selector you have assigned. So if the trigger button is on the right of that container, the bootstrap arrow will also appear on the right while the popover is inside that area. See jsfiddle.net

You can also use padding if you want some space from the edge of container. If you want no padding just use viewport: '.container'

$('#popoverButton').popover({
   container: 'body',
   placement: "bottom",
   html: true,   
   viewport: { selector: '.container', padding: 5 },
   content: '<strong>Hello Wooooooooooooooooooooooorld</strong>'
 });

in the following html example:

<div class="container">
   <button type="button" id="popoverButton">Click Me!</button>
</div>

and with CSS:

.container {
  text-align:right;
  width: 100px;
  padding: 20px;
  background: blue;
}

Popover's Boundary (Bootstrap v4)

Similar to viewport, in Bootstrap version 4, popover introduced the new option boundary

https://getbootstrap.com/docs/4.1/components/popovers/#options

Generate random numbers following a normal distribution in C/C++

Here's a C++ example, based on some of the references. This is quick and dirty, you are better off not re-inventing and using the boost library.

#include "math.h" // for RAND, and rand
double sampleNormal() {
    double u = ((double) rand() / (RAND_MAX)) * 2 - 1;
    double v = ((double) rand() / (RAND_MAX)) * 2 - 1;
    double r = u * u + v * v;
    if (r == 0 || r > 1) return sampleNormal();
    double c = sqrt(-2 * log(r) / r);
    return u * c;
}

You can use a Q-Q plot to examine the results and see how well it approximates a real normal distribution (rank your samples 1..x, turn the ranks into proportions of total count of x ie. how many samples, get the z-values and plot them. An upwards straight line is the desired result).

How to update core-js to core-js@3 dependency?

For ng9 upgraders:

npm i -g core-js@^3

..then:

npm cache clean -f

..followed by:

npm i

Enable & Disable a Div and its elements in Javascript

If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.

try this.

$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');

Set max-height on inner div so scroll bars appear, but not on parent div

This would work just fine, set the height to desired pixel

#inner-right{
            height: 100px;
            overflow:auto;
            }

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

in case your Latitude and Longitude lists are large and lazily loaded:

from itertools import izip
for lat, lon in izip(latitudes, longitudes):
    process(lat, lon)

or if you want to avoid the for-loop

from itertools import izip, imap
out = imap(process, izip(latitudes, longitudes))

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

HTML Table width in percentage, table rows separated equally

You need to enter the width % for each cell. But wait, there's a better way to do that, it's called CSS:

<style>
     .equalDivide tr td { width:25%; }
</style>

<table class="equalDivide" cellpadding="0" cellspacing="0" width="100%" border="0">
   <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
   </tr>
</table>

rawQuery(query, selectionArgs)

if your SQL query is this

SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'

then rawQuery will be

String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"} 
db.rawQuery(query, selectionArgs);

checking if a number is divisible by 6 PHP

Assuming $foo is an integer:

$answer = (int) (floor(($foo + 5) / 6) * 6)

Core dump file is not generated

Although this isn't going to be a problem for the person who asked the question, because they ran the program that was to produce the core file in a script with the ulimit command, I'd like to document that the ulimit command is specific to the shell in which you run it (like environment variables). I spent way too much time running ulimit and sysctl and stuff in one shell, and the command that I wanted to dump core in the other shell, and wondering why the core file was not produced.

I will be adding it to my bashrc. The sysctl works for all processes once it is issued, but the ulimit only works for the shell in which it is issued (maybe also the descendents too) - but not for other shells that happen to be running.

How can I read user input from the console?

You're missing a semicolon: double b = a * Math.PI;

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

How to make a list of n numbers in Python and randomly select any number?

After that I would like to select another number from the remaining numbers of the list (N-1) and then use that also.

Then you arguably do not really want to create a list of numbers from 1 to N just for the purpose of picking one (why not just ask for a random number in that range directly, instead of explicitly creating it to choose from?), but instead to shuffle such a list. Fortunately, the random module has you covered for this, too: just use random.shuffle.

Of course, if you have a huge list of numbers and you only want to draw a few, then it certainly makes sense to draw each using random.choice and remove it.

But... why do you want to select numbers from a range, that corresponds to the count of some items? Are you going to use the number to select one of the items? Don't do that; that's going out of your way to make things too complicated. If you want to select one of the items, then do so directly - again with random.choice.

How do I set the visibility of a text box in SSRS using an expression?

the rdl file content:

<Visibility><Hidden>=Parameters!casetype.Value=300</Hidden></Visibility>

so the text box will hidden, if your expression is true.

What do &lt; and &gt; stand for?

&gt; and &lt; is a character entity reference for the > and < character in HTML.

It is not possible to use the less than (<) or greater than (>) signs in your file, because the browser will mix them with tags.

for these difficulties you can use entity names(&gt;) and entity numbers(&#60;).

pip cannot install anything

This has happened to my because of proxy-authntication, so I did this to resolve it

export http_proxy=http://uname:[email protected]:8080
export https_proxy=http://uname:[email protected]:8080
export ftp_proxy=http://uname:[email protected]:8080

Check mySQL version on Mac 10.8.5

You should be able to open terminal and just type

mysql -v

Java double comparison epsilon

If you are dealing with money I suggest checking the Money design pattern (originally from Martin Fowler's book on enterprise architectural design).

I suggest reading this link for the motivation: http://wiki.moredesignpatterns.com/space/Value+Object+Motivation+v2

What is HTML5 ARIA?

I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them

What is ARIA?

If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.

ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.

And see this you tube video for ARIA live.

How do function pointers in C work?

Function pointer is usually defined by typedef, and used as param & return value.

Above answers already explained a lot, I just give a full example:

#include <stdio.h>

#define NUM_A 1
#define NUM_B 2

// define a function pointer type
typedef int (*two_num_operation)(int, int);

// an actual standalone function
static int sum(int a, int b) {
    return a + b;
}

// use function pointer as param,
static int sum_via_pointer(int a, int b, two_num_operation funp) {
    return (*funp)(a, b);
}

// use function pointer as return value,
static two_num_operation get_sum_fun() {
    return &sum;
}

// test - use function pointer as variable,
void test_pointer_as_variable() {
    // create a pointer to function,
    two_num_operation sum_p = &sum;
    // call function via pointer
    printf("pointer as variable:\t %d + %d = %d\n", NUM_A, NUM_B, (*sum_p)(NUM_A, NUM_B));
}

// test - use function pointer as param,
void test_pointer_as_param() {
    printf("pointer as param:\t %d + %d = %d\n", NUM_A, NUM_B, sum_via_pointer(NUM_A, NUM_B, &sum));
}

// test - use function pointer as return value,
void test_pointer_as_return_value() {
    printf("pointer as return value:\t %d + %d = %d\n", NUM_A, NUM_B, (*get_sum_fun())(NUM_A, NUM_B));
}

int main() {
    test_pointer_as_variable();
    test_pointer_as_param();
    test_pointer_as_return_value();

    return 0;
}

Javascript Error Null is not an Object

Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.

So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.

Then you can add an event listener for document load to execute the function.

That will give you something like:

<script>
  function init() {
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");
    myButton.onclick = function() {
      var userName = myTextfield.value;
      greetUser(userName);
    }
  }

  function greetUser(userName) {
    var greeting = "Hello " + userName + "!";
    document.getElementsByTagName ("h2")[0].innerHTML = greeting;
  }

  document.addEventListener('readystatechange', function() {
    if (document.readyState === "complete") {
      init();
    }
  });

</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="button" id="myButton" value="Go" />
</form>

Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/

how to auto select an input field and the text in it on page load

try this. this will work on both Firefox and chrome.

<input type="text" value="test" autofocus="autofocus" onfocus="this.select()">

SQL Server query to find all permissions/access for all users in a database

From SQL Server 2005 on, you can use system views for that. For example, this query lists all users in a database, with their rights:

select  princ.name
,       princ.type_desc
,       perm.permission_name
,       perm.state_desc
,       perm.class_desc
,       object_name(perm.major_id)
from    sys.database_principals princ
left join
        sys.database_permissions perm
on      perm.grantee_principal_id = princ.principal_id

Be aware that a user can have rights through a role as well. For example, the db_data_reader role grants select rights on most objects.

SQL to find the number of distinct values in a column

**

Using following SQL we can get the distinct column value count in Oracle 11g.

**

Select count(distinct(Column_Name)) from TableName

What is the best way to repeatedly execute a function every x seconds?

One possible answer:

import time
t=time.time()

while True:
    if time.time()-t>10:
        #run your task here
        t=time.time()

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

Twitter Bootstrap - how to center elements horizontally or vertically

You may directly write into your css file like this :

_x000D_
_x000D_
.content {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left:50%;_x000D_
  transform: translate(-50%,-50%);_x000D_
  }
_x000D_
<div class = "content" >_x000D_
  _x000D_
   <p> some text </p>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Android: making a fullscreen application

In onCreate call

requestWindowFeature(Window.FEATURE_NO_TITLE); // for hiding title

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

Split and join C# string

You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.

string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');

if (lnSpace > -1)
{
    string lcFirst = lcStart.Substring(0, lnSpace);
    string lcRest = lcStart.Substring(lnSpace + 1);
}

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

Installing Java on OS X 10.9 (Mavericks)

The OP implied that Java 7 was the need. And Java 6 is in fact no longer being 'supported' so 7 is the version you should be installing at this point unless you have legacy app concerns.

You can get it here: http://java.com/en/download/mac_download.jsp?locale=en

Can someone explain how to append an element to an array in C programming?

There are only two ways to put a value into an array, and one is just syntactic sugar for the other:

a[i] = v;
*(a+i) = v;

Thus, to put something as the 4th element, you don't have any choice but arr[4] = 5. However, it should fail in your code, because the array is only allocated for 4 elements.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

I spent half a day searching for answers to an identical "Illegal mix of collations" error with conflicts between utf8_unicode_ci and utf8_general_ci.

I found that some columns in my database were not specifically collated utf8_unicode_ci. It seems mysql implicitly collated these columns utf8_general_ci.

Specifically, running a 'SHOW CREATE TABLE table1' query outputted something like the following:

| table1 | CREATE TABLE `table1` (
`id` int(11) NOT NULL,
`col1` varchar(4) CHARACTER SET utf8 NOT NULL,
`col2` int(11) NOT NULL,
PRIMARY KEY (`col1`,`col2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |

Note the line 'col1' varchar(4) CHARACTER SET utf8 NOT NULL does not have a collation specified. I then ran the following query:

ALTER TABLE table1 CHANGE col1 col1 VARCHAR(4) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;

This solved my "Illegal mix of collations" error. Hope this might help someone else out there.

Likelihood of collision using most significant bits of a UUID in Java

You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.

There are different levels of uniqueness.

If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.

If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)

In bash, how to store a return value in a variable?

The answer above suggests changing the function to echo data rather than return it so that it can be captured.

For a function or program that you can't modify where the return value needs to be saved to a variable (like test/[, which returns a 0/1 success value), echo $? within the command substitution:

# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"

# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"

E.g.

$ echo $REMOTE_ADDR

$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0

For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:

# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []

# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0

How to drop unique in MySQL?

Try it to remove uique of a column:

ALTER TABLE  `0_ms_labdip_details` DROP INDEX column_tcx

Run this code in phpmyadmin and remove unique of column

Inconsistent Accessibility: Parameter type is less accessible than method

If sounds like the type ACTInterface is not public, but is using the default accessibility of either internal (if it is top-level) or private (if it is nested in another type).

Giving the type the public modifier would fix it.

Another approach is to make both the type and the method internal, if that is your intent.

The issue is not the accessibility of the field (oActInterface), but rather of the type ACTInterface itself.

When to use async false and async true in ajax function in jquery

In basic terms synchronous requests wait for the response to be received from the request before it allows any code processing to continue. At first this may seem like a good thing to do, but it absolutely is not.

As mentioned, while the request is in process the browser will halt execution of all script and also rendering of the UI as the JS engine of the majority of browsers is (effectively) single-threaded. This means that to your users the browser will appear unresponsive and they may even see OS-level warnings that the program is not responding and to ask them if its process should be ended. It's for this reason that synchronous JS has been deprecated and you see warnings about its use in the devtools console.

The alternative of asynchronous requests is by far the better practice and should always be used where possible. This means that you need to know how to use callbacks and/or promises in order to handle the responses to your async requests when they complete, and also how to structure your JS to work with this pattern. There are many resources already available covering this, this, for example, so I won't go into it here.

There are very few occasions where a synchronous request is necessary. In fact the only one I can think of is when making a request within the beforeunload event handler, and even then it's not guaranteed to work.

In summary. you should look to learn and employ the async pattern in all requests. Synchronous requests are now an anti-pattern which cause more issues than they generally solve.

php: Get html source code with cURL

Try the following:

$ch = curl_init("http://www.example-webpage.com/file.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);

I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.


EDIT: after some discussion in the comments we found out that the problem was that the server couldn't resolve the host name and the page was in addition a HTTPS resource so here comes your temporary solution (until your server admin fixes the name resolving).

what i did is just pinging graph.facebook.com to see the IP address, replace the host name with the IP address and instead specify the header manually. This however renders the SSL certificate invalid so we have to suppress peer verification.

//$url = "https://graph.facebook.com/19165649929?fields=name";
$url = "https://66.220.146.224/19165649929?fields=name";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
$output = curl_exec($ch);
curl_close($ch); 

Keep in mind that the IP address might change and this is an error source. you should also do some error handling using curl_error();.

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

When the callee throws an exception i.e. void showfile() throws java.io.IOException the caller should handle it or throw it again.

And also learn naming conventions. A class name should start with a capital letter.

How to programmatically close a JFrame

 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

How to convert a color integer to a hex String in Android?

With this method Integer.toHexString, you can have an Unknown color exception for some colors when using Color.parseColor.

And with this method String.format("#%06X", (0xFFFFFF & intColor)), you'll lose alpha value.

So I recommend this method:

public static String ColorToHex(int color) {
        int alpha = android.graphics.Color.alpha(color);
        int blue = android.graphics.Color.blue(color);
        int green = android.graphics.Color.green(color);
        int red = android.graphics.Color.red(color);

        String alphaHex = To00Hex(alpha);
        String blueHex = To00Hex(blue);
        String greenHex = To00Hex(green);
        String redHex = To00Hex(red);

        // hexBinary value: aabbggrr
        StringBuilder str = new StringBuilder("#");
        str.append(alphaHex);
        str.append(blueHex);
        str.append(greenHex);
        str.append(redHex );

        return str.toString();
    }

    private static String To00Hex(int value) {
        String hex = "00".concat(Integer.toHexString(value));
        return hex.substring(hex.length()-2, hex.length());
    }

Sublime Text 3, convert spaces to tabs

if you have Mac just use help option (usually the last option on Mac's menu bar) then type: "tab indentation" and choose a tab indentation width

but generally, you can follow this path: view -> indentation

Compute mean and standard deviation by group for multiple variables in a data.frame

There is a helpful function in the psych package.

You should try the following implementation:

psych::describeBy(data$dependentvariable, group = data$groupingvariable)

Validate form field only on submit or user input

Use $dirty flag to show the error only after user interacted with the input:

<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>

If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};

Then, if all that JS inside ng-showexpression looks too much for you, you can abstract it into a separate method:

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field, validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email', 'required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

How do I flush the cin buffer?

The following should work:

cin.flush();

On some systems it's not available and then you can use:

cin.ignore(INT_MAX);

Concatenate two slices in Go

Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:

func append

func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)